Exemplo n.º 1
0
BOOL LLWindowMacOSX::createContext(int x, int y, int width, int height, int bits, BOOL fullscreen, BOOL disable_vsync)
{
	BOOL			glNeedsInit = FALSE;

	mFullscreen = fullscreen;
	
	if (mWindow == NULL)
	{
		mWindow = getMainAppWindow();
	}

	if(mContext == NULL)
	{
		// Our OpenGL view is already defined within SecondLife.xib.
		// Get the view instead.
		mGLView = createOpenGLView(mWindow, mFSAASamples, !disable_vsync);
		mContext = getCGLContextObj(mGLView);
		
		// Since we just created the context, it needs to be set up.
		glNeedsInit = TRUE;
		
		gGLManager.mVRAM = getVramSize(mGLView);
	}
	
	// This sets up our view to recieve text from our non-inline text input window.
	setupInputWindow(mWindow, mGLView);
	
	// Hook up the context to a drawable

	if(mContext != NULL)
	{
		
		// <FS:CR> Mac OpenGL
		//U32 err = CGLSetCurrentContext(mContext);
		CGLError err = CGLSetCurrentContext(mContext);		
		if (err != kCGLNoError)
		{
			setupFailure("Can't activate GL rendering context", "Error", OSMB_OK);
			return FALSE;
		}
	}

	// Disable vertical sync for swap
	GLint frames_per_swap = 0;
	if (disable_vsync)
	{
		frames_per_swap = 0;
	}
	else
	{
		frames_per_swap = 1;
	}
	
	CGLSetParameter(mContext, kCGLCPSwapInterval, &frames_per_swap);

	//enable multi-threaded OpenGL
	if (sUseMultGL)
	{
		CGLError cgl_err;
		CGLContextObj ctx = CGLGetCurrentContext();

		cgl_err =  CGLEnable( ctx, kCGLCEMPEngine);

		if (cgl_err != kCGLNoError )
		{
			LL_DEBUGS("GLInit") << "Multi-threaded OpenGL not available." << LL_ENDL;
		}
		else
		{
			LL_DEBUGS("GLInit") << "Multi-threaded OpenGL enabled." << LL_ENDL;
		}
	}
	makeFirstResponder(mWindow, mGLView);
    
	return TRUE;
}
Exemplo n.º 2
0
int main(int argc, char ** argv) {
	unsigned int displayMode;
#ifdef __APPLE__
	GLint VBL = 1;
#endif
	
	configuration.windowX = 2;
	configuration.windowY = 28;
	configuration.windowWidth = 800;
	configuration.windowHeight = 600;
	configuration.windowTitle = "GLUTShell";
	configuration.displayMode.doubleBuffer = true;
	configuration.displayMode.depthBuffer = false;
	configuration.displayMode.stencilBuffer = false;
	configuration.displayMode.accumBuffer = false;
	configuration.displayMode.multisample = false;
	
	GLUTTarget_configure(argc, argv, &configuration);
	
	displayMode = GLUT_RGBA;
	if (configuration.displayMode.doubleBuffer) {
		displayMode |= GLUT_DOUBLE;
	}
	if (configuration.displayMode.depthBuffer) {
		displayMode |= GLUT_DEPTH;
	}
	if (configuration.displayMode.stencilBuffer) {
		displayMode |= GLUT_STENCIL;
	}
	if (configuration.displayMode.accumBuffer) {
		displayMode |= GLUT_ACCUM;
	}
	if (configuration.displayMode.multisample) {
		displayMode |= GLUT_MULTISAMPLE;
	}
	
	glutInit(&argc, argv);
	glutInitDisplayMode(displayMode);
	glutInitWindowPosition(configuration.windowX, configuration.windowY);
	glutInitWindowSize(configuration.windowWidth, configuration.windowHeight);
	glutCreateWindow(configuration.windowTitle);
	
	glutReshapeFunc(reshapeFunc);
	glutDisplayFunc(displayFunc);
	glutKeyboardFunc(keyDownFunc);
	glutKeyboardUpFunc(keyUpFunc);
	glutSpecialFunc(specialDownFunc);
	glutSpecialUpFunc(specialUpFunc);
	glutMouseFunc(mouseFunc);
	glutMotionFunc(motionFunc);
	glutPassiveMotionFunc(motionFunc);
	
#ifdef __APPLE__
	CGLSetParameter(CGLGetCurrentContext(), kCGLCPSwapInterval, &VBL);
#endif
	
	GLGraphics_init(GL_API_VERSION_DESKTOP_1);
	
	Target_init(argc, argv);
	
	return EXIT_SUCCESS;
}
Exemplo n.º 3
0
int main(int argc, char **argv)
{
  GLenum status;
  GLboolean hasDSA;
  int samples = 0;
  int i;

  glutInitWindowSize(canvas_width, canvas_height);
  glutInit(&argc, argv);
  for (i=1; i<argc; i++) {
    if (argv[i][0] == '-') {
      int value = atoi(argv[i]+1);
      if (value >= 1) {
        samples = value;
        continue;
      }
    }
    fprintf(stderr, "usage: %s [-#]\n       where # is the number of samples/pixel\n",
      programName);
    exit(1);
  }

  if (samples > 0) {
    char buffer[200];
    if (samples == 1)
      samples = 0;
    printf("requesting %d samples\n", samples);
    sprintf(buffer, "rgb stencil~4 double samples~%d", samples);
    glutInitDisplayString(buffer);
  } else {
    /* Request a double-buffered window with at least 4 stencil bits and
    8 samples per pixel. */
#if 0
	glutInitDisplayString("rgb stencil~4 double samples~8");
#else
	glutInitDisplayString("rgb stencil~4 double");
#endif
  }

  glutCreateWindow("Classic PostScript tiger NV_path_rendering example");

  // Regal workaround for OSX GLUT

  #ifdef __APPLE__
  extern void *CGLGetCurrentContext(void);
  RegalMakeCurrent(CGLGetCurrentContext());
  #endif

  status = glewInit();
  if (status != GLEW_OK) {
    fatalError("OpenGL Extension Wrangler (GLEW) failed to initialize");
  }

  printf("vendor: %s\n", glGetString(GL_VENDOR));
  printf("version: %s\n", glGetString(GL_VERSION));
  printf("renderer: %s\n", glGetString(GL_RENDERER));
  printf("samples per pixel = %d\n", glutGet(GLUT_WINDOW_NUM_SAMPLES));
  printf("Executable: %d bit\n", (int)(8*sizeof(int *)));
  printf("\n");
  printf("Use left mouse button to scale/zoom (vertical, up/down) and rotate (right=clockwise, left=ccw)\n");
  printf("Rotate and zooming is centered where you first left mouse click\n");
  printf("Hold down Ctrl at left mouse click to JUST SCALE\n");
  printf("Hold down Shift at left mouse click to JUST ROTATE\n");
  printf("\n");
  printf("Use middle mouse button to slide (translate)\n");

  glutDisplayFunc(display);
  glutReshapeFunc(reshape);
  glutKeyboardFunc(keyboard);
  glutMouseFunc(mouse);
  glutMotionFunc(motion);

  initModelAndViewMatrices();

  glutCreateMenu(menu);
  glutAddMenuEntry("[f] Toggle filling", 'f');
  glutAddMenuEntry("[s] Toggle stroking", 's');
  glutAddMenuEntry("[r] Reset view", 'r');
  glutAddMenuEntry("[Esc] Quit", 27);
  glutAttachMenu(GLUT_RIGHT_BUTTON);

  if (!glewIsSupported("GL_REGAL_extension_query"))
    printf("GL_REGAL_extension_query is not supported.\n");

  if (!glewIsSupported("GL_EXT_debug_marker"))
    printf("GL_EXT_debug_marker is not supported.\n");

  hasDSA = glewIsSupported("GL_EXT_direct_state_access");
  if (!hasDSA) {
    fatalError("OpenGL implementation doesn't support GL_EXT_direct_state_access (you should be using NVIDIA GPUs...)");
  }

  if (!glewIsSupported("GL_NV_path_rendering")) {
    fatalError("required NV_path_rendering OpenGL extension is not present");
  }

  initGraphics();

  path_count = getTigerPathCount();

  glutMainLoop();
  return 0;
}
Exemplo n.º 4
0
// Intitialize OpenCL
//*****************************************************************************
void createCLContext() {
    //Get the NVIDIA platform
    ciErrNum = oclGetPlatformID(&cpPlatform);
    oclCheckErrorEX(ciErrNum, CL_SUCCESS, pCleanup);

    // Get the number of GPU devices available to the platform
    ciErrNum = clGetDeviceIDs(cpPlatform, CL_DEVICE_TYPE_GPU, 0, NULL, &uiDevCount);
    oclCheckErrorEX(ciErrNum, CL_SUCCESS, pCleanup);

    // Create the device list
    cdDevices = new cl_device_id [uiDevCount];
    ciErrNum = clGetDeviceIDs(cpPlatform, CL_DEVICE_TYPE_GPU, uiDevCount, cdDevices, NULL);
    oclCheckErrorEX(ciErrNum, CL_SUCCESS, pCleanup);

    // Get device requested on command line, if any
    uiDeviceUsed = 0;
    unsigned int uiEndDev = uiDevCount - 1;
 

	// Check if the requested device (or any of the devices if none requested) supports context sharing with OpenGL
    if(0)
    {
        bool bSharingSupported = false;
        for(unsigned int i = uiDeviceUsed; (!bSharingSupported && (i <= uiEndDev)); ++i) 
        {
            size_t extensionSize;
            ciErrNum = clGetDeviceInfo(cdDevices[i], CL_DEVICE_EXTENSIONS, 0, NULL, &extensionSize );
            oclCheckErrorEX(ciErrNum, CL_SUCCESS, pCleanup);
            if(extensionSize > 0) 
            {
                char* extensions = (char*)malloc(extensionSize);
                ciErrNum = clGetDeviceInfo(cdDevices[i], CL_DEVICE_EXTENSIONS, extensionSize, extensions, &extensionSize);
                oclCheckErrorEX(ciErrNum, CL_SUCCESS, pCleanup);
                std::string stdDevString(extensions);
                free(extensions);

                size_t szOldPos = 0;
                size_t szSpacePos = stdDevString.find(' ', szOldPos); // extensions string is space delimited
                while (szSpacePos != stdDevString.npos)
                {
                    if( strcmp(GL_SHARING_EXTENSION, stdDevString.substr(szOldPos, szSpacePos - szOldPos).c_str()) == 0 ) 
                    {
                        // Device supports context sharing with OpenGL
                        uiDeviceUsed = i;
                        bSharingSupported = true;
                        break;
                    }
                    do 
                    {
                        szOldPos = szSpacePos + 1;
                        szSpacePos = stdDevString.find(' ', szOldPos);
                    } 
                    while (szSpacePos == szOldPos);
                }
            }
        }
       
        // Log CL-GL interop support and quit if not available (sample needs it)
 //       shrLog("%s...\n", bSharingSupported ? "Using CL-GL Interop" : "No device found that supports CL/GL context sharing");  
        oclCheckErrorEX(bSharingSupported, true, pCleanup);

        // Define OS-specific context properties and create the OpenCL context
        #if defined (__APPLE__)
            CGLContextObj kCGLContext = CGLGetCurrentContext();
            CGLShareGroupObj kCGLShareGroup = CGLGetShareGroup(kCGLContext);
            cl_context_properties props[] = 
            {
                CL_CONTEXT_PROPERTY_USE_CGL_SHAREGROUP_APPLE, (cl_context_properties)kCGLShareGroup, 
                0 
            };
            cxGPUContext = clCreateContext(props, 0,0, NULL, NULL, &ciErrNum);
        #else
            #ifdef UNIX
                cl_context_properties props[] = 
                {
                    CL_GL_CONTEXT_KHR, (cl_context_properties)glXGetCurrentContext(), 
                    CL_GLX_DISPLAY_KHR, (cl_context_properties)glXGetCurrentDisplay(), 
                    CL_CONTEXT_PLATFORM, (cl_context_properties)cpPlatform, 
                    0
                };
                cxGPUContext = clCreateContext(props, 1, &cdDevices[uiDeviceUsed], NULL, NULL, &ciErrNum);
            #else // Win32
                cl_context_properties props[] = 
                {
                    CL_GL_CONTEXT_KHR, (cl_context_properties)wglGetCurrentContext(), 
                    CL_WGL_HDC_KHR, (cl_context_properties)wglGetCurrentDC(), 
                    CL_CONTEXT_PLATFORM, (cl_context_properties)cpPlatform, 
                    0
                };
                cxGPUContext = clCreateContext(props, 1, &cdDevices[uiDeviceUsed], NULL, NULL, &ciErrNum);
            #endif
        #endif
    }
    else 
    {
		// No GL interop
        cl_context_properties props[] = {CL_CONTEXT_PLATFORM, (cl_context_properties)cpPlatform, 0};
        cxGPUContext = clCreateContext(props, 1, &cdDevices[uiDeviceUsed], NULL, NULL, &ciErrNum);

		g_glInterop = false;
    }
    oclCheckErrorEX(ciErrNum, CL_SUCCESS, pCleanup);
}
// Init OpenCL
//*****************************************************************************
int initCL(int argc, const char** argv)
{
    cl_platform_id cpPlatform;
    cl_uint uiDevCount;
    cl_device_id *cdDevices;

    //Get the NVIDIA platform
    ciErrNum = oclGetPlatformID(&cpPlatform);
    oclCheckErrorEX(ciErrNum, CL_SUCCESS, pCleanup);

    // Get the number of GPU devices available to the platform
    ciErrNum = clGetDeviceIDs(cpPlatform, CL_DEVICE_TYPE_GPU, 0, NULL, &uiDevCount);
    oclCheckErrorEX(ciErrNum, CL_SUCCESS, pCleanup);

    // Create the device list
    cdDevices = new cl_device_id [uiDevCount];
    ciErrNum = clGetDeviceIDs(cpPlatform, CL_DEVICE_TYPE_GPU, uiDevCount, cdDevices, NULL);
    oclCheckErrorEX(ciErrNum, CL_SUCCESS, pCleanup);

    // Get device requested on command line, if any
    unsigned int uiDeviceUsed = 0;
    unsigned int uiEndDev = uiDevCount - 1;
    if(shrGetCmdLineArgumentu(argc, argv, "device", &uiDeviceUsed))
    {
      uiDeviceUsed = CLAMP(uiDeviceUsed, 0, uiEndDev);
      uiEndDev = uiDeviceUsed; 
    } 

    // Check if the requested device (or any of the devices if none requested) supports context sharing with OpenGL   
    if(bGLinterop && !bQATest)
    {
        bool bSharingSupported = false;
        for(unsigned int i = uiDeviceUsed; (!bSharingSupported && (i <= uiEndDev)); ++i) 
        {
            size_t extensionSize;
            ciErrNum = clGetDeviceInfo(cdDevices[i], CL_DEVICE_EXTENSIONS, 0, NULL, &extensionSize );
            oclCheckErrorEX(ciErrNum, CL_SUCCESS, pCleanup);
            if(extensionSize > 0) 
            {
                char* extensions = (char*)malloc(extensionSize);
                ciErrNum = clGetDeviceInfo(cdDevices[i], CL_DEVICE_EXTENSIONS, extensionSize, extensions, &extensionSize);
                oclCheckErrorEX(ciErrNum, CL_SUCCESS, pCleanup);
                std::string stdDevString(extensions);
                free(extensions);

                size_t szOldPos = 0;
                size_t szSpacePos = stdDevString.find(' ', szOldPos); // extensions string is space delimited
                while (szSpacePos != stdDevString.npos)
                {
                    if( strcmp(GL_SHARING_EXTENSION, stdDevString.substr(szOldPos, szSpacePos - szOldPos).c_str()) == 0 ) 
                    {
                        // Device supports context sharing with OpenGL
                        uiDeviceUsed = i;
                        bSharingSupported = true;
                        break;
                    }
                    do 
                    {
                        szOldPos = szSpacePos + 1;
                        szSpacePos = stdDevString.find(' ', szOldPos);
                    } 
                    while (szSpacePos == szOldPos);
                }
            }
        }
       
        shrLog("%s...\n\n", bSharingSupported ? "Using CL-GL Interop" : "No device found that supports CL/GL context sharing");  
        oclCheckErrorEX(bSharingSupported, true, pCleanup);

        // Define OS-specific context properties and create the OpenCL context
        #if defined (__APPLE__) || defined (MACOSX)
            CGLContextObj kCGLContext = CGLGetCurrentContext();
            CGLShareGroupObj kCGLShareGroup = CGLGetShareGroup(kCGLContext);
            cl_context_properties props[] = 
            {
                CL_CONTEXT_PROPERTY_USE_CGL_SHAREGROUP_APPLE, (cl_context_properties)kCGLShareGroup, 
                0 
            };
            cxGPUContext = clCreateContext(props, 0,0, NULL, NULL, &ciErrNum);
        #else
            #ifdef UNIX
                cl_context_properties props[] = 
                {
                    CL_GL_CONTEXT_KHR, (cl_context_properties)glXGetCurrentContext(), 
                    CL_GLX_DISPLAY_KHR, (cl_context_properties)glXGetCurrentDisplay(), 
                    CL_CONTEXT_PLATFORM, (cl_context_properties)cpPlatform, 
                    0
                };
                cxGPUContext = clCreateContext(props, 1, &cdDevices[uiDeviceUsed], NULL, NULL, &ciErrNum);
            #else // Win32
                cl_context_properties props[] = 
                {
                    CL_GL_CONTEXT_KHR, (cl_context_properties)wglGetCurrentContext(), 
                    CL_WGL_HDC_KHR, (cl_context_properties)wglGetCurrentDC(), 
                    CL_CONTEXT_PLATFORM, (cl_context_properties)cpPlatform, 
                    0
                };
                cxGPUContext = clCreateContext(props, 1, &cdDevices[uiDeviceUsed], NULL, NULL, &ciErrNum);
            #endif
        #endif
    }
    else 
    {
		// No GL interop
        cl_context_properties props[] = {CL_CONTEXT_PLATFORM, (cl_context_properties)cpPlatform, 0};
        cxGPUContext = clCreateContext(props, 1, &cdDevices[uiDeviceUsed], NULL, NULL, &ciErrNum);

		bGLinterop = shrFALSE;
    }

    shrCheckErrorEX(ciErrNum, CL_SUCCESS, pCleanup);

    // Log device used 
    shrLog("Device # %u, ", uiDeviceUsed);
    oclPrintDevName(LOGBOTH, cdDevices[uiDeviceUsed]);
    shrLog("\n");

    // create a command-queue
    cqCommandQueue = clCreateCommandQueue(cxGPUContext, cdDevices[uiDeviceUsed], 0, &ciErrNum);
    oclCheckErrorEX(ciErrNum, CL_SUCCESS, pCleanup);

    // Memory Setup
	if( bGLinterop ) {
        cl_pbos[0] = clCreateFromGLBuffer(cxGPUContext, CL_MEM_READ_ONLY, pbo_source, &ciErrNum);
        cl_pbos[1] = clCreateFromGLBuffer(cxGPUContext, CL_MEM_WRITE_ONLY, pbo_dest, &ciErrNum);
	} else {
        cl_pbos[0] = clCreateBuffer(cxGPUContext, CL_MEM_READ_ONLY, 4 * image_width * image_height, NULL, &ciErrNum);
        cl_pbos[1] = clCreateBuffer(cxGPUContext, CL_MEM_WRITE_ONLY, 4 * image_width * image_height, NULL, &ciErrNum);
	}
    oclCheckErrorEX(ciErrNum, CL_SUCCESS, pCleanup);

    // Program Setup
    size_t program_length;
    const char* source_path = shrFindFilePath(clSourcefile, argv[0]);
    char *source = oclLoadProgSource(source_path, "", &program_length);
    oclCheckErrorEX(source != NULL, shrTRUE, pCleanup);

    // create the program
    cpProgram = clCreateProgramWithSource(cxGPUContext, 1,(const char **) &source, &program_length, &ciErrNum);
    oclCheckErrorEX(ciErrNum, CL_SUCCESS, pCleanup);
    free(source);

    // build the program
    ciErrNum = clBuildProgram(cpProgram, 0, NULL, "-cl-fast-relaxed-math", NULL, NULL);
    if (ciErrNum != CL_SUCCESS)
    {
        // write out standard error, Build Log and PTX, then cleanup and exit
        shrLogEx(LOGBOTH | ERRORMSG, ciErrNum, STDERROR);
        oclLogBuildInfo(cpProgram, oclGetFirstDev(cxGPUContext));
        oclLogPtx(cpProgram, oclGetFirstDev(cxGPUContext), "oclPostProcessGL.ptx");
        Cleanup(EXIT_FAILURE); 
    }

    // create the kernel
    ckKernel = clCreateKernel(cpProgram, "postprocess", &ciErrNum);

    // set the args values
    ciErrNum |= clSetKernelArg(ckKernel, 0, sizeof(cl_mem), (void *) &(cl_pbos[0]));
    ciErrNum |= clSetKernelArg(ckKernel, 1, sizeof(cl_mem), (void *) &(cl_pbos[1]));
    ciErrNum |= clSetKernelArg(ckKernel, 2, sizeof(image_width), &image_width);
    ciErrNum |= clSetKernelArg(ckKernel, 3, sizeof(image_width), &image_height);
    oclCheckErrorEX(ciErrNum, CL_SUCCESS, pCleanup);
    
    return 0;
}
Exemplo n.º 6
0
void create_context_on(const char *plat_name, const char*dev_name, cl_uint idx,
    cl_context *ctx, cl_command_queue *queue, int enable_profiling)
{
  char dev_sel_buf[MAX_NAME_LEN];
  char platform_sel_buf[MAX_NAME_LEN];

  // get number of platforms
  cl_uint plat_count;
  CALL_CL_GUARDED(clGetPlatformIDs, (0, NULL, &plat_count));

  // allocate memory, get list of platform handles
  cl_platform_id *platforms =
    (cl_platform_id *) malloc(plat_count*sizeof(cl_platform_id));
  CHECK_SYS_ERROR(!platforms, "allocating platform array");
  CALL_CL_GUARDED(clGetPlatformIDs, (plat_count, platforms, NULL));

  // print menu, if requested
#ifndef CL_HELPER_FORCE_INTERACTIVE
  if (plat_name == CHOOSE_INTERACTIVELY) // yes, we want exactly that pointer
#endif
  {
    puts("Choose platform:");
    for (cl_uint i = 0; i < plat_count; ++i)
    {
      char buf[MAX_NAME_LEN];
      CALL_CL_GUARDED(clGetPlatformInfo, (platforms[i], CL_PLATFORM_VENDOR,
            sizeof(buf), buf, NULL));
      printf("[%d] %s\n", i, buf);
    }

    printf("Enter choice: ");
    fflush(stdout);

    char *sel = read_a_line();
    if (!sel)
    {
      fprintf(stderr, "error reading line from stdin");
      abort();
    }

    int sel_int = MIN(MAX(0, atoi(sel)), (int) plat_count-1);
    free(sel);

    CALL_CL_GUARDED(clGetPlatformInfo, (platforms[sel_int], CL_PLATFORM_VENDOR,
          sizeof(platform_sel_buf), platform_sel_buf, NULL));
    plat_name = platform_sel_buf;
  }

  // iterate over platforms
  for (cl_uint i = 0; i < plat_count; ++i)
  {
    // get platform name
    char buf[MAX_NAME_LEN];
    CALL_CL_GUARDED(clGetPlatformInfo, (platforms[i], CL_PLATFORM_VENDOR,
          sizeof(buf), buf, NULL));

    // does it match?
    if (!plat_name || strstr(buf, plat_name))
    {
      // get number of devices in platform
      cl_uint dev_count;
      CALL_CL_GUARDED(clGetDeviceIDs, (platforms[i], CL_DEVICE_TYPE_ALL,
            0, NULL, &dev_count));

      // allocate memory, get list of device handles in platform
      cl_device_id *devices =
        (cl_device_id *) malloc(dev_count*sizeof(cl_device_id));
      CHECK_SYS_ERROR(!devices, "allocating device array");

      CALL_CL_GUARDED(clGetDeviceIDs, (platforms[i], CL_DEVICE_TYPE_ALL,
            dev_count, devices, NULL));

      // {{{ print device menu, if requested
#ifndef CL_HELPER_FORCE_INTERACTIVE
      if (dev_name == CHOOSE_INTERACTIVELY) // yes, we want exactly that pointer
#endif
      {
        puts("Choose device:");
        for (cl_uint j = 0; j < dev_count; ++j)
        {
          char buf[MAX_NAME_LEN];
          CALL_CL_GUARDED(clGetDeviceInfo, (devices[j], CL_DEVICE_NAME,
                sizeof(buf), buf, NULL));
          printf("[%d] %s\n", j, buf);
        }

        printf("Enter choice: ");
        fflush(stdout);

        char *sel = read_a_line();
        if (!sel)
        {
          fprintf(stderr, "error reading line from stdin");
          abort();
        }

        int int_sel = MIN(MAX(0, atoi(sel)), (int) dev_count-1);
        free(sel);

        CALL_CL_GUARDED(clGetDeviceInfo, (devices[int_sel], CL_DEVICE_NAME,
              sizeof(dev_sel_buf), dev_sel_buf, NULL));
        dev_name = dev_sel_buf;
      }

      // }}}

      // iterate over devices
      for (cl_uint j = 0; j < dev_count; ++j)
      {
        // get device name
        char buf[MAX_NAME_LEN];
        CALL_CL_GUARDED(clGetDeviceInfo, (devices[j], CL_DEVICE_NAME,
              sizeof(buf), buf, NULL));

        // does it match?
        if (!dev_name || strstr(buf, dev_name))
        {
          if (idx == 0)
          {
            cl_platform_id plat = platforms[i];
            cl_device_id dev = devices[j];

            free(devices);
            free(platforms);

            cl_int status;
            
            // create a context
#if OPENCL_SHARE_WITH_OPENGL
  #if __APPLE__
//              CGLContextObj kCGLContext = CGLGetCurrentContext();
//              CGLShareGroupObj kCGLShareGroup = CGLGetShareGroup(kCGLContext);
//              cl_context_properties cps[] = {
//                CL_CONTEXT_PROPERTY_USE_CGL_SHAREGROUP_APPLE, (cl_context_properties)kCGLShareGroup,
//                CL_CONTEXT_PLATFORM, (cl_context_properties) plat, 0 };
//            
            
            CGLContextObj gl_context = CGLGetCurrentContext();
            CGLShareGroupObj share_group = CGLGetShareGroup(gl_context);
            
            cl_context_properties properties[] = {
              CL_CONTEXT_PROPERTY_USE_CGL_SHAREGROUP_APPLE,
              (cl_context_properties)share_group, 0
            };
            *ctx = clCreateContext(properties, 0, 0, 0, 0, 0);
            clGetGLContextInfoAPPLE(*ctx, gl_context,
                                    CL_CGL_DEVICE_FOR_CURRENT_VIRTUAL_SCREEN_APPLE, sizeof(dev),
                                    &dev, NULL);
            
            
            
  #elif WIN32
              cl_context_properties cps[] = {
                CL_GL_CONTEXT_KHR, (cl_context_properties) wglGetCurrentContext(), CL_WGL_HDC_KHR, (cl_context_properties) wglGetCurrentDC(), CL_CONTEXT_PLATFORM, (cl_context_properties) plat, 0};
            
            //Probably won't work because &dev should correspond to glContext
            *ctx = clCreateContext(cps, 1, &dev, NULL, NULL, &status);
            CHECK_CL_ERROR(status, "clCreateContext");
  #else
              // Linux
              cl_context_properties cps[] = {
                CL_GL_CONTEXT_KHR, ( cl_context_properties) glXGetCurrentContext(), CL_GLX_DISPLAY_KHR, (cl_context_properties) glXGetCurrentDisplay(), CL_CONTEXT_PLATFORM, (cl_context_properties) plat, 0 };
            //Probably won't work because &dev should correspond to glContext
            *ctx = clCreateContext(cps, 1, &dev, NULL, NULL, &status);
            CHECK_CL_ERROR(status, "clCreateContext");
#endif

#else
            // create a context
            cl_context_properties cps[3] = {
              CL_CONTEXT_PLATFORM, (cl_context_properties) plat, 0 };
            // create a command queue
            cl_command_queue_properties qprops = 0;
            if (enable_profiling)
              qprops |= CL_QUEUE_PROFILING_ENABLE;
            
            *queue = clCreateCommandQueue(*ctx, dev, qprops, &status);
            CHECK_CL_ERROR(status, "clCreateCommandQueue");
#endif
//            *ctx = clCreateContext(
//                                   cps, 1, &dev, NULL, NULL, &status);
//            CHECK_CL_ERROR(status, "clCreateContext");

//            // create a command queue
            cl_command_queue_properties qprops = 0;
            if (enable_profiling)
              qprops |= CL_QUEUE_PROFILING_ENABLE;

            *queue = clCreateCommandQueue(*ctx, dev, qprops, &status);
            CHECK_CL_ERROR(status, "clCreateCommandQueue");

            return;
          }
          else
            --idx;
        }
      }

      free(devices);
    }
  }

  free(platforms);

  fputs("create_context_on: specified device not found.\n", stderr);
  abort();
}
Exemplo n.º 7
0
bool wglSwapIntervalEXT(int swapInterval)
{
    /* I really have no idea what the expected return value for success. If it was an int
    * I would return 0, since it is a bool, I'm going to guess that true is success. */
    return !CGLSetParameter(CGLGetCurrentContext(), kCGLCPSwapInterval, (long*)(&swapInterval));
}
Exemplo n.º 8
0
//----------------------------------------------------------------------------//
void OpenGLApplePBTextureTarget::disablePBuffer() const
{
    if (CGLGetCurrentContext() == d_context)
        CGLSetCurrentContext(d_prevContext);
}
Exemplo n.º 9
0
extern "C" int main(int argcount, char** argvec)
{

	#ifdef NO_STDERR
	std::freopen("/dev/null", "w", stderr);
	std::cerr.sync_with_stdio(true);
	#endif

	std::cerr << "Frogatto engine version " << preferences::version() << "\n";
	LOG( "After print engine version" );

	#if defined(TARGET_BLACKBERRY)
		chdir("app/native");
		std::cout<< "Changed working directory to: " << getcwd(0, 0) << std::endl;
	#endif

	std::string level_cfg = "titlescreen.cfg";
	bool unit_tests_only = false, skip_tests = false;
	bool run_benchmarks = false;
	std::vector<std::string> benchmarks_list;
	std::string utility_program;
	std::vector<std::string> util_args;
	std::string server = "wesnoth.org";

	const char* profile_output = NULL;
	std::string profile_output_buf;

	std::string orig_level_cfg = level_cfg;
	std::string override_level_cfg = "";

	int modules_loaded = 0;

	std::vector<std::string> argv;
	for(int n = 1; n < argcount; ++n) {
		argv.push_back(argvec[n]);
        
        if(argv.size() >= 2 && argv[argv.size()-2] == "-NSDocumentRevisionsDebugMode" && argv.back() == "YES") {
            //XCode passes these arguments by default when debugging -- make sure they are ignored.
            argv.resize(argv.size()-2);
        }
	}

	if(sys::file_exists("./master-config.cfg")) {
		variant cfg = json::parse_from_file("./master-config.cfg");
		if(cfg.is_map()) {
			if(cfg["name"].is_null() == false) {
				preferences::set_preferences_path_from_module(cfg["name"].as_string());
				//XXX module::set_module_name(cfg["name"].as_string(), cfg["name"].as_string());
			} else if( cfg["id"].is_null() == false) {
				preferences::set_preferences_path_from_module(cfg["id"].as_string());
				//XXX module::set_module_name(cfg["id"].as_string(), cfg["id"].as_string());
			}
			if(cfg["arguments"].is_null() == false) {
				std::vector<std::string> additional_args = cfg["arguments"].as_list_string();
				argv.insert(argv.begin(), additional_args.begin(), additional_args.end());
			}
		}
	}

	for(int n = 0; n < argv.size(); ++n) {
		const int argc = argv.size();
		const std::string arg(argv[n]);
		std::string arg_name, arg_value;
		std::string::const_iterator equal = std::find(arg.begin(), arg.end(), '=');
		if(equal != arg.end()) {
			arg_name = std::string(arg.begin(), equal);
			arg_value = std::string(equal+1, arg.end());
		}
		if(arg_name == "--module") {
			if(load_module(arg_value, &argv) != 0) {
				std::cerr << "FAILED TO LOAD MODULE: " << arg_value << "\n";
				return -1;
			}
			++modules_loaded;
		}
	}

	if(modules_loaded == 0) {
		if(load_module(DEFAULT_MODULE, &argv) != 0) {
			std::cerr << "FAILED TO LOAD MODULE: " << DEFAULT_MODULE << "\n";
			return -1;
		}
	}

	preferences::load_preferences();
	LOG( "After load_preferences()" );

	// load difficulty settings after module, before rest of args.
	difficulty::manager();

	for(int n = 0; n < argv.size(); ++n) {
		const int argc = argv.size();
		const std::string arg(argv[n]);
		std::string arg_name, arg_value;
		std::string::const_iterator equal = std::find(arg.begin(), arg.end(), '=');
		if(equal != arg.end()) {
			arg_name = std::string(arg.begin(), equal);
			arg_value = std::string(equal+1, arg.end());
		}
		
		if(arg_name == "--module") {
			// ignore already processed.
		} else if(arg_name == "--profile" || arg == "--profile") {
			profile_output_buf = arg_value;
			profile_output = profile_output_buf.c_str();
		} else if(arg_name == "--utility") {
			utility_program = arg_value;
			for(++n; n < argc; ++n) {
				const std::string arg(argv[n]);
				util_args.push_back(arg);
			}

			break;
		} else if(arg == "--benchmarks") {
			run_benchmarks = true;
		} else if(arg_name == "--benchmarks") {
			run_benchmarks = true;
			benchmarks_list = util::split(arg_value);
		} else if(arg == "--tests") {
			unit_tests_only = true;
		} else if(arg == "--no-tests") {
			skip_tests = true;
		} else if(arg == "--width" && n+1 < argc) {
			std::string w(argv[++n]);
			preferences::set_actual_screen_width(boost::lexical_cast<int>(w));
		} else if(arg == "--height" && n+1 < argc) {
			std::string h(argv[++n]);
			preferences::set_actual_screen_height(boost::lexical_cast<int>(h));
		} else if(arg == "--level" && n+1 < argc) {
			override_level_cfg = argv[++n];
		} else if(arg == "--host" && n+1 < argc) {
			server = argv[++n];
		} else if(arg == "--compiled") {
			preferences::set_load_compiled(true);
#ifndef NO_EDITOR
		} else if(arg == "--edit") {
			preferences::set_edit_on_start(true);
#endif
		} else if(arg == "--no-compiled") {
			preferences::set_load_compiled(false);
#if defined(TARGET_PANDORA)
		} else if(arg == "--no-fbo") {
			preferences::set_fbo(false);
		} else if(arg == "--no-bequ") {
			preferences::set_bequ(false);
#endif
		} else if(arg == "--help" || arg == "-h") {
			print_help(std::string(argvec[0]));
			return 0;
		} else {
			const bool res = preferences::parse_arg(argv[n].c_str());
			if(!res) {
				std::cerr << "unrecognized arg: '" << arg << "'\n";
				return -1;
			}
		}
	}

	checksum::manager checksum_manager;

	preferences::expand_data_paths();
	LOG( "After expand_data_paths()" );

	std::cerr << "Preferences dir: " << preferences::user_data_path() << '\n';

	//make sure that the user data path exists.
	if(!preferences::setup_preferences_dir()) {
		std::cerr << "cannot create preferences dir!\n";
	}

	std::cerr << "\n";

	if(utility_program.empty() == false && test::utility_needs_video(utility_program) == false) {
		test::run_utility(utility_program, util_args);
		return 0;
	}

#if defined(TARGET_PANDORA)
    EGL_Open();
#endif

#if defined(__ANDROID__)
	std::freopen("stdout.txt","w",stdout);
	std::freopen("stderr.txt","w",stderr);
	std::cerr.sync_with_stdio(true);
#endif

	LOG( "Start of main" );
	
	Uint32 sdl_init_flags = SDL_INIT_VIDEO | SDL_INIT_JOYSTICK;
#ifdef _WINDOWS
	sdl_init_flags |= SDL_INIT_TIMER;
#endif
	if(SDL_Init(sdl_init_flags) < 0) {
		std::cerr << "could not init SDL\n";
		return -1;
	}
	LOG( "After SDL_Init" );

#ifdef TARGET_OS_HARMATTAN
	g_type_init();
#endif
	i18n::init ();
	LOG( "After i18n::init()" );

//	SDL_GL_SetAttribute(SDL_GL_STENCIL_SIZE, 1);

#if defined(TARGET_OS_IPHONE) || defined(TARGET_BLACKBERRY) || defined(__ANDROID__)
	//on the iPhone and PlayBook, try to restore the auto-save if it exists
	if(sys::file_exists(preferences::auto_save_file_path()) && sys::read_file(std::string(preferences::auto_save_file_path()) + ".stat") == "1") {
		level_cfg = "autosave.cfg";
		sys::write_file(std::string(preferences::auto_save_file_path()) + ".stat", "0");

	}
#endif

	if(override_level_cfg.empty() != true) {
		level_cfg = override_level_cfg;
		orig_level_cfg = level_cfg;
	}

#if TARGET_OS_IPHONE || TARGET_IPHONE_SIMULATOR
	int width, height;
	iphone_screen_res(&width, &height);
	preferences::set_actual_screen_width(width);
	preferences::set_actual_screen_height(height);
	int multiplier = 2;
	if (width > 320)
	{
		//preferences::set_use_pretty_scaling(true);
		multiplier = 1;
	}
	preferences::set_virtual_screen_width(height*multiplier);
	preferences::set_virtual_screen_height(width*multiplier);
	preferences::set_control_scheme(height % 1024 ? "iphone_2d" : "ipad_2d");
	
	SDL_WindowID windowID = SDL_CreateWindow (NULL, 0, 0, preferences::actual_screen_width(), preferences::actual_screen_height(),
		SDL_WINDOW_OPENGL | SDL_WINDOW_SHOWN |
		SDL_WINDOW_BORDERLESS);
	if (windowID == 0) { 
		std::cerr << "Could not create window: " << SDL_GetError() << "\n"; 
		return -1;
	}
	
	//	if (SDL_GL_CreateContext(windowID) == 0) {
	//		std::cerr << "Could not create GL context: " << SDL_GetError() << "\n";
	//		return -1;
	//	}
	if (SDL_CreateRenderer(windowID, -1, 0) != 0) {
		std::cerr << "Could not create renderer\n";
		return -1;
	}
	
#else
#ifdef TARGET_OS_HARMATTAN
	SDL_GL_SetAttribute(SDL_GL_CONTEXT_MAJOR_VERSION, 1);
	if (SDL_SetVideoMode(preferences::actual_screen_width(),preferences::actual_screen_height(),0,SDL_OPENGLES | SDL_FULLSCREEN) == NULL) {
		std::cerr << "could not set video mode\n";
		return -1;
	}

	preferences::init_oes();
	SDL_ShowCursor(0);
#else
#ifndef __APPLE__
	graphics::surface wm_icon = graphics::surface_cache::get("window-icon.png");
	if(!wm_icon.null()) {
		SDL_WM_SetIcon(wm_icon, NULL);
	}
#endif

#if defined(TARGET_PANDORA)
	if (SDL_SetVideoMode(preferences::actual_screen_width(),preferences::actual_screen_height(),16,SDL_FULLSCREEN) == NULL) {
		std::cerr << "could not set video mode\n";
		return -1;
	}
    EGL_Init();
    preferences::init_oes();
#elif defined(TARGET_TEGRA)
	//if (SDL_SetVideoMode(preferences::actual_screen_width(),preferences::actual_screen_height(),0,preferences::resizable() ? SDL_RESIZABLE : 0|preferences::fullscreen() ? SDL_FULLSCREEN : 0) == NULL) {
	if (SDL_SetVideoMode(preferences::actual_screen_width(),preferences::actual_screen_height(),0,SDL_FULLSCREEN) == NULL) {
		std::cerr << "could not set video mode\n";
		return -1;
	}
    EGL_Init();
    preferences::init_oes();
#elif defined(TARGET_BLACKBERRY)
	if (SDL_SetVideoMode(preferences::actual_screen_width(),preferences::actual_screen_height(),0,SDL_OPENGL|SDL_FULLSCREEN) == NULL) {
		std::cerr << "could not set video mode\n";
		return -1;
	}
	preferences::init_oes();
#elif defined(__ANDROID__)
    SDL_Rect** r = SDL_ListModes(NULL, SDL_FULLSCREEN|SDL_OPENGL);
    if( r != (SDL_Rect**)0 && r != (SDL_Rect**)-1 ) {
        preferences::set_actual_screen_width(r[0]->w);
        preferences::set_actual_screen_height(r[0]->h);
		if(r[0]->w < 640) {
        	preferences::set_virtual_screen_width(r[0]->w*2);
        	preferences::set_virtual_screen_height(r[0]->h*2);
		} else {
			preferences::set_virtual_screen_width(r[0]->w);
			preferences::set_virtual_screen_height(r[0]->h);
		}
		preferences::set_control_scheme(r[0]->h >= 1024 ? "ipad_2d" : "android_med");
    }

    if (SDL_SetVideoMode(preferences::actual_screen_width(),preferences::actual_screen_height(),16,SDL_FULLSCREEN|SDL_OPENGL) == NULL) {
		std::cerr << "could not set video mode\n";
		return -1;
    }
#else
	if (SDL_SetVideoMode(preferences::actual_screen_width(),preferences::actual_screen_height(),0,SDL_OPENGL|(preferences::resizable() ? SDL_RESIZABLE : 0)|(preferences::fullscreen() ? SDL_FULLSCREEN : 0)) == NULL) {
		std::cerr << "could not set video mode\n";
		return -1;
	}
#endif
#endif

#endif

//	srand(time(NULL));

	const stats::manager stats_manager;
#ifndef NO_EDITOR
	const external_text_editor::manager editor_manager;
#endif // NO_EDITOR

	std::cerr
		<< "\n"
		<< "OpenGL vendor: " << reinterpret_cast<const char *>(glGetString(GL_VENDOR)) << "\n"
		<< "OpenGL version: " << reinterpret_cast<const char *>(glGetString(GL_VERSION)) << "\n"
		<< "OpenGL extensions: " << reinterpret_cast<const char *>(glGetString(GL_EXTENSIONS)) << "\n"
		<< "\n";
	glShadeModel(GL_SMOOTH);
	glEnable(GL_BLEND);
	glEnable(GL_TEXTURE_2D);
	glEnableClientState(GL_VERTEX_ARRAY);
	glEnableClientState(GL_TEXTURE_COORD_ARRAY);
	
	glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA);

	SDL_WM_SetCaption(module::get_module_pretty_name().c_str(), module::get_module_pretty_name().c_str());

	std::cerr << "JOYSTICKS: " << SDL_NumJoysticks() << "\n";

	const load_level_manager load_manager;

	{ //manager scope
	const font::manager font_manager;
	const sound::manager sound_manager;
	const joystick::manager joystick_manager;
		
	#if !TARGET_OS_IPHONE && !TARGET_IPHONE_SIMULATOR
	const SDL_Surface* fb = SDL_GetVideoSurface();
	if(fb == NULL) {
		return 0;
	}
	#endif

	graphics::texture::manager texture_manager;

#ifndef NO_EDITOR
	editor::manager editor_manager;
#endif

	variant preloads;
	loading_screen loader;
	try {
		sound::init_music(json::parse_from_file(module::map_file("data/music.cfg")));

		std::string filename = "data/fonts." + i18n::get_locale() + ".cfg";
		if (!sys::file_exists(filename))
			filename = "data/fonts.cfg";
		graphical_font::init(json::parse_from_file(module::map_file(filename)));

		preloads = json::parse_from_file(module::map_file("data/preload.cfg"));
		int preload_items = preloads["preload"].num_elements();
		loader.set_number_of_items(preload_items+7); // 7 is the number of items that will be loaded below
		custom_object::init();
		loader.draw_and_increment(_("Initializing custom object functions"));
		init_custom_object_functions(json::parse_from_file(module::map_file("data/functions.cfg")));
		loader.draw_and_increment(_("Initializing textures"));
		loader.load(preloads);
		loader.draw_and_increment(_("Initializing tiles"));
		tile_map::init(json::parse_from_file(module::map_file("data/tiles.cfg")));
		loader.draw_and_increment(_("Initializing GUI"));

		variant gui_node = json::parse_from_file(module::map_file(preferences::load_compiled() ? "data/compiled/gui.cfg" : "data/gui.cfg"));
		gui_section::init(gui_node);
		loader.draw_and_increment(_("Initializing GUI"));
		framed_gui_element::init(gui_node);

	} catch(const json::parse_error& e) {
		std::cerr << "ERROR PARSING: " << e.error_message() << "\n";
		return 0;
	}
	loader.draw(_("Loading level"));

	if(!skip_tests && !test::run_tests()) {
		return -1;
	}

	if(unit_tests_only) {
		return 0;
	}
#if defined(__APPLE__) && !(TARGET_IPHONE_SIMULATOR || TARGET_OS_IPHONE)
	GLint swapInterval = 1;
	CGLSetParameter(CGLGetCurrentContext(), kCGLCPSwapInterval, &swapInterval);
#endif

#ifndef SDL_VIDEO_OPENGL_ES
	GLenum glew_status = glewInit();
	ASSERT_EQ(glew_status, GLEW_OK);
#endif

	loader.finish_loading();
	//look to see if we got any quit events while loading.
	{
	SDL_Event event;
	while(SDL_PollEvent(&event)) {
		if(event.type == SDL_QUIT) {
			return 0;
		}
	}
	}

	formula_profiler::manager profiler(profile_output);
	texture_frame_buffer::init();

	if(run_benchmarks) {
		if(benchmarks_list.empty() == false) {
			test::run_benchmarks(&benchmarks_list);
		} else {
			test::run_benchmarks();
		}
		return 0;
	} else if(utility_program.empty() == false) {
		test::run_utility(utility_program, util_args);
		return 0;
	}

	bool quit = false;
	bool of_initialized = false;

	while(!quit && !show_title_screen(level_cfg)) {
		boost::intrusive_ptr<level> lvl(load_level(level_cfg));
		
#if TARGET_OS_IPHONE || TARGET_IPHONE_SIMULATOR
		if (!of_initialized)
		{
			of_init();
			of_initialized = true;
		}
#endif

		//see if we're loading a multiplayer level, in which case we
		//connect to the server.
		multiplayer::manager mp_manager(lvl->is_multiplayer());
		if(lvl->is_multiplayer()) {
			multiplayer::setup_networked_game(server);
		}

		if(lvl->is_multiplayer()) {
			last_draw_position() = screen_position();
			std::string level_cfg = "waiting-room.cfg";
			boost::intrusive_ptr<level> wait_lvl(load_level(level_cfg));
			wait_lvl->finish_loading();
			wait_lvl->set_multiplayer_slot(0);
			if(wait_lvl->player()) {
				wait_lvl->player()->set_current_level(level_cfg);
			}
			wait_lvl->set_as_current_level();

			level_runner runner(wait_lvl, level_cfg, orig_level_cfg);

			multiplayer::sync_start_time(*lvl, boost::bind(&level_runner::play_cycle, &runner));

			lvl->set_multiplayer_slot(multiplayer::slot());
		}

		last_draw_position() = screen_position();

		assert(lvl.get());
		if(!lvl->music().empty()) {
			sound::play_music(lvl->music());
		}

		if(lvl->player() && level_cfg != "autosave.cfg") {
			lvl->player()->set_current_level(level_cfg);
			lvl->player()->get_entity().save_game();
		}

		set_scene_title(lvl->title());

		try {
			quit = level_runner(lvl, level_cfg, orig_level_cfg).play_level();
			level_cfg = orig_level_cfg;
		} catch(multiplayer_exception&) {
		}
	}

	level::clear_current_level();

	} //end manager scope, make managers destruct before calling SDL_Quit
//	controls::debug_dump_controls();
#if defined(TARGET_PANDORA) || defined(TARGET_TEGRA)
    EGL_Destroy();
#endif

	SDL_Quit();
	
	preferences::save_preferences();
	std::cerr << SDL_GetError() << "\n";
#if !defined(TARGET_OS_HARMATTAN) && !defined(TARGET_TEGRA) && !defined(TARGET_BLACKBERRY) && !defined(__ANDROID__)
	std::cerr << gluErrorString(glGetError()) << "\n";
#endif
	return 0;
}
Exemplo n.º 10
0
Arquivo: ocl.c Projeto: amilliet/GPU
void ocl_init(sotl_device_t *dev)
{
  cl_int err = 0;

  // Create context
  //
#ifdef HAVE_LIBGL
  if(dev->display) {
#ifdef __APPLE__
    CGLContextObj cgl_context = CGLGetCurrentContext ();
    CGLShareGroupObj sharegroup = CGLGetShareGroup (cgl_context);
    cl_context_properties properties[] = {
      CL_CONTEXT_PROPERTY_USE_CGL_SHAREGROUP_APPLE,
      (cl_context_properties) sharegroup,
      0
    };

#else
    cl_context_properties properties[] = {
      CL_GL_CONTEXT_KHR,
      (cl_context_properties) glXGetCurrentContext (),
      CL_GLX_DISPLAY_KHR,
      (cl_context_properties) glXGetCurrentDisplay (),
      CL_CONTEXT_PLATFORM, (cl_context_properties) dev->platform->id,
      0
    };
#endif

    dev->context = clCreateContext (properties, 1, &dev->id, NULL, NULL, &err);
  } else
#endif
    {
      dev->context = clCreateContext (0, 1, &dev->id, NULL, NULL, &err);
    }
    check (err, "Failed to create compute context \n");

    // Load program source
    // 
    const char *opencl_prog;
    opencl_prog = file_get_contents(PROGRAM_NAME);
    if (!opencl_prog) {
        sotl_log(CRITICAL, "Failed to read contents of the OpenCL program '%s'.\n", PROGRAM_NAME);
    }

    // Build program
    // 
    dev->program = clCreateProgramWithSource (dev->context, 1, &opencl_prog, NULL, &err);
    check (err, "Failed to create program");

    char options[OPENCL_PROG_MAX_STRING_SIZE_OPTIONS];

    // Tile size of 32 works better on Xeon/Xeon Phi
    //
    if(dev->type != CL_DEVICE_TYPE_GPU)
      dev->tile_size = 32;
    else
      dev->tile_size = TILE_SIZE;

#ifdef SLIDE
      dev->slide_steps = SLIDE;
#else
      dev->slide_steps = 1;
#endif

    sprintf (options,
	     OPENCL_BUILD_OPTIONS
	     "-DTILE_SIZE=%d "
	     "-DSUBCELL=%d "
             "-DDELTA_T=%.10f "
#ifdef SLIDE
	     "-DSLIDE=%d "
#endif
	     OPENCL_PROG_STRING_OPTIONS " -I "OCL_INCLUDE " " 
	     LENNARD_STRING,
	     dev->tile_size,
	     SUBCELL,
             1.0f,
#ifdef SLIDE
	     dev->slide_steps,
#endif
	     OPENCL_PROG_PARAM_OPTIONS,
	     LENNARD_PARAM);

    // If not a GPU, do not use Tiling
    //
    if (dev->type != CL_DEVICE_TYPE_GPU)
      strcat (options, " -DNO_LOCAL_MEM");

#ifdef TILE_CACHE
    // On GPU, use a cache of TILES
    //
    if (dev->type == CL_DEVICE_TYPE_GPU)
      strcat (options, " -DTILE_CACHE");
#endif

    // Multi-accelerators configuration
    //
    if (sotl_have_multi())
      strcat (options, " -DHAVE_MULTI");

#ifdef FORCE_N_UPDATE
    if (!sotl_have_multi())
      strcat (options, " -DFORCE_N_UPDATE");
#endif

#ifdef TORUS
    strcat (options, " -DXY_TORUS -DZ_TORUS");
#endif

#ifdef XEON_VECTORIZATION
    strcat (options, " -DXEON_VECTORIZATION");
#endif

#if defined(__APPLE__)
    strcat(options, " -DHAVE_PRINTF");
#endif

    if (sotl_verbose)
      sotl_log(INFO, "--- Compiler flags ---\n%s\n----------------------\n",
               options);

    err = clBuildProgram (dev->program, 0, NULL, options, NULL, NULL);
    if(sotl_verbose || err != CL_SUCCESS) {
      size_t len;

      // Display compiler error log
      // 
      clGetProgramBuildInfo (dev->program, dev->id,
			     CL_PROGRAM_BUILD_LOG, 0, NULL, &len);
        {
	  char buffer[len + 1];

	  clGetProgramBuildInfo (dev->program, dev->id,
				 CL_PROGRAM_BUILD_LOG,
				 sizeof (buffer), buffer, NULL);
	  sotl_log(INFO, "---- Compiler log ----\n%s\n----------------------\n",
		   buffer);
        }
        check (err, "Failed to build program");
    }

    // Create an OpenCL command queue
    //
    dev->queue = clCreateCommandQueue (dev->context, dev->id,
                CL_QUEUE_PROFILING_ENABLE, &err);
    check (err, "Failed to create a command queue");

    cl_create_kernels(dev);
}
Exemplo n.º 11
0
static cl::Context PlatformContext(cl_device_type device_type, char* platform_vendor_name, bool enable_gl_interop = false)
    {
        cl_uint numPlatforms;
        cl_platform_id platform = NULL;
        clGetPlatformIDs(0, NULL, &numPlatforms);
        if (numPlatforms > 0)
        {
            cl_platform_id* platforms = new cl_platform_id[numPlatforms];
            clGetPlatformIDs(numPlatforms, platforms, NULL);
            for (unsigned i = 0; i < numPlatforms; ++i)
            {
                char pbuf[100];
                clGetPlatformInfo(platforms[i],
                                   CL_PLATFORM_VENDOR,
                                   sizeof(pbuf),
                                   pbuf,
                                   NULL);

                platform = platforms[i];
                std::cout << "platform: " << pbuf << std::endl;
                if (!strcmp(pbuf, platform_vendor_name))
                {
                    break;
                }
            }
            delete[] platforms;
        }

        if (enable_gl_interop)
        {
        // Define OS-specific context properties and create the OpenCL context
        #if defined (__APPLE__)
            CGLContextObj kCGLContext = CGLGetCurrentContext();
            CGLShareGroupObj kCGLShareGroup = CGLGetShareGroup(kCGLContext);
            cl_context_properties cps[] =
            {
                CL_CONTEXT_PROPERTY_USE_CGL_SHAREGROUP_APPLE, (cl_context_properties)kCGLShareGroup,
                0
            };
        #else
            #if defined(linux)
                cl_context_properties cps[] =
                {
                    CL_GL_CONTEXT_KHR, cl_context_properties(glXGetCurrentContext()),
                    CL_GLX_DISPLAY_KHR, cl_context_properties(glXGetCurrentDisplay()),
                    CL_CONTEXT_PLATFORM, cl_context_properties(platform),
                    0
                };
            #else // Win32
                cl_context_properties cps[] =
                {
                    CL_GL_CONTEXT_KHR, (cl_context_properties)wglGetCurrentContext(),
                    CL_WGL_HDC_KHR, (cl_context_properties)wglGetCurrentDC(),
                    CL_CONTEXT_PLATFORM, (cl_context_properties)platform,
                    0
                };
            #endif
        #endif

        cl::Platform _platform(platform);
        cl::vector<cl::Device> *_devices = new cl::vector<cl::Device>();
        _platform.getDevices(CL_DEVICE_TYPE_GPU, _devices);

        if(_devices->size() > 1)
            _devices->pop_back();
        if (platform == NULL)
            return cl::Context(device_type, NULL);
        else
            return cl::Context(*_devices,cps);

        return (NULL == platform) ? cl::Context(device_type, NULL) :  cl::Context(*_devices, cps);

        }else //no opengl interoperability
        {
            cl_context_properties cps[] =
            {
                CL_CONTEXT_PLATFORM, cl_context_properties(platform),
                0
            };
            return (NULL == platform) ? cl::Context(device_type, NULL) : cl::Context(device_type, cps);
        }
    }
Exemplo n.º 12
0
CL::CL()
{
    printf("Initialize OpenCL object and context\n");
    //setup devices and context
    std::vector<cl::Platform> platforms;
    err = cl::Platform::get(&platforms);
    printf("cl::Platform::get(): %s\n", oclErrorString(err));
    printf("platforms.size(): %d\n", platforms.size());

    deviceUsed = 0;
    err = platforms[0].getDevices(CL_DEVICE_TYPE_GPU, &devices);
    printf("getDevices: %s\n", oclErrorString(err));
    printf("devices.size(): %d\n", devices.size());
    int t = devices.front().getInfo<CL_DEVICE_TYPE>();
    printf("type: device: %d CL_DEVICE_TYPE_GPU: %d \n", t, CL_DEVICE_TYPE_GPU);

    // Define OS-specific context properties and create the OpenCL context
    // We setup OpenGL context sharing slightly differently on each OS
    // this code comes mostly from NVIDIA's SDK examples
    // we could also check to see if the device supports GL sharing
    // but that is just searching through the properties
    // an example is avaible in the NVIDIA code
    #if defined (__APPLE__) || defined(MACOSX)
        CGLContextObj kCGLContext = CGLGetCurrentContext();
        CGLShareGroupObj kCGLShareGroup = CGLGetShareGroup(kCGLContext);
        cl_context_properties props[] =
        {
            CL_CONTEXT_PROPERTY_USE_CGL_SHAREGROUP_APPLE, (cl_context_properties)kCGLShareGroup,
            0
        };
        //Apple's implementation is weird, and the default values assumed by cl.hpp don't work
        //this works
        //cl_context cxGPUContext = clCreateContext(props, 0, 0, NULL, NULL, &err);
        //these dont
        //cl_context cxGPUContext = clCreateContext(props, 1,(cl_device_id*)&devices.front(), NULL, NULL, &err);
        //cl_context cxGPUContext = clCreateContextFromType(props, CL_DEVICE_TYPE_GPU, NULL, NULL, &err);
        //printf("error? %s\n", oclErrorString(err));
        try{
            context = cl::Context(props);   //had to edit line 1448 of cl.hpp to add this constructor
        }
        catch (cl::Error er) {
            printf("ERROR: %s(%s)\n", er.what(), oclErrorString(er.err()));
        }
    #else
        #if defined WIN32 // Win32
            cl_context_properties props[] =
            {
                CL_GL_CONTEXT_KHR, (cl_context_properties)wglGetCurrentContext(),
                CL_WGL_HDC_KHR, (cl_context_properties)wglGetCurrentDC(),
                CL_CONTEXT_PLATFORM, (cl_context_properties)(platforms[0])(),
                0
            };
            //cl_context cxGPUContext = clCreateContext(props, 1, &cdDevices[uiDeviceUsed], NULL, NULL, &err);
            try{
                context = cl::Context(CL_DEVICE_TYPE_GPU, props);
            }
            catch (cl::Error er) {
                printf("ERROR: %s(%s)\n", er.what(), oclErrorString(er.err()));
            }
        #else
            cl_context_properties props[] =
            {
                CL_GL_CONTEXT_KHR, (cl_context_properties)glXGetCurrentContext(),
                CL_GLX_DISPLAY_KHR, (cl_context_properties)glXGetCurrentDisplay(),
                CL_CONTEXT_PLATFORM, (cl_context_properties)(platforms[0])(),
                0
            };
            //cl_context cxGPUContext = clCreateContext(props, 1, &cdDevices[uiDeviceUsed], NULL, NULL, &err);
            try{
                context = cl::Context(CL_DEVICE_TYPE_GPU, props);
            }
            catch (cl::Error er) {
                printf("ERROR: %s(%s)\n", er.what(), oclErrorString(er.err()));
            }
        #endif
    #endif

    //create the command queue we will use to execute OpenCL commands
    try{
        queue = cl::CommandQueue(context, devices[deviceUsed], 0, &err);
    }
    catch (cl::Error er) {
        printf("ERROR: %s(%d)\n", er.what(), er.err());
    }

}
Exemplo n.º 13
0
static int create(struct gl_hwdec *hw)
{
    if (!check_hwdec(hw))
        return -1;

    struct priv *p = talloc_zero(hw, struct priv);
    hw->priv = p;

    hw->gl->GenTextures(MP_MAX_PLANES, p->gl_planes);

    p->hwctx = (struct mp_hwdec_ctx){
        .type = HWDEC_VIDEOTOOLBOX,
        .download_image = mp_vt_download_image,
        .ctx = &p->hwctx,
    };
    hwdec_devices_add(hw->devs, &p->hwctx);

    return 0;
}

static int reinit(struct gl_hwdec *hw, struct mp_image_params *params)
{
    struct priv *p = hw->priv;

    assert(params->imgfmt == hw->driver->imgfmt);

    if (!params->hw_subfmt) {
        MP_ERR(hw, "Unsupported CVPixelBuffer format.\n");
        return -1;
    }

    if (!gl_get_imgfmt_desc(hw->gl, params->hw_subfmt, &p->desc)) {
        MP_ERR(hw, "Unsupported texture format.\n");
        return -1;
    }

    params->imgfmt = params->hw_subfmt;
    params->hw_subfmt = 0;
    return 0;
}

static int map_frame(struct gl_hwdec *hw, struct mp_image *hw_image,
                     struct gl_hwdec_frame *out_frame)
{
    struct priv *p = hw->priv;
    GL *gl = hw->gl;

    CVPixelBufferRelease(p->pbuf);
    p->pbuf = (CVPixelBufferRef)hw_image->planes[3];
    CVPixelBufferRetain(p->pbuf);
    IOSurfaceRef surface = CVPixelBufferGetIOSurface(p->pbuf);
    if (!surface) {
        MP_ERR(hw, "CVPixelBuffer has no IOSurface\n");
        return -1;
    }

    const bool planar = CVPixelBufferIsPlanar(p->pbuf);
    const int planes  = CVPixelBufferGetPlaneCount(p->pbuf);
    assert((planar && planes == p->desc.num_planes) || p->desc.num_planes == 1);

    GLenum gl_target = GL_TEXTURE_RECTANGLE;

    for (int i = 0; i < p->desc.num_planes; i++) {
        const struct gl_format *fmt = p->desc.planes[i];

        gl->BindTexture(gl_target, p->gl_planes[i]);

        CGLError err = CGLTexImageIOSurface2D(
            CGLGetCurrentContext(), gl_target,
            fmt->internal_format,
            IOSurfaceGetWidthOfPlane(surface, i),
            IOSurfaceGetHeightOfPlane(surface, i),
            fmt->format, fmt->type, surface, i);

        if (err != kCGLNoError)
            MP_ERR(hw, "error creating IOSurface texture for plane %d: %s (%x)\n",
                   i, CGLErrorString(err), gl->GetError());

        gl->BindTexture(gl_target, 0);

        out_frame->planes[i] = (struct gl_hwdec_plane){
            .gl_texture = p->gl_planes[i],
            .gl_target = gl_target,
            .tex_w = IOSurfaceGetWidthOfPlane(surface, i),
            .tex_h = IOSurfaceGetHeightOfPlane(surface, i),
        };
    }

    snprintf(out_frame->swizzle, sizeof(out_frame->swizzle), "%s",
             p->desc.swizzle);

    return 0;
}

static void destroy(struct gl_hwdec *hw)
{
    struct priv *p = hw->priv;
    GL *gl = hw->gl;

    CVPixelBufferRelease(p->pbuf);
    gl->DeleteTextures(MP_MAX_PLANES, p->gl_planes);

    hwdec_devices_remove(hw->devs, &p->hwctx);
}

const struct gl_hwdec_driver gl_hwdec_videotoolbox = {
    .name = "videotoolbox",
    .api = HWDEC_VIDEOTOOLBOX,
    .imgfmt = IMGFMT_VIDEOTOOLBOX,
    .create = create,
    .reinit = reinit,
    .map_frame = map_frame,
    .destroy = destroy,
};
Exemplo n.º 14
0
OCLRendererThread::OCLRendererThread(const size_t threadIndex, OCLRenderer *renderer,
			cl::Device device) : index(threadIndex), renderer(renderer),
		dev(device), usedDeviceMemory(0) {
	const GameLevel &gameLevel(*(renderer->gameLevel));
	const unsigned int width = gameLevel.gameConfig->GetScreenWidth();
	const unsigned int height = gameLevel.gameConfig->GetScreenHeight();

	const CompiledScene &compiledScene(*(renderer->compiledScene));

	if (renderer->renderThread.size() > 1)
		cpuFrameBuffer = new FrameBuffer(width, height);
	else
		cpuFrameBuffer = NULL;

	//--------------------------------------------------------------------------
	// OpenCL setup
	//--------------------------------------------------------------------------

	// Allocate a context with the selected device

	VECTOR_CLASS<cl::Device> devices;
	devices.push_back(dev);
	cl::Platform platform = dev.getInfo<CL_DEVICE_PLATFORM>();

	// The first thread uses OpenCL/OpenGL interoperability
	if (index == 0) {
#if defined (__APPLE__)
		CGLContextObj kCGLContext = CGLGetCurrentContext();
		CGLShareGroupObj kCGLShareGroup = CGLGetShareGroup(kCGLContext);
		cl_context_properties cps[] = {
			CL_CONTEXT_PROPERTY_USE_CGL_SHAREGROUP_APPLE, (cl_context_properties)kCGLShareGroup,
			0
		};
#else
#ifdef WIN32
		cl_context_properties cps[] = {
			CL_GL_CONTEXT_KHR, (intptr_t)wglGetCurrentContext(),
			CL_WGL_HDC_KHR, (intptr_t)wglGetCurrentDC(),
			CL_CONTEXT_PLATFORM, (cl_context_properties)platform(),
			0
		};
#else
		cl_context_properties cps[] = {
			CL_GL_CONTEXT_KHR, (intptr_t)glXGetCurrentContext(),
			CL_GLX_DISPLAY_KHR, (intptr_t)glXGetCurrentDisplay(),
			CL_CONTEXT_PLATFORM, (cl_context_properties)platform(),
			0
		};
#endif
#endif

		ctx = new cl::Context(devices, cps);
	} else
		ctx = new cl::Context(devices);

	// Allocate the queue for this device
	cmdQueue = new cl::CommandQueue(*ctx, dev);

	//--------------------------------------------------------------------------
	// Allocate the buffers
	//--------------------------------------------------------------------------

	passFrameBuffer = NULL;
	tmpFrameBuffer = NULL;
	frameBuffer = NULL;
	toneMapFrameBuffer = NULL;
	bvhBuffer = NULL;
	gpuTaskBuffer = NULL;
	cameraBuffer = NULL;
	infiniteLightBuffer = NULL;
	matBuffer = NULL;
	matIndexBuffer = NULL;
	texMapBuffer = NULL;
	texMapRGBBuffer = NULL;
	texMapInstanceBuffer = NULL;
	bumpMapInstanceBuffer = NULL;

	AllocOCLBufferRW(&passFrameBuffer, sizeof(Pixel) * width * height, "Pass FrameBuffer");
	AllocOCLBufferRW(&tmpFrameBuffer, sizeof(Pixel) * width * height, "Temporary FrameBuffer");
	if (index == 0) {
		AllocOCLBufferRW(&frameBuffer, sizeof(Pixel) * width * height, "FrameBuffer");
		AllocOCLBufferRW(&toneMapFrameBuffer, sizeof(Pixel) * width * height, "ToneMap FrameBuffer");
	}
	AllocOCLBufferRW(&gpuTaskBuffer, sizeof(ocl_kernels::GPUTask) * width * height, "GPUTask");
	AllocOCLBufferRO(&cameraBuffer, sizeof(compiledscene::Camera), "Camera");
	AllocOCLBufferRO(&infiniteLightBuffer, (void *)(gameLevel.scene->infiniteLight->GetTexture()->GetTexMap()->GetPixels()),
			sizeof(Spectrum) * gameLevel.scene->infiniteLight->GetTexture()->GetTexMap()->GetWidth() *
			gameLevel.scene->infiniteLight->GetTexture()->GetTexMap()->GetHeight(), "Inifinite Light");

	AllocOCLBufferRO(&matBuffer, (void *)(&compiledScene.mats[0]),
			sizeof(compiledscene::Material) * compiledScene.mats.size(), "Materials");
	AllocOCLBufferRO(&matIndexBuffer, (void *)(&compiledScene.sphereMats[0]),
			sizeof(unsigned int) * compiledScene.sphereMats.size(), "Material Indices");

	if (compiledScene.texMaps.size() > 0) {
		AllocOCLBufferRO(&texMapBuffer, (void *)(&compiledScene.texMaps[0]),
				sizeof(compiledscene::TexMap) * compiledScene.texMaps.size(), "Texture Maps");

		AllocOCLBufferRO(&texMapRGBBuffer, (void *)(compiledScene.rgbTexMem),
				sizeof(Spectrum) * compiledScene.totRGBTexMem, "Texture Map Images");

		AllocOCLBufferRO(&texMapInstanceBuffer, (void *)(&compiledScene.sphereTexs[0]),
				sizeof(compiledscene::TexMapInstance) * compiledScene.sphereTexs.size(), "Texture Map Instances");

		if (compiledScene.sphereBumps.size() > 0)
			AllocOCLBufferRO(&bumpMapInstanceBuffer, (void *)(&compiledScene.sphereBumps[0]),
					sizeof(compiledscene::BumpMapInstance) * compiledScene.sphereBumps.size(), "Bump Map Instances");
	}

	SFERA_LOG("[OCLRenderer] Total OpenCL device memory used: " << fixed << setprecision(2) << usedDeviceMemory / (1024 * 1024) << "Mbytes");

	if (index == 0) {
		//--------------------------------------------------------------------------
		// Create pixel buffer object for display
		//--------------------------------------------------------------------------

		glGenBuffersARB(1, &pbo);
		glBindBufferARB(GL_PIXEL_UNPACK_BUFFER_ARB, pbo);
		glBufferDataARB(GL_PIXEL_UNPACK_BUFFER_ARB, width * height *
				sizeof(GLubyte) * 4, 0, GL_STREAM_DRAW_ARB);
		glBindBufferARB(GL_PIXEL_UNPACK_BUFFER_ARB, 0);
		pboBuff = new cl::BufferGL(*ctx, CL_MEM_READ_WRITE, pbo);
	}

	//--------------------------------------------------------------------------
	// Compile the kernel source
	//--------------------------------------------------------------------------

	// Set #define symbols
	stringstream ss;
	ss.precision(6);
	ss << scientific <<
			" -D PARAM_SCREEN_WIDTH=" << width <<
			" -D PARAM_SCREEN_HEIGHT=" << height <<
			" -D PARAM_SCREEN_SAMPLEPERPASS="******" -D PARAM_RAY_EPSILON=" << EPSILON << "f" <<
			" -D PARAM_MAX_DIFFUSE_BOUNCE=" << gameLevel.maxPathDiffuseBounces <<
			" -D PARAM_MAX_SPECULARGLOSSY_BOUNCE=" << gameLevel.maxPathSpecularGlossyBounces <<
			" -D PARAM_IL_SHIFT_U=" << gameLevel.scene->infiniteLight->GetShiftU() << "f" <<
			" -D PARAM_IL_SHIFT_V=" << gameLevel.scene->infiniteLight->GetShiftV() << "f" <<
			" -D PARAM_IL_GAIN_R=" << gameLevel.scene->infiniteLight->GetGain().r << "f" <<
			" -D PARAM_IL_GAIN_G=" << gameLevel.scene->infiniteLight->GetGain().g << "f" <<
			" -D PARAM_IL_GAIN_B=" << gameLevel.scene->infiniteLight->GetGain().b << "f" <<
			" -D PARAM_IL_MAP_WIDTH=" << gameLevel.scene->infiniteLight->GetTexture()->GetTexMap()->GetWidth() <<
			" -D PARAM_IL_MAP_HEIGHT=" << gameLevel.scene->infiniteLight->GetTexture()->GetTexMap()->GetHeight() <<
			" -D PARAM_GAMMA=" << gameLevel.toneMap->GetGamma() << "f" <<
			" -D PARAM_MEM_TYPE=" << gameLevel.gameConfig->GetOpenCLMemType();

	if (compiledScene.enable_MAT_MATTE)
		ss << " -D PARAM_ENABLE_MAT_MATTE";
	if (compiledScene.enable_MAT_MIRROR)
		ss << " -D PARAM_ENABLE_MAT_MIRROR";
	if (compiledScene.enable_MAT_GLASS)
		ss << " -D PARAM_ENABLE_MAT_GLASS";
	if (compiledScene.enable_MAT_METAL)
		ss << " -D PARAM_ENABLE_MAT_METAL";
	if (compiledScene.enable_MAT_ALLOY)
		ss << " -D PARAM_ENABLE_MAT_ALLOY";

	if (texMapBuffer) {
		ss << " -D PARAM_HAS_TEXTUREMAPS";

		if (compiledScene.sphereBumps.size() > 0)
			ss << " -D PARAM_HAS_BUMPMAPS";
	}

	switch (gameLevel.toneMap->GetType()) {
		case TONEMAP_REINHARD02:
			ss << " -D PARAM_TM_LINEAR_SCALE=1.0f";
			break;
		case TONEMAP_LINEAR: {
			LinearToneMap *tm = (LinearToneMap *)gameLevel.toneMap;
			ss << " -D PARAM_TM_LINEAR_SCALE=" << tm->scale << "f";
			break;
		}
		default:
			assert (false);

	}

#if defined(__APPLE__)
	ss << " -D __APPLE__";
#endif

	SFERA_LOG("[OCLRenderer] Defined symbols: " << ss.str());
	SFERA_LOG("[OCLRenderer] Compiling kernels");

	cl::Program::Sources source(1, std::make_pair(KernelSource_kernel_core.c_str(), KernelSource_kernel_core.length()));
	cl::Program program = cl::Program(*ctx, source);
	try {
		VECTOR_CLASS<cl::Device> buildDevice;
		buildDevice.push_back(dev);
		program.build(buildDevice, ss.str().c_str());
	} catch (cl::Error err) {
		cl::STRING_CLASS strError = program.getBuildInfo<CL_PROGRAM_BUILD_LOG>(dev);
		SFERA_LOG("[OCLRenderer] Kernel compilation error:\n" << strError.c_str());

		throw err;
	}

	kernelInit = new cl::Kernel(program, "Init");
	kernelInit->setArg(0, *gpuTaskBuffer);
	cmdQueue->enqueueNDRangeKernel(*kernelInit, cl::NullRange,
			cl::NDRange(RoundUp<unsigned int>(width * height, WORKGROUP_SIZE)),
			cl::NDRange(WORKGROUP_SIZE));

	kernelInitFrameBuffer = new cl::Kernel(program, "InitFB");
	if (index == 0) {
		kernelInitFrameBuffer->setArg(0, *frameBuffer);
		cmdQueue->enqueueNDRangeKernel(*kernelInitFrameBuffer, cl::NullRange,
			cl::NDRange(RoundUp<unsigned int>(width * height, WORKGROUP_SIZE)),
			cl::NDRange(WORKGROUP_SIZE));
	}
	kernelInitFrameBuffer->setArg(0, *passFrameBuffer);

	kernelPathTracing = new cl::Kernel(program, "PathTracing");
	unsigned int argIndex = 0;
	kernelPathTracing->setArg(argIndex++, *gpuTaskBuffer);
	argIndex++;
	kernelPathTracing->setArg(argIndex++, *cameraBuffer);
	kernelPathTracing->setArg(argIndex++, *infiniteLightBuffer);
	kernelPathTracing->setArg(argIndex++, *passFrameBuffer);
	kernelPathTracing->setArg(argIndex++, *matBuffer);
	kernelPathTracing->setArg(argIndex++, *matIndexBuffer);
	if (texMapBuffer) {
		kernelPathTracing->setArg(argIndex++, *texMapBuffer);
		kernelPathTracing->setArg(argIndex++, *texMapRGBBuffer);
		kernelPathTracing->setArg(argIndex++, *texMapInstanceBuffer);
		if (compiledScene.sphereBumps.size() > 0)
			kernelPathTracing->setArg(argIndex++, *bumpMapInstanceBuffer);
	}

	kernelApplyBlurLightFilterXR1 = new cl::Kernel(program, "ApplyBlurLightFilterXR1");
	kernelApplyBlurLightFilterXR1->setArg(0, *passFrameBuffer);
	kernelApplyBlurLightFilterXR1->setArg(1, *tmpFrameBuffer);

	kernelApplyBlurLightFilterYR1 = new cl::Kernel(program, "ApplyBlurLightFilterYR1");
	kernelApplyBlurLightFilterYR1->setArg(0, *tmpFrameBuffer);
	kernelApplyBlurLightFilterYR1->setArg(1, *passFrameBuffer);

	kernelApplyBlurHeavyFilterXR1 = new cl::Kernel(program, "ApplyBlurHeavyFilterXR1");
	kernelApplyBlurHeavyFilterXR1->setArg(0, *passFrameBuffer);
	kernelApplyBlurHeavyFilterXR1->setArg(1, *tmpFrameBuffer);

	kernelApplyBlurHeavyFilterYR1 = new cl::Kernel(program, "ApplyBlurHeavyFilterYR1");
	kernelApplyBlurHeavyFilterYR1->setArg(0, *tmpFrameBuffer);
	kernelApplyBlurHeavyFilterYR1->setArg(1, *passFrameBuffer);

	kernelApplyBoxFilterXR1 = new cl::Kernel(program, "ApplyBoxFilterXR1");
	kernelApplyBoxFilterXR1->setArg(0, *passFrameBuffer);
	kernelApplyBoxFilterXR1->setArg(1, *tmpFrameBuffer);

	kernelApplyBoxFilterYR1 = new cl::Kernel(program, "ApplyBoxFilterYR1");
	kernelApplyBoxFilterYR1->setArg(0, *tmpFrameBuffer);
	kernelApplyBoxFilterYR1->setArg(1, *passFrameBuffer);

	if (index == 0) {
		kernelBlendFrame = new cl::Kernel(program, "BlendFrame");
		kernelBlendFrame->setArg(0, *passFrameBuffer);
		kernelBlendFrame->setArg(1, *frameBuffer);

		kernelToneMapLinear = new cl::Kernel(program, "ToneMapLinear");
		kernelToneMapLinear->setArg(0, *frameBuffer);
		kernelToneMapLinear->setArg(1, *toneMapFrameBuffer);

		kernelUpdatePixelBuffer = new cl::Kernel(program, "UpdatePixelBuffer");
		kernelUpdatePixelBuffer->setArg(0, *toneMapFrameBuffer);
		kernelUpdatePixelBuffer->setArg(1, *pboBuff);
	} else {
		kernelBlendFrame = NULL;
		kernelToneMapLinear = NULL;
		kernelUpdatePixelBuffer = NULL;
	}
}
Exemplo n.º 15
0
bool nglContext::Build(WindowRef Win, const nglContextInfo& rInfo, const nglContext* pShared, bool Fullscreen)
{
  mTargetAPI = rInfo.TargetAPI;
  if (mTargetAPI != eTargetAPI_OpenGL || mTargetAPI != eTargetAPI_OpenGL2)
    return false;
  
#ifndef __NOGLCONTEXT__
  mFullscreen = Fullscreen;

  std::vector<GLint> attribs;
  attribs.push_back(AGL_RGBA);
  if (rInfo.FrameCnt != 1)
    attribs.push_back(AGL_DOUBLEBUFFER);
  
  attribs.push_back(AGL_DEPTH_SIZE);
  attribs.push_back(rInfo.DepthBits);
  
  attribs.push_back(AGL_STENCIL_SIZE);
  attribs.push_back(rInfo.StencilBits);

  if (rInfo.AuxCnt)
  {
    attribs.push_back(AGL_AUX_BUFFERS);
    attribs.push_back(rInfo.AuxCnt);
  }
  
  if (rInfo.AABufferCnt)
  {
    attribs.push_back(AGL_SAMPLE_BUFFERS_ARB);
    attribs.push_back(rInfo.AABufferCnt);
    attribs.push_back(AGL_SAMPLES_ARB);
    attribs.push_back(rInfo.AASampleCnt);
  }

  attribs.push_back(AGL_RED_SIZE);
  attribs.push_back(rInfo.FrameBitsR);
  attribs.push_back(AGL_GREEN_SIZE);
  attribs.push_back(rInfo.FrameBitsG);
  attribs.push_back(AGL_BLUE_SIZE);
  attribs.push_back(rInfo.FrameBitsB);
  attribs.push_back(AGL_ALPHA_SIZE);
  attribs.push_back(rInfo.FrameBitsA);
  attribs.push_back(AGL_PIXEL_SIZE);
  attribs.push_back(rInfo.FrameBitsR + rInfo.FrameBitsG + rInfo.FrameBitsB + rInfo.FrameBitsA);

  if (rInfo.AccumBitsR || rInfo.AccumBitsG || rInfo.AccumBitsB || rInfo.AccumBitsA)
  {
    attribs.push_back(AGL_ACCUM_RED_SIZE);
    attribs.push_back(rInfo.AccumBitsR);
    attribs.push_back(AGL_ACCUM_GREEN_SIZE);
    attribs.push_back(rInfo.AccumBitsG);
    attribs.push_back(AGL_ACCUM_BLUE_SIZE);
    attribs.push_back(rInfo.AccumBitsB);
    attribs.push_back(AGL_ACCUM_ALPHA_SIZE);
    attribs.push_back(rInfo.AccumBitsA);
  }

  
  if (rInfo.Stereo) 
    attribs.push_back(AGL_STEREO);
  
  attribs.push_back(AGL_MINIMUM_POLICY);
  attribs.push_back(AGL_NO_RECOVERY);
  
  if (rInfo.CopyOnSwap)
    attribs.push_back(AGL_BACKING_STORE);
  
  attribs.push_back(AGL_NONE);
     
  /* Choose pixel format */
  AGLPixelFormat Format = aglChoosePixelFormat(NULL, 0, &attribs[0]);
  
  //NGL_OUT("Pixel Format: 0x%x\n", Format);
  
  if (!Format)
  {
    if (rInfo.CopyOnSwap)
    {
      attribs[attribs.size() - 2] = AGL_NONE;
      Format = aglChoosePixelFormat(NULL, 0, &attribs[0]);
    } 

    if (!Format)
    {
      SetError(_T("context"), NGL_CONTEXT_ENOMATCH);
      return false;
    }
  }

  //DumpFormat(Format);
  
  /* Create an AGL context */
  mCtx = aglCreateContext(Format, pShared?pShared->mCtx:NULL);
  long err = aglGetError();

  GLint value;
  aglDescribePixelFormat(Format, AGL_DOUBLEBUFFER, &value);
  mContextInfo.FrameCnt = value ? 2 : 1;     ///< Number of frame buffers (two means double-buffering)

  aglDescribePixelFormat(Format, AGL_RED_SIZE, (GLint*)&mContextInfo.FrameBitsR);   ///< Bits per red component (frame buffer)
  aglDescribePixelFormat(Format, AGL_GREEN_SIZE, (GLint*)&mContextInfo.FrameBitsG);   ///< Bits per green component (frame buffer)
  aglDescribePixelFormat(Format, AGL_BLUE_SIZE, (GLint*)&mContextInfo.FrameBitsB);   ///< Bits per blue component (frame buffer)
  aglDescribePixelFormat(Format, AGL_ALPHA_SIZE, (GLint*)&mContextInfo.FrameBitsA);   ///< Bits per alpha component (frame buffer)
  aglDescribePixelFormat(Format, AGL_DEPTH_SIZE, (GLint*)&mContextInfo.DepthBits);    ///< Depth buffer resolution (ie. Z buffer, 0 means no Z buffer)
  aglDescribePixelFormat(Format, AGL_STENCIL_SIZE, (GLint*)&mContextInfo.StencilBits);  ///< Stencil buffer resolution (0 means no stencil)
  aglDescribePixelFormat(Format, AGL_ACCUM_RED_SIZE, (GLint*)&mContextInfo.AccumBitsR);   ///< Bits per red component (accumulator buffer)
  aglDescribePixelFormat(Format, AGL_ACCUM_GREEN_SIZE, (GLint*)&mContextInfo.AccumBitsG);   ///< Bits per green component (accumulator buffer)
  aglDescribePixelFormat(Format, AGL_ACCUM_BLUE_SIZE, (GLint*)&mContextInfo.AccumBitsB);   ///< Bits per blue component (accumulator buffer)
  aglDescribePixelFormat(Format, AGL_ACCUM_ALPHA_SIZE, (GLint*)&mContextInfo.AccumBitsA);   ///< Bits per alpha component (accumulator buffer)
  aglDescribePixelFormat(Format, AGL_AUX_BUFFERS, (GLint*)&mContextInfo.AuxCnt);       ///< Number of auxiliary buffers
  aglDescribePixelFormat(Format, AGL_SAMPLE_BUFFERS_ARB, (GLint*)&mContextInfo.AABufferCnt);  ///< Number of anti-aliasing buffers
  aglDescribePixelFormat(Format, AGL_SAMPLES_ARB, (GLint*)&mContextInfo.AASampleCnt);  ///< Anti-alisaing oversampling count
  aglDescribePixelFormat(Format, AGL_STEREO, &value);       ///< Stereoscopic display

  mContextInfo.Stereo = value != 0;
  mContextInfo.Offscreen = false;       ///< This context can render in memory instead of to a window. (false by default).
  mContextInfo.RenderToTexture = false; ///< This context must be able to be bound as a texture. (false by default)
  aglDescribePixelFormat(Format, AGL_BACKING_STORE, &value);  ///< This context must be able to use copy the back buffer to the front buffer instead of swaping them. (false by default) 
  mContextInfo.CopyOnSwap = value != 0;
  if (rInfo.CopyOnSwap && !mContextInfo.CopyOnSwap)
    mValidBackBufferRequestedNotGranted = true;
  
  aglDestroyPixelFormat(Format);
  if (!mCtx)
  {
    SetError(_T("context"), NGL_CONTEXT_EGLCTX);
    /*
    switch (err)
    {
    case AGL_BAD_MATCH:
      NGL_OUT("AGL Error: Bad Context Match (shared context incompatible with requested pixel format).\n");
      break;
    case AGL_BAD_CONTEXT:
      NGL_OUT("AGL Error: Bad Shared Context.\n");
      break;
    case AGL_BAD_PIXELFMT:
      NGL_OUT("AGL Error: Bad Pixel Format.\n");
      break;
    default:
      NGL_OUT("AGL Error: Unknown error\n");
      break;
    }
    */
    return false;
  }

  /* Attach the context to the window */
  if (!aglSetDrawable(mCtx, GetWindowPort (Win)))
  {
    SetError(_T("context"), NGL_CONTEXT_EBIND);
    return false;
  }

  {
    CGLError err = kCGLNoError;
    CGLContextObj ctx = CGLGetCurrentContext();
    
    // Enable the multi-threading
    //err =  CGLEnable( ctx, kCGLCEMPEngine);
    
    if (err != kCGLNoError )
    {
      // Multi-threaded execution is possibly not available
      // Insert your code to take appropriate action
    }
  }
  
  GLint vsync = rInfo.VerticalSync ? 1 : 0;
  aglSetInteger(mCtx, AGL_SWAP_INTERVAL, &vsync);
  
  InitPainter();
  MakeCurrent(Win);
#endif
  glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
  return true;
}
Exemplo n.º 16
0
int art_init(int width,
                int height,
                int fullScreen,
                int colorDepth,
                int resizable,
                int windowDecorations,
                int vsync)
{
    _art_sessionInit();

    if (SDL_Init(SDL_INIT_VIDEO) != 0)
    {
        return -1;
        //TODO: Set error SDL_GetError()
    }
 
    SDL_GL_SetAttribute(SDL_GL_DOUBLEBUFFER, 1);

    unsigned int flags = SDL_OPENGL;

    if (fullScreen)
    {
        flags |= SDL_FULLSCREEN; 
    }

    if (resizable)
    {
        flags |= SDL_RESIZABLE;
    }

    if (!windowDecorations)
    {
        flags |= SDL_NOFRAME;
    }

    if (SDL_SetVideoMode(width, height, colorDepth, flags) == NULL)
    {
        return -1;
        //TODO: Set error SDL_GetError()
    }

    artG_session.windowWidth = width;
    artG_session.windowHeight = height;

    Art_Layer* rootLayer = malloc(sizeof(Art_Layer));
    _art_initLayer(rootLayer);
    _art_setRoot(rootLayer, width, height);
    art_setClearLayerOnUpdate(rootLayer, artG_session.clearOnUpdate);

    artG_session.rootLayer = rootLayer;
    artG_session.currentLayer = NULL;

    art_drawToRoot();

    if (vsync)
    {
        // Activate vertical refresh synch on macs
        #if defined (__ARTIST_OS_OSX)
        GLint VBL = 1;
        CGLSetParameter(CGLGetCurrentContext(),  kCGLCPSwapInterval, &VBL);
        #endif
    }

    return 0;
}
Exemplo n.º 17
0
/*!
    Creates an OpenCL context that is compatible with the current
    QGLContext and \a platform.  Returns false if there is no OpenGL
    context current or the OpenCL context could not be created for
    some reason.

    This function will first try to create a QCLDevice::GPU device,
    and will then fall back to QCLDevice::Default if a GPU is not found.

    If \a platform is null, then the first platform that has a GPU
    will be used.  If there is no GPU, then the first platform with a
    default device will be used.

    \sa supportsObjectSharing()
*/
bool QCLContextGL::create(const QCLPlatform &platform)
{
    Q_D(QCLContextGL);

    // Bail out if the context already exists.
    if (isCreated())
        return true;

    // Bail out if we don't have an OpenGL context.
    if (!QGLContext::currentContext()) {
        qWarning() << "QCLContextGL::create: needs a current GL context";
        setLastError(CL_INVALID_CONTEXT);
        return false;
    }

    // Find the first gpu device.
    QList<QCLDevice> devices;
    cl_device_type deviceType = CL_DEVICE_TYPE_GPU;
    devices = QCLDevice::devices(QCLDevice::GPU, platform);
    if (devices.isEmpty()) {
        // Find the first default device.
        devices = QCLDevice::devices(QCLDevice::Default, platform);
        deviceType = CL_DEVICE_TYPE_DEFAULT;
    }
    if (devices.isEmpty()) {
        qWarning() << "QCLContextGL::create: no gpu devices found";
        setLastError(CL_DEVICE_NOT_FOUND);
        return false;
    }
    QCLDevice gpu = devices[0];
    QVarLengthArray<cl_device_id> devs;
    foreach (QCLDevice dev, devices)
        devs.append(dev.deviceId());

    // Add the platform identifier to the properties.
    QVarLengthArray<cl_context_properties> properties;
    properties.append(CL_CONTEXT_PLATFORM);
    properties.append(cl_context_properties(gpu.platform().platformId()));

    bool hasSharing = false;
#ifndef QT_NO_CL_OPENGL
    // Determine what kind of OpenCL-OpenGL sharing we have and enable it.
#if defined(__APPLE__) || defined(__MACOSX)
    bool appleSharing = gpu.hasExtension("cl_apple_gl_sharing");
    if (appleSharing) {
        CGLContextObj cglContext = CGLGetCurrentContext();
        CGLShareGroupObj cglShareGroup = CGLGetShareGroup(cglContext);
        properties.append(CL_CGL_SHAREGROUP_KHR);
        properties.append(cl_context_properties(cglShareGroup));
        hasSharing = true;
    }
#else
    bool khrSharing = gpu.hasExtension("cl_khr_gl_sharing");
#if defined(QT_OPENGL_ES_2) || defined(QT_OPENGL_ES)
    if (khrSharing) {
        properties.append(CL_EGL_DISPLAY_KHR);
        properties.append(cl_context_properties(eglGetCurrentDisplay()));
#ifdef EGL_OPENGL_ES_API
        eglBindAPI(EGL_OPENGL_ES_API);
#endif
        properties.append(CL_GL_CONTEXT_KHR);
        properties.append(cl_context_properties(eglGetCurrentContext()));
        hasSharing = true;
    }
#elif defined(Q_WS_X11)
    if (khrSharing) {
        properties.append(CL_GLX_DISPLAY_KHR);
        properties.append(cl_context_properties(glXGetCurrentDisplay()));
        properties.append(CL_GL_CONTEXT_KHR);
        properties.append(cl_context_properties(glXGetCurrentContext()));
        hasSharing = true;
    }
#else
    // Needs to be ported to other platforms.
    if (khrSharing)
        qWarning() << "QCLContextGL::create: do not know how to enable sharing";
#endif
#endif
#endif // !QT_NO_CL_OPENGL
    properties.append(0);

#ifndef QT_NO_CL_OPENGL
    // Query the actual OpenCL devices we should use with the OpenGL context.
    typedef cl_int (*q_PFNCLGETGLCONTEXTINFOKHR)
        (const cl_context_properties *, cl_uint, size_t, void *, size_t *);
    q_PFNCLGETGLCONTEXTINFOKHR getGLContextInfo =
        (q_PFNCLGETGLCONTEXTINFOKHR)clGetExtensionFunctionAddress
            ("clGetGLContextInfoKHR");
    if (getGLContextInfo && hasSharing) {
        size_t size;
        cl_device_id currentDev;
        if(getGLContextInfo(properties.data(),
                            CL_DEVICES_FOR_GL_CONTEXT_KHR,
                            0, 0, &size) == CL_SUCCESS && size > 0) {
            QVarLengthArray<cl_device_id> buf(size / sizeof(cl_device_id));
            getGLContextInfo(properties.data(),
                             CL_DEVICES_FOR_GL_CONTEXT_KHR,
                             size, buf.data(), 0);
            devs = buf;
            gpu = QCLDevice(devs[0]);
        }
        if (getGLContextInfo(properties.data(),
                             CL_CURRENT_DEVICE_FOR_GL_CONTEXT_KHR,
                             sizeof(currentDev), &currentDev, 0)
                == CL_SUCCESS) {
            gpu = QCLDevice(currentDev);
        }
    }
#endif

    // Create the OpenCL context.
    cl_context id;
    cl_int error;
    id = clCreateContext
        (properties.data(), devs.size(), devs.data(),
         qt_clgl_context_notify, 0, &error);
    if (!id && hasSharing) {
        // Try again without the sharing parameters.
        properties.resize(2);
        properties.append(0);
        hasSharing = false;
        id = clCreateContext
            (properties.data(), devs.size(), devs.data(),
             qt_clgl_context_notify, 0, &error);
    }
    setLastError(error);
    if (id == 0) {
        qWarning() << "QCLContextGL::create:" << errorName(error);
        d->supportsSharing = false;
    } else {
        setContextId(id);
        clReleaseContext(id);   // setContextId() adds an extra reference.
        setDefaultDevice(gpu);
        d->supportsSharing = hasSharing;
    }
    return id != 0;
}
Exemplo n.º 18
0
/* Initialize OpenCl processing */
void init_cl() {

   char *program_buffer, *program_log;
   size_t program_size, log_size;
   int err;

   /* Identify a platform */
   err = clGetPlatformIDs(1, &platform, NULL);
   if(err < 0) {
      perror("Couldn't identify a platform");
      exit(1);
   }

   /* Access a device */
   err = clGetDeviceIDs(platform, CL_DEVICE_TYPE_GPU, 1, &device, NULL);
   if(err == CL_DEVICE_NOT_FOUND) {
      err = clGetDeviceIDs(platform, CL_DEVICE_TYPE_CPU, 1, &device, NULL);
   }
   if(err < 0) {
      perror("Couldn't access any devices");
      exit(1);   
   }

   /* Create OpenCL context properties */
#ifdef MAC
   CGLContextObj mac_context = CGLGetCurrentContext();
   CGLShareGroupObj group = CGLGetShareGroup(mac_context);
   cl_context_properties properties[] = {
      CL_CONTEXT_PROPERTY_USE_CGL_SHAREGROUP_APPLE, 
      (cl_context_properties)group, 0};
#else 
#ifdef UNIX
   cl_context_properties properties[] = {
      CL_GL_CONTEXT_KHR, (cl_context_properties)glXGetCurrentContext(), 
      CL_GLX_DISPLAY_KHR, (cl_context_properties)glXGetCurrentDisplay(), 
      CL_CONTEXT_PLATFORM, (cl_context_properties)platform, 0};
#else
   cl_context_properties properties[] = {
      CL_GL_CONTEXT_KHR, (cl_context_properties)wglGetCurrentContext(), 
      CL_WGL_HDC_KHR, (cl_context_properties)wglGetCurrentDC(), 
      CL_CONTEXT_PLATFORM, (cl_context_properties)platform, 0};
#endif
#endif

   /* Create context */
   context = clCreateContext(properties, 1, &device, NULL, NULL, &err);
   if(err < 0) {
      perror("Couldn't create a context");
      exit(1);   
   }

   /* Create program from file */
   program_buffer = read_file(PROGRAM_FILE, &program_size);
   program = clCreateProgramWithSource(context, 1, 
      (const char**)&program_buffer, &program_size, &err);
   if(err < 0) {
      perror("Couldn't create the program");
      exit(1);
   }
   free(program_buffer);

   /* Build program */
   err = clBuildProgram(program, 0, NULL, NULL, NULL, NULL);
   if(err < 0) {

      /* Find size of log and print to std output */
      clGetProgramBuildInfo(program, device, CL_PROGRAM_BUILD_LOG, 
            0, NULL, &log_size);
      program_log = (char*) malloc(log_size + 1);
      program_log[log_size] = '\0';
      clGetProgramBuildInfo(program, device, CL_PROGRAM_BUILD_LOG, 
            log_size + 1, program_log, NULL);
      printf("%s\n", program_log);
      free(program_log);
      exit(1);
   }

   /* Create a command queue */
   queue = clCreateCommandQueue(context, device, 0, &err);
   if(err < 0) {
      perror("Couldn't create a command queue");
      exit(1);   
   };

   /* Create kernel */
   kernel = clCreateKernel(program, KERNEL_FUNC, &err);
   if(err < 0) {
      printf("Couldn't create a kernel: %d", err);
      exit(1);
   };
}
Exemplo n.º 19
0
void ConfigManager::CreateConfigs(Mode mode, bool interop, std::vector<Config>& configs, int initial_num_bounces)
{
	std::vector<CLWPlatform> platforms;

	CLWPlatform::CreateAllPlatforms(platforms);

	if (platforms.size() == 0)
	{
		throw std::runtime_error("No OpenCL platforms installed.");
	}

	configs.clear();

	bool hasprimary = false;
	for (int i = 0; i < platforms.size(); ++i)
	{
		std::vector<CLWDevice> devices;
		int startidx = configs.size();

		for (int d = 0; d < (int)platforms[i].GetDeviceCount(); ++d)
		{
			if ((mode == kUseGpus || mode == kUseSingleGpu) && platforms[i].GetDevice(d).GetType() != CL_DEVICE_TYPE_GPU)
				continue;

			if ((mode == kUseCpus || mode == kUseSingleCpu) && platforms[i].GetDevice(d).GetType() != CL_DEVICE_TYPE_CPU)
				continue;

			Config cfg;
			cfg.caninterop = false;
#ifdef WIN32
			if (platforms[i].GetDevice(d).HasGlInterop() && !hasprimary && interop)
			{
				cl_context_properties props[] =
				{
					//OpenCL platform
					CL_CONTEXT_PLATFORM, (cl_context_properties)((cl_platform_id)platforms[i]),
					//OpenGL context
					CL_GL_CONTEXT_KHR, (cl_context_properties)wglGetCurrentContext(),
					//HDC used to create the OpenGL context
					CL_WGL_HDC_KHR, (cl_context_properties)wglGetCurrentDC(),
					0
				};

				cfg.context = CLWContext::Create(platforms[i].GetDevice(d), props);
				devices.push_back(platforms[i].GetDevice(d));
				cfg.devidx = 0;
				cfg.type = kPrimary;
				cfg.caninterop = true;
				hasprimary = true;
			}
			else
#elif __linux__

			if (platforms[i].GetDevice(d).HasGlInterop() && !hasprimary && interop)
			{
				cl_context_properties props[] =
				{
					//OpenCL platform
					CL_CONTEXT_PLATFORM, (cl_context_properties)((cl_platform_id)platforms[i]),
					//OpenGL context
					CL_GL_CONTEXT_KHR, (cl_context_properties)glXGetCurrentContext(),
					//HDC used to create the OpenGL context
					CL_GLX_DISPLAY_KHR, (cl_context_properties)glXGetCurrentDisplay(),
					0
				};

				cfg.context = CLWContext::Create(platforms[i].GetDevice(d), props);
				devices.push_back(platforms[i].GetDevice(d));
				cfg.devidx = 0;
				cfg.type = kPrimary;
				cfg.caninterop = true;
				hasprimary = true;
			}
			else
#elif __APPLE__
                if (platforms[i].GetDevice(d).HasGlInterop() && !hasprimary && interop)
                {
                    CGLContextObj kCGLContext = CGLGetCurrentContext();
                    CGLShareGroupObj kCGLShareGroup = CGLGetShareGroup(kCGLContext);
                    // Create CL context properties, add handle & share-group enum !
                    cl_context_properties props[] = {
                    CL_CONTEXT_PROPERTY_USE_CGL_SHAREGROUP_APPLE,
                    (cl_context_properties)kCGLShareGroup, 0
                    };

                    cfg.context = CLWContext::Create(platforms[i].GetDevice(d), props);
                    devices.push_back(platforms[i].GetDevice(d));
                    cfg.devidx = 0;
                    cfg.type = kPrimary;
                    cfg.caninterop = true;
                    hasprimary = true;
                }
                else
#endif
			{
				cfg.context = CLWContext::Create(platforms[i].GetDevice(d));
				cfg.devidx = 0;
				cfg.type = kSecondary;
			}

			configs.push_back(cfg);

			if (mode == kUseSingleGpu || mode == kUseSingleCpu)
				break;
		}

		if (configs.size() == 1 && (mode == kUseSingleGpu || mode == kUseSingleCpu))
			break;
	}

	if (!hasprimary)
	{
		configs[0].type = kPrimary;
	}

	for (int i = 0; i < configs.size(); ++i)
	{
		configs[i].renderer = new Baikal::PtRenderer(configs[i].context, configs[i].devidx, initial_num_bounces);
	}
}
Exemplo n.º 20
0
bool
CLDeviceContext::Initialize() {

#ifdef OPENSUBDIV_HAS_CLEW
    if (!clGetPlatformIDs) {
        error("Error clGetPlatformIDs function not bound.\n");
        return false;
    }
#endif

    cl_int ciErrNum;
    cl_platform_id cpPlatform = findPlatform();

#if defined(_WIN32)
    cl_context_properties props[] = {
        CL_GL_CONTEXT_KHR, (cl_context_properties)wglGetCurrentContext(),
        CL_WGL_HDC_KHR, (cl_context_properties)wglGetCurrentDC(),
        CL_CONTEXT_PLATFORM, (cl_context_properties)cpPlatform,
        0
    };
#elif defined(__APPLE__)
    CGLContextObj kCGLContext = CGLGetCurrentContext();
    CGLShareGroupObj kCGLShareGroup = CGLGetShareGroup(kCGLContext);
    cl_context_properties props[] = {
        CL_CONTEXT_PROPERTY_USE_CGL_SHAREGROUP_APPLE, (cl_context_properties)kCGLShareGroup,
        0
    };
#else
    cl_context_properties props[] = {
        CL_GL_CONTEXT_KHR, (cl_context_properties)glXGetCurrentContext(),
        CL_GLX_DISPLAY_KHR, (cl_context_properties)glXGetCurrentDisplay(),
        CL_CONTEXT_PLATFORM, (cl_context_properties)cpPlatform,
        0
    };
#endif

#if defined(__APPLE__)
    _clContext = clCreateContext(props, 0, NULL, clLogMessagesToStdoutAPPLE,
                                 NULL, &ciErrNum);
    if (ciErrNum != CL_SUCCESS) {
        error("Error %d in clCreateContext\n", ciErrNum);
        return false;
    }

    size_t devicesSize = 0;
    clGetGLContextInfoAPPLE(_clContext, kCGLContext,
                            CL_CGL_DEVICES_FOR_SUPPORTED_VIRTUAL_SCREENS_APPLE,
                            0, NULL, &devicesSize);
    int numDevices = int(devicesSize / sizeof(cl_device_id));
    if (numDevices == 0) {
        error("No sharable devices.\n");
        return false;
    }
    cl_device_id *clDevices = new cl_device_id[numDevices];
    clGetGLContextInfoAPPLE(_clContext, kCGLContext,
                            CL_CGL_DEVICES_FOR_SUPPORTED_VIRTUAL_SCREENS_APPLE,
                            numDevices * sizeof(cl_device_id), clDevices, NULL);
    int clDeviceUsed = 0;

#else   // not __APPLE__

    // get the number of GPU devices available to the platform
    cl_uint numDevices = 0;
    clGetDeviceIDs(cpPlatform, CL_DEVICE_TYPE_GPU, 0, NULL, &numDevices);
    if (numDevices == 0) {
        error("No CL GPU device found.\n");
        return false;
    }

    // create the device list
    cl_device_id *clDevices = new cl_device_id[numDevices];
    clGetDeviceIDs(cpPlatform, CL_DEVICE_TYPE_GPU, numDevices, clDevices, NULL);

    const char *extension = "cl_khr_gl_sharing";
    int clDeviceUsed = findExtensionSupportedDevice(clDevices, numDevices,
                                                    extension);

    if (clDeviceUsed < 0) {
        error("No device found that supports CL/GL context sharing\n");
        delete[] clDevices;
        return false;
    }

    _clContext = clCreateContext(props, 1, &clDevices[clDeviceUsed],
                                 NULL, NULL, &ciErrNum);

#endif   // not __APPLE__

    if (ciErrNum != CL_SUCCESS) {
        error("Error %d in clCreateContext\n", ciErrNum);
        delete[] clDevices;
        return false;
    }

    _clCommandQueue = clCreateCommandQueue(_clContext, clDevices[clDeviceUsed],
                                    0, &ciErrNum);
    delete[] clDevices;
    if (ciErrNum != CL_SUCCESS) {
        error("Error %d in clCreateCommandQueue\n", ciErrNum);
        return false;
    }
    return true;
}
Exemplo n.º 21
0
/// Creates a shared OpenCL/OpenGL context for the currently active
/// OpenGL context.
///
/// Once created, the shared context can be used to create OpenCL memory
/// objects which can interact with OpenGL memory objects (e.g. VBOs).
///
/// \throws unsupported_extension_error if no CL-GL sharing capable devices
///         are found.
inline context opengl_create_shared_context()
{
    // name of the OpenGL sharing extension for the system
#if defined(__APPLE__)
    const char *cl_gl_sharing_extension = "cl_APPLE_gl_sharing";
#else
    const char *cl_gl_sharing_extension = "cl_khr_gl_sharing";
#endif

#if defined(__APPLE__)
    // get OpenGL share group
    CGLContextObj cgl_current_context = CGLGetCurrentContext();
    CGLShareGroupObj cgl_share_group = CGLGetShareGroup(cgl_current_context);

    cl_context_properties properties[] = {
        CL_CONTEXT_PROPERTY_USE_CGL_SHAREGROUP_APPLE,
        (cl_context_properties) cgl_share_group,
        0
    };

    cl_int error = 0;
    cl_context cl_gl_context = clCreateContext(properties, 0, 0, 0, 0, &error);
    if(!cl_gl_context){
        BOOST_THROW_EXCEPTION(opencl_error(error));
    }

    return context(cl_gl_context, false);
#else
    typedef cl_int(*GetGLContextInfoKHRFunction)(
        const cl_context_properties*, cl_gl_context_info, size_t, void *, size_t *
    );

    std::vector<platform> platforms = system::platforms();
    for(size_t i = 0; i < platforms.size(); i++){
        const platform &platform = platforms[i];

        // check whether this platform supports OpenCL/OpenGL sharing
        if (!platform.supports_extension("cl_gl_sharing_extension"))
          continue;

        // load clGetGLContextInfoKHR() extension function
        GetGLContextInfoKHRFunction GetGLContextInfoKHR =
            reinterpret_cast<GetGLContextInfoKHRFunction>(
                reinterpret_cast<size_t>(
                    platform.get_extension_function_address("clGetGLContextInfoKHR")
                )
            );
        if(!GetGLContextInfoKHR){
            continue;
        }

        // create context properties listing the platform and current OpenGL display
        cl_context_properties properties[] = {
            CL_CONTEXT_PLATFORM, (cl_context_properties) platform.id(),
        #if defined(__linux__)
            CL_GL_CONTEXT_KHR, (cl_context_properties) glXGetCurrentContext(),
            CL_GLX_DISPLAY_KHR, (cl_context_properties) glXGetCurrentDisplay(),
        #elif defined(_WIN32)
            CL_GL_CONTEXT_KHR, (cl_context_properties) wglGetCurrentContext(),
            CL_WGL_HDC_KHR, (cl_context_properties) wglGetCurrentDC(),
        #endif
            0
        };

        // lookup current OpenCL device for current OpenGL context
        cl_device_id gpu_id;
        cl_int ret = GetGLContextInfoKHR(
            properties,
            CL_CURRENT_DEVICE_FOR_GL_CONTEXT_KHR,
            sizeof(cl_device_id),
            &gpu_id,
            0
        );
        if(ret != CL_SUCCESS){
            continue;
        }

        // create device object for the GPU and ensure it supports CL-GL sharing
        device gpu(gpu_id, false);
        if(!gpu.supports_extension("cl_gl_sharing_extension")){
            continue;
        }

        // return CL-GL sharing context
        return context(gpu, properties);
    }
#endif

    // no CL-GL sharing capable devices found
    BOOST_THROW_EXCEPTION(
        unsupported_extension_error("cl_gl_sharing_extension")
    );
}
Exemplo n.º 22
0
/**
 *Create OCL Contxt
 */
OclContext* OclEngine::createGPUContext(OclContext::ContextProperties contextProperties) {


    int contextPropertiSize = 3;
    const int PLATFORM_PROPERTY_END=2;
    if(contextProperties.useSharedGPUContex);
        contextPropertiSize+=4;
    cl_context_properties* properties = new cl_context_properties[contextPropertiSize];
    //Add the common part
    properties[0] = CL_CONTEXT_PLATFORM;
    properties[1] = (cl_context_properties)contextProperties.context_platform;
    properties[PLATFORM_PROPERTY_END] = 0;

#if defined(_WIN32)

//    // Windows
//    cl_context_properties properties[] = {
//      CL_GL_CONTEXT_KHR, (cl_context_properties)wglGetCurrentContext(),
//      CL_WGL_HDC_KHR, (cl_context_properties)wglGetCurrentDC(),
//      CL_CONTEXT_PLATFORM,(cl_context_properties) contextProperties.context_platform,
//      CL_CONTEXT_INTEROP_USER_SYNC,(cl_context_properties) contextProperties.context_interop_user_sync,
//      0
//    };
    if(contextProperties.useSharedGPUContex && (wglGetCurrentContext()!=nullptr)
    && wglGetCurrentDC()!=nullptr)
    {
         properties[PLATFORM_PROPERTY_END+4] = 0;
         properties[PLATFORM_PROPERTY_END] = CL_GL_CONTEXT_KHR;
         properties[PLATFORM_PROPERTY_END+1] = (cl_context_properties)wglGetCurrentContext();
         properties[PLATFORM_PROPERTY_END+2] = CL_WGL_HDC_KHR;
         properties[PLATFORM_PROPERTY_END+3] = (cl_context_properties)wglGetCurrentDC();

    }

#elif defined(__APPLE__)

    // OS X

    CGLContextObj     kCGLContext     = CGLGetCurrentContext();

    CGLShareGroupObj  kCGLShareGroup  = CGLGetShareGroup(kCGLContext);

    if(contextProperties.useSharedGPUContex && kCGLShareGroup!= nullptr)
    {
        properties[PLATFORM_PROPERTY_END+2]  = 0;
        properties[PLATFORM_PROPERTY_END] = CL_CONTEXT_PROPERTY_USE_CGL_SHAREGROUP_APPLE;
        properties[PLATFORM_PROPERTY_END+1] = (cl_context_properties) kCGLShareGroup;
    }
//    {
//            CL_CONTEXT_PLATFORM,(cl_context_properties) contextProperties.context_platform,
//            0
//    };
#else

//    // Linux
//    cl_context_properties properties[] = {
////      CL_GL_CONTEXT_KHR, (cl_context_properties)glXGetCurrentContext(),
// //     CL_GLX_DISPLAY_KHR, (cl_context_properties)glXGetCurrentDisplay(),
//      CL_CONTEXT_PLATFORM,(cl_context_properties) contextProperties.context_platform,
// //     CL_CONTEXT_INTEROP_USER_SYNC,(cl_context_properties) contextProperties.context_interop_user_sync,
//      0
//    };
if(contextProperties.useSharedGPUContex && (glXGetCurrentContext()!=nullptr)
    && glXGetCurrentDisplay()!=nullptr)
    {
         properties[PLATFORM_PROPERTY_END+4] = 0;
         properties[PLATFORM_PROPERTY_END] = CL_GL_CONTEXT_KHR;
         properties[PLATFORM_PROPERTY_END+1] = (cl_context_properties)glXGetCurrentContext();
         properties[PLATFORM_PROPERTY_END+2] = CL_GLX_DISPLAY_KHR;
         properties[PLATFORM_PROPERTY_END+3] = (cl_context_properties)glXGetCurrentDisplay();

    }
#endif

    PlatformInfo* defaultPlatform = getDefaultPlatform();
    if(defaultPlatform== nullptr)
        return nullptr;
    cl_int errCode;
    cl_context clContext = clCreateContext(properties,
                                           defaultPlatform->num_devices,
                                           defaultPlatform->devices,NULL,NULL,&errCode);

    if(OclErrors::success(errCode))
    {
        OclContext *context = new OclContext(clContext);
        this->_contexts.push_back(context);
        return context;
    }
    else
        return nullptr;
}
Exemplo n.º 23
0
extern "C" int main(int argcount, char* argvec[])
#endif
{
#if defined(__native_client__)
	std::cerr << "Running game_main" << std::endl;

	chdir("/frogatto");
	{
		char buf[256];
		const char* const res = getcwd(buf,sizeof(buf));
		std::cerr << "Current working directory: " << res << std::endl;
	}
#endif 

#if defined(__APPLE__) && TARGET_OS_MAC
    chdir([[[NSBundle mainBundle] resourcePath] fileSystemRepresentation]);
#endif

	#ifdef NO_STDERR
	std::freopen("/dev/null", "w", stderr);
	std::cerr.sync_with_stdio(true);
	#endif

	std::cerr << "Frogatto engine version " << preferences::version() << "\n";
	LOG( "After print engine version" );

	#if defined(TARGET_BLACKBERRY)
		chdir("app/native");
		std::cout<< "Changed working directory to: " << getcwd(0, 0) << std::endl;
	#endif

	game_logic::init_callable_definitions();

	std::string level_cfg = "titlescreen.cfg";
	bool unit_tests_only = false, skip_tests = false;
	bool run_benchmarks = false;
	std::vector<std::string> benchmarks_list;
	std::string utility_program;
	std::vector<std::string> util_args;
	std::string server = "wesnoth.org";
#if defined(UTILITY_IN_PROC)
	bool create_utility_in_new_process = false;
	std::string utility_name;
#endif
	bool is_child_utility = false;

	const char* profile_output = NULL;
	std::string profile_output_buf;

#if defined(__ANDROID__)
	//monstartup("libapplication.so");
#endif

	std::string orig_level_cfg = level_cfg;
	std::string override_level_cfg = "";

	int modules_loaded = 0;

	std::vector<std::string> argv;
	for(int n = 1; n < argcount; ++n) {
#if defined(UTILITY_IN_PROC)
		std::string sarg(argvec[n]);
		if(sarg.compare(0, 15, "--utility-proc=") == 0) {
			create_utility_in_new_process = true;
			utility_name = "--utility-child=" + sarg.substr(15);
		} else {
			argv.push_back(argvec[n]);
		}
#else
		argv.push_back(argvec[n]);
#endif
        
        if(argv.size() >= 2 && argv[argv.size()-2] == "-NSDocumentRevisionsDebugMode" && argv.back() == "YES") {
            //XCode passes these arguments by default when debugging -- make sure they are ignored.
            argv.resize(argv.size()-2);
        }
	}

#if defined(UTILITY_IN_PROC)
	if(create_utility_in_new_process) {
		argv.push_back(utility_name);
#if defined(_MSC_VER)
		// app name is ignored for windows, we get windows to tell us.
		is_child_utility = create_utility_process("", argv);
#else 
		is_child_utility = create_utility_process(argvec[0], argv);
#endif
		if(!is_child_utility) {
			argv.pop_back();
		}
#if defined(_MSC_VER)
		atexit(terminate_utility_process);
#endif
	}
#endif

	if(sys::file_exists("./master-config.cfg")) {
		std::cerr << "LOADING CONFIGURATION FROM master-config.cfg" << std::endl;
		variant cfg = json::parse_from_file("./master-config.cfg");
		if(cfg.is_map()) {
			if( cfg["id"].is_null() == false) {
				std::cerr << "SETTING MODULE PATH FROM master-config.cfg: " << cfg["id"].as_string() << std::endl;
				preferences::set_preferences_path_from_module(cfg["id"].as_string());
				//XXX module::set_module_name(cfg["id"].as_string(), cfg["id"].as_string());
			}
			if(cfg["arguments"].is_null() == false) {
				std::vector<std::string> additional_args = cfg["arguments"].as_list_string();
				argv.insert(argv.begin(), additional_args.begin(), additional_args.end());
				std::cerr << "ADDING ARGUMENTS FROM master-config.cfg:";
				for(size_t n = 0; n < cfg["arguments"].num_elements(); ++n) {
					std::cerr << " " << cfg["arguments"][n].as_string();
				}
				std::cerr << std::endl;
			}
		}
	}

	stats::record_program_args(argv);

	for(size_t n = 0; n < argv.size(); ++n) {
		const int argc = argv.size();
		const std::string arg(argv[n]);
		std::string arg_name, arg_value;
		std::string::const_iterator equal = std::find(arg.begin(), arg.end(), '=');
		if(equal != arg.end()) {
			arg_name = std::string(arg.begin(), equal);
			arg_value = std::string(equal+1, arg.end());
		}
		if(arg_name == "--module") {
			if(load_module(arg_value, &argv) != 0) {
				std::cerr << "FAILED TO LOAD MODULE: " << arg_value << "\n";
				return -1;
			}
			++modules_loaded;
		} else if(arg == "--tests") {
			unit_tests_only = true;
		}
	}

	if(modules_loaded == 0 && !unit_tests_only) {
		if(load_module(DEFAULT_MODULE, &argv) != 0) {
			std::cerr << "FAILED TO LOAD MODULE: " << DEFAULT_MODULE << "\n";
			return -1;
		}
	}

	preferences::load_preferences();
	LOG( "After load_preferences()" );

	// load difficulty settings after module, before rest of args.
	difficulty::manager();

	for(size_t n = 0; n < argv.size(); ++n) {
		const size_t argc = argv.size();
		const std::string arg(argv[n]);
		std::string arg_name, arg_value;
		std::string::const_iterator equal = std::find(arg.begin(), arg.end(), '=');
		if(equal != arg.end()) {
			arg_name = std::string(arg.begin(), equal);
			arg_value = std::string(equal+1, arg.end());
		}
		std::cerr << "ARGS: " << arg << std::endl;
		if(arg.substr(0,4) == "-psn") {
			// ignore.
		} else if(arg_name == "--module") {
			// ignore already processed.
		} else if(arg_name == "--profile" || arg == "--profile") {
			profile_output_buf = arg_value;
			profile_output = profile_output_buf.c_str();
		} else if(arg_name == "--utility" || arg_name == "--utility-child") {
			if(arg_name == "--utility-child") {
				is_child_utility = true;
			}
			utility_program = arg_value;
			for(++n; n < argc; ++n) {
				const std::string arg(argv[n]);
				util_args.push_back(arg);
			}

			break;
		} else if(arg == "--benchmarks") {
			run_benchmarks = true;
		} else if(arg_name == "--benchmarks") {
			run_benchmarks = true;
			benchmarks_list = util::split(arg_value);
		} else if(arg == "--tests") {
			// ignore as already processed.
		} else if(arg == "--no-tests") {
			skip_tests = true;
		} else if(arg_name == "--width") {
			std::string w(arg_value);
			preferences::set_actual_screen_width(boost::lexical_cast<int>(w));
		} else if(arg == "--width" && n+1 < argc) {
			std::string w(argv[++n]);
			preferences::set_actual_screen_width(boost::lexical_cast<int>(w));
		} else if(arg_name == "--height") {
			std::string h(arg_value);
			preferences::set_actual_screen_height(boost::lexical_cast<int>(h));
		} else if(arg == "--height" && n+1 < argc) {
			std::string h(argv[++n]);
			preferences::set_actual_screen_height(boost::lexical_cast<int>(h));
		} else if(arg_name == "--level") {
			override_level_cfg = arg_value;
		} else if(arg == "--level" && n+1 < argc) {
			override_level_cfg = argv[++n];
		} else if(arg_name == "--host") {
			server = arg_value;
		} else if(arg == "--host" && n+1 < argc) {
			server = argv[++n];
		} else if(arg == "--compiled") {
			preferences::set_load_compiled(true);
#ifndef NO_EDITOR
		} else if(arg == "--edit") {
			preferences::set_edit_on_start(true);
#endif
		} else if(arg == "--no-compiled") {
			preferences::set_load_compiled(false);
#if defined(TARGET_PANDORA)
		} else if(arg == "--no-fbo") {
			preferences::set_fbo(false);
		} else if(arg == "--no-bequ") {
			preferences::set_bequ(false);
#endif
		} else if(arg == "--help" || arg == "-h") {
			print_help(std::string(argvec[0]));
			return 0;
		} else {
			const bool res = preferences::parse_arg(argv[n].c_str());
			if(!res) {
				std::cerr << "unrecognized arg: '" << arg << "'\n";
				return -1;
			}
		}
	}

	checksum::manager checksum_manager;
#ifndef NO_EDITOR
	sys::filesystem_manager fs_manager;
#endif // NO_EDITOR

	preferences::expand_data_paths();

	background_task_pool::manager bg_task_pool_manager;
	LOG( "After expand_data_paths()" );

	std::cerr << "Preferences dir: " << preferences::user_data_path() << '\n';

	//make sure that the user data path exists.
	if(!preferences::setup_preferences_dir()) {
		std::cerr << "cannot create preferences dir!\n";
	}

	std::cerr << "\n";

	if(preferences::internal_tbs_server()) {
		tbs::internal_server::init();
	}

	if(utility_program.empty() == false 
		&& test::utility_needs_video(utility_program) == false) {
#if defined(UTILITY_IN_PROC)
		if(is_child_utility) {
			ASSERT_LOG(ipc::semaphore::create(shared_sem_name, 1) != false, 
				"Unable to create shared semaphore: " << errno);
			std::cerr.sync_with_stdio(true);
		}
#endif
		test::run_utility(utility_program, util_args);
		return 0;
	}

#if defined(TARGET_PANDORA)
    EGL_Open();
#endif

#if defined(__ANDROID__)
	std::freopen("stdout.txt","w",stdout);
	std::freopen("stderr.txt","w",stderr);
	std::cerr.sync_with_stdio(true);
#endif

	LOG( "Start of main" );

	if(!skip_tests && !test::run_tests()) {
		return -1;
	}

	if(unit_tests_only) {
		return 0;
	}

#if !defined(__native_client__)
	Uint32 sdl_init_flags = SDL_INIT_VIDEO | SDL_INIT_JOYSTICK;
#if defined(_WINDOWS) || TARGET_OS_IPHONE
	sdl_init_flags |= SDL_INIT_TIMER;
#endif
	if(SDL_Init(sdl_init_flags) < 0) {
		std::cerr << "could not init SDL\n";
		return -1;
	}
	LOG( "After SDL_Init" );
#endif

#ifdef TARGET_OS_HARMATTAN
	g_type_init();
#endif
	i18n::init ();
	LOG( "After i18n::init()" );

	SDL_GL_SetAttribute(SDL_GL_DEPTH_SIZE, 24);
	SDL_GL_SetAttribute(SDL_GL_STENCIL_SIZE, 8);

#if TARGET_OS_IPHONE || defined(TARGET_BLACKBERRY) || defined(__ANDROID__)
	//on the iPhone and PlayBook, try to restore the auto-save if it exists
	if(sys::file_exists(preferences::auto_save_file_path()) && sys::read_file(std::string(preferences::auto_save_file_path()) + ".stat") == "1") {
		level_cfg = "autosave.cfg";
		sys::write_file(std::string(preferences::auto_save_file_path()) + ".stat", "0");

	}
#endif

	if(override_level_cfg.empty() != true) {
		level_cfg = override_level_cfg;
		orig_level_cfg = level_cfg;
	}

#if !SDL_VERSION_ATLEAST(2, 0, 0) && defined(USE_GLES2)
	wm.create_window(preferences::actual_screen_width(),
		preferences::actual_screen_height(),
		0,
		(preferences::resizable() ? SDL_RESIZABLE : 0) | (preferences::fullscreen() ? SDL_FULLSCREEN : 0));
#else

#if TARGET_OS_IPHONE || TARGET_IPHONE_SIMULATOR
	int width, height;
	iphone_screen_res(&width, &height);
	preferences::set_actual_screen_width(width);
	preferences::set_actual_screen_height(height);
	int multiplier = 2;
	if (width > 320)
	{
		//preferences::set_use_pretty_scaling(true);
		multiplier = 1;
	}
	preferences::set_virtual_screen_width(height*multiplier);
	preferences::set_virtual_screen_height(width*multiplier);
	preferences::set_control_scheme(height % 1024 ? "iphone_2d" : "ipad_2d");
	
	SDL_WindowID windowID = SDL_CreateWindow (NULL, 0, 0, preferences::actual_screen_width(), preferences::actual_screen_height(),
		SDL_WINDOW_OPENGL | SDL_WINDOW_SHOWN |
		SDL_WINDOW_BORDERLESS);
	if (windowID == 0) { 
		std::cerr << "Could not create window: " << SDL_GetError() << "\n"; 
		return -1;
	}
	
	//	if (SDL_GL_CreateContext(windowID) == 0) {
	//		std::cerr << "Could not create GL context: " << SDL_GetError() << "\n";
	//		return -1;
	//	}
	if (SDL_CreateRenderer(windowID, -1, 0) != 0) {
		std::cerr << "Could not create renderer\n";
		return -1;
	}
	
#else
#ifdef TARGET_OS_HARMATTAN
	SDL_GL_SetAttribute(SDL_GL_CONTEXT_MAJOR_VERSION, 1);
	if (SDL_SetVideoMode(preferences::actual_screen_width(),preferences::actual_screen_height(),0,SDL_OPENGLES | SDL_FULLSCREEN) == NULL) {
		std::cerr << "could not set video mode\n";
		return -1;
	}

	preferences::init_oes();
	SDL_ShowCursor(0);
#else

#if defined(TARGET_PANDORA)
	if (SDL_SetVideoMode(preferences::actual_screen_width(),preferences::actual_screen_height(),16,SDL_FULLSCREEN) == NULL) {
		std::cerr << "could not set video mode\n";
		return -1;
	}
    EGL_Init();
    preferences::init_oes();
#elif defined(TARGET_TEGRA)
	//if (SDL_SetVideoMode(preferences::actual_screen_width(),preferences::actual_screen_height(),0,preferences::resizable() ? SDL_RESIZABLE : 0|preferences::fullscreen() ? SDL_FULLSCREEN : 0) == NULL) {
	if (SDL_SetVideoMode(preferences::actual_screen_width(),preferences::actual_screen_height(),0,SDL_FULLSCREEN) == NULL) {
		std::cerr << "could not set video mode\n";
		return -1;
	}
    EGL_Init();
    preferences::init_oes();
#elif defined(TARGET_BLACKBERRY)
	if (SDL_SetVideoMode(preferences::actual_screen_width(),preferences::actual_screen_height(),0,SDL_OPENGL|SDL_FULLSCREEN) == NULL) {
		std::cerr << "could not set video mode\n";
		return -1;
	}
	preferences::init_oes();
#elif defined(__ANDROID__)
#if SDL_VERSION_ATLEAST(2, 0, 0)
	int num_video_displays = SDL_GetNumVideoDisplays();
	SDL_Rect r;
	if(num_video_displays < 0) {
		std::cerr << "no video displays available" << std::endl;
		return -1;
	}
	if(SDL_GetDisplayBounds(0, &r) < 0) {
        preferences::set_actual_screen_width(r.w);
        preferences::set_actual_screen_height(r.h);
		if(r.w < 640) {
        	preferences::set_virtual_screen_width(r.w*2);
        	preferences::set_virtual_screen_height(r.h*2);
		} else {
			preferences::set_virtual_screen_width(r.w);
			preferences::set_virtual_screen_height(r.h);
		}
		preferences::set_control_scheme(r.h >= 1024 ? "ipad_2d" : "android_med");
    }
#else
    SDL_Rect** r = SDL_ListModes(NULL, SDL_FULLSCREEN|SDL_OPENGL);
    if( r != (SDL_Rect**)0 && r != (SDL_Rect**)-1 ) {
        preferences::set_actual_screen_width(r[0]->w);
        preferences::set_actual_screen_height(r[0]->h);
		if(r[0]->w < 640) {
        	preferences::set_virtual_screen_width(r[0]->w*2);
        	preferences::set_virtual_screen_height(r[0]->h*2);
		} else {
			preferences::set_virtual_screen_width(r[0]->w);
			preferences::set_virtual_screen_height(r[0]->h);
		}
		preferences::set_control_scheme(r[0]->h >= 1024 ? "ipad_2d" : "android_med");
    }
#endif

#if SDL_VERSION_ATLEAST(2, 0, 0)
	if(!graphics::set_video_mode(preferences::actual_screen_width(), preferences::actual_screen_height())) {
#else
    if (SDL_SetVideoMode(preferences::actual_screen_width(),preferences::actual_screen_height(),0,SDL_FULLSCREEN|SDL_OPENGL) == NULL) {
#endif
		std::cerr << "could not set video mode\n";
		return -1;
    }
#elif defined(__native_client__)
    SDL_Rect** r = SDL_ListModes(NULL, SDL_OPENGL);
	std::cerr << "Video modes";
	if(r == (SDL_Rect**)0) {
		std::cerr << "No modes available";
		return -1;
	}
	if(r == (SDL_Rect**)-1) {
		std::cerr << "All modes available";
	} else {
		for(int i = 0; r[i]; ++i) {
			std::cerr << r[i]->w << r[i]->h << std::endl;
		}
	}

    if (SDL_SetVideoMode(preferences::actual_screen_width(),preferences::actual_screen_height(),0,0) == NULL) {
		std::cerr << "could not set video mode\n";
		return -1;
    }
#else
#if SDL_VERSION_ATLEAST(2, 0, 0)
	if(preferences::auto_size_window()) {
		const SDL_DisplayMode mode = graphics::set_video_mode_auto_select();
		preferences::set_actual_screen_width(mode.w);
		preferences::set_actual_screen_height(mode.h);
		preferences::set_virtual_screen_width(mode.w);
		preferences::set_virtual_screen_height(mode.h);
	} else if(!graphics::set_video_mode(preferences::actual_screen_width(), preferences::actual_screen_height(), SDL_WINDOW_RESIZABLE|SDL_WINDOW_OPENGL)) {
#else
	if(SDL_SetVideoMode(preferences::actual_screen_width(),preferences::actual_screen_height(),0,SDL_OPENGL|(preferences::resizable() ? SDL_RESIZABLE : 0)|(preferences::fullscreen() ? SDL_FULLSCREEN : 0)) == NULL) {
#endif
		std::cerr << "could not set video mode\n";
		return -1;
	}
#ifndef __APPLE__
	graphics::surface wm_icon = graphics::surface_cache::get("window-icon.png");
	if(!wm_icon.null()) {
#if SDL_VERSION_ATLEAST(2, 0, 0)
		SDL_SetWindowIcon(graphics::get_window(), wm_icon.get());
#else
		SDL_WM_SetIcon(wm_icon, NULL);
#endif
	}
#endif // __APPLE__
#endif
#endif
#endif

#endif

#if !SDL_VERSION_ATLEAST(2, 0, 0) && defined(__GLEW_H__)
	GLenum glew_status = glewInit();
	ASSERT_EQ(glew_status, GLEW_OK);
#endif

#if defined(USE_GLES2)
	if(glCreateShader == NULL) {
		const GLubyte* glstrings;
		if(glGetString != NULL && (glstrings = glGetString(GL_VERSION)) != NULL) {
			std::cerr << "OpenGL version: " << reinterpret_cast<const char *>(glstrings) << std::endl;
		}
		std::cerr << "glCreateShader is NULL. Check that your current video card drivers support "
			<< "an OpenGL version >= 2. Exiting." << std::endl;
		return 0;
	}
	// Has to happen after the call to glewInit().
	gles2::init_default_shader();
#endif

//	srand(time(NULL));

	const stats::manager stats_manager;
#ifndef NO_EDITOR
	const external_text_editor::manager editor_manager;
#endif // NO_EDITOR

#if defined(USE_BOX2D)
	box2d::manager b2d_manager;
#endif

	std::cerr << std::endl;
	const GLubyte* glstrings;
	if((glstrings = glGetString(GL_VENDOR)) != NULL) {
		std::cerr << "OpenGL vendor: " << reinterpret_cast<const char *>(glstrings) << std::endl;
	} else {
		GLenum err = glGetError();
		std::cerr << "Error in vendor string: " << std::hex << err << std::endl;
	}
	if((glstrings = glGetString(GL_VERSION)) != NULL) {
		std::cerr << "OpenGL version: " << reinterpret_cast<const char *>(glstrings) << std::endl;
	} else {
		GLenum err = glGetError();
		std::cerr << "Error in version string: " << std::hex << err << std::endl;
	}
	if((glstrings = glGetString(GL_EXTENSIONS)) != NULL) {
		std::cerr << "OpenGL extensions: " << reinterpret_cast<const char *>(glstrings) << std::endl;
	} else {
		GLenum err = glGetError();
		std::cerr << "Error in extensions string: " << std::hex << err << std::endl;
	}
#ifdef GL_SHADING_LANGUAGE_VERSION
	if((glstrings = glGetString(GL_SHADING_LANGUAGE_VERSION)) != NULL) {
		std::cerr << "GLSL Version: " << reinterpret_cast<const char *>(glstrings) << std::endl;
	} else {
		GLenum err = glGetError();
		std::cerr << "Error in GLSL string: " << std::hex << err << std::endl;
	}
#endif
	std::cerr << std::endl;

	GLint stencil_bits = 0;
	glGetIntegerv(GL_STENCIL_BITS, &stencil_bits);
	std::cerr << "Stencil bits: " << stencil_bits << std::endl;

#if defined(USE_GLES2)
#if !defined(GL_ES_VERSION_2_0)
	GLfloat min_pt_sz;
	glGetFloatv(GL_POINT_SIZE_MIN, &min_pt_sz);
	GLfloat max_pt_sz;
	glGetFloatv(GL_POINT_SIZE_MAX, &max_pt_sz);
	std::cerr << "Point size range: " << min_pt_sz << " < size < " << max_pt_sz << std::endl;
	glEnable(GL_POINT_SPRITE);
	glEnable(GL_VERTEX_PROGRAM_POINT_SIZE);
#endif
#endif

	glShadeModel(GL_SMOOTH);
	glEnable(GL_BLEND);
#if !defined(USE_GLES2)
	glEnable(GL_TEXTURE_2D);
	glEnableClientState(GL_VERTEX_ARRAY);
	glEnableClientState(GL_TEXTURE_COORD_ARRAY);
#endif

	glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA);

	std::cerr << "JOYSTICKS: " << SDL_NumJoysticks() << "\n";

	const load_level_manager load_manager;

	{ //manager scope
	const font::manager font_manager;
	const sound::manager sound_manager;
#if !defined(__native_client__)
	const joystick::manager joystick_manager;
#endif 
	
	graphics::texture::manager texture_manager;

#ifndef NO_EDITOR
	editor::manager editor_manager;
#endif

	variant preloads;
	loading_screen loader;
	try {
		sound::init_music(json::parse_from_file("data/music.cfg"));
		graphical_font::init_for_locale(i18n::get_locale());
		preloads = json::parse_from_file("data/preload.cfg");
		int preload_items = preloads["preload"].num_elements();
		loader.set_number_of_items(preload_items+7); // 7 is the number of items that will be loaded below
		custom_object::init();
		loader.draw_and_increment(_("Initializing custom object functions"));
		init_custom_object_functions(json::parse_from_file("data/functions.cfg"));
		loader.draw_and_increment(_("Initializing textures"));
		loader.load(preloads);
		loader.draw_and_increment(_("Initializing tiles"));
		tile_map::init(json::parse_from_file("data/tiles.cfg"));
		loader.draw_and_increment(_("Initializing GUI"));

		variant gui_node = json::parse_from_file(preferences::load_compiled() ? "data/compiled/gui.cfg" : "data/gui.cfg");
		gui_section::init(gui_node);
		loader.draw_and_increment(_("Initializing GUI"));
		framed_gui_element::init(gui_node);

		game_logic::formula_object::load_all_classes();

	} catch(const json::parse_error& e) {
		std::cerr << "ERROR PARSING: " << e.error_message() << "\n";
		return 0;
	}
	loader.draw(_("Loading level"));

#if defined(__native_client__)
	while(1) {
	}
#endif

#if defined(__APPLE__) && !(TARGET_IPHONE_SIMULATOR || TARGET_OS_IPHONE) && !defined(USE_GLES2)
	GLint swapInterval = 1;
	CGLSetParameter(CGLGetCurrentContext(), kCGLCPSwapInterval, &swapInterval);
#endif

	loader.finish_loading();
	//look to see if we got any quit events while loading.
	{
	SDL_Event event;
	while(SDL_PollEvent(&event)) {
		if(event.type == SDL_QUIT) {
			return 0;
		}
	}
	}

	formula_profiler::manager profiler(profile_output);

#ifdef USE_GLES2
	texture_frame_buffer::init(preferences::actual_screen_width(), preferences::actual_screen_height());
#else
	texture_frame_buffer::init();
#endif

	if(run_benchmarks) {
		if(benchmarks_list.empty() == false) {
			test::run_benchmarks(&benchmarks_list);
		} else {
			test::run_benchmarks();
		}
		return 0;
	} else if(utility_program.empty() == false && test::utility_needs_video(utility_program) == true) {
		test::run_utility(utility_program, util_args);
		return 0;
	}

	bool quit = false;

	while(!quit && !show_title_screen(level_cfg)) {
		boost::intrusive_ptr<level> lvl(load_level(level_cfg));
		

#if !defined(__native_client__)
		//see if we're loading a multiplayer level, in which case we
		//connect to the server.
		multiplayer::manager mp_manager(lvl->is_multiplayer());
		if(lvl->is_multiplayer()) {
			multiplayer::setup_networked_game(server);
		}

		if(lvl->is_multiplayer()) {
			last_draw_position() = screen_position();
			std::string level_cfg = "waiting-room.cfg";
			boost::intrusive_ptr<level> wait_lvl(load_level(level_cfg));
			wait_lvl->finish_loading();
			wait_lvl->set_multiplayer_slot(0);
			if(wait_lvl->player()) {
				wait_lvl->player()->set_current_level(level_cfg);
			}
			wait_lvl->set_as_current_level();

			level_runner runner(wait_lvl, level_cfg, orig_level_cfg);

			multiplayer::sync_start_time(*lvl, boost::bind(&level_runner::play_cycle, &runner));

			lvl->set_multiplayer_slot(multiplayer::slot());
		}
#endif

		last_draw_position() = screen_position();

		assert(lvl.get());
		if(!lvl->music().empty()) {
			sound::play_music(lvl->music());
		}

		if(lvl->player() && level_cfg != "autosave.cfg") {
			lvl->player()->set_current_level(level_cfg);
			lvl->player()->get_entity().save_game();
		}

		set_scene_title(lvl->title());

		try {
			quit = level_runner(lvl, level_cfg, orig_level_cfg).play_level();
			level_cfg = orig_level_cfg;
		} catch(multiplayer_exception&) {
		}
	}

	level::clear_current_level();

	} //end manager scope, make managers destruct before calling SDL_Quit
//	controls::debug_dump_controls();
#if defined(TARGET_PANDORA) || defined(TARGET_TEGRA)
    EGL_Destroy();
#endif

#if SDL_VERSION_ATLEAST(2, 0, 0)
	// Be nice and destroy the GL context and the window.
	graphics::set_video_mode(0, 0, CLEANUP_WINDOW_CONTEXT);
#elif defined(USE_GLES2)
	wm.destroy_window();
#endif
	SDL_Quit();
	
	preferences::save_preferences();
	std::cerr << SDL_GetError() << "\n";

#if !defined(_MSC_VER) && defined(UTILITY_IN_PROC)
	if(create_utility_in_new_process) {
		terminate_utility_process();
	}
#endif

#ifdef _MSC_VER
	ExitProcess(0);
#endif

	return 0;
}
Exemplo n.º 24
0
bool gl_initialize(int screen_wid,int screen_high,bool lock_fps_refresh,int fsaa_mode,bool reset,char *err_str)
{
    GLint				ntxtunit,ntxtsize;
#ifdef D3_OS_MAC
    long				swapint,rect[4];
	CGLContextObj		current_ctx;
	CFDictionaryRef		mode_info;
	CFNumberRef			cf_rate;
#else
	GLenum				glew_error;
#endif
		
		// setup rendering sizes
        
	setup.screen.x_sz=screen_wid;
	setup.screen.y_sz=screen_high;
	
		// normal attributes
		
	SDL_GL_SetAttribute(SDL_GL_RED_SIZE,8);
	SDL_GL_SetAttribute(SDL_GL_GREEN_SIZE,8);
	SDL_GL_SetAttribute(SDL_GL_BLUE_SIZE,8);
	SDL_GL_SetAttribute(SDL_GL_ALPHA_SIZE,8);
	SDL_GL_SetAttribute(SDL_GL_DEPTH_SIZE,16);
	SDL_GL_SetAttribute(SDL_GL_STENCIL_SIZE,8);
	SDL_GL_SetAttribute(SDL_GL_DOUBLEBUFFER,1);
	
		// full screen anti-aliasing attributes
		
	switch (fsaa_mode) {
		case fsaa_mode_low:
			SDL_GL_SetAttribute(SDL_GL_MULTISAMPLEBUFFERS,1);
			SDL_GL_SetAttribute(SDL_GL_MULTISAMPLESAMPLES,2);
			break;
		case fsaa_mode_medium:
			SDL_GL_SetAttribute(SDL_GL_MULTISAMPLEBUFFERS,1);
			SDL_GL_SetAttribute(SDL_GL_MULTISAMPLESAMPLES,4);
			break;
		case fsaa_mode_high:
			SDL_GL_SetAttribute(SDL_GL_MULTISAMPLEBUFFERS,1);
			SDL_GL_SetAttribute(SDL_GL_MULTISAMPLESAMPLES,6);
			break;
	}

		// start window or full screen
		
	if (gl_in_window_mode()) {
		surface=SDL_SetVideoMode(setup.screen.x_sz,setup.screen.y_sz,32,SDL_OPENGL|SDL_HWSURFACE);
		SDL_WM_SetCaption("dim3",NULL);
	}
	else {
		surface=SDL_SetVideoMode(setup.screen.x_sz,setup.screen.y_sz,32,SDL_OPENGL|SDL_FULLSCREEN);
	}

	if (surface==NULL) {
		sprintf(err_str,"SDL: Could not set video mode (Error: %s)",SDL_GetError());
		return(FALSE);
	}
	
		// work around the dock losing minimize buttons because
		// of SDL luncancy
		
#ifdef D3_OS_MAC
	if (!gl_in_window_mode()) SetSystemUIMode(kUIModeContentSuppressed,0);
#endif
	
		// use glew on linux and windows
		
#ifndef D3_OS_MAC
	glew_error=glewInit();
	if (glew_error!=GL_NO_ERROR) {
		strcpy(err_str,glewGetErrorString(glew_error));
		return(FALSE);
	}
#endif

		// grab openGL attributes
		
	strncpy(render_info.name,(char*)glGetString(GL_RENDERER),64);
	render_info.name[63]=0x0;
	
	strncpy(render_info.ext_string,(char*)glGetString(GL_EXTENSIONS),8192);
	render_info.ext_string[8191]=0x0;
			
	glGetIntegerv(GL_MAX_TEXTURE_UNITS,&ntxtunit);
	render_info.texture_unit_count=(int)ntxtunit;

	glGetIntegerv(GL_MAX_TEXTURE_SIZE,&ntxtsize);
	render_info.texture_max_size=(int)ntxtsize;

		// in case screen is bigger than desired drawing surface
		
    render_info.monitor_x_sz=surface->w;
	render_info.monitor_y_sz=surface->h;

	render_info.view_x=(render_info.monitor_x_sz-setup.screen.x_sz)>>1;
	render_info.view_y=(render_info.monitor_y_sz-setup.screen.y_sz)>>1;
	
		// determine the referesh rate

	render_info.monitor_refresh_rate=60;				// windows XP has a stuck refresh rate of 60
		
#ifdef D3_OS_MAC
	mode_info=CGDisplayCurrentMode(CGMainDisplayID());
	if (mode_info!=NULL) {
		cf_rate=(CFNumberRef)CFDictionaryGetValue(mode_info,kCGDisplayRefreshRate);
		if (cf_rate) {
			CFNumberGetValue(cf_rate,kCFNumberIntType,&render_info.monitor_refresh_rate);
			if (render_info.monitor_refresh_rate==0) render_info.monitor_refresh_rate=60;
		}
	}
#endif

        // clear the entire window so it doesn't flash
        
	glClearColor(0,0,0,0);
	glClear(GL_COLOR_BUFFER_BIT);
   
	SDL_GL_SwapBuffers();

        // setup renderer

#ifdef D3_OS_MAC
	current_ctx=CGLGetCurrentContext();
	
	rect[0]=render_info.view_x;
	rect[1]=render_info.view_y;
	rect[2]=setup.screen.x_sz;
	rect[3]=setup.screen.y_sz;
 
 	CGLSetParameter(current_ctx,kCGLCPSwapRectangle,rect);
	CGLEnable(current_ctx,kCGLCESwapRectangle);

	if (lock_fps_refresh) {
		swapint=1;
		CGLSetParameter(current_ctx,kCGLCPSwapInterval,&swapint);
	}
#endif

	glViewport(render_info.view_x,render_info.view_y,setup.screen.x_sz,setup.screen.y_sz);
	
		// perspective correction
		
	glHint(GL_PERSPECTIVE_CORRECTION_HINT,GL_NICEST);
		
		// smoothing and anti-aliasing
		
	glDisable(GL_DITHER);
	
	glEnable(GL_LINE_SMOOTH);
	glHint(GL_LINE_SMOOTH_HINT,GL_NICEST);
	
	if (fsaa_mode!=fsaa_mode_none) glEnable(GL_MULTISAMPLE);
	
		// texture compression
		
	glHint(GL_TEXTURE_COMPRESSION_HINT,GL_NICEST);
	glHint(GL_GENERATE_MIPMAP_HINT,GL_NICEST);
	
		// all alphas by 8 bit component
		
	glDisable(GL_ALPHA_TEST);

		// texture utility initialize
		
	gl_texture_initialize();
	
		// do an initial draw
		
	if (!reset) {
		glClearColor(0,0,0,0);
		glClear(GL_COLOR_BUFFER_BIT);
		
		SDL_GL_SwapBuffers();
	}
	
	return(TRUE);
}
Exemplo n.º 25
0
 inline void createContext(CLcontext& c){
     cl_int err = CL_SUCCESS;
     err |= clGetPlatformIDs(1, &c.platform, NULL);
     if(err != CL_SUCCESS){
         THROW_EXCEPTION("Failed to find platform ID");
     }
     
     err |= clGetDeviceIDs(c.platform, CL_DEVICE_TYPE_GPU, 1, &c.device, NULL);
     if(c.device == NULL){
         err &= clGetDeviceIDs(c.platform, CL_DEVICE_TYPE_CPU, 1, &c.device, NULL);
     }
     if(err != CL_SUCCESS){
         THROW_EXCEPTION("Failed to find device ID");
     }
     
     // Create the properties for this context.
     cl_context_properties prop[] = {
         // We need to add information about the OpenGL context with
         // which we want to exchange information with the OpenCL context
         CL_CONTEXT_PROPERTY_USE_CGL_SHAREGROUP_APPLE , (cl_context_properties) CGLGetShareGroup(CGLGetCurrentContext()) ,
         CL_CONTEXT_PLATFORM , (cl_context_properties) c.platform ,
         0 , 0 ,
     };
     
     c.context   = clCreateContext(prop, 1, &c.device, NULL, NULL, &err);
     if(err != CL_SUCCESS){
         THROW_EXCEPTION("Failed to create context");
     }
     
     c.queue     = clCreateCommandQueue(c.context, c.device, NULL, &err);
     if(err != CL_SUCCESS){
         THROW_EXCEPTION("Failed to initialize command queue");
     }
 }
Exemplo n.º 26
0
void OpenCLKernel::initialize()
{
	string sourceString;
	const char *sourceCString;
	cl_platform_id *platform_ids, platform_id = NULL;
	cl_device_id *device_ids, device_id = NULL;
	cl_uint ret_num_devices;
	cl_uint ret_num_platforms;
	cl_uint extensions_size;
	char* extensions;
	bool deviceSelected = false;

	/* Load the source code containing the kernel*/
	sourceString = getFileContents(fileName);
	sourceCString = sourceString.c_str();

	//Wait until all opengl commands are processed
	glFinish();

	/* Get Platform and Device Info */
	status = clGetPlatformIDs( 0, NULL, &ret_num_platforms);
	if (status != CL_SUCCESS)
		return;

	platform_ids = new cl_platform_id[ret_num_platforms];
	status = clGetPlatformIDs(ret_num_platforms, platform_ids, &ret_num_platforms);
	if (status != CL_SUCCESS)
		return;

	for(cl_uint i = 0; i < ret_num_platforms && !deviceSelected; i++)
	{
		platform_id = platform_ids[i];

		/* Get GPU type devices */
		status = clGetDeviceIDs( platform_id, CL_DEVICE_TYPE_GPU, 0, NULL, &ret_num_devices);
		device_ids = new cl_device_id[ret_num_devices];
		status = clGetDeviceIDs(platform_id, CL_DEVICE_TYPE_GPU, ret_num_devices, device_ids, NULL);

		for(cl_uint j = 0; j < ret_num_devices && !deviceSelected; j++)
		{
			device_id = device_ids[j];

			/* Look for device with CL_GL_SHARING_EXT extension */
			status = clGetDeviceInfo( device_id, CL_DEVICE_EXTENSIONS, 0, NULL, &extensions_size);
			extensions = new char[extensions_size];
			status = clGetDeviceInfo( device_id, CL_DEVICE_EXTENSIONS, extensions_size, extensions, NULL);

			string ext = extensions;   
			deviceSelected = ext.find(CL_GL_SHARING_EXT) != string::npos;
			delete[] extensions;
		}

		delete[] device_ids;
	}

	delete[] platform_ids;

// Apple use share group
#ifdef __APPLE__
	// Get current CGL Context and CGL Share group
	CGLContextObj kCGLContext = CGLGetCurrentContext();
	CGLShareGroupObj kCGLShareGroup = CGLGetShareGroup(kCGLContext);
#endif

	// Create CL context properties
	cl_context_properties properties[] = 
	{
//Windows properties
#if defined(WIN32) || defined(WIN64)
		CL_GL_CONTEXT_KHR, (cl_context_properties) wglGetCurrentContext(), // WGL Context
		CL_WGL_HDC_KHR, (cl_context_properties) wglGetCurrentDC(), // WGL HDC
		CL_CONTEXT_PLATFORM, (cl_context_properties) platform_id, // OpenCL platform
//Apple properties
#elif __APPLE__
		CL_CONTEXT_PROPERTY_USE_CGL_SHAREGROUP_APPLE,
		(cl_context_properties) kCGLShareGroup,
//Other unix properties 
#elif __unix
		CL_GL_CONTEXT_KHR, (cl_context_properties) glXGetCurrentContext(), // GLX Context
		CL_GLX_DISPLAY_KHR, (cl_context_properties) glXGetCurrentDisplay(), // GLX Display
		CL_CONTEXT_PLATFORM, (cl_context_properties) platform_id, // OpenCL platform
#endif
		0
	};

#ifdef __APPLE__
	// Create a context with device in the CGL share group
	context = clCreateContext(properties, 0, 0, NULL, 0, 0);
#else
	/* Create OpenCL context */
	context = clCreateContext(properties, 1, &device_id, NULL, NULL, &status);
#endif

	/* Create Command Queue */
	command_queue = clCreateCommandQueue(context, device_id, 0, &status);

	/* Create Kernel Program from the source */
	program = clCreateProgramWithSource(context, 1, &sourceCString,
		NULL, &status);

	/* Build Kernel Program */
	status = clBuildProgram(program, 1, &device_id, NULL, NULL, NULL);

	/* Create OpenCL Kernel */
	kernel = clCreateKernel(program, kernelName.c_str(), &status);
}
Exemplo n.º 27
0
NS_IMETHODIMP
nsCanvasRenderingContextGLPrivate::Render(gfxContext *ctx, gfxPattern::GraphicsFilter f)
{
    nsresult rv = NS_OK;

    if (!mGLPbuffer)
        return NS_OK;

    // use GL Drawing if we can get a target GL context; otherwise
    // go through the fallback path.
#ifdef HAVE_GL_DRAWING
    if (mCanvasElement->GLWidgetBeginDrawing()) {
        glClearColor(0.0, 0.0, 0.0, 0.0);
        glClear(GL_COLOR_BUFFER_BIT);

        int bwidth = mGLPbuffer->Width();
        int bheight = mGLPbuffer->Height();

        GLuint tex = 0;
        glGenTextures(1, &tex);
        glBindTexture(GL_TEXTURE_RECTANGLE_EXT, tex);

        CGLError err =
            CGLTexImagePBuffer(CGLGetCurrentContext(),
                               ((nsGLPbufferCGL*)mGLPbuffer)->GetCGLPbuffer(),
                               GL_BACK);
        if (err) {
            fprintf (stderr, "CGLTexImagePBuffer failed: %d\n", err);
            glDeleteTextures(1, &tex);
            return NS_OK;
        }

        glEnable(GL_TEXTURE_RECTANGLE_EXT);

        glMatrixMode(GL_PROJECTION);
        glLoadIdentity();
        //glFrustum(-halfWidth, halfWidth, halfHeight, -halfHeight, 1.0, 100000.0);
        glOrtho(0, bwidth, bheight, 0, -0.5, 10.0);

        glMatrixMode(GL_MODELVIEW);
        glLoadIdentity();

        glBegin(GL_QUADS);

        /* Note that the texture needs a y-flip */
        glTexCoord2f(0.0, bheight);
        glVertex3f(0.0, 0.0, 0.0);

        glTexCoord2f(bwidth, bheight);
        glVertex3f(bwidth, 0.0, 0.0);

        glTexCoord2f(bwidth, 0);
        glVertex3f(bwidth, bheight, 0.0);

        glTexCoord2f(0.0, 0);
        glVertex3f(0.0, bheight, 0.0);

        glEnd();

        glDisable(GL_TEXTURE_RECTANGLE_EXT);
        glDeleteTextures(1, &tex);

        mCanvasElement->GLWidgetSwapBuffers();
        mCanvasElement->GLWidgetEndDrawing();
    } else
#endif
    {
        nsRefPtr<gfxASurface> surf = mGLPbuffer->ThebesSurface();
        if (!surf)
            return NS_OK;

        nsRefPtr<gfxPattern> pat = CanvasGLThebes::CreatePattern(surf);
        gfxMatrix m;
        m.Translate(gfxPoint(0.0, mGLPbuffer->Height()));
        m.Scale(1.0, -1.0);
        pat->SetMatrix(m);

        // XXX I don't want to use PixelSnapped here, but layout doesn't guarantee
        // pixel alignment for this stuff!
        ctx->NewPath();
        ctx->PixelSnappedRectangleAndSetPattern(gfxRect(0, 0, mWidth, mHeight), pat);
        ctx->Fill();
    }
    return rv;
}
Exemplo n.º 28
0
void CheckOpenGLCaps (CGDisplayCount maxDspys, 
                      GLCaps dCaps[], 
                      CGDisplayCount * dCnt)
{
  CGLContextObj curr_ctx = 0;
  CGDirectDisplayID dspys[32];
  CGDisplayErr theErr;
  short i;
  short size = sizeof (GLCaps);
  
  // no devices
  *dCnt = 0;
  
  if (maxDspys == 0) { // find number of displays
    *dCnt = 0;
    theErr = CGGetActiveDisplayList (32, dspys, dCnt);
    if (theErr) // theErr getting list
      *dCnt = 0; // 0 displays since can't correctly find any
    // zero list to ensure the routines are used correctly
    memset (dspys, 0, sizeof (CGDirectDisplayID) * *dCnt);
    return; // return dCnt
  }
  if (NULL == dCaps) return;

  theErr = CGGetActiveDisplayList(maxDspys, dspys, dCnt);
  if (theErr) return; // theErr getting list
  if (0 == *dCnt) return; // no displays
  
  memset (dCaps, 0, size * *dCnt); // zero memory
  
  for (i = 0; i < *dCnt; i++) {
    // get device ids
    dCaps[i].cgDisplayID = dspys[i];
    dCaps[i].cglDisplayMask = CGDisplayIDToOpenGLDisplayMask(dspys[i]);
    
    { // get current geometry
      CGRect displayRect = CGDisplayBounds (dspys[i]);
      // get mode dictionary
      CFDictionaryRef dispMode = CGDisplayCurrentMode (dspys[i]); 
      dCaps[i].deviceWidth = (long) displayRect.size.width;   
      dCaps[i].deviceHeight = (long) displayRect.size.height;   
      dCaps[i].deviceOriginX = (long) displayRect.origin.x;   
      dCaps[i].deviceOriginY = (long) displayRect.origin.y;   
      dCaps[i].deviceDepth = (short) _getDictLong (dispMode,  
                                              kCGDisplayBitsPerPixel);    
      dCaps[i].deviceRefresh = (short) (_getDictDouble (dispMode,
                                        kCGDisplayRefreshRate) + 0.5); 
    }    

    { // get renderer info based on gDevice
      CGLRendererInfoObj info;
      long j, numRenderers = 0, rv = 0;
      CGLError theErr2 = 0;
      
      theErr2 = CGLQueryRendererInfo (dCaps[i].cglDisplayMask, 
                                  &info, 
                                  &numRenderers);
      if(0 == theErr2) {
        CGLDescribeRenderer (info, 0, kCGLRPRendererCount, &numRenderers);
        for (j = 0; j < numRenderers; j++) {
          // find accelerated renderer (assume only one)
          CGLDescribeRenderer (info, j, kCGLRPAccelerated, &rv); 
          if (true == rv) { // if accelerated
            // what is the renderer ID
            CGLDescribeRenderer (info, j, kCGLRPRendererID,
                                 &dCaps[i].rendererID);
            // can we do full screen?
            CGLDescribeRenderer (info, j, kCGLRPFullScreen, &rv); 
            dCaps[i].fullScreenCapable = (bool) rv;
            // what is the VRAM?
            CGLDescribeRenderer (info, j, kCGLRPVideoMemory,
                                 &dCaps[i].deviceVRAM);
            // what is the current texture memory? 
            CGLDescribeRenderer (info, j, kCGLRPTextureMemory,
                                 &dCaps[i].deviceTextureRAM);
            break; // done
          }
        }
      }
      CGLDestroyRendererInfo (info);
    }

    { // build context and context specific info
      CGLPixelFormatAttribute attribs[] = { kCGLPFADisplayMask,
                                            dCaps[i].cglDisplayMask, 
                                            (CGLPixelFormatAttribute)0 };
      CGLPixelFormatObj pixelFormat = NULL;
      long numPixelFormats = 0;
      CGLContextObj cglContext;
      
      curr_ctx = CGLGetCurrentContext (); // get current CGL context
      CGLChoosePixelFormat (attribs, &pixelFormat, &numPixelFormats);
      if (pixelFormat) {
        CGLCreateContext(pixelFormat, NULL, &cglContext);
        CGLDestroyPixelFormat (pixelFormat);
        CGLSetCurrentContext (cglContext);
        if (cglContext) {
          const GLubyte * strExt;
          const GLubyte * strRend;
          const GLubyte * strVers;
          const GLubyte * strVend;

          // get renderer strings
          strRend = glGetString (GL_RENDERER);
          strncpy (dCaps[i].strRendererName, (char *) strRend, 255);
          strVend = glGetString (GL_VENDOR);
          strncpy (dCaps[i].strRendererVendor, (char *) strVend, 255);
          strVers = glGetString (GL_VERSION);
          strncpy (dCaps[i].strRendererVersion, (char *) strVers, 255);
          { // get BCD version
            short j = 0;
            short shiftVal = 8;
            while (((strVers[j] <= '9') && (strVers[j] >= '0')) ||
                                            (strVers[j] == '.')) { 
            // get only basic version info (until first non-digit or non-.)
              if ((strVers[j] <= '9') && (strVers[j] >= '0')) {
                dCaps[i].glVersion += (strVers[j] - '0') << shiftVal;
                shiftVal -= 4;
              }
              j++;
            }
          }
          strExt = glGetString (GL_EXTENSIONS);

          // get caps
          glGetIntegerv (GL_MAX_TEXTURE_UNITS, 
                         &dCaps[i].textureUnits);
          glGetIntegerv (GL_MAX_TEXTURE_SIZE,
                         &dCaps[i].maxTextureSize); 
          glGetIntegerv (GL_MAX_3D_TEXTURE_SIZE, 
                         &dCaps[i].max3DTextureSize);
          glGetIntegerv (GL_MAX_CUBE_MAP_TEXTURE_SIZE, 
                         &dCaps[i].maxCubeMapTextureSize);

          // get functionality info
		  dCaps[i].fSpecularVector = 
			  gluCheckExtension ((const GLubyte *) "GL_APPLE_specular_vector", strExt);
          dCaps[i].fTransformHint = 
			  gluCheckExtension ((const GLubyte *) "GL_APPLE_transform_hint", strExt);
          dCaps[i].fPackedPixels = 
			  gluCheckExtension ((const GLubyte *) "GL_APPLE_packed_pixels", strExt) || 
			  gluCheckExtension ((const GLubyte *) "GL_APPLE_packed_pixel", strExt)  || 
			  (dCaps[i].glVersion >= 0x0120);
          dCaps[i].fClientStorage = 
			  gluCheckExtension ((const GLubyte *) "GL_APPLE_client_storage", strExt);
          dCaps[i].fYCbCr = 
			  gluCheckExtension ((const GLubyte *) "GL_APPLE_ycbcr_422", strExt);
          dCaps[i].fTextureRange = 
			  gluCheckExtension ((const GLubyte *) "GL_APPLE_texture_range", strExt);
          dCaps[i].fFence = 
			  gluCheckExtension ((const GLubyte *) "GL_APPLE_fence", strExt);
          dCaps[i].fVAR = 
			  gluCheckExtension ((const GLubyte *) "GL_APPLE_vertex_array_range", strExt);
          dCaps[i].fVAO = 
			  gluCheckExtension ((const GLubyte *) "GL_APPLE_vertex_array_object", strExt);
          dCaps[i].fElementArray = 
			  gluCheckExtension ((const GLubyte *) "GL_APPLE_element_array", strExt);
          dCaps[i].fVPEvals = 
			  gluCheckExtension ((const GLubyte *) "GL_APPLE_vertex_program_evaluators",strExt);
          dCaps[i].fFloatPixels = 
			  gluCheckExtension ((const GLubyte *) "GL_APPLE_float_pixels", strExt);
          dCaps[i].fFlushRenderer = 
			  gluCheckExtension ((const GLubyte *) "GL_APPLE_flush_render", strExt);
          dCaps[i].fPixelBuffer = 
			  gluCheckExtension ((const GLubyte *) "GL_APPLE_pixel_buffer", strExt);
          dCaps[i].fImaging = 
			  gluCheckExtension ((const GLubyte *) "GL_ARB_imaging", strExt);
          dCaps[i].fTransposeMatrix = 
			  gluCheckExtension ((const GLubyte *) "GL_ARB_transpose_matrix", strExt) ||
			  (dCaps[i].glVersion >= 0x0130);
          dCaps[i].fMultitexture = 
			  gluCheckExtension ((const GLubyte *) "GL_ARB_multitexture", strExt) ||
			  (dCaps[i].glVersion >= 0x0130);
          dCaps[i].fTexEnvAdd = 
			  gluCheckExtension ((const GLubyte *) "GL_ARB_texture_env_add", strExt) ||
			  gluCheckExtension ((const GLubyte *) "GL_EXT_texture_env_add", strExt) ||
			  (dCaps[i].glVersion >= 0x0130);
          dCaps[i].fTexEnvCombine = 
			  gluCheckExtension ((const GLubyte *) "GL_ARB_texture_env_combine", strExt) ||
			  (dCaps[i].glVersion >= 0x0130);
          dCaps[i].fTexEnvDot3 = 
			  gluCheckExtension ((const GLubyte *) "GL_ARB_texture_env_dot3", strExt) ||
			  (dCaps[i].glVersion >= 0x0130);
          dCaps[i].fTexEnvCrossbar = 
			  gluCheckExtension ((const GLubyte *) "GL_ARB_texture_env_crossbar", strExt) ||
			  (dCaps[i].glVersion >= 0x0140);
          dCaps[i].fTexCubeMap = 
			  gluCheckExtension ((const GLubyte *) "GL_ARB_texture_cube_map", strExt) ||
			  (dCaps[i].glVersion >= 0x0130);
          dCaps[i].fTexCompress = 
			  gluCheckExtension ((const GLubyte *) "GL_ARB_texture_compression", strExt) ||
			  (dCaps[i].glVersion >= 0x0130);
          dCaps[i].fMultisample = 
			  gluCheckExtension ((const GLubyte *) "GL_ARB_multisample", strExt) ||
			  (dCaps[i].glVersion >= 0x0130);
          dCaps[i].fTexBorderClamp = 
			  gluCheckExtension ((const GLubyte *) "GL_ARB_texture_border_clamp", strExt) ||
			  (dCaps[i].glVersion >= 0x0130);
          dCaps[i].fPointParam = 
			  gluCheckExtension ((const GLubyte *) "GL_ARB_point_parameters", strExt) ||
			  (dCaps[i].glVersion >= 0x0140);
          dCaps[i].fVertexProg = 
			  gluCheckExtension ((const GLubyte *) "GL_ARB_vertex_program", strExt);
          dCaps[i].fFragmentProg = 
			  gluCheckExtension ((const GLubyte *) "GL_ARB_fragment_program", strExt);
          dCaps[i].fTexMirrorRepeat = 
			  gluCheckExtension ((const GLubyte *) "GL_ARB_texture_mirrored_repeat", strExt) ||
			  (dCaps[i].glVersion >= 0x0140);
          dCaps[i].fDepthTex = 
			  gluCheckExtension ((const GLubyte *) "GL_ARB_depth_texture", strExt) ||
			  (dCaps[i].glVersion >= 0x0140);
          dCaps[i].fShadow = 
			  gluCheckExtension ((const GLubyte *) "GL_ARB_shadow", strExt) ||
			  (dCaps[i].glVersion >= 0x0140);
          dCaps[i].fShadowAmbient = 
			  gluCheckExtension ((const GLubyte *) "GL_ARB_shadow_ambient", strExt);
          dCaps[i].fVertexBlend = 
			  gluCheckExtension ((const GLubyte *) "GL_ARB_vertex_blend", strExt);
          dCaps[i].fWindowPos = 
			  gluCheckExtension ((const GLubyte *) "GL_ARB_window_pos", strExt) ||
			  (dCaps[i].glVersion >= 0x0140);
          dCaps[i].fTex3D = 
			  gluCheckExtension ((const GLubyte *) "GL_EXT_texture3D", strExt) ||
			  (dCaps[i].glVersion >= 0x0120);
          dCaps[i].fClipVolHint = 
			  gluCheckExtension ((const GLubyte *) "GL_EXT_clip_volume_hint", strExt);
          dCaps[i].fRescaleNorm = 
			  gluCheckExtension ((const GLubyte *) "GL_EXT_rescale_normal", strExt) ||
			  (dCaps[i].glVersion >= 0x0120);
          dCaps[i].fBlendColor = 
			  gluCheckExtension ((const GLubyte *) "GL_EXT_blend_color", strExt) ||
			  gluCheckExtension ((const GLubyte *) "GL_ARB_imaging", strExt);
          dCaps[i].fBlendMinMax = 
			  gluCheckExtension ((const GLubyte *) "GL_EXT_blend_minmax", strExt) ||
			  gluCheckExtension ((const GLubyte *) "GL_ARB_imaging", strExt);
          dCaps[i].fBlendSub = 
			  gluCheckExtension ((const GLubyte *) "GL_EXT_blend_subtract", strExt) ||
			  gluCheckExtension ((const GLubyte *) "GL_ARB_imaging", strExt);
          dCaps[i].fCVA = 
			  gluCheckExtension ((const GLubyte *) "GL_EXT_compiled_vertex_array", strExt);
          dCaps[i].fTexLODBias = 
			  gluCheckExtension ((const GLubyte *) "GL_EXT_texture_lod_bias", strExt) ||
			  (dCaps[i].glVersion >= 0x0140);
          dCaps[i].fABGR = 
			  gluCheckExtension ((const GLubyte *) "GL_EXT_abgr", strExt);
          dCaps[i].fBGRA = 
			  gluCheckExtension ((const GLubyte *) "GL_EXT_bgra", strExt) ||
			  (dCaps[i].glVersion >= 0x0120);
          dCaps[i].fTexFilterAniso = 
			  gluCheckExtension ((const GLubyte *) "GL_EXT_texture_filter_anisotropic",strExt);
          dCaps[i].fPaletteTex = 
			  gluCheckExtension ((const GLubyte *) "GL_EXT_paletted_texture", strExt);
          dCaps[i].fShareTexPalette = 
			  gluCheckExtension ((const GLubyte *) "GL_EXT_shared_texture_palette", strExt);
          dCaps[i].fSecColor = 
			  gluCheckExtension ((const GLubyte *) "GL_EXT_secondary_color", strExt) ||
			  (dCaps[i].glVersion >= 0x0140);
          dCaps[i].fTexCompressS3TC = 
			  gluCheckExtension ((const GLubyte *) "GL_EXT_texture_compression_s3tc", strExt);
          dCaps[i].fTexRect = 
			  gluCheckExtension ((const GLubyte *) "GL_EXT_texture_rectangle", strExt);
          dCaps[i].fFogCoord = 
			  gluCheckExtension ((const GLubyte *) "GL_EXT_fog_coord", strExt);
          dCaps[i].fDrawRangeElements = 
			  gluCheckExtension ((const GLubyte *) "GL_EXT_draw_range_elements", strExt);
          dCaps[i].fStencilWrap = 
			  gluCheckExtension ((const GLubyte *) "GL_EXT_stencil_wrap", strExt) ||
			  (dCaps[i].glVersion >= 0x0140);
          dCaps[i].fBlendFuncSep = 
			  gluCheckExtension ((const GLubyte *) "GL_EXT_blend_func_separate", strExt) ||
			  (dCaps[i].glVersion >= 0x0140);
          dCaps[i].fMultiDrawArrays = 
			  gluCheckExtension ((const GLubyte *) "GL_EXT_multi_draw_arrays", strExt) ||
			  (dCaps[i].glVersion >= 0x0140);
          dCaps[i].fShadowFunc = 
			  gluCheckExtension ((const GLubyte *) "GL_EXT_shadow_funcs", strExt);
          dCaps[i].fStencil2Side = 
			  gluCheckExtension ((const GLubyte *) "GL_EXT_stencil_two_side", strExt) ||
			  (dCaps[i].glVersion >= 0x0140);
          dCaps[i].fColorSubtable = 
			  gluCheckExtension ((const GLubyte *) "GL_EXT_color_subtable", strExt) || 
			  gluCheckExtension ((const GLubyte *) "GL_ARB_imaging", strExt);
          dCaps[i].fConvolution = 
			  gluCheckExtension ((const GLubyte *) "GL_EXT_convolution", strExt) || 
			  gluCheckExtension ((const GLubyte *) "GL_ARB_imaging", strExt);
          dCaps[i].fHistogram = 
			  gluCheckExtension ((const GLubyte *) "GL_EXT_histogram", strExt) || 
			  gluCheckExtension ((const GLubyte *) "GL_ARB_imaging", strExt);
          dCaps[i].fColorTable = 
			  gluCheckExtension ((const GLubyte *) "GL_SGI_color_table", strExt) || 
			  gluCheckExtension ((const GLubyte *) "GL_ARB_imaging", strExt);
          dCaps[i].fColorMatrix = 
			  gluCheckExtension ((const GLubyte *) "GL_SGI_color_matrix", strExt) || 
			  gluCheckExtension ((const GLubyte *) "GL_ARB_imaging", strExt);
          dCaps[i].fTexEdgeClamp = 
			  gluCheckExtension ((const GLubyte *) "GL_SGIS_texture_edge_clamp", strExt) ||
			  (dCaps[i].glVersion >= 0x0120);
          dCaps[i].fGenMipmap = 
			  gluCheckExtension ((const GLubyte *) "GL_SGIS_generate_mipmap", strExt);
          dCaps[i].fTexLOD = 
			  gluCheckExtension ((const GLubyte *) "GL_SGIS_texture_lod", strExt) ||
			  (dCaps[i].glVersion >= 0x0120);
          dCaps[i].fPointCull = 
			  gluCheckExtension ((const GLubyte *) "GL_ATI_point_cull_mode", strExt);
          dCaps[i].fTexMirrorOnce = 
			  gluCheckExtension ((const GLubyte *) "GL_ATI_texture_mirror_once", strExt);
          dCaps[i].fPNtriangles = 
			  gluCheckExtension ((const GLubyte *) "GL_ATI_pn_triangles", strExt) ||
			  gluCheckExtension ((const GLubyte *) "GL_ATIX_pn_triangles", strExt);
          dCaps[i].fTextFragShader = 
			  gluCheckExtension ((const GLubyte *) "GL_ATI_text_fragment_shader", strExt);
          dCaps[i].fATIBlendEqSep = 
			  gluCheckExtension ((const GLubyte *) "GL_ATI_blend_equation_separate", strExt);
          dCaps[i].fBlendWeightMinMax = 
			  gluCheckExtension ((const GLubyte *) "GL_ATI_blend_weighted_minmax", strExt);
          dCaps[i].fCombine3 = 
			  gluCheckExtension ((const GLubyte *) "GL_ATI_texture_env_combine3", strExt);
          dCaps[i].fSepStencil = 
			  gluCheckExtension ((const GLubyte *) "GL_ATI_separate_stencil", strExt);
          dCaps[i].fArrayRevComps4Byte = 
			  gluCheckExtension ((const GLubyte *) "GL_ATI_array_rev_comps_in_4_bytes",strExt);
          dCaps[i].fNVPointSprite = 
			  gluCheckExtension ((const GLubyte *) "GL_NV_point_sprite", strExt);
          dCaps[i].fRegCombiners = 
			  gluCheckExtension ((const GLubyte *) "GL_NV_register_combiners", strExt);
          dCaps[i].fRegCombiners2 = 
			  gluCheckExtension ((const GLubyte *) "GL_NV_register_combiners2", strExt);
          dCaps[i].fTexEnvCombine4 = 
			  gluCheckExtension ((const GLubyte *) "GL_NV_texture_env_combine4", strExt);
          dCaps[i].fBlendSquare = 
			  gluCheckExtension ((const GLubyte *) "GL_NV_blend_square", strExt) ||
			  (dCaps[i].glVersion >= 0x0140);
          dCaps[i].fFogDist = 
			  gluCheckExtension ((const GLubyte *) "GL_NV_fog_distance", strExt);
          dCaps[i].fMultisampleFilterHint = 
			  gluCheckExtension ((const GLubyte *) "GL_NV_multisample_filter_hint", strExt);
          dCaps[i].fTexGenReflect = 
			  gluCheckExtension ((const GLubyte *) "GL_NV_texgen_reflection", strExt);
          dCaps[i].fTexShader = 
			  gluCheckExtension ((const GLubyte *) "GL_NV_texture_shader", strExt);
          dCaps[i].fTexShader2 = 
			  gluCheckExtension ((const GLubyte *) "GL_NV_texture_shader2", strExt);
          dCaps[i].fTexShader3 = 
			  gluCheckExtension ((const GLubyte *) "GL_NV_texture_shader3", strExt);
          dCaps[i].fDepthClamp = 
			  gluCheckExtension ((const GLubyte *) "GL_NV_depth_clamp", strExt);
          dCaps[i].fLightMaxExp = 
			  gluCheckExtension ((const GLubyte *) "GL_NV_light_max_exponent", strExt);
          dCaps[i].fRasterPosClip = 
			  gluCheckExtension ((const GLubyte *) "GL_IBM_rasterpos_clip", strExt);
          dCaps[i].fConvBorderModes = 
			  gluCheckExtension ((const GLubyte *) "GL_HP_convolution_border_modes", strExt) ||
			  gluCheckExtension ((const GLubyte *) "GL_ARB_imaging", strExt);
		  dCaps[i].fAuxDeptStencil =
			  gluCheckExtension ((const GLubyte *) "GL_APPLE_aux_depth_stencil", strExt);
		  dCaps[i].fFlushBufferRange =
			  gluCheckExtension ((const GLubyte *) "GL_APPLE_flush_buffer_range", strExt);
		  dCaps[i].fObjectPurgeable =
			  gluCheckExtension ((const GLubyte *) "GL_APPLE_object_purgeable", strExt);
		  dCaps[i].fDrawBuffers =
			  gluCheckExtension ((const GLubyte *) "GL_ARB_draw_buffers", strExt) ||
			  (dCaps[i].glVersion >= 0x0200);
		  dCaps[i].fFragmentProgShadow =
			  gluCheckExtension ((const GLubyte *) "GL_ARB_fragment_program_shadow", strExt);
		  dCaps[i].fFragmentShader = 
			  gluCheckExtension ((const GLubyte *) "GL_ARB_fragment_shader", strExt) ||
			  (dCaps[i].glVersion >= 0x0200);
		  dCaps[i].fHalfFloatPixel = 
			  gluCheckExtension ((const GLubyte *) "GL_ARB_half_float_pixel", strExt);
		  dCaps[i].fOcclusionQuery = 
			  gluCheckExtension ((const GLubyte *) "GL_ARB_occlusion_query", strExt) ||
			  (dCaps[i].glVersion >= 0x0150);
		  dCaps[i].fPBO = 
			  gluCheckExtension ((const GLubyte *) "GL_ARB_pixel_buffer_object", strExt) ||
			  (dCaps[i].glVersion >= 0x0210);
		  dCaps[i].fPointSprite = 			
			  gluCheckExtension ((const GLubyte *) "GL_ARB_point_sprite", strExt) ||
			  (dCaps[i].glVersion >= 0x0200);
		  dCaps[i].fShaderObjects = 
			  gluCheckExtension ((const GLubyte *) "GL_ARB_shader_objects", strExt) ||
			  (dCaps[i].glVersion >= 0x0200);
		  dCaps[i].fShaderTextureLOD = 
			  gluCheckExtension ((const GLubyte *) "GL_ARB_shader_texture_lod", strExt);
		  dCaps[i].fShadingLanguage100 =
			  gluCheckExtension ((const GLubyte *) "GL_ARB_shading_language_100", strExt) ||
			  (dCaps[i].glVersion >= 0x0200);
		  dCaps[i].fTexFloat =
			  gluCheckExtension ((const GLubyte *) "GL_ARB_texture_float", strExt);
		  dCaps[i].fTexNPOT = 
			  gluCheckExtension ((const GLubyte *) "GL_ARB_texture_non_power_of_two", strExt) ||
			  (dCaps[i].glVersion >= 0x0200);
		  dCaps[i].fVBO = 
			  gluCheckExtension ((const GLubyte *) "GL_ARB_vertex_buffer_object", strExt) ||
			  (dCaps[i].glVersion >= 0x0150);
		  dCaps[i].fVertexShader = 
			  gluCheckExtension ((const GLubyte *) "GL_ARB_vertex_shader", strExt) ||
			  (dCaps[i].glVersion >= 0x0200);
		  dCaps[i].fTexComp3dc = 
			  gluCheckExtension ((const GLubyte *) "GL_ATI_texture_compression_3dc", strExt);
		  dCaps[i].fTexATIfloat = 
			  gluCheckExtension ((const GLubyte *) "GL_ATI_texture_float", strExt);
		  dCaps[i].fBlendEqSep = 
			  gluCheckExtension ((const GLubyte *) "GL_EXT_blend_equation_separate", strExt) ||
			  (dCaps[i].glVersion >= 0x0200);
		  dCaps[i].fDepthBounds = 
			  gluCheckExtension ((const GLubyte *) "GL_EXT_depth_bounds_test", strExt);
		  dCaps[i].fFBOblit =
			  gluCheckExtension ((const GLubyte *) "GL_EXT_framebuffer_blit", strExt);
		  dCaps[i].fFBO = 
			  gluCheckExtension ((const GLubyte *) "GL_EXT_framebuffer_object", strExt);
		  dCaps[i].fGeometryShader4 = 
			  gluCheckExtension ((const GLubyte *) "GL_EXT_geometry_shader4", strExt);
		  dCaps[i].fGPUProgParams = 
			  gluCheckExtension ((const GLubyte *) "GL_EXT_gpu_program_parameters", strExt);
		  dCaps[i].fGPUShader4 = 
			  gluCheckExtension ((const GLubyte *) "GL_EXT_gpu_shader4", strExt);
		  dCaps[i].fDepthStencil = 
			  gluCheckExtension ((const GLubyte *) "GL_EXT_packed_depth_stencil", strExt);
		  dCaps[i].fSepSpecColor = 
			  gluCheckExtension ((const GLubyte *) "GL_EXT_separate_specular_color", strExt) ||
			  (dCaps[i].glVersion >= 0x0120);
		  dCaps[i].fTexCompDXT1 =
			  gluCheckExtension ((const GLubyte *) "GL_EXT_texture_compression_dxt1", strExt);
		  dCaps[i].fTexMirrorClamp = 
			  gluCheckExtension ((const GLubyte *) "GL_EXT_texture_mirror_clamp", strExt);
		  dCaps[i].fTexSRGB = 
			  gluCheckExtension ((const GLubyte *) "GL_EXT_texture_sRGB", strExt) ||
			  (dCaps[i].glVersion >= 0x0210);		  
		  
		  if (dCaps[i].fTexRect) // only check if extension supported
				glGetIntegerv (GL_MAX_RECTANGLE_TEXTURE_SIZE_EXT,
							   &dCaps[i].maxRectTextureSize);
			else
				dCaps[i].maxRectTextureSize = 0;
			
          CGLDestroyContext (cglContext);
        }
      }
      CGLSetCurrentContext (curr_ctx); // reset current CGL context
    }
  }
}
Exemplo n.º 29
0
static bool
getDrawableBounds(GLint *width, GLint *height) {
#if defined(_WIN32)

    HDC hDC = wglGetCurrentDC();
    if (!hDC) {
        return false;
    }

    HWND hWnd = WindowFromDC(hDC);
    RECT rect;

    if (!GetClientRect(hWnd, &rect)) {
       return false;
    }

    *width  = rect.right  - rect.left;
    *height = rect.bottom - rect.top;

#elif defined(__APPLE__)

    CGLContextObj ctx = CGLGetCurrentContext();
    if (ctx == NULL) {
        return false;
    }

    CGSConnectionID cid;
    CGSWindowID wid;
    CGSSurfaceID sid;

    if (CGLGetSurface(ctx, &cid, &wid, &sid) != kCGLNoError) {
        return false;
    }

    CGRect rect;

    if (CGSGetSurfaceBounds(cid, wid, sid, &rect) != 0) {
        return false;
    }

    *width = rect.size.width;
    *height = rect.size.height;

#else

    Display *display;
    Drawable drawable;
    Window root;
    int x, y;
    unsigned int w, h, bw, depth;

    display = glXGetCurrentDisplay();
    if (!display) {
        return false;
    }

    drawable = glXGetCurrentDrawable();
    if (drawable == None) {
        return false;
    }

    if (!XGetGeometry(display, drawable, &root, &x, &y, &w, &h, &bw, &depth)) {
        return false;
    }

    *width = w;
    *height = h;

#endif

    return true;
}
Exemplo n.º 30
0
ITunesPixelFormat ivis_render( ITunesVis* plugin, short audio_data[][512], float freq_data[][512],
                               void* buffer, long buffer_size, bool idle )
{
  ITunesPixelFormat format = ITunesPixelFormatUnknown;

  /* make sure we have a plugin and a visual handler */
  if ( !plugin || !plugin->imports.visual_handler )
    return format;

  int i=0, w=0;
  RenderVisualData visual_data;
  DSPSplitComplex splitComplex[2];
  float *data[2];

  /* perform FFT if we're not idling */
  if ( ! idle )
  {
    /* allocate some complex vars */
    for ( i = 0 ; i < 2 ; i++ )
    {
      splitComplex[i].realp = calloc( 512, sizeof(float) );
      splitComplex[i].imagp = calloc( 512, sizeof(float) );
      data[i] = calloc( 512, sizeof(float) );
    }

    /* 2 channels for spectrum and waveform data */
    visual_data.numWaveformChannels = 2;
    visual_data.numSpectrumChannels = 2;

    /* copy spectrum audio data to visual data strucure */
    for ( w = 0 ; w < 512 ; w++ )
    {
      /* iTunes visualizers expect waveform data from 0 - 255, with level 0 at 128 */
      visual_data.waveformData[0][w] = (UInt8)( (long)(audio_data[0][w]) / 128 + 128 );
      visual_data.waveformData[1][w] = (UInt8)( (long)(audio_data[1][w]) / 128 + 128 );

      /* scale to -1, +1 */
      *( data[0] + w ) = (float)(( audio_data[0][w]) / (2.0 * 8192.0) );
      *( data[1] + w ) = (float)(( audio_data[1][w]) / (2.0 * 8192.0) );
    }

    /* FFT scaler */
    float scale = ( 1.0 / 1024.0 ) ; /* scale by length of input * 2 (due to how vDSP does FFTs) */
    float nyq=0, dc=0, freq=0;

    for ( i = 0 ; i < 2 ; i++ )
    {
      /* pack data into format fft_zrip expects it */
      vDSP_ctoz( (COMPLEX*)( data[i] ), 2, &( splitComplex[i] ), 1, 256 );

      /* perform FFT on normalized audio data */
      fft_zrip( plugin->fft_setup, &( splitComplex[i] ), 1, 9, FFT_FORWARD );

      /* scale the values */
      vDSP_vsmul( splitComplex[i].realp, 1, &scale, splitComplex[i].realp, 1, 256 );
      vDSP_vsmul( splitComplex[i].imagp, 1, &scale, splitComplex[i].imagp, 1, 256 );

      /* unpack data */
      vDSP_ztoc( &splitComplex[i], 1, (COMPLEX*)( data[i] ), 2, 256 );

      /* ignore phase */
      dc = *(data[i]) = fabs( *(data[i]) );
      nyq = fabs( *(data[i] + 1) );

      for ( w = 1 ; w < 256 ; w++ )
      {
        /* don't use vDSP for this since there's some overflow */
        freq = hypot( *(data[i] + w * 2), *(data[i] + w * 2 + 1) ) * 256 * 16;
        freq = MAX( 0, freq );
        freq = MIN( 255, freq );
        visual_data.spectrumData[i][ w - 1 ] = (UInt8)( freq );
      }
      visual_data.spectrumData[i][256] = nyq;
    }

    /* deallocate complex vars */
    for ( i = 0 ; i < 2 ; i++ )
    {
      free( splitComplex[i].realp );
      free( splitComplex[i].imagp );
      free( data[i] );
    }

    /* update the render message with the new visual data and timestamp */
    plugin->visual_message.u.renderMessage.renderData = &visual_data;
    plugin->visual_message.u.renderMessage.timeStampID++;
  }

  /* update time */
  plugin->visual_message.u.renderMessage.currentPositionInMS =
    ivis_current_time() - plugin->start_time; // FIXME: real time

  /* save our GL context and send the vis a render message */
  CGLContextObj currentContext = CGLGetCurrentContext();
  if ( plugin->gl_context )
    aglSetCurrentContext( (AGLContext)(plugin->gl_context ) );

  /* call the plugin's render method */
  if ( idle )
  {
    /* idle message */
    if ( plugin->wants_idle )
      plugin->imports.visual_handler( kVisualPluginIdleMessage,
                                      &( plugin->visual_message ),
                                      plugin->vis_ref );
  }
  else
  {
    /* render message */
    plugin->imports.visual_handler( kVisualPluginRenderMessage,
                                    &( plugin->visual_message ),
                                    plugin->vis_ref );

    /* set position message */
    plugin->visual_message.u.setPositionMessage.positionTimeInMS
      = plugin->visual_message.u.renderMessage.currentPositionInMS;
    plugin->imports.visual_handler( kVisualPluginSetPositionMessage, &( plugin->visual_message ),
                                    plugin->vis_ref );
  }
  /* update message */
  plugin->imports.visual_handler( kVisualPluginUpdateMessage, NULL,
                                  plugin->vis_ref );

  /* read pixels and restore our GL context */
  CGLLockContext( CGLGetCurrentContext() );

  switch ( get_pixels( buffer, buffer_size, CGLGetCurrentContext() != currentContext ) )
  {
  case 3:
    format = ITunesPixelFormatRGB24;
    break;

  case 4:
    format = ITunesPixelFormatRGBA32;
    break;

  default:
    break;
  }

  CGLUnlockContext ( CGLGetCurrentContext() );

  /* restore our GL context */
  CGLSetCurrentContext( currentContext );
  return format;
}