コード例 #1
0
static INLINE boolean
st_hardpipe_load(void)
{
   Display *dpy;
   int scrnum;
   Window root;
   int attribSingle[] = {
      GLX_RGBA,
      GLX_RED_SIZE, 1,
      GLX_GREEN_SIZE, 1,
      GLX_BLUE_SIZE, 1,
      None };
   int attribDouble[] = {
      GLX_RGBA,
      GLX_RED_SIZE, 1,
      GLX_GREEN_SIZE, 1,
      GLX_BLUE_SIZE, 1,
      GLX_DOUBLEBUFFER,
      None };
   XVisualInfo *visinfo;
   GLXContext ctx = NULL;
   XSetWindowAttributes attr;
   unsigned long mask;
   int width = 100, height = 100;
   Window win;

   dpy = XOpenDisplay(NULL);
   if (!dpy)
      return FALSE;

   scrnum = 0;
   
   root = RootWindow(dpy, scrnum);

   visinfo = glXChooseVisual(dpy, scrnum, attribSingle);
   if (!visinfo)
      visinfo = glXChooseVisual(dpy, scrnum, attribDouble);
   if (!visinfo)
      return FALSE;
      
   ctx = glXCreateContext( dpy, visinfo, NULL, True );

   if (!ctx)
      return FALSE;

   attr.background_pixel = 0;
   attr.border_pixel = 0;
   attr.colormap = XCreateColormap(dpy, root, visinfo->visual, AllocNone);
   attr.event_mask = StructureNotifyMask | ExposureMask;
   
   mask = CWBackPixel | CWBorderPixel | CWColormap | CWEventMask;
   
   win = XCreateWindow(dpy, root, 0, 0, width, height,
                       0, visinfo->depth, InputOutput,
                       visinfo->visual, mask, &attr);

   if (!glXMakeCurrent(dpy, win, ctx))
      return FALSE;

   pfnGetGalliumScreenMESA = (PFNGETGALLIUMSCREENMESAPROC)glXGetProcAddressARB((const GLubyte *)"glXGetGalliumScreenMESA");
   if(!pfnGetGalliumScreenMESA)
      return FALSE;

   pfnCreateGalliumContextMESA = (PFNCREATEGALLIUMCONTEXTMESAPROC)glXGetProcAddressARB((const GLubyte *)"glXCreateGalliumContextMESA");
   if(!pfnCreateGalliumContextMESA)
      return FALSE;

   glXDestroyContext(dpy, ctx);
   XFree(visinfo);
   XDestroyWindow(dpy, win);
   XCloseDisplay(dpy);

   return TRUE;
}
コード例 #2
0
	//-------------------------------------------------------------------------------------------------//
	void* GLXGLSupport::getProcAddress(const String& procname) {
		return (void*)glXGetProcAddressARB((const GLubyte*)procname.c_str());
	}
コード例 #3
0
//------------------------------------------------------------------------------
// eglCreateContext
//------------------------------------------------------------------------------
EGLAPI EGLContext EGLAPIENTRY
eglCreateContext(
	EGLDisplay display,
	EGLConfig config,
	EGLContext egl_share_context,
	const EGLint *egl_attrib_list
)
{
	if(!eglplus_egl_valid_display(display))
	{
		eglplus_egl_SetErrorCode(EGL_BAD_DISPLAY);
		return EGL_NO_CONTEXT;
	}

	if(!display->initialized())
	{
		eglplus_egl_SetErrorCode(EGL_NOT_INITIALIZED);
		return EGL_NO_CONTEXT;
	}

	if(!config._glx_fb_config)
	{
		eglplus_egl_SetErrorCode(EGL_BAD_CONFIG);
		return EGL_NO_CONTEXT;
	}

	if(eglplus_egl_CurrentAPI != EGL_OPENGL_API)
	{
		eglplus_egl_SetErrorCode(EGL_BAD_MATCH);
		return EGL_NO_CONTEXT;
	}

	if(eglplus_egl_glXCreateContextAttribsARB == nullptr)
	{
		eglplus_egl_glXCreateContextAttribsARB = (glXCreateContextAttribsARBProc)
		glXGetProcAddressARB((const unsigned char*)"glXCreateContextAttribsARB");
	}

	if(eglplus_egl_glXCreateContextAttribsARB == nullptr)
	{
		eglplus_egl_SetErrorCode(EGL_BAD_DISPLAY);
		return EGL_NO_CONTEXT;
	}

	::GLXContext glx_share_context = ::GLXContext(0);

	if(egl_share_context != EGL_NO_CONTEXT)
	{
		if(eglplus_egl_valid_context(egl_share_context))
		{
			glx_share_context = egl_share_context->_glx_context;
		}
		else
		{
			eglplus_egl_SetErrorCode(EGL_BAD_CONFIG);
			return EGL_NO_CONTEXT;
		}
	}

	EGLint empty_list = EGL_NONE;
	if(!egl_attrib_list)
	{
		egl_attrib_list = &empty_list;
	}

	int glx_attrib_count = 0;

	if(*egl_attrib_list != EGL_NONE)
	{
		const EGLint* tmp_attrib_list = egl_attrib_list;
		while(*tmp_attrib_list != EGL_NONE)
		{
			bool bad_attrib = false;

			switch(*tmp_attrib_list++)
			{
				case 0x3098: //EGL_CONTEXT_MAJOR_VERSION_KHR
				case 0x30FB: //EGL_CONTEXT_MINOR_VERSION_KHR
					break;
				case 0x30FC: //EGL_CONTEXT_FLAGS_KHR
				{
					if((*tmp_attrib_list & ~0x07) != 0)
					{
						bad_attrib = true;
					}
					break;
				}
				case 0x31BD: //EGL_CONTEXT_OPENGL_RESET_NOTIFICATION_STRATEGY_KHR
				{
					switch(*tmp_attrib_list)
					{
						case 0x31BE:
						case 0x31BF:
							break;
						default: bad_attrib = true;
					}
					break;
				}
				case 0x30FD: //EGL_CONTEXT_OPENGL_PROFILE_MASK_KHR
				{
					if((*tmp_attrib_list & ~0x03) != 0)
					{
						bad_attrib = true;
					}
					break;
				}
				default: bad_attrib = true;
			}

			if(bad_attrib)
			{
				eglplus_egl_SetErrorCode(EGL_BAD_ATTRIBUTE);
				return EGL_NO_CONTEXT;
			}
			++tmp_attrib_list;
			glx_attrib_count += 2;
		}
	}

	std::vector<int> glx_attrib_list(glx_attrib_count+1);
	glx_attrib_count = 0;

	if(*egl_attrib_list != EGL_NONE)
	{
		const EGLint* tmp_attrib_list = egl_attrib_list;
		while(*tmp_attrib_list != EGL_NONE)
		{
			switch(*tmp_attrib_list++)
			{
				case 0x3098: //EGL_CONTEXT_MAJOR_VERSION_KHR
				{
					glx_attrib_list[glx_attrib_count++] =
						//GLX_CONTEXT_MAJOR_VERSION_ARB
						0x2091;
					glx_attrib_list[glx_attrib_count++] =
						int(*tmp_attrib_list++);
					break;
				}
				case 0x30FB: //EGL_CONTEXT_MINOR_VERSION_KHR
				{
					glx_attrib_list[glx_attrib_count++] =
						//GLX_CONTEXT_MINOR_VERSION_ARB
						0x2092;
					glx_attrib_list[glx_attrib_count++] =
						int(*tmp_attrib_list++);
					break;
				}
				case 0x30FC: //EGL_CONTEXT_FLAGS_KHR
				{
					glx_attrib_list[glx_attrib_count++] =
						//GLX_CONTEXT_FLAGS_ARB
						0x2094;
					EGLint egl_flags = *tmp_attrib_list++;
					int glx_flags = 0;

					// EGL_CONTEXT_OPENGL_DEBUG_BIT_KHR
					if((egl_flags & 0x00000001) == 0x00000001)
						glx_flags |= 0x0001;
					// EGL_CONTEXT_OPENGL_FORWARD_COMPATIBLE_BIT_KHR
					if((egl_flags & 0x00000002) == 0x00000002)
						glx_flags |= 0x0002;
					// EGL_CONTEXT_OPENGL_ROBUST_ACCESS_BIT_KHR
					// TODO: currently ignored

					glx_attrib_list[glx_attrib_count++] =
						glx_flags;
					break;
				}
				case 0x31BD: //EGL_CONTEXT_OPENGL_RESET_NOTIFICATION_STRATEGY_KHR
				{
					// TODO: currently ignored
					break;
				}
				case 0x30FD: //EGL_CONTEXT_OPENGL_PROFILE_MASK_KHR
				{
					glx_attrib_list[glx_attrib_count++] =
						//GLX_CONTEXT_PROFILE_MASK_ARB
						0x9126;
					EGLint egl_flags = *tmp_attrib_list++;
					int glx_flags = 0;

					// EGL_CONTEXT_OPENGL_CORE_PROFILE_BIT_KHR
					if((egl_flags & 0x00000001) == 0x00000001)
						glx_flags |= 0x0001;
					// EGL_CONTEXT_OPENGL_COMPATIBILITY_PROFILE_BIT_KHR
					if((egl_flags & 0x00000002) == 0x00000002)
						glx_flags |= 0x0002;

					glx_attrib_list[glx_attrib_count++] =
						glx_flags;
					break;
				}
				default:;
			}
		}
	}
	glx_attrib_list[glx_attrib_count] = None;

	::GLXContext context = eglplus_egl_glXCreateContextAttribsARB(
		display->_x_open_display,
		static_cast< ::GLXFBConfig>(config._glx_fb_config),
		glx_share_context,
		True, // direct rendering
		glx_attrib_list.data()
	);

	if(context == ::GLXContext(0))
	{
		eglplus_egl_SetErrorCode(EGL_BAD_ALLOC);
		return EGL_NO_CONTEXT;
	}

	::XSync(display->_x_open_display, False);

	int empty_surf_attr[] = {
		GLX_PBUFFER_WIDTH, 0,
		GLX_PBUFFER_HEIGHT, 0,
		GLX_PRESERVED_CONTENTS, False,
		None
	};
	::GLXPbuffer empty_surf = ::glXCreatePbuffer(
		display->_x_open_display,
		static_cast< ::GLXFBConfig>(config._glx_fb_config),
		empty_surf_attr
	);

	try { return new eglplus_egl_glx_ContextImpl(context, empty_surf); }
	catch(...)
	{
		eglplus_egl_SetErrorCode(EGL_BAD_ALLOC);
		return EGL_NO_CONTEXT;
	}
}
コード例 #4
0
void (*QOffscreenX11GLXContext::getProcAddress(const QByteArray &procName)) ()
{
    return (void (*)())glXGetProcAddressARB(reinterpret_cast<const GLubyte *>(procName.constData()));
}
コード例 #5
0
VoidExtFunc getFunctionByName(const char* name)
{
   VoidExtFunc found_func(NULL);

   return glXGetProcAddressARB((const GLubyte*)name);
}
コード例 #6
0
ファイル: egl_glx.c プロジェクト: souryogurt/eglproxy
__eglMustCastToProperFunctionPointerType platform_get_proc_address (
    const char *procname)
{
    return (__eglMustCastToProperFunctionPointerType)glXGetProcAddressARB ((
                const GLubyte *)procname);
}
コード例 #7
0
ファイル: glxmain.c プロジェクト: Spudd86/julia-vis
int main(int argc, char **argv)
{
	opt_data opts; optproc(argc, argv, &opts);
	if(audio_init(&opts) < 0) exit(1);
	int x = 0, y = 0, w, h;
	if(opts.w < 0 && opts.h < 0) opts.w = opts.h = 512;
	else if(opts.w < 0) opts.w = opts.h;
	else if(opts.h < 0) opts.h = opts.w;
	w = opts.w; h = opts.h;
	
	XEvent event;
	
	dpy = XOpenDisplay( NULL );
	if(dpy == NULL) {
        printf("Error: couldn't open display %s\n", getenv("DISPLAY"));
        exit(EXIT_FAILURE);
    }
    
    int glx_major, glx_minor;
    if(!glXQueryVersion(dpy, &glx_major, &glx_minor)) {
    	printf("GLX extension missing!\n");
    	XCloseDisplay(dpy);
    	exit(EXIT_FAILURE); 
    }
    printf("GLX version %i.%i\n", glx_major, glx_minor);

    int glxErrBase, glxEventBase;
    glXQueryExtension(dpy, &glxErrBase, &glxEventBase);
    printf("GLX: errorBase = %i, eventBase = %i\n", glxErrBase, glxEventBase);
    
    
    Window xwin, root;
    int numReturned;
    GLXFBConfig *fbConfigs;
    fbConfigs = glXChooseFBConfig( dpy, DefaultScreen(dpy), fbattrib, &numReturned );
    
   	if(fbConfigs == NULL) {  //TODO: handle this?
   		printf("No suitable fbconfigs!\n");
   		exit(EXIT_FAILURE);
   	}
   	
   	XVisualInfo  *vinfo = glXGetVisualFromFBConfig( dpy, fbConfigs[0] );
   	
	root = DefaultRootWindow(dpy);
   	
   	/* window attributes */
   	XSetWindowAttributes attrs;
	attrs.background_pixel = 0;
	attrs.border_pixel = 0;
	attrs.colormap = XCreateColormap(dpy, root, vinfo->visual, AllocNone);
	//attrs.event_mask = StructureNotifyMask | ExposureMask | KeyPressMask;
	attrs.event_mask = StructureNotifyMask | KeyPressMask;
	unsigned long mask = CWBackPixel | CWBorderPixel | CWColormap | CWEventMask;
	xwin = XCreateWindow(dpy, root, x, y, w, h,
		                 0, vinfo->depth, InputOutput,
		                 vinfo->visual, mask, &attrs);
	XFree(vinfo);
	
	// Set hints and properties:
	{
		XSizeHints sizehints;
		sizehints.x = x;
		sizehints.y = y;
		sizehints.width  = w;
		sizehints.height = h;
		sizehints.flags = USSize | USPosition;
		XSetNormalHints(dpy, xwin, &sizehints);
		XSetStandardProperties(dpy, xwin, "Julia-vis", "Julia-vis",
				               None, (char **)NULL, 0, &sizehints);
	}
   	
   	/* Create a GLX context for OpenGL rendering */
    GLXContext context = glXCreateNewContext(dpy, fbConfigs[0], GLX_RGBA_TYPE, NULL, True );
    
#if 0
	GLXContext context = 0;
	
	glXCreateContextAttribsARBProc glXCreateContextAttribsARB = 0;
	glXCreateContextAttribsARB = (glXCreateContextAttribsARBProc)glXGetProcAddressARB( (const GLubyte *) "glXCreateContextAttribsARB" );

	if(strstr(glXQueryExtensionsString(dpy, 0), "GLX_ARB_create_context") || !glXCreateContextAttribsARB) {
		printf("glXCreateContextAttribsARB() not found ... using old-style GLX context\n");
		context = glXCreateNewContext(dpy, fbConfigs[0], GLX_RGBA_TYPE, 0, True);
	} else {
		const int context_attribs[] = {
			GLX_RENDER_TYPE, GLX_RGBA_TYPE,
			GLX_CONTEXT_MAJOR_VERSION_ARB, 2,
			GLX_CONTEXT_MINOR_VERSION_ARB, 1,
			None
		};
		context = glXCreateContextAttribsARB(dpy, fbConfigs[0], NULL, True, context_attribs);
    }
    
    if(context == NULL) {
    	printf("Failed to create context!\n");
    	return EXIT_FAILURE;
    }
#endif
    
    glxWin = glXCreateWindow(dpy, fbConfigs[0], xwin, NULL );
    
    XMapWindow(dpy, xwin);
    XIfEvent(dpy, &event, WaitForNotify, (XPointer) xwin);
    
    glXMakeContextCurrent(dpy, glxWin, glxWin, context);
	
	init_gl(&opts, w, h);
	
	if(strstr(glXQueryExtensionsString(dpy, 0), "GLX_MESA_swap_control")) {
		PFNGLXSWAPINTERVALMESAPROC swap_interval = glXGetProcAddressARB("glXSwapIntervalMESA");
		swap_interval(1);
		opts.draw_rate = 600;
	}
	
	if(strstr(glXQueryExtensionsString(dpy, 0), "GLX_INTEL_swap_event")) {
    	glXSelectEvent(dpy, glxWin, GLX_BUFFER_SWAP_COMPLETE_INTEL_MASK);
    	have_intel_swap_event = GL_TRUE;
    }

	int debug_maxsrc = 0, debug_pal = 0, show_mandel = 0, show_fps_hist = 0;
	
	if(have_intel_swap_event)
		render_frame(debug_maxsrc, debug_pal, show_mandel, show_fps_hist);
	
	while(1) {
		if(!have_intel_swap_event) render_frame(debug_maxsrc, debug_pal, show_mandel, show_fps_hist);
		
		int clear_key = 1;
		while (XPending(dpy) > 0) 
		{
			XNextEvent(dpy, &event);
			
			if(event.type == glxEventBase + GLX_BufferSwapComplete) {
				render_frame(debug_maxsrc, debug_pal, show_mandel, show_fps_hist);
				continue;
			}
			
			switch (event.type) {
				case Expose:
				/* we'll redraw below */
				break;
				/*case ConfigureNotify:
				window_w = event.xconfigure.width;
				window_h = event.xconfigure.height;
				if (surface_type == EGL_WINDOW_BIT)
				reshape(window_w, window_h);
				break;*/
				case KeyPress:
				{
					clear_key = 0;
					char buffer[10];
					int r, code;
					code = XLookupKeysym(&event.xkey, 0);
					if (code == XK_F1) {
						debug_maxsrc = !debug_maxsrc;
					} else if (code == XK_F2) {
						debug_pal = !debug_pal;
					} else if (code == XK_F3) {
						show_mandel = !show_mandel;
					} else if (code == XK_F4) {
						show_fps_hist = !show_fps_hist;
					} else {
						code = XLookupKeysym(&event.xkey, 1);
						if(code == XK_Escape) {
							goto glx_main_loop_quit;
						}
					}
				}
				break;
				
				default:
					//printf("Bar %i!\n", event.type);
					
					break;
			}
		}
	}
glx_main_loop_quit:
	audio_shutdown();
	
	XDestroyWindow(dpy, xwin);
	XCloseDisplay(dpy);
	
	return 0;
}
コード例 #8
0
ファイル: lookup.c プロジェクト: ssvb/glshim
void *glXGetProcAddress(const char *name) {
    return glXGetProcAddressARB(name);
}
コード例 #9
0
ファイル: opengl.cpp プロジェクト: jschwartzenberg/kicker
static void
print_limits(Q3ListViewItem *l1, const char * glExtensions, bool GetProcAddress)
{
 /*  TODO
      GL_SAMPLE_BUFFERS
      GL_SAMPLES
      GL_COMPRESSED_TEXTURE_FORMATS
*/

  if (!glExtensions)
	return;

  struct token_name {
      GLuint type;  // count and flags, !!! count must be <=2 for now
      GLenum token;
      const QString name;
   };

   struct token_group {
   	int count;
	int type;
	const token_name *group;
	const QString descr;
	const char *ext;
   };

   Q3ListViewItem *l2 = NULL, *l3 = NULL;
#if defined(PFNGLGETPROGRAMIVARBPROC)
   PFNGLGETPROGRAMIVARBPROC kcm_glGetProgramivARB = NULL;
#endif

   #define KCMGL_FLOAT 128
   #define KCMGL_PROG 256
   #define KCMGL_COUNT_MASK(x) (x & 127)
   #define KCMGL_SIZE(x) (sizeof(x)/sizeof(x[0]))

   const struct token_name various_limits[] = {
      { 1, GL_MAX_LIGHTS, 		i18n("Max. number of light sources") },
      { 1, GL_MAX_CLIP_PLANES,		i18n("Max. number of clipping planes") },
      { 1, GL_MAX_PIXEL_MAP_TABLE, 	i18n("Max. pixel map table size") },
      { 1, GL_MAX_LIST_NESTING, 	i18n("Max. display list nesting level") },
      { 1, GL_MAX_EVAL_ORDER, 		i18n("Max. evaluator order") },
      { 1, GL_MAX_ELEMENTS_VERTICES, 	i18n("Max. recommended vertex count") },
      { 1, GL_MAX_ELEMENTS_INDICES, 	i18n("Max. recommended index count") },
#ifdef GL_QUERY_COUNTER_BITS
      { 1, GL_QUERY_COUNTER_BITS, 	i18n("Occlusion query counter bits")},
#endif
#ifdef GL_MAX_VERTEX_UNITS_ARB
      { 1, GL_MAX_VERTEX_UNITS_ARB, 	i18n("Max. vertex blend matrices") },
#endif
#ifdef GL_MAX_PALETTE_MATRICES_ARB
      { 1, GL_MAX_PALETTE_MATRICES_ARB, i18n("Max. vertex blend matrix palette size") },
#endif
      {0,0,0}
     };

   const struct token_name texture_limits[] = {
      { 1, GL_MAX_TEXTURE_SIZE, 	i18n("Max. texture size") },
      { 1, GL_MAX_TEXTURE_UNITS_ARB, 	i18n("Num. of texture units") },
      { 1, GL_MAX_3D_TEXTURE_SIZE, 		i18n("Max. 3D texture size") },
      { 1, GL_MAX_CUBE_MAP_TEXTURE_SIZE_ARB, 	i18n("Max. cube map texture size") },
#ifdef GL_MAX_RECTANGLE_TEXTURE_SIZE_NV
      { 1, GL_MAX_RECTANGLE_TEXTURE_SIZE_NV, 	i18n("Max. rectangular texture size") },
#endif
      { 1 | KCMGL_FLOAT, GL_MAX_TEXTURE_LOD_BIAS_EXT, i18n("Max. texture LOD bias") },
      { 1, GL_MAX_TEXTURE_MAX_ANISOTROPY_EXT, 	i18n("Max. anisotropy filtering level") },
      { 1, GL_NUM_COMPRESSED_TEXTURE_FORMATS_ARB, i18n("Num. of compressed texture formats") },
      {0,0,0}
     };

   const struct token_name float_limits[] = {
      { 2 | KCMGL_FLOAT, GL_ALIASED_POINT_SIZE_RANGE, 	"ALIASED_POINT_SIZE_RANGE" },
      { 2 | KCMGL_FLOAT, GL_SMOOTH_POINT_SIZE_RANGE, 	"SMOOTH_POINT_SIZE_RANGE" },
      { 1 | KCMGL_FLOAT, GL_SMOOTH_POINT_SIZE_GRANULARITY,"SMOOTH_POINT_SIZE_GRANULARITY"},
      { 2 | KCMGL_FLOAT, GL_ALIASED_LINE_WIDTH_RANGE, 	"ALIASED_LINE_WIDTH_RANGE" },
      { 2 | KCMGL_FLOAT, GL_SMOOTH_LINE_WIDTH_RANGE, 	"SMOOTH_LINE_WIDTH_RANGE" },
      { 1 | KCMGL_FLOAT, GL_SMOOTH_LINE_WIDTH_GRANULARITY,"SMOOTH_LINE_WIDTH_GRANULARITY"},
      {0,0,0}
     };

   const struct token_name stack_depth[] = {
      { 1, GL_MAX_MODELVIEW_STACK_DEPTH, 	"MAX_MODELVIEW_STACK_DEPTH" },
      { 1, GL_MAX_PROJECTION_STACK_DEPTH, 	"MAX_PROJECTION_STACK_DEPTH" },
      { 1, GL_MAX_TEXTURE_STACK_DEPTH, 		"MAX_TEXTURE_STACK_DEPTH" },
      { 1, GL_MAX_NAME_STACK_DEPTH, 		"MAX_NAME_STACK_DEPTH" },
      { 1, GL_MAX_ATTRIB_STACK_DEPTH, 		"MAX_ATTRIB_STACK_DEPTH" },
      { 1, GL_MAX_CLIENT_ATTRIB_STACK_DEPTH, 	"MAX_CLIENT_ATTRIB_STACK_DEPTH" },
      { 1, GL_MAX_COLOR_MATRIX_STACK_DEPTH, 	"MAX_COLOR_MATRIX_STACK_DEPTH" },
#ifdef GL_MAX_MATRIX_PALETTE_STACK_DEPTH_ARB
      { 1, GL_MAX_MATRIX_PALETTE_STACK_DEPTH_ARB,"MAX_MATRIX_PALETTE_STACK_DEPTH"},
#endif
      {0,0,0}
   };

#ifdef GL_ARB_fragment_program
   const struct token_name arb_fp[] = {
    { 1, GL_MAX_TEXTURE_COORDS_ARB, "MAX_TEXTURE_COORDS" },
    { 1, GL_MAX_TEXTURE_IMAGE_UNITS_ARB, "MAX_TEXTURE_IMAGE_UNITS" },
    { 1 | KCMGL_PROG, GL_MAX_PROGRAM_ENV_PARAMETERS_ARB, "MAX_PROGRAM_ENV_PARAMETERS" },
    { 1 | KCMGL_PROG, GL_MAX_PROGRAM_LOCAL_PARAMETERS_ARB, "MAX_PROGRAM_LOCAL_PARAMETERS" },
    { 1, GL_MAX_PROGRAM_MATRICES_ARB, "MAX_PROGRAM_MATRICES" },
    { 1, GL_MAX_PROGRAM_MATRIX_STACK_DEPTH_ARB, "MAX_PROGRAM_MATRIX_STACK_DEPTH" },
    { 1 | KCMGL_PROG, GL_MAX_PROGRAM_INSTRUCTIONS_ARB, "MAX_PROGRAM_INSTRUCTIONS" },
    { 1 | KCMGL_PROG, GL_MAX_PROGRAM_ALU_INSTRUCTIONS_ARB, "MAX_PROGRAM_ALU_INSTRUCTIONS" },
    { 1 | KCMGL_PROG, GL_MAX_PROGRAM_TEX_INSTRUCTIONS_ARB, "MAX_PROGRAM_TEX_INSTRUCTIONS" },
    { 1 | KCMGL_PROG, GL_MAX_PROGRAM_TEX_INDIRECTIONS_ARB, "MAX_PROGRAM_TEX_INDIRECTIONS" },
    { 1 | KCMGL_PROG, GL_MAX_PROGRAM_TEMPORARIES_ARB, "MAX_PROGRAM_TEMPORARIES" },
    { 1 | KCMGL_PROG, GL_MAX_PROGRAM_PARAMETERS_ARB, "MAX_PROGRAM_PARAMETERS" },
    { 1 | KCMGL_PROG, GL_MAX_PROGRAM_ATTRIBS_ARB, "MAX_PROGRAM_ATTRIBS" },
    { 1 | KCMGL_PROG, GL_MAX_PROGRAM_NATIVE_INSTRUCTIONS_ARB, "MAX_PROGRAM_NATIVE_INSTRUCTIONS" },
    { 1 | KCMGL_PROG, GL_MAX_PROGRAM_NATIVE_ALU_INSTRUCTIONS_ARB, "MAX_PROGRAM_NATIVE_ALU_INSTRUCTIONS" },
    { 1 | KCMGL_PROG, GL_MAX_PROGRAM_NATIVE_TEX_INSTRUCTIONS_ARB, "MAX_PROGRAM_NATIVE_TEX_INSTRUCTIONS" },
    { 1 | KCMGL_PROG, GL_MAX_PROGRAM_NATIVE_TEX_INDIRECTIONS_ARB, "MAX_PROGRAM_NATIVE_TEX_INDIRECTIONS" },
    { 1 | KCMGL_PROG, GL_MAX_PROGRAM_NATIVE_TEMPORARIES_ARB, "MAX_PROGRAM_NATIVE_TEMPORARIES" },
    { 1 | KCMGL_PROG, GL_MAX_PROGRAM_NATIVE_PARAMETERS_ARB, "MAX_PROGRAM_NATIVE_PARAMETERS" },
    { 1 | KCMGL_PROG, GL_MAX_PROGRAM_NATIVE_ATTRIBS_ARB, "MAX_PROGRAM_NATIVE_ATTRIBS" },
    {0,0,0}
   };
#endif

#ifdef GL_ARB_vertex_program
   const struct token_name arb_vp[] = {
{ 1 | KCMGL_PROG, GL_MAX_PROGRAM_ENV_PARAMETERS_ARB,"MAX_PROGRAM_ENV_PARAMETERS"},
{ 1 | KCMGL_PROG, GL_MAX_PROGRAM_LOCAL_PARAMETERS_ARB,"MAX_PROGRAM_LOCAL_PARAMETERS"},
{ 1, GL_MAX_VERTEX_ATTRIBS_ARB, "MAX_VERTEX_ATTRIBS"},
{ 1, GL_MAX_PROGRAM_MATRICES_ARB,"MAX_PROGRAM_MATRICES"},
{ 1, GL_MAX_PROGRAM_MATRIX_STACK_DEPTH_ARB,"MAX_PROGRAM_MATRIX_STACK_DEPTH"},
{ 1 | KCMGL_PROG, GL_MAX_PROGRAM_INSTRUCTIONS_ARB,"MAX_PROGRAM_INSTRUCTIONS"},
{ 1 | KCMGL_PROG, GL_MAX_PROGRAM_TEMPORARIES_ARB,"MAX_PROGRAM_TEMPORARIES"},
{ 1 | KCMGL_PROG, GL_MAX_PROGRAM_PARAMETERS_ARB,"MAX_PROGRAM_PARAMETERS"},
{ 1 | KCMGL_PROG, GL_MAX_PROGRAM_ATTRIBS_ARB,"MAX_PROGRAM_ATTRIBS"},
{ 1 | KCMGL_PROG, GL_MAX_PROGRAM_ADDRESS_REGISTERS_ARB,"MAX_PROGRAM_ADDRESS_REGISTERS"},
{ 1 | KCMGL_PROG, GL_MAX_PROGRAM_NATIVE_INSTRUCTIONS_ARB,"MAX_PROGRAM_NATIVE_INSTRUCTIONS"},
{ 1 | KCMGL_PROG, GL_MAX_PROGRAM_NATIVE_TEMPORARIES_ARB,"MAX_PROGRAM_NATIVE_TEMPORARIES"},
{ 1 | KCMGL_PROG, GL_MAX_PROGRAM_NATIVE_PARAMETERS_ARB,"MAX_PROGRAM_NATIVE_PARAMETERS"},
{ 1 | KCMGL_PROG, GL_MAX_PROGRAM_NATIVE_ATTRIBS_ARB,"MAX_PROGRAM_NATIVE_ATTRIBS"},
{ 1 | KCMGL_PROG, GL_MAX_PROGRAM_NATIVE_ADDRESS_REGISTERS_ARB ,"MAX_PROGRAM_NATIVE_ADDRESS_REGISTERS"},
{0,0,0}
};
#endif

#ifdef GL_ARB_vertex_shader
   const struct token_name arb_vs[] = {
    { 1, GL_MAX_VERTEX_ATTRIBS_ARB,"MAX_VERTEX_ATTRIBS"},
    { 1, GL_MAX_VERTEX_UNIFORM_COMPONENTS_ARB,"MAX_VERTEX_UNIFORM_COMPONENTS"},
    { 1, GL_MAX_VARYING_FLOATS_ARB,"MAX_VARYING_FLOATS"},
    { 1, GL_MAX_COMBINED_TEXTURE_IMAGE_UNITS_ARB,"MAX_COMBINED_TEXTURE_IMAGE_UNITS"},
    { 1, GL_MAX_VERTEX_TEXTURE_IMAGE_UNITS_ARB,"MAX_VERTEX_TEXTURE_IMAGE_UNITS"},
    { 1, GL_MAX_TEXTURE_IMAGE_UNITS_ARB,"MAX_TEXTURE_IMAGE_UNITS"},
    { 1, GL_MAX_TEXTURE_COORDS_ARB,"MAX_TEXTURE_COORDS"},
    {0,0,0}
   };
#endif

#ifdef GL_ARB_fragment_shader
   const struct token_name arb_fs[] = {
    { 1, GL_MAX_FRAGMENT_UNIFORM_COMPONENTS_ARB,"MAX_FRAGMENT_UNIFORM_COMPONENTS"},
    { 1, GL_MAX_TEXTURE_IMAGE_UNITS_ARB,"MAX_TEXTURE_IMAGE_UNITS"},
    { 1, GL_MAX_TEXTURE_COORDS_ARB,"MAX_TEXTURE_COORDS"},
    {0,0,0}
   };
#endif

   const struct token_name frame_buffer_props[] = {
      { 2, GL_MAX_VIEWPORT_DIMS, 	i18n("Max. viewport dimensions") },
      { 1, GL_SUBPIXEL_BITS, 		i18n("Subpixel bits") },
      { 1, GL_AUX_BUFFERS, 		i18n("Aux. buffers")},
      {0,0,0}
    };

   const struct token_group groups[] =
   {
    {KCMGL_SIZE(frame_buffer_props), 0, frame_buffer_props, i18n("Frame buffer properties"), NULL},
    {KCMGL_SIZE(various_limits), 0, texture_limits, i18n("Texturing"), NULL},
    {KCMGL_SIZE(various_limits), 0, various_limits, i18n("Various limits"), NULL},
    {KCMGL_SIZE(float_limits), 0, float_limits, i18n("Points and lines"), NULL},
    {KCMGL_SIZE(stack_depth), 0, stack_depth, i18n("Stack depth limits"), NULL},
#ifdef GL_ARB_vertex_program
    {KCMGL_SIZE(arb_vp), GL_VERTEX_PROGRAM_ARB, arb_vp, "ARB_vertex_program", "GL_ARB_vertex_program"},
#endif
#ifdef GL_ARB_fragment_program
    {KCMGL_SIZE(arb_fp), GL_FRAGMENT_PROGRAM_ARB, arb_fp, "ARB_fragment_program", "GL_ARB_fragment_program"},
#endif
#ifdef GL_ARB_vertex_shader
    {KCMGL_SIZE(arb_vs), 0, arb_vs, "ARB_vertex_shader", "GL_ARB_vertex_shader"},
#endif
#ifdef GL_ARB_fragment_shader
    {KCMGL_SIZE(arb_fs), 0, arb_fs, "ARB_fragment_shader", "GL_ARB_fragment_shader"},
#endif
   };

#if defined(GLX_ARB_get_proc_address) && defined(PFNGLGETPROGRAMIVARBPROC)
   if (GetProcAddress && strstr(glExtensions, "GL_ARB_vertex_program"))
   kcm_glGetProgramivARB = (PFNGLGETPROGRAMIVARBPROC) glXGetProcAddressARB((const GLubyte *)"glGetProgramivARB");
#endif

   for (uint i = 0; i<KCMGL_SIZE(groups); i++) {
   	if (groups[i].ext && !strstr(glExtensions, groups[i].ext)) continue;

	if (l2) l2 = new Q3ListViewItem(l1, l2, groups[i].descr);
   	   else l2 = new Q3ListViewItem(l1, groups[i].descr);
	l3 = NULL;
   	const struct token_name *cur_token;
	for (cur_token = groups[i].group; cur_token->type; cur_token++) {

   		bool tfloat = cur_token->type & KCMGL_FLOAT;
		int count = KCMGL_COUNT_MASK(cur_token->type);
		GLint max[2]={0,0};
   		GLfloat fmax[2]={0.0,0.0};

#if defined(PFNGLGETPROGRAMIVARBPROC) && defined(GL_ARB_vertex_program)
   		bool tprog = cur_token->type & KCMGL_PROG;
		if (tprog && kcm_glGetProgramivARB)
			kcm_glGetProgramivARB(groups[i].type, cur_token->token, max);
		else
#endif
		if (tfloat) glGetFloatv(cur_token->token, fmax);
   			else glGetIntegerv(cur_token->token, max);

		if (glGetError() == GL_NONE) {
			QString s;
		 	if (!tfloat && count == 1) s = QString::number(max[0]); else
		 	if (!tfloat && count == 2) s = QString("%1, %2").arg(max[0]).arg(max[1]); else
		 	if (tfloat && count == 2) s = QString("%1 - %2").arg(fmax[0],0,'f',6).arg(fmax[1],0,'f',6); else
			if (tfloat && count == 1) s = QString::number(fmax[0],'f',6);
   			if (l3) l3 = new Q3ListViewItem(l2, l3, cur_token->name, s);
   	   			else l3 = new Q3ListViewItem(l2, cur_token->name, s);

		}
	}

     }
}
コード例 #10
0
		// -------------------------------- OpenGLRenderer::Impl definition
		OpenGLRenderer::OpenGLRenderer(Window& window)
			: m_wrapper { }, m_systemInfo { m_wrapper }, m_window{ window }, m_logManager { CROISSANT_GET_LOG(OpenGLRenderer) }
		{
			m_logManager.Write("Initialisation du renderer OpenGL");
			//serviceProvider.Resolve(m_frameProvider);

#if defined(CROISSANT_WINDOWS)
			auto hwnd = m_window.GetSystemHandle();
	        m_ghDC = GetDC(hwnd);
	        if (NULL == m_ghDC)
	        {
	        	throw OpenGLRendererException("Erreur lors de la récupération du Draw Context");
	        }

	        SetupPixelFormat(m_ghDC);

	        m_contextGl = wglCreateContext(m_ghDC);
	        if (NULL == m_contextGl)
	        {
	        	throw OpenGLRendererException("Erreur lors de la création du contexte OpenGL.");
	        }

	        if (FALSE == wglMakeCurrent(m_ghDC, m_contextGl))
	        {
	        	throw OpenGLRendererException("Erreur lors de la définition du contexte OpenGL comme courant.");
	        }


	        RECT rect;

	        GetClientRect(hwnd, &rect);
	        InitializeGLExtentions();
	        InitializeGL(rect.right, rect.bottom);
#elif defined(CROISSANT_LINUX)
            auto hwnd = m_window.GetSystemHandle();
			// Get a matching FB config
			static int visual_attribs[] =
					{
							GLX_X_RENDERABLE    , True,
							GLX_DRAWABLE_TYPE   , GLX_WINDOW_BIT,
							GLX_RENDER_TYPE     , GLX_RGBA_BIT,
							GLX_X_VISUAL_TYPE   , GLX_TRUE_COLOR,
							GLX_RED_SIZE        , 8,
							GLX_GREEN_SIZE      , 8,
							GLX_BLUE_SIZE       , 8,
							GLX_ALPHA_SIZE      , 8,
							GLX_DEPTH_SIZE      , 24,
							GLX_STENCIL_SIZE    , 8,
							GLX_DOUBLEBUFFER    , True,
							//GLX_SAMPLE_BUFFERS  , 1,
							//GLX_SAMPLES         , 4,
							None
					};

			int glx_major, glx_minor;

			// FBConfigs were added in GLX version 1.3.
			if ( !glXQueryVersion( hwnd.m_display, &glx_major, &glx_minor ) ||
				 ( ( glx_major == 1 ) && ( glx_minor < 3 ) ) || ( glx_major < 1 ) )
			{
				printf("Invalid GLX version");
				exit(1);
			}

			printf( "Getting matching framebuffer configs\n" );
			int fbcount;
			GLXFBConfig* fbc = glXChooseFBConfig(hwnd.m_display, DefaultScreen(hwnd.m_display), visual_attribs, &fbcount);
			if (!fbc)
			{
				printf( "Failed to retrieve a framebuffer config\n" );
				exit(1);
			}
			printf( "Found %d matching FB configs.\n", fbcount );

			// Pick the FB config/visual with the most samples per pixel
			printf( "Getting XVisualInfos\n" );
			int best_fbc = -1, worst_fbc = -1, best_num_samp = -1, worst_num_samp = 999;

			int i;
			for (i=0; i<fbcount; ++i)
			{
				XVisualInfo *vi = glXGetVisualFromFBConfig( hwnd.m_display, fbc[i] );
				if ( vi )
				{
					int samp_buf, samples;
					glXGetFBConfigAttrib( hwnd.m_display, fbc[i], GLX_SAMPLE_BUFFERS, &samp_buf );
					glXGetFBConfigAttrib( hwnd.m_display, fbc[i], GLX_SAMPLES       , &samples  );

					printf( "  Matching fbconfig %d, visual ID 0x%2x: SAMPLE_BUFFERS = %d,"
									" SAMPLES = %d\n",
							i, vi -> visualid, samp_buf, samples );

					if ( best_fbc < 0 || samp_buf && samples > best_num_samp )
						best_fbc = i, best_num_samp = samples;
					if ( worst_fbc < 0 || !samp_buf || samples < worst_num_samp )
						worst_fbc = i, worst_num_samp = samples;
				}
				XFree( vi );
			}

			GLXFBConfig bestFbc = fbc[ best_fbc ];

			// Be sure to free the FBConfig list allocated by glXChooseFBConfig()
			XFree( fbc );

			// Get a visual
			//XVisualInfo *vi = glXGetVisualFromFBConfig( hwnd, bestFbc );
			//printf( "Chosen visual ID = 0x%x\n", vi->visualid );


			// NOTE: It is not necessary to create or make current to a context before
			// calling glXGetProcAddressARB
			glXCreateContextAttribsARBProc glXCreateContextAttribsARB = 0;
			glXCreateContextAttribsARB = (glXCreateContextAttribsARBProc)
					glXGetProcAddressARB( (const GLubyte *) "glXCreateContextAttribsARB" );

			int context_attribs[] =
					{
							GLX_CONTEXT_MAJOR_VERSION_ARB, 3,
							GLX_CONTEXT_MINOR_VERSION_ARB, 0,
							//GLX_CONTEXT_FLAGS_ARB        , GLX_CONTEXT_FORWARD_COMPATIBLE_BIT_ARB,
							None
					};

			printf( "Creating context\n" );
			m_contextGl = glXCreateContextAttribsARB( hwnd.m_display, bestFbc, 0,
											  True, context_attribs );

			// Sync to ensure any errors generated are processed.
			XSync( hwnd.m_display, False );

			// Verifying that context is a direct context
			if ( ! glXIsDirect ( hwnd.m_display, m_contextGl ) )
			{
				printf( "Indirect GLX rendering context obtained\n" );
			}
			else
			{
				printf( "Direct GLX rendering context obtained\n" );
			}

			printf( "Making context current\n" );
			glXMakeCurrent( hwnd.m_display, hwnd.m_window, m_contextGl );

#endif


			//serviceProvider.Resolve(m_eventManager);
			//m_eventManager->RegisterListener("Frame::Render", m_renderDelegate);
		    m_logManager.Write("Renderer OpenGL initialisé avec succès");
		}
コード例 #11
0
ファイル: glContext.hpp プロジェクト: shehzan10/glContext
void createGLContext()
{
    printf("Creating OpenGL Context...");
    display = XOpenDisplay(NULL);

    if (!display) {
        MSG("Fatal: Failed to open X display");
        exit(1);
    }

    // Get a matching FB config
    static int visual_attribs[] = {
        GLX_X_RENDERABLE    , True,
        GLX_DRAWABLE_TYPE   , GLX_WINDOW_BIT,
        GLX_RENDER_TYPE     , GLX_RGBA_BIT,
        GLX_X_VISUAL_TYPE   , GLX_TRUE_COLOR,
        GLX_RED_SIZE        , 8,
        GLX_GREEN_SIZE      , 8,
        GLX_BLUE_SIZE       , 8,
        GLX_ALPHA_SIZE      , 8,
        GLX_DEPTH_SIZE      , 24,
        GLX_STENCIL_SIZE    , 8,
        GLX_DOUBLEBUFFER    , True,
        //GLX_SAMPLE_BUFFERS  , 1,
        //GLX_SAMPLES         , 4,
        None
    };

    int glx_major, glx_minor;

    // FBConfigs were added in GLX version 1.3.
    if (!glXQueryVersion(display, &glx_major, &glx_minor) ||
            ((glx_major == 1) && (glx_minor < 3)) || (glx_major < 1)) {
        MSG("Fatal: Invalid GLX version");
        exit(1);
    }

    MSG("Getting matching framebuffer configs");
    int fbcount;
    GLXFBConfig *fbc = glXChooseFBConfig(display, DefaultScreen(display),
                                         visual_attribs, &fbcount);

    if (!fbc) {
        MSG("Fatal: Failed to retrieve a framebuffer config");
        exit(1);
    }

    MSG("Found %d matching FB configs.", fbcount);

    // Pick the FB config/visual with the most samples per pixel
    MSG("Getting XVisualInfos");
    int best_fbc = -1, worst_fbc = -1, best_num_samp = -1, worst_num_samp = 999;

    int i;

    for (i = 0; i < fbcount; ++i) {
        XVisualInfo *vi = glXGetVisualFromFBConfig(display, fbc[i]);

        if (vi) {
            int samp_buf, samples;
            glXGetFBConfigAttrib(display, fbc[i], GLX_SAMPLE_BUFFERS, &samp_buf);
            glXGetFBConfigAttrib(display, fbc[i], GLX_SAMPLES       , &samples);

            //Commented to reduce output
            //MSG("Matching fbconfig %d, visual ID 0x%2x:"
            //                "SAMPLE_BUFFERS = %d, SAMPLES = %d",
            //                 i, vi -> visualid, samp_buf, samples);

            if (best_fbc < 0 || samp_buf && samples > best_num_samp) {
                best_fbc = i, best_num_samp = samples;
            }

            if (worst_fbc < 0 || !samp_buf || samples < worst_num_samp) {
                worst_fbc = i, worst_num_samp = samples;
            }
        }

        XFree(vi);
    }

    GLXFBConfig bestFbc = fbc[best_fbc];

    // Be sure to free the FBConfig list allocated by glXChooseFBConfig()
    XFree(fbc);

    // Get a visual
    XVisualInfo *vi = glXGetVisualFromFBConfig(display, bestFbc);
    MSG("Chosen visual ID = 0x%x", vi->visualid);

    MSG("Creating colormap");
    XSetWindowAttributes swa;
    swa.colormap = cmap = XCreateColormap(display,
                                          RootWindow(display, vi->screen),
                                          vi->visual, AllocNone);
    swa.background_pixmap = None ;
    swa.border_pixel      = 0;
    swa.event_mask        = StructureNotifyMask;

    MSG("Creating window");
    win = XCreateWindow(display, RootWindow(display, vi->screen),
                        0, 0, 10, 10, 0, vi->depth, InputOutput,
                        vi->visual,
                        CWBorderPixel | CWColormap | CWEventMask, &swa);

    if (!win) {
        MSG("Fatal: Failed to create window.");
        exit(1);
    }

    // Done with the visual info data
    XFree(vi);

    XStoreName(display, win, "Window");

    MSG("Mapping window");
    XMapWindow(display, win);

    // Get the default screen's GLX extension list
    const char *glxExts = glXQueryExtensionsString(display,
                          DefaultScreen(display));

    // NOTE: It is not necessary to create or make current to a context before
    // calling glXGetProcAddressARB
    glXCreateContextAttribsARBProc glXCreateContextAttribsARB = 0;
    glXCreateContextAttribsARB = (glXCreateContextAttribsARBProc)
                                 glXGetProcAddressARB((const GLubyte *) "glXCreateContextAttribsARB");

    // Install an X error handler so the application won't exit if GL <VERSION>
    // context allocation fails.
    //
    // Note this error handler is global.  All display connections in all threads
    // of a process use the same error handler, so be sure to guard against other
    // threads issuing X commands while this code is running.
    ctxErrorOccurred = false;
    int (*oldHandler)(Display *, XErrorEvent *) = XSetErrorHandler(&ctxErrorHandler);

    // Check for the GLX_ARB_create_context extension string and the function.
    // If either is not present, use GLX 1.3 context creation method.
    if (!isExtensionSupported(glxExts, "GLX_ARB_create_context") ||
            !glXCreateContextAttribsARB) {
        MSG("glXCreateContextAttribsARB() not found"
                        "... using old-style GLX context");
        ctx = glXCreateNewContext(display, bestFbc, GLX_RGBA_TYPE, 0, True);
    }

    // If it does, try to get a GL <VERSION> context!
    // GL_<>_VERSION defined at top of file
    else {
        int context_attribs[] = {
            GLX_CONTEXT_MAJOR_VERSION_ARB, GL_VER_MAJOR,
            GLX_CONTEXT_MINOR_VERSION_ARB, GL_VER_MINOR,
            GLX_CONTEXT_FLAGS_ARB        , GLX_CONTEXT_FORWARD_COMPATIBLE_BIT_ARB,
            None
        };

        MSG("Creating context");
        ctx = glXCreateContextAttribsARB(display, bestFbc, 0,
                                         True, context_attribs);

        // Sync to ensure any errors generated are processed.
        XSync(display, False);

        if (!ctxErrorOccurred && ctx) {
            MSG("Created GL %d.%d context", GL_VER_MAJOR, GL_VER_MINOR);
        } else {
            MSG("Fatal: Failed to create GL %d.%d context",
                 GL_VER_MAJOR, GL_VER_MINOR);
            // Remove this exit to fall back to 2.1 context.
            exit(1);

            // Couldn't create GL <VERSION> context.  Fall back to old-style 2.x context.
            // When a context version below <VERSION> is requested, implementations will
            // return the newest context version compatible with OpenGL versions less
            // than version <VERSION>.
            // GLX_CONTEXT_MAJOR_VERSION_ARB = 1
            context_attribs[1] = 1;
            // GLX_CONTEXT_MINOR_VERSION_ARB = 0
            context_attribs[3] = 0;

            ctxErrorOccurred = false;

            ctx = glXCreateContextAttribsARB(display, bestFbc, 0,
                                             True, context_attribs);
        }
    }

    // Sync to ensure any errors generated are processed.
    XSync(display, False);

    // Restore the original error handler
    XSetErrorHandler(oldHandler);

    if (ctxErrorOccurred || !ctx) {
        MSG("Fatal: Failed to create an OpenGL context");
        exit(1);
    }

    // Verifying that context is a direct context
    if (! glXIsDirect(display, ctx)) {
        MSG("Indirect GLX rendering context obtained");
    } else {
        MSG("Direct GLX rendering context obtained");
    }

    MSG("Making context current");
    glXMakeCurrent(display, win, ctx);

    MSG("Getting OpenGL Version information...");
    MSG("GL Version  = %s", glGetString(GL_VERSION));
    MSG("GL Vendor   = %s", glGetString(GL_VENDOR));
    MSG("GL Renderer = %s", glGetString(GL_RENDERER));
    MSG("GL Shader   = %s", glGetString(GL_SHADING_LANGUAGE_VERSION));

}
コード例 #12
0
int main(int argc, char* argv[])
{
  Display *display = XOpenDisplay(NULL);
 
  if (!display)
  {
    printf("Failed to open X display\n");
    exit(1);
  }
 
  // Get a matching FB config
  static int visual_attribs[] =
    {
      GLX_X_RENDERABLE    , True,
      GLX_DRAWABLE_TYPE   , GLX_WINDOW_BIT,
      GLX_RENDER_TYPE     , GLX_RGBA_BIT,
      GLX_X_VISUAL_TYPE   , GLX_TRUE_COLOR,
      GLX_RED_SIZE        , 8,
      GLX_GREEN_SIZE      , 8,
      GLX_BLUE_SIZE       , 8,
      GLX_ALPHA_SIZE      , 8,
      GLX_DEPTH_SIZE      , 24,
      GLX_STENCIL_SIZE    , 8,
      GLX_DOUBLEBUFFER    , True,
      //GLX_SAMPLE_BUFFERS  , 1,
      //GLX_SAMPLES         , 4,
      None
    };
 
  int glx_major, glx_minor;
 
  // FBConfigs were added in GLX version 1.3.
  if ( !glXQueryVersion( display, &glx_major, &glx_minor ) || 
       ( ( glx_major == 1 ) && ( glx_minor < 3 ) ) || ( glx_major < 1 ) )
  {
    printf("Invalid GLX version");
    exit(1);
  }
 
  printf( "Getting matching framebuffer configs\n" );
  int fbcount;
  GLXFBConfig* fbc = glXChooseFBConfig(display, DefaultScreen(display), visual_attribs, &fbcount);
  if (!fbc)
  {
    printf( "Failed to retrieve a framebuffer config\n" );
    exit(1);
  }
  printf( "Found %d matching FB configs.\n", fbcount );
 
  // Pick the FB config/visual with the most samples per pixel
  printf( "Getting XVisualInfos\n" );
  int best_fbc = -1, worst_fbc = -1, best_num_samp = -1, worst_num_samp = 999;
 
  int i;
  for (i=0; i<fbcount; ++i)
  {
    XVisualInfo *vi = glXGetVisualFromFBConfig( display, fbc[i] );
    if ( vi )
    {
      int samp_buf, samples;
      glXGetFBConfigAttrib( display, fbc[i], GLX_SAMPLE_BUFFERS, &samp_buf );
      glXGetFBConfigAttrib( display, fbc[i], GLX_SAMPLES       , &samples  );
 
      printf( "  Matching fbconfig %d, visual ID 0x%2x: SAMPLE_BUFFERS = %d,"
              " SAMPLES = %d\n", 
              i, vi -> visualid, samp_buf, samples );
 
      if ( best_fbc < 0 || samp_buf && samples > best_num_samp )
        best_fbc = i, best_num_samp = samples;
      if ( worst_fbc < 0 || !samp_buf || samples < worst_num_samp )
        worst_fbc = i, worst_num_samp = samples;
    }
    XFree( vi );
  }
 
  GLXFBConfig bestFbc = fbc[ best_fbc ];
 
  // Be sure to free the FBConfig list allocated by glXChooseFBConfig()
  XFree( fbc );
 
  // Get a visual
  XVisualInfo *vi = glXGetVisualFromFBConfig( display, bestFbc );
  printf( "Chosen visual ID = 0x%x\n", vi->visualid );
 
  printf( "Creating colormap\n" );
  XSetWindowAttributes swa;
  Colormap cmap;
  swa.colormap = cmap = XCreateColormap( display,
                                         RootWindow( display, vi->screen ), 
                                         vi->visual, AllocNone );
  swa.background_pixmap = None ;
  swa.border_pixel      = 0;
  swa.event_mask        = StructureNotifyMask;
 
  printf( "Creating window\n" );
  Window win = XCreateWindow( display, RootWindow( display, vi->screen ), 
                              0, 0, 400, 400, 0, vi->depth, InputOutput, 
                              vi->visual, 
                              CWBorderPixel|CWColormap|CWEventMask, &swa );
  if ( !win )
  {
    printf( "Failed to create window.\n" );
    exit(1);
  }
 
  // Done with the visual info data
  XFree( vi );
  
  char windowName[50];
  
  sprintf(windowName, "GL ES %d.%d Window", DESIRED_GL_ES_MAJOR_VERSION, DESIRED_GL_ES_MINOR_VERSION);
 
  XStoreName( display, win, windowName );
 
  printf( "Mapping window\n" );
  XMapWindow( display, win );
 
  // Get the default screen's GLX extension list
  const char *glxExts = glXQueryExtensionsString( display,
                                                  DefaultScreen( display ) );
 
  // NOTE: It is not necessary to create or make current to a context before
  // calling glXGetProcAddressARB
  glXCreateContextAttribsARBProc glXCreateContextAttribsARB = 0;
  glXCreateContextAttribsARB = (glXCreateContextAttribsARBProc)
           glXGetProcAddressARB( (const GLubyte *) "glXCreateContextAttribsARB" );
 
  GLXContext ctx = 0;
 
  // Install an X error handler so the application won't exit if GL 3.0
  // context allocation fails.
  //
  // Note this error handler is global.  All display connections in all threads
  // of a process use the same error handler, so be sure to guard against other
  // threads issuing X commands while this code is running.
  ctxErrorOccurred = false;
  int (*oldHandler)(Display*, XErrorEvent*) =
      XSetErrorHandler(&ctxErrorHandler);
 
  // Check for the GLX_ARB_create_context extension string and the function.
  // If either is not present, use GLX 1.3 context creation method.
  if ( !isExtensionSupported( glxExts, "GLX_ARB_create_context" ) ||
       !glXCreateContextAttribsARB )
  {
    printf( "glXCreateContextAttribsARB() not found"
            " ... using old-style GLX context\n" );
    ctx = glXCreateNewContext( display, bestFbc, GLX_RGBA_TYPE, 0, True );
  }
 
  // If it does, try to get a GL DESIRED_GL_ES_MAJOR_VERSION.DESIRED_GL_ES_MINOR_VERSION context!
  else
  {
      int context_attribs[] =
          {
            GLX_CONTEXT_MAJOR_VERSION_ARB, DESIRED_GL_ES_MAJOR_VERSION,
            GLX_CONTEXT_MINOR_VERSION_ARB, DESIRED_GL_ES_MINOR_VERSION,
            GLX_CONTEXT_PROFILE_MASK_ARB, GLX_CONTEXT_ES_PROFILE_BIT_EXT,
            None
          };
 
    printf( "Creating context\n" );
    ctx = glXCreateContextAttribsARB( display, bestFbc, 0,
                                      True, context_attribs );
 
    // Sync to ensure any errors generated are processed.
    XSync( display, False );
    if ( !ctxErrorOccurred && ctx )
      printf( "Created GL ES %d.%d context\n", DESIRED_GL_ES_MAJOR_VERSION, DESIRED_GL_ES_MINOR_VERSION );
    else
    {
      // Couldn't create GL 3.0 context.  Fall back to old-style 2.x context.
      // When a context version below 3.0 is requested, implementations will
      // return the newest context version compatible with OpenGL versions less
      // than version 3.0.
      // GLX_CONTEXT_MAJOR_VERSION_ARB = 1
      context_attribs[1] = DESIRED_GL_ES_MAJOR_VERSION;
      // GLX_CONTEXT_MINOR_VERSION_ARB = 0
      context_attribs[3] = DESIRED_GL_ES_MINOR_VERSION;
 
      ctxErrorOccurred = false;
 
      printf( "Failed to create GL ES %d.%d context"
              " ... using old-style GLX context\n", DESIRED_GL_ES_MAJOR_VERSION, DESIRED_GL_ES_MINOR_VERSION );
      ctx = glXCreateContextAttribsARB( display, bestFbc, 0, 
                                        True, context_attribs );
    }
  }
 
  // Sync to ensure any errors generated are processed.
  XSync( display, False );
 
  // Restore the original error handler
  XSetErrorHandler( oldHandler );
 
  if ( ctxErrorOccurred || !ctx )
  {
    printf( "Failed to create an OpenGL ES %d.%d context\n", DESIRED_GL_ES_MAJOR_VERSION, DESIRED_GL_ES_MINOR_VERSION );
    exit(1);
  }
 
  // Verifying that context is a direct context
  if ( ! glXIsDirect ( display, ctx ) )
  {
    printf( "Indirect GLX rendering context obtained\n" );
  }
  else
  {
    printf( "Direct GLX rendering context obtained\n" );
  }
 
  printf( "Making context current\n" );
  glXMakeCurrent( display, win, ctx );
 
  glClearColor( 0, 0.5, 1, 1 );
  glClear( GL_COLOR_BUFFER_BIT );
  glXSwapBuffers ( display, win );
 
  sleep( 2 );
 
  glClearColor ( 1, 0.5, 0, 1 );
  glClear ( GL_COLOR_BUFFER_BIT );
  glXSwapBuffers ( display, win );
 
  sleep( 2 );
  
  glClearColor( 1, 0.5, 1, 1 );
  glClear( GL_COLOR_BUFFER_BIT );
  glXSwapBuffers ( display, win );
 
  sleep( 2 );
 
  glXMakeCurrent( display, 0, 0 );
  glXDestroyContext( display, ctx );
 
  XDestroyWindow( display, win );
  XFreeColormap( display, cmap );
  XCloseDisplay( display );
 
  return 0;
}
コード例 #13
0
static gboolean
gst_gl_context_glx_create_context (GstGLContext * context,
    GstGLAPI gl_api, GstGLContext * other_context, GError ** error)
{
  GstGLContextGLX *context_glx;
  GstGLWindow *window;
  GstGLWindowX11 *window_x11;
  GstGLDisplay *display;
  gboolean create_context;
  const char *glx_exts;
  Display *device;
  guintptr external_gl_context = 0;

  context_glx = GST_GL_CONTEXT_GLX (context);
  window = gst_gl_context_get_window (context);
  window_x11 = GST_GL_WINDOW_X11 (window);
  display = gst_gl_context_get_display (context);

  if (other_context) {
    if (gst_gl_context_get_gl_platform (other_context) != GST_GL_PLATFORM_GLX) {
      g_set_error (error, GST_GL_CONTEXT_ERROR,
          GST_GL_CONTEXT_ERROR_WRONG_CONFIG,
          "Cannot share context with non-GLX context");
      goto failure;
    }

    external_gl_context = gst_gl_context_get_gl_context (other_context);
  }

  device = (Display *) gst_gl_display_get_handle (display);
  glx_exts = glXQueryExtensionsString (device, DefaultScreen (device));

  create_context = gst_gl_check_extension ("GLX_ARB_create_context", glx_exts);
  context_glx->priv->glXCreateContextAttribsARB =
      (gpointer) glXGetProcAddressARB ((const GLubyte *)
      "glXCreateContextAttribsARB");

  if (create_context && context_glx->priv->glXCreateContextAttribsARB) {
    gint i;

    for (i = 0; i < G_N_ELEMENTS (gl_versions); i++) {
      GstGLAPI selected_gl_api;
      gint profileMask = 0;
      gint contextFlags = 0;

      if (gl_api & GST_GL_API_OPENGL3 && (gl_versions[i].major > 3
              || (gl_versions[i].major == 3 && gl_versions[i].minor >= 2))) {
        profileMask |= GLX_CONTEXT_CORE_PROFILE_BIT_ARB;
        selected_gl_api = GST_GL_API_OPENGL3;
        contextFlags |= GLX_CONTEXT_DEBUG_BIT_ARB;
      } else {
        selected_gl_api = GST_GL_API_OPENGL;
      }

      GST_DEBUG_OBJECT (context, "trying to create a GL %d.%d context",
          gl_versions[i].major, gl_versions[i].minor);

      context_glx->glx_context = _create_context_with_flags (context_glx,
          device, context_glx->priv->fbconfigs[0],
          (GLXContext) external_gl_context, gl_versions[i].major,
          gl_versions[i].minor, contextFlags, profileMask);

      if (context_glx->glx_context) {
        context_glx->priv->context_api = selected_gl_api;
        break;
      }
    }
  } else {
    context_glx->glx_context =
        glXCreateContext (device, window_x11->visual_info,
        (GLXContext) external_gl_context, TRUE);
    context_glx->priv->context_api = GST_GL_API_OPENGL;
  }

  if (context_glx->priv->fbconfigs)
    XFree (context_glx->priv->fbconfigs);

  if (!context_glx->glx_context) {
    g_set_error (error, GST_GL_CONTEXT_ERROR,
        GST_GL_CONTEXT_ERROR_CREATE_CONTEXT, "Failed to create opengl context");
    goto failure;
  }

  GST_LOG ("gl context id: %ld", (gulong) context_glx->glx_context);

  gst_object_unref (window);
  gst_object_unref (display);

  return TRUE;

failure:
  if (window)
    gst_object_unref (window);
  gst_object_unref (display);

  return FALSE;
}
コード例 #14
0
void* RenderContext_Base_GL::GetExtension(const char* name) {
    size_t len = std::strlen(name);
    if (len > 3 && !std::strcmp((name + len - 3), "ARB"))
        return (void*) glXGetProcAddressARB((const GLubyte *) name);
    return (void*) glXGetProcAddress((const GLubyte *) name);
}
コード例 #15
0
int
main(int argc, char *argv[])
{
   Display *dpy;
   Window win;
   GLXContext ctx;
   char *dpyName = NULL;
   int swap_interval = 1;
   GLboolean do_swap_interval = GL_FALSE;
   GLboolean force_get_rate = GL_FALSE;
   GLboolean fullscreen = GL_FALSE;
   GLboolean printInfo = GL_FALSE;
   int i;
   PFNGLXSWAPINTERVALMESAPROC set_swap_interval = NULL;
   PFNGLXGETSWAPINTERVALMESAPROC get_swap_interval = NULL;
   int width = 300, height = 300;

   for (i = 1; i < argc; i++) {
      if (strcmp(argv[i], "-display") == 0 && i + 1 < argc) {
         dpyName = argv[i+1];
         i++;
      }
      else if (strcmp(argv[i], "-info") == 0) {
         printInfo = GL_TRUE;
      }
      else if (strcmp(argv[i], "-swap") == 0 && i + 1 < argc) {
	 swap_interval = atoi( argv[i+1] );
	 do_swap_interval = GL_TRUE;
	 i++;
      }
      else if (strcmp(argv[i], "-forcegetrate") == 0) {
	 /* This option was put in because some DRI drivers don't support the
	  * full GLX_OML_sync_control extension, but they do support
	  * glXGetMscRateOML.
	  */
	 force_get_rate = GL_TRUE;
      }
      else if (strcmp(argv[i], "-fullscreen") == 0) {
         fullscreen = GL_TRUE;
      }
      else if (strcmp(argv[i], "-ztrick") == 0) {
	 use_ztrick = GL_TRUE;
      }
      else if (strcmp(argv[i], "-help") == 0) {
         printf("Usage:\n");
         printf("  gears [options]\n");
         printf("Options:\n");
         printf("  -help                   Print this information\n");
         printf("  -display displayName    Specify X display\n");
         printf("  -info                   Display GL information\n");
         printf("  -swap N                 Swap no more than once per N vertical refreshes\n");
         printf("  -forcegetrate           Try to use glXGetMscRateOML function\n");
         printf("  -fullscreen             Full-screen window\n");
         return 0;
      }
   }

   dpy = XOpenDisplay(dpyName);
   if (!dpy) {
      printf("Error: couldn't open display %s\n", XDisplayName(dpyName));
      return -1;
   }

   make_window(dpy, "glxgears", 0, 0, width, height, fullscreen, &win, &ctx);
   XMapWindow(dpy, win);
   glXMakeCurrent(dpy, win, ctx);

   make_extension_table( (char *) glXQueryExtensionsString(dpy,DefaultScreen(dpy)) );
   has_OML_sync_control = is_extension_supported( "GLX_OML_sync_control" );
   has_SGI_swap_control = is_extension_supported( "GLX_SGI_swap_control" );
   has_MESA_swap_control = is_extension_supported( "GLX_MESA_swap_control" );
   has_MESA_swap_frame_usage = is_extension_supported( "GLX_MESA_swap_frame_usage" );

   if ( has_MESA_swap_control ) {
      set_swap_interval = (PFNGLXSWAPINTERVALMESAPROC) glXGetProcAddressARB( (const GLubyte *) "glXSwapIntervalMESA" );
      get_swap_interval = (PFNGLXGETSWAPINTERVALMESAPROC) glXGetProcAddressARB( (const GLubyte *) "glXGetSwapIntervalMESA" );
   }
   else if ( has_SGI_swap_control ) {
      set_swap_interval = (PFNGLXSWAPINTERVALMESAPROC) glXGetProcAddressARB( (const GLubyte *) "glXSwapIntervalSGI" );
   }


   if ( has_MESA_swap_frame_usage ) {
      get_frame_usage = (PFNGLXGETFRAMEUSAGEMESAPROC)  glXGetProcAddressARB( (const GLubyte *) "glXGetFrameUsageMESA" );
   }
      

   if (printInfo) {
      printf("GL_RENDERER   = %s\n", (char *) glGetString(GL_RENDERER));
      printf("GL_VERSION    = %s\n", (char *) glGetString(GL_VERSION));
      printf("GL_VENDOR     = %s\n", (char *) glGetString(GL_VENDOR));
      printf("GL_EXTENSIONS = %s\n", (char *) glGetString(GL_EXTENSIONS));
      if ( has_OML_sync_control || force_get_rate ) {
	 show_refresh_rate( dpy );
      }

      if ( get_swap_interval != NULL ) {
	 printf("Default swap interval = %d\n", (*get_swap_interval)() );
      }
   }

   if ( do_swap_interval ) {
      if ( set_swap_interval != NULL ) {
	 if ( ((swap_interval == 0) && !has_MESA_swap_control)
	      || (swap_interval < 0) ) {
	    printf( "Swap interval must be non-negative or greater than zero "
		    "if GLX_MESA_swap_control is not supported.\n" );
	 }
	 else {
	    (*set_swap_interval)( swap_interval );
	 }

	 if ( printInfo && (get_swap_interval != NULL) ) {
	    printf("Current swap interval = %d\n", (*get_swap_interval)() );
	 }
      }
      else {
	 printf("Unable to set swap-interval.  Neither GLX_SGI_swap_control "
		"nor GLX_MESA_swap_control are supported.\n" );
      }
   }

   init();

   /* Set initial projection/viewing transformation.
    * same as glxgears.c
    */
   reshape(width, height);

   event_loop(dpy, win);

   glXDestroyContext(dpy, ctx);
   XDestroyWindow(dpy, win);
   XCloseDisplay(dpy);

   return 0;
}
コード例 #16
0
ファイル: glxinfo.c プロジェクト: Bluerise/bitrig-xenocara
/**
 * Print interesting limits for vertex/fragment programs.
 */
static void
print_program_limits(GLenum target)
{
#if defined(GL_ARB_vertex_program) || defined(GL_ARB_fragment_program)
   struct token_name {
      GLenum token;
      const char *name;
   };
   static const struct token_name common_limits[] = {
      { GL_MAX_PROGRAM_INSTRUCTIONS_ARB, "GL_MAX_PROGRAM_INSTRUCTIONS_ARB" },
      { GL_MAX_PROGRAM_NATIVE_INSTRUCTIONS_ARB, "GL_MAX_PROGRAM_NATIVE_INSTRUCTIONS_ARB" },
      { GL_MAX_PROGRAM_TEMPORARIES_ARB, "GL_MAX_PROGRAM_TEMPORARIES_ARB" },
      { GL_MAX_PROGRAM_NATIVE_TEMPORARIES_ARB, "GL_MAX_PROGRAM_NATIVE_TEMPORARIES_ARB" },
      { GL_MAX_PROGRAM_PARAMETERS_ARB, "GL_MAX_PROGRAM_PARAMETERS_ARB" },
      { GL_MAX_PROGRAM_NATIVE_PARAMETERS_ARB, "GL_MAX_PROGRAM_NATIVE_PARAMETERS_ARB" },
      { GL_MAX_PROGRAM_ATTRIBS_ARB, "GL_MAX_PROGRAM_ATTRIBS_ARB" },
      { GL_MAX_PROGRAM_NATIVE_ATTRIBS_ARB, "GL_MAX_PROGRAM_NATIVE_ATTRIBS_ARB" },
      { GL_MAX_PROGRAM_ADDRESS_REGISTERS_ARB, "GL_MAX_PROGRAM_ADDRESS_REGISTERS_ARB" },
      { GL_MAX_PROGRAM_NATIVE_ADDRESS_REGISTERS_ARB, "GL_MAX_PROGRAM_NATIVE_ADDRESS_REGISTERS_ARB" },
      { GL_MAX_PROGRAM_LOCAL_PARAMETERS_ARB, "GL_MAX_PROGRAM_LOCAL_PARAMETERS_ARB" },
      { GL_MAX_PROGRAM_ENV_PARAMETERS_ARB, "GL_MAX_PROGRAM_ENV_PARAMETERS_ARB" },
      { (GLenum) 0, NULL }
   };
   static const struct token_name fragment_limits[] = {
      { GL_MAX_PROGRAM_ALU_INSTRUCTIONS_ARB, "GL_MAX_PROGRAM_ALU_INSTRUCTIONS_ARB" },
      { GL_MAX_PROGRAM_TEX_INSTRUCTIONS_ARB, "GL_MAX_PROGRAM_TEX_INSTRUCTIONS_ARB" },
      { GL_MAX_PROGRAM_TEX_INDIRECTIONS_ARB, "GL_MAX_PROGRAM_TEX_INDIRECTIONS_ARB" },
      { GL_MAX_PROGRAM_NATIVE_ALU_INSTRUCTIONS_ARB, "GL_MAX_PROGRAM_NATIVE_ALU_INSTRUCTIONS_ARB" },
      { GL_MAX_PROGRAM_NATIVE_TEX_INSTRUCTIONS_ARB, "GL_MAX_PROGRAM_NATIVE_TEX_INSTRUCTIONS_ARB" },
      { GL_MAX_PROGRAM_NATIVE_TEX_INDIRECTIONS_ARB, "GL_MAX_PROGRAM_NATIVE_TEX_INDIRECTIONS_ARB" },
      { (GLenum) 0, NULL }
   };

   PFNGLGETPROGRAMIVARBPROC GetProgramivARB_func = (PFNGLGETPROGRAMIVARBPROC)
      glXGetProcAddressARB((GLubyte *) "glGetProgramivARB");

   GLint max[1];
   int i;

   if (target == GL_VERTEX_PROGRAM_ARB) {
      printf("    GL_VERTEX_PROGRAM_ARB:\n");
   }
   else if (target == GL_FRAGMENT_PROGRAM_ARB) {
      printf("    GL_FRAGMENT_PROGRAM_ARB:\n");
   }
   else {
      return; /* something's wrong */
   }

   for (i = 0; common_limits[i].token; i++) {
      GetProgramivARB_func(target, common_limits[i].token, max);
      if (glGetError() == GL_NO_ERROR) {
         printf("        %s = %d\n", common_limits[i].name, max[0]);
      }
   }
   if (target == GL_FRAGMENT_PROGRAM_ARB) {
      for (i = 0; fragment_limits[i].token; i++) {
         GetProgramivARB_func(target, fragment_limits[i].token, max);
         if (glGetError() == GL_NO_ERROR) {
            printf("        %s = %d\n", fragment_limits[i].name, max[0]);
         }
      }
   }
#endif /* GL_ARB_vertex_program / GL_ARB_fragment_program */
}
コード例 #17
0
ファイル: main.cpp プロジェクト: zenogears/reicast-emulator
void os_CreateWindow()
{
  #if defined(SUPPORT_X11)
    if (cfgLoadInt("pvr", "nox11", 0) == 0)
    {
      XInitThreads();
      // X11 variables
      Window       x11Window = 0;
      Display*     x11Display = 0;
      long         x11Screen = 0;
      XVisualInfo* x11Visual = 0;
      Colormap     x11Colormap = 0;

      /*
      Step 0 - Create a NativeWindowType that we can use it for OpenGL ES output
      */
      Window sRootWindow;
      XSetWindowAttributes sWA;
      unsigned int ui32Mask;
      int i32Depth;

      // Initializes the display and screen
      x11Display = XOpenDisplay(0);
      if (!x11Display && !(x11Display = XOpenDisplay(":0")))
      {
        printf("Error: Unable to open X display\n");
        return;
      }
      x11Screen = XDefaultScreen(x11Display);

      // Gets the window parameters
      sRootWindow = RootWindow(x11Display, x11Screen);

      int depth = CopyFromParent;

      #if !defined(GLES)
        // Get a matching FB config
        static int visual_attribs[] =
        {
          GLX_X_RENDERABLE    , True,
          GLX_DRAWABLE_TYPE   , GLX_WINDOW_BIT,
          GLX_RENDER_TYPE     , GLX_RGBA_BIT,
          GLX_X_VISUAL_TYPE   , GLX_TRUE_COLOR,
          GLX_RED_SIZE        , 8,
          GLX_GREEN_SIZE      , 8,
          GLX_BLUE_SIZE       , 8,
          GLX_ALPHA_SIZE      , 8,
          GLX_DEPTH_SIZE      , 24,
          GLX_STENCIL_SIZE    , 8,
          GLX_DOUBLEBUFFER    , True,
          //GLX_SAMPLE_BUFFERS  , 1,
          //GLX_SAMPLES         , 4,
          None
        };

        int glx_major, glx_minor;

        // FBConfigs were added in GLX version 1.3.
        if (!glXQueryVersion(x11Display, &glx_major, &glx_minor) ||
            ((glx_major == 1) && (glx_minor < 3)) || (glx_major < 1))
        {
          printf("Invalid GLX version");
          exit(1);
        }

        int fbcount;
        GLXFBConfig* fbc = glXChooseFBConfig(x11Display, x11Screen, visual_attribs, &fbcount);
        if (!fbc)
        {
          printf("Failed to retrieve a framebuffer config\n");
          exit(1);
        }
        printf("Found %d matching FB configs.\n", fbcount);

        GLXFBConfig bestFbc = fbc[0];
        XFree(fbc);

        // Get a visual
        XVisualInfo *vi = glXGetVisualFromFBConfig(x11Display, bestFbc);
        printf("Chosen visual ID = 0x%x\n", vi->visualid);


        depth = vi->depth;
        x11Visual = vi;

        x11Colormap = XCreateColormap(x11Display, RootWindow(x11Display, x11Screen), vi->visual, AllocNone);
      #else
        i32Depth = DefaultDepth(x11Display, x11Screen);
        x11Visual = new XVisualInfo;
        XMatchVisualInfo(x11Display, x11Screen, i32Depth, TrueColor, x11Visual);
        if (!x11Visual)
        {
          printf("Error: Unable to acquire visual\n");
          return;
        }
        x11Colormap = XCreateColormap(x11Display, sRootWindow, x11Visual->visual, AllocNone);
      #endif

      sWA.colormap = x11Colormap;

      // Add to these for handling other events
      sWA.event_mask = StructureNotifyMask | ExposureMask | ButtonPressMask | ButtonReleaseMask | KeyPressMask | KeyReleaseMask;
      ui32Mask = CWBackPixel | CWBorderPixel | CWEventMask | CWColormap;

      #ifdef TARGET_PANDORA
        int width = 800;
        int height = 480;
      #else
        int width = cfgLoadInt("x11", "width", WINDOW_WIDTH);
        int height = cfgLoadInt("x11", "height", WINDOW_HEIGHT);
      #endif

      if (width == -1)
      {
        width = XDisplayWidth(x11Display, x11Screen);
        height = XDisplayHeight(x11Display, x11Screen);
      }

      // Creates the X11 window
      x11Window = XCreateWindow(x11Display, RootWindow(x11Display, x11Screen), (ndcid%3)*640, (ndcid/3)*480, width, height,
        0, depth, InputOutput, x11Visual->visual, ui32Mask, &sWA);

      #ifdef TARGET_PANDORA
        // fullscreen
        Atom wmState = XInternAtom(x11Display, "_NET_WM_STATE", False);
        Atom wmFullscreen = XInternAtom(x11Display, "_NET_WM_STATE_FULLSCREEN", False);
        XChangeProperty(x11Display, x11Window, wmState, XA_ATOM, 32, PropModeReplace, (unsigned char *)&wmFullscreen, 1);

        XMapRaised(x11Display, x11Window);
      #else
        XMapWindow(x11Display, x11Window);

        #if !defined(GLES)
          #define GLX_CONTEXT_MAJOR_VERSION_ARB       0x2091
          #define GLX_CONTEXT_MINOR_VERSION_ARB       0x2092
          typedef GLXContext (*glXCreateContextAttribsARBProc)(Display*, GLXFBConfig, GLXContext, Bool, const int*);

          glXCreateContextAttribsARBProc glXCreateContextAttribsARB = 0;
          glXCreateContextAttribsARB = (glXCreateContextAttribsARBProc)glXGetProcAddressARB((const GLubyte*)"glXCreateContextAttribsARB");
          verify(glXCreateContextAttribsARB != 0);
          int context_attribs[] =
          {
            GLX_CONTEXT_MAJOR_VERSION_ARB, 3,
            GLX_CONTEXT_MINOR_VERSION_ARB, 1,
            GLX_CONTEXT_FLAGS_ARB, GLX_CONTEXT_DEBUG_BIT_ARB,
            GLX_CONTEXT_PROFILE_MASK_ARB, GLX_CONTEXT_CORE_PROFILE_BIT_ARB,
            None
          };

          x11_glc = glXCreateContextAttribsARB(x11Display, bestFbc, 0, True, context_attribs);
          XSync(x11Display, False);

          if (!x11_glc)
          {
            die("Failed to create GL3.1 context\n");
          }
        #endif
      #endif

      XFlush(x11Display);

      //(EGLNativeDisplayType)x11Display;
      x11_disp = (void*)x11Display;
      x11_win = (void*)x11Window;
    }
    else
    {
      printf("Not creating X11 window ..\n");
    }
  #endif
}
コード例 #18
0
WEAK void *halide_opengl_get_proc_address(void *user_context, const char *name) {
    return glXGetProcAddressARB(name);
}
コード例 #19
0
ファイル: xdriinfo.c プロジェクト: bitrig/bitrig-xenocara
int main (int argc, char *argv[]) {
    Display *dpy;
    int nScreens, screenNum, i;
    enum INFO_FUNC func = LIST;
    char *funcArg = NULL;
    char *dpyName = NULL;

    GetScreenDriver = (glXGetScreenDriver_t *)glXGetProcAddressARB ((const GLubyte *)"glXGetScreenDriver");
    GetDriverConfig = (glXGetDriverConfig_t *)glXGetProcAddressARB ((const GLubyte *)"glXGetDriverConfig");
    if (!GetScreenDriver || !GetDriverConfig) {
	fprintf (stderr, "libGL is too old.\n");
	return 1;
    }

  /* parse the command line */
    for (i = 1; i < argc; ++i) {
	char **argPtr = NULL;
	if (!strcmp (argv[i], "-display"))
	    argPtr = &dpyName;
	else if (!strcmp (argv[i], "nscreens"))
	    func = NSCREENS;
	else if (!strcmp (argv[i], "driver")) {
	    func = DRIVER;
	    argPtr = &funcArg;
	} else if (!strcmp (argv[i], "options")) {
	    func = OPTIONS;
	    argPtr = &funcArg;
	} else if (!strcmp (argv[i], "-version")) {
	    puts(PACKAGE_STRING);
	    return 0;
	} else {
	    fprintf (stderr, "%s: unrecognized argument '%s'\n",
		     argv[0], argv[i]);
	    printUsage ();
	    return 1;
	}
	if (argPtr) {
	    if (++i == argc) {
		fprintf (stderr, "%s: '%s' requires an argument\n",
			 argv[0], argv[i-1]);
		printUsage ();
		return 1;
	    }
	    *argPtr = argv[i];
	}
    }

  /* parse screen number argument */
    if (func == DRIVER || func == OPTIONS) {
	if (sscanf (funcArg, "%i", &screenNum) != 1)
	    screenNum = -1;
	else if (screenNum < 0) {
	    fprintf (stderr, "Negative screen number \"%s\".\n", funcArg);
	    return 1;
	}
    }
  /* if the argument to the options command is a driver name, we can handle
   * it without opening an X connection */
    if (func == OPTIONS && screenNum == -1) {
	const char *options = (*GetDriverConfig) (funcArg);
	if (!options) {
	    fprintf (stderr,
		     "Driver \"%s\" is not installed or does not support configuration.\n",
		     funcArg);
	    return 1;
	}
	printf ("%s", options);
	if (isatty (STDOUT_FILENO))
	    printf ("\n");
	return 0;
    } 
  /* driver command needs a valid screen number */
    else if (func == DRIVER && screenNum == -1) {
	fprintf (stderr, "Invalid screen number \"%s\".\n", funcArg);
	return 1;
    }

  /* open display and count the number of screens */
    if (!(dpy = XOpenDisplay (dpyName))) {
	fprintf (stderr, "Error: Couldn't open display\n");
	return 1;
    }
    nScreens = ScreenCount (dpy);

  /* final check on the screen number argument (if any)*/
    if ((func == DRIVER || func == OPTIONS) && screenNum >= nScreens) {
	fprintf (stderr, "Screen number \"%d\" out of range.\n", screenNum);
	return 1;
    }

    switch (func) {
      case NSCREENS:
	printf ("%d", nScreens);
	if (isatty (STDOUT_FILENO))
	    printf ("\n");
	break;
      case DRIVER: {
	  const char *name = (*GetScreenDriver) (dpy, screenNum);
	  if (!name) {
	      fprintf (stderr, "Screen \"%d\" is not direct rendering capable.\n",
		       screenNum);
	      return 1;
	  }
	  printf ("%s", name);
	  if (isatty (STDOUT_FILENO))
	      printf ("\n");
	  break;
      }
      case OPTIONS: {
	  const char *name = (*GetScreenDriver) (dpy, screenNum), *options;
	  if (!name) {
	      fprintf (stderr, "Screen \"%d\" is not direct rendering capable.\n",
		       screenNum);
	      return 1;
	  }
	  options = (*GetDriverConfig) (name);
	  if (!options) {
	      fprintf (stderr,
		       "Driver \"%s\" is not installed or does not support configuration.\n",
		       name);
	      return 1;
	  }
	  printf ("%s", options);
	  if (isatty (STDOUT_FILENO))
	      printf ("\n");
	  break;
      }
      case LIST:
	for (i = 0; i < nScreens; ++i) {
	    const char *name = (*GetScreenDriver) (dpy, i);
	    if (name)
		printf ("Screen %d: %s\n", i, name);
	    else
		printf ("Screen %d: not direct rendering capable.\n", i);
	}
    }

    return 0;
}
コード例 #20
0
void initShader( void )
{
	// If the required extension is present, get the addresses of its 
	// functions that we wish to use...
	char *ext = (char*)glGetString( GL_EXTENSIONS );
	
	if( strstr( ext, "GL_ARB_shading_language_100" ) == NULL )
	{
		// This extension string indicates that the OpenGL Shading Language,
		// version 1.00, is supported.
		printf( "GL_ARB_shading_language_100 extension was not found\n" );
		return;
	}
	
	if( strstr( ext, "GL_ARB_shader_objects" ) == NULL )
	{
		printf( "GL_ARB_shader_objects extension was not found\n" );
		return;
	}
	else
	{
        glCreateProgramObjectARB  = (PFNGLCREATEPROGRAMOBJECTARBPROC)glXGetProcAddressARB((GLubyte*)"glCreateProgramObjectARB");
        glDeleteObjectARB         = (PFNGLDELETEOBJECTARBPROC)glXGetProcAddressARB((GLubyte*)"glDeleteObjectARB");
        glUseProgramObjectARB     = (PFNGLUSEPROGRAMOBJECTARBPROC)glXGetProcAddressARB((GLubyte*)"glUseProgramObjectARB");
        glCreateShaderObjectARB   = (PFNGLCREATESHADEROBJECTARBPROC)glXGetProcAddressARB((GLubyte*)"glCreateShaderObjectARB");
        glShaderSourceARB         = (PFNGLSHADERSOURCEARBPROC)glXGetProcAddressARB((GLubyte*)"glShaderSourceARB");
        glCompileShaderARB        = (PFNGLCOMPILESHADERARBPROC)glXGetProcAddressARB((GLubyte*)"glCompileShaderARB");
        glGetObjectParameterivARB = (PFNGLGETOBJECTPARAMETERIVARBPROC)glXGetProcAddressARB((GLubyte*)"glGetObjectParameterivARB");
        glAttachObjectARB         = (PFNGLATTACHOBJECTARBPROC)glXGetProcAddressARB((GLubyte*)"glAttachObjectARB");
        glGetInfoLogARB           = (PFNGLGETINFOLOGARBPROC)glXGetProcAddressARB((GLubyte*)"glGetInfoLogARB");
        glLinkProgramARB          = (PFNGLLINKPROGRAMARBPROC)glXGetProcAddressARB((GLubyte*)"glLinkProgramARB");
        glGetUniformLocationARB   = (PFNGLGETUNIFORMLOCATIONARBPROC)glXGetProcAddressARB((GLubyte*)"glGetUniformLocationARB");
        glUniform4fARB            = (PFNGLUNIFORM4FARBPROC)glXGetProcAddressARB((GLubyte*)"glUniform4fARB");
		glUniform1iARB            = (PFNGLUNIFORM1IARBPROC)glXGetProcAddressARB((GLubyte*)"glUniform1iARB");
		glUniform2fARB            = (PFNGLUNIFORM2FARBPROC)glXGetProcAddressARB((GLubyte*)"glUniform2fARB");

        if( !glCreateProgramObjectARB || !glDeleteObjectARB || !glUseProgramObjectARB ||
            !glCreateShaderObjectARB || !glCreateShaderObjectARB || !glCompileShaderARB || 
            !glGetObjectParameterivARB || !glAttachObjectARB || !glGetInfoLogARB || 
            !glLinkProgramARB || !glGetUniformLocationARB || !glUniform4fARB ||
			!glUniform1iARB || !glUniform2fARB )
        {
			printf( "One or more GL_ARB_shader_objects functions were not found\n" );
			return;
		}
	}
	
    const char *vertexShaderStrings[1];
    const char *fragmentShaderStrings[1];
    GLint bVertCompiled;
    GLint bFragCompiled;
    GLint bLinked;
    char str[4096];
	
    // Create the vertex shader...
    g_vertexShader = glCreateShaderObjectARB( GL_VERTEX_SHADER_ARB );
	
	unsigned char *vertexShaderAssembly = readShaderFile( "./brightness.slv" );
    vertexShaderStrings[0] = (char*)vertexShaderAssembly;
    glShaderSourceARB( g_vertexShader, 1, vertexShaderStrings, NULL );
    glCompileShaderARB( g_vertexShader);
    delete [] vertexShaderAssembly;
	
    glGetObjectParameterivARB( g_vertexShader, GL_OBJECT_COMPILE_STATUS_ARB, &bVertCompiled );
    if( bVertCompiled  == false )
	{
		glGetInfoLogARB(g_vertexShader, sizeof(str), NULL, str);
        sprintf( str, "Vertex Shader Compile Error" );
    }
	
	// Create the fragment shader...
    g_fragmentShader = glCreateShaderObjectARB( GL_FRAGMENT_SHADER_ARB );
	
    unsigned char *fragmentShaderAssembly = readShaderFile( "./brightness.slf" );
    fragmentShaderStrings[0] = (char*)fragmentShaderAssembly;
    glShaderSourceARB( g_fragmentShader, 1, fragmentShaderStrings, NULL );
    glCompileShaderARB( g_fragmentShader );
    delete [] fragmentShaderAssembly;
	
    glGetObjectParameterivARB( g_fragmentShader, GL_OBJECT_COMPILE_STATUS_ARB, &bFragCompiled );
    if( bFragCompiled == false )
	{
		glGetInfoLogARB( g_fragmentShader, sizeof(str), NULL, str );
		sprintf( str, "Fragment Shader Compile Error" );
	}
	
    // Create a program object and attach the two compiled shaders...
    g_programObj = glCreateProgramObjectARB();
    glAttachObjectARB( g_programObj, g_vertexShader );
    glAttachObjectARB( g_programObj, g_fragmentShader );
	
    // Link the program object and print out the info log...
    glLinkProgramARB( g_programObj );
    glGetObjectParameterivARB( g_programObj, GL_OBJECT_LINK_STATUS_ARB, &bLinked );
	
    if( bLinked == false )
	{
		glGetInfoLogARB( g_programObj, sizeof(str), NULL, str );
		printf( "Linking Error\n" );
	}
}
コード例 #21
0
ファイル: glxapi.c プロジェクト: ChristophHaag/mesa-mesa
/* GLX 1.4 */
void PUBLIC
(*glXGetProcAddress(const GLubyte *procName))()
{
   return glXGetProcAddressARB(procName);
}
コード例 #22
0
// Create window
// 
// Much of the Creation code was taken from the openGL wiki at:
// 
// http://www.opengl.org/wiki/Tutorial:_OpenGL_3.0_Context_Creation_(GLX) on 2/1/13
// 
//-----------------------------------------------------------------------------
CPUTResult CPUTWindowX::Create(CPUT* cput, const std::string WindowTitle, CPUTWindowCreationParams windowParams)
{
    CPUTResult result = CPUT_ERROR;
    
    pDisplay = XOpenDisplay(NULL);
    if (!pDisplay) {
        return result;
    }

    int glx_major, glx_minor;

    // FBConfigs were added in GLX version 1.3.
    if (!glXQueryVersion(pDisplay, &glx_major, &glx_minor)) {
        printf( "glXQueryVersion failed" );
        exit(1);
    }
    
    if (((glx_major == 1) && (glx_minor < 3)) || (glx_major < 1)) {
        printf( "Invalid GLX version" );
        exit(1);
    }
    printf( "GLX version: %d.%d\n", glx_major, glx_minor );

    // Get a matching FB config
    int visual_attribs[] =
    {
        GLX_X_RENDERABLE    , True,
        GLX_DRAWABLE_TYPE   , GLX_WINDOW_BIT,
        GLX_RENDER_TYPE     , GLX_RGBA_BIT,
        GLX_X_VISUAL_TYPE   , GLX_TRUE_COLOR,
        GLX_RED_SIZE        , 8,
        GLX_GREEN_SIZE      , 8,
        GLX_BLUE_SIZE       , 8,
        GLX_ALPHA_SIZE      , 8,
        GLX_DEPTH_SIZE      , 24,
        GLX_STENCIL_SIZE    , 8,
        GLX_DOUBLEBUFFER    , True,
        //GLX_SAMPLE_BUFFERS  , 1,
        //GLX_SAMPLES         , 4,
        None
    };
    int fbcount;
    GLXFBConfig *fbc = glXChooseFBConfig(pDisplay, DefaultScreen( pDisplay ), visual_attribs, &fbcount );
    if ( !fbc )
    {
        printf( "Failed to retrieve a framebuffer config\n" );
        exit(1);
    }

    // Pick the FB config/visual with the most samples per pixel
    printf( "Getting XVisualInfos\n" );
    int best_fbc = -1, worst_fbc = -1, best_num_samp = -1, worst_num_samp = 999;
    
    for ( int i = 0; i < fbcount; i++ )
    {
        XVisualInfo *vi = glXGetVisualFromFBConfig( pDisplay, fbc[i] );
        if (vi)
        {
            int samp_buf, samples;
            glXGetFBConfigAttrib( pDisplay, fbc[i], GLX_SAMPLE_BUFFERS, &samp_buf );
            glXGetFBConfigAttrib( pDisplay, fbc[i], GLX_SAMPLES       , &samples  );
 
            printf( "  Matching fbconfig %d, visual ID 0lx%2lx: SAMPLE_BUFFERS = %d,"
                    " SAMPLES = %d\n", 
                    i, vi -> visualid, samp_buf, samples );
 
            if ( best_fbc < 0 || samp_buf && samples > best_num_samp ) {
                best_fbc = i, best_num_samp = samples;
            }
            if ( worst_fbc < 0 || !samp_buf || samples < worst_num_samp ) {
                worst_fbc = i, worst_num_samp = samples;
            }
        }
        XFree( vi );
    }
    
    GLXFBConfig bestFbc = fbc[ best_fbc ];

    // Be sure to free the FBConfig list allocated by glXChooseFBConfig()
    XFree( fbc );
    
    // Get a visual
    XVisualInfo *vi = glXGetVisualFromFBConfig( pDisplay, bestFbc );
    printf( "Chosen visual ID = 0x%lx\n", vi->visualid );
 
    printf( "Creating colormap\n" );
    XSetWindowAttributes swa;
    swa.colormap = XCreateColormap(pDisplay,
                                          RootWindow(pDisplay, vi->screen), 
                                          vi->visual, AllocNone );
    swa.background_pixmap = None ;
    swa.border_pixel      = 0;
    swa.event_mask        = ExposureMask | Button1MotionMask | ButtonPressMask | ButtonReleaseMask | KeyPressMask | KeyReleaseMask | StructureNotifyMask;
    
    printf( "Creating window\n" );
    win = XCreateWindow( pDisplay, RootWindow(pDisplay, vi->screen ), 
                        0, 0, windowParams.windowWidth, windowParams.windowHeight, 0, vi->depth, InputOutput, 
                        vi->visual, 
                        CWBorderPixel | CWColormap | CWEventMask, &swa );
    if ( !win )
    {
        printf( "Failed to create window.\n" );
        exit(1);
    }

    // Done with the visual info data
    XFree( vi );
 
    // register interest in the delete window message
    wmDeleteMessage = XInternAtom(pDisplay, "WM_DELETE_WINDOW", False);
    XSetWMProtocols(pDisplay, win, &wmDeleteMessage, 1);
   
    XStoreName( pDisplay, win, WindowTitle.c_str() );
    
    printf( "Mapping window\n" );
    XMapWindow( pDisplay, win );
 
    // Get the default screen's GLX extension list
    const char *glxExts = glXQueryExtensionsString(pDisplay,
                                                   DefaultScreen( pDisplay ) );

    // NOTE: It is not necessary to create or make current to a context before
    // calling glXGetProcAddressARB
    glXCreateContextAttribsARBProc glXCreateContextAttribsARB = 0;
    glXCreateContextAttribsARB = (glXCreateContextAttribsARBProc)
                                  glXGetProcAddressARB( (const GLubyte *) "glXCreateContextAttribsARB" );
 
    ctx = 0;
    
    // Install an X error handler so the application won't exit if GL 3.0
    // context allocation fails.
    //
    // Note this error handler is global.  All display connections in all threads
    // of a process use the same error handler, so be sure to guard against other
    // threads issuing X commands while this code is running.
    ctxErrorOccurred = false;
    int (*oldHandler)(Display*, XErrorEvent*) =
         XSetErrorHandler(&ctxErrorHandler);
 
    // Check for the GLX_ARB_create_context extension string and the function.
    // If either is not present, use GLX 1.3 context creation method.
    if (!isExtensionSupported( glxExts, "GLX_ARB_create_context" ) ||
        !glXCreateContextAttribsARB )
    {
        printf("glXCreateContextAttribsARB() not found"
               " ... using old-style GLX context\n" );
        ctx = glXCreateNewContext( pDisplay, bestFbc, GLX_RGBA_TYPE, 0, True );
    }
    else
    {
        int contextMajor = 3;
        int contextMinor = 3;
        printf( "Creating context %d.%d\n",  contextMajor, contextMinor);
        int context_attribs[] =
        {
            GLX_CONTEXT_MAJOR_VERSION_ARB, contextMajor,
            GLX_CONTEXT_MINOR_VERSION_ARB, contextMinor,
            GLX_CONTEXT_FLAGS_ARB        , GLX_CONTEXT_DEBUG_BIT_ARB,
            None
        };

        ctx = glXCreateContextAttribsARB(pDisplay, bestFbc, 0,
                                         True, context_attribs );

        // Sync to ensure any errors generated are processed.
        XSync( pDisplay, False );
        if ( !ctxErrorOccurred && ctx ) {
            printf( "Created GL 3.2 context\n" );
        } else {
            printf( "Failed to create requested context" );
        }
    }

    // Sync to ensure any errors generated are processed.
    XSync( pDisplay, False );
 
    // Restore the original error handler
    XSetErrorHandler( oldHandler );
    
    if ( ctxErrorOccurred || !ctx )
    {
        printf( "Failed to create an OpenGL context\n" );
        exit(1);
    }
 
    // Verifying that context is a direct context
    if ( ! glXIsDirect ( pDisplay, ctx ) )
    {
        printf( "Indirect GLX rendering context obtained\n" );
    }
    else
    {
        printf( "Direct GLX rendering context obtained\n" );
    }

    if (glXMakeCurrent( pDisplay, win, ctx ) == False) {
        printf( "glXMakeCurrent failed.");
    }

    glewExperimental=true;
    GLenum err = glewInit();
    if (GLEW_OK != err)
    {
        fprintf(stderr, "Error: %s\n", glewGetErrorString(err));
    }
    
    // glewInit can generate an error which is apparently innocuous. Clear it out here.
    // http://www.opengl.org/wiki/OpenGL_Loading_Library on 2/20/13
    glGetError();
    
    printf("Status: Using GLEW %s\n", glewGetString(GLEW_VERSION));
    printf("GL Version: %s\n", glGetString(GL_VERSION));


    return CPUT_SUCCESS;
}
コード例 #23
0
/**
 * Initialize fbconfig related function pointers.
 */
static void
init_fbconfig_functions(Display *dpy, int scrnum)
{
   const char * glx_extensions;
   const char * match;
   static const char ext_name[] = "GLX_SGIX_fbconfig";
   const size_t len = strlen( ext_name );
   int major;
   int minor;
   GLboolean ext_version_supported;
   GLboolean glx_1_3_supported;


   /* Determine if GLX 1.3 or greater is supported.
    */
   glXQueryVersion(dpy, & major, & minor);
   glx_1_3_supported = (major == 1) && (minor >= 3);

   /* Determine if GLX_SGIX_fbconfig is supported.
    */
   glx_extensions = glXQueryExtensionsString(dpy, scrnum);
   match = strstr( glx_extensions, ext_name );

   ext_version_supported = (match != NULL)
       && ((match[len] == '\0') || (match[len] == ' '));

   printf( "GLX 1.3 is %ssupported.\n",
	   (glx_1_3_supported) ? "" : "not " );
   printf( "%s is %ssupported.\n",
	   ext_name, (ext_version_supported) ? "" : "not " );

   if ( glx_1_3_supported ) {
      choose_fbconfig = (PFNGLXCHOOSEFBCONFIGSGIXPROC) glXGetProcAddressARB( 
		(GLbyte *) "glXChooseFBConfig");
      get_visual_from_fbconfig = (PFNGLXGETVISUALFROMFBCONFIGSGIXPROC) glXGetProcAddressARB( 
		(GLbyte *) "glXGetVisualFromFBConfig");
      create_new_context = (PFNGLXCREATECONTEXTWITHCONFIGSGIXPROC) glXGetProcAddressARB(
		(GLbyte *) "glXCreateNewContext");
   }
   else if ( ext_version_supported ) {
      choose_fbconfig = (PFNGLXCHOOSEFBCONFIGSGIXPROC) glXGetProcAddressARB( 
		(GLbyte *) "glXChooseFBConfigSGIX");
      get_visual_from_fbconfig = (PFNGLXGETVISUALFROMFBCONFIGSGIXPROC) glXGetProcAddressARB( 
		(GLbyte *) "glXGetVisualFromFBConfigSGIX");
      create_new_context = (PFNGLXCREATECONTEXTWITHCONFIGSGIXPROC) glXGetProcAddressARB(
		(GLbyte *) "glXCreateContextWithConfigSGIX");
   }
   else {
      printf( "This demo requires either GLX 1.3 or %s be supported.\n",
	      ext_name );
      exit(1);
   }

   if ( choose_fbconfig == NULL ) {
      printf( "glXChooseFBConfig not found!\n" );
      exit(1);
   }

   if ( get_visual_from_fbconfig == NULL ) {
      printf( "glXGetVisualFromFBConfig not found!\n" );
      exit(1);
   }

   if ( create_new_context == NULL ) {
      printf( "glXCreateNewContext not found!\n" );
      exit(1);
   }
}
コード例 #24
0
void X11OpenGLWindow::enableOpenGL()
{


    if (forceOpenGL3)
    {
 // Get the default screen's GLX extension list
  const char *glxExts = glXQueryExtensionsString( m_data->m_dpy,
                                                  DefaultScreen( m_data->m_dpy ) );

  // NOTE: It is not necessary to create or make current to a context before
  // calling glXGetProcAddressARB, unless we dynamically load OpenGL/GLX/X11

  glXCreateContextAttribsARBProc glXCreateContextAttribsARB = 0;
  glXCreateContextAttribsARB = (glXCreateContextAttribsARBProc)
           glXGetProcAddressARB( (const GLubyte *) "glXCreateContextAttribsARB" );

  GLXContext ctx = 0;

  // Install an X error handler so the application won't exit if GL 3.0
  // context allocation fails.
  //
  // Note this error handler is global.  All display connections in all threads
  // of a process use the same error handler, so be sure to guard against other
  // threads issuing X commands while this code is running.
  ctxErrorOccurred = false;
  int (*oldHandler)(Display*, XErrorEvent*) =
         MyXSetErrorHandler(&ctxErrorHandler);

  // Check for the GLX_ARB_create_context extension string and the function.
  // If either is not present, use GLX 1.3 context creation method.
  if ( !isExtensionSupported( glxExts, "GLX_ARB_create_context" ) ||
       !glXCreateContextAttribsARB )
  {
    printf( "glXCreateContextAttribsARB() not found"
            " ... using old-style GLX context\n" );
    ctx = glXCreateNewContext( m_data->m_dpy, m_data->m_bestFbc, GLX_RGBA_TYPE, 0, True );
  }

  // If it does, try to get a GL 3.0 context!
  else
  {
	 int context_attribs[] = {
          GLX_CONTEXT_MAJOR_VERSION_ARB ,3,
          GLX_CONTEXT_MINOR_VERSION_ARB, 2,
          GLX_CONTEXT_FLAGS_ARB, GLX_CONTEXT_DEBUG_BIT_ARB,
          GLX_CONTEXT_PROFILE_MASK_ARB, GLX_CONTEXT_CORE_PROFILE_BIT_ARB,None
     };
/*
    int context_attribs[] =
      {
        GLX_CONTEXT_MAJOR_VERSION_ARB, 3,
        GLX_CONTEXT_MINOR_VERSION_ARB, 2,

        //GLX_CONTEXT_FLAGS_ARB        , GLX_CONTEXT_FORWARD_COMPATIBLE_BIT_ARB,
        None
      };
*/
    printf( "Creating context\n" );
    ctx = glXCreateContextAttribsARB( m_data->m_dpy, m_data->m_bestFbc, 0,
                                      True, context_attribs );

    // Sync to ensure any errors generated are processed.
    MyXSync( m_data->m_dpy, False );
    if ( !ctxErrorOccurred && ctx )
      printf( "Created GL 3.0 context\n" );
    else
    {
      // Couldn't create GL 3.0 context.  Fall back to old-style 2.x context.
      // When a context version below 3.0 is requested, implementations will
      // return the newest context version compatible with OpenGL versions less
      // than version 3.0.
      // GLX_CONTEXT_MAJOR_VERSION_ARB = 1
      context_attribs[1] = 1;
      // GLX_CONTEXT_MINOR_VERSION_ARB = 0
      context_attribs[3] = 0;

      ctxErrorOccurred = false;

      printf( "Failed to create GL 3.0 context"
              " ... using old-style GLX context\n" );
      ctx = glXCreateContextAttribsARB( m_data->m_dpy, m_data->m_bestFbc, 0,
                                        True, context_attribs );
    }
  }

  // Sync to ensure any errors generated are processed.
  MyXSync( m_data->m_dpy, False );

  // Restore the original error handler
  MyXSetErrorHandler( oldHandler );

  if ( ctxErrorOccurred || !ctx )
  {
    printf( "Failed to create an OpenGL context\n" );
    exit(1);
  }

  // Verifying that context is a direct context
  if ( ! glXIsDirect ( m_data->m_dpy, ctx ) )
  {
    printf( "Indirect GLX rendering context obtained\n" );
  }
  else
  {
    printf( "Direct GLX rendering context obtained\n" );
  }

  printf( "Making context current\n" );
  glXMakeCurrent( m_data->m_dpy, m_data->m_win, ctx );
  m_data->m_glc = ctx;

    } else
    {
        m_data->m_glc = glXCreateContext(m_data->m_dpy, m_data->m_vi, NULL, GL_TRUE);
        glXMakeCurrent(m_data->m_dpy, m_data->m_win, m_data->m_glc);
    }

#ifdef GLEW_INIT_OPENGL11_FUNCTIONS
{
	GLboolean res = glewOpenGL11Init();
	if (res==0)
		{
			printf("glewOpenGL11Init OK!\n");
		} else
			{
				printf("ERROR: glewOpenGL11Init failed, exiting!\n");
				exit(0);
			}
}

#endif //GLEW_INIT_OPENGL11_FUNCTIONS

    const GLubyte* ven = glGetString(GL_VENDOR);
    printf("GL_VENDOR=%s\n", ven);

    const GLubyte* ren = glGetString(GL_RENDERER);
    printf("GL_RENDERER=%s\n",ren);
    const GLubyte* ver = glGetString(GL_VERSION);
    printf("GL_VERSION=%s\n", ver);
    const GLubyte* sl = glGetString(GL_SHADING_LANGUAGE_VERSION);
    printf("GL_SHADING_LANGUAGE_VERSION=%s\n", sl);

//Access pthreads as a workaround for a bug in Linux/Ubuntu
//See https://bugs.launchpad.net/ubuntu/+source/nvidia-graphics-drivers-319/+bug/1248642

	int i=pthread_getconcurrency();
        printf("pthread_getconcurrency()=%d\n",i);

//    const GLubyte* ext = glGetString(GL_EXTENSIONS);
//    printf("GL_EXTENSIONS=%s\n", ext);
}
コード例 #25
0
// Create window
// 
// Much of the Creation code was taken from the openGL wiki at:
// 
// http://www.opengl.org/wiki/Tutorial:_OpenGL_3.0_Context_Creation_(GLX) on 2/1/13
// 
//-----------------------------------------------------------------------------
CPUTResult CPUTWindowX::Create(CPUT* cput, const cString WindowTitle, const int windowWidth, const int windowHeight, int windowX, int windowY)
{
    CPUTResult result = CPUT_ERROR;
    
	pDisplay = XOpenDisplay(NULL);
    if (!pDisplay) {
        return result;
    }
    
    // Get a matching FB config
    int visual_attribs[] =
    {
        GLX_X_RENDERABLE    , True,
        GLX_DRAWABLE_TYPE   , GLX_WINDOW_BIT,
        GLX_RENDER_TYPE     , GLX_RGBA_BIT,
        GLX_X_VISUAL_TYPE   , GLX_TRUE_COLOR,
        GLX_RED_SIZE        , 8,
        GLX_GREEN_SIZE      , 8,
        GLX_BLUE_SIZE       , 8,
        GLX_ALPHA_SIZE      , 8,
        GLX_DEPTH_SIZE      , 24,
        GLX_STENCIL_SIZE    , 8,
        GLX_DOUBLEBUFFER    , True,
        //GLX_SAMPLE_BUFFERS  , 1,
        //GLX_SAMPLES         , 4,
        None
    };
    
    int glx_major, glx_minor;

    // FBConfigs were added in GLX version 1.3.
    if (!glXQueryVersion(pDisplay, &glx_major, &glx_minor)) {
        printf( "glXQueryVersion failed" );
        exit(1);
    }
    
    if (((glx_major == 1) && (glx_minor < 3)) || (glx_major < 1)) {
        printf( "Invalid GLX version" );
        exit(1);
    }
    printf( "GLX version: %d.%d\n", glx_major, glx_minor );
    
    // Getting matching framebuffer configs
    int fbcount;
    GLXFBConfig *fbc = glXChooseFBConfig(pDisplay, DefaultScreen( pDisplay ), visual_attribs, &fbcount );
    if ( !fbc )
    {
        printf( "Failed to retrieve a framebuffer config\n" );
        exit(1);
    }

    // Pick the FB config/visual with the most samples per pixel
    printf( "Getting XVisualInfos\n" );
    int best_fbc = -1, worst_fbc = -1, best_num_samp = -1, worst_num_samp = 999;
    
    for ( int i = 0; i < fbcount; i++ )
    {
        XVisualInfo *vi = glXGetVisualFromFBConfig( pDisplay, fbc[i] );
        if (vi)
        {
            int samp_buf, samples;
            glXGetFBConfigAttrib( pDisplay, fbc[i], GLX_SAMPLE_BUFFERS, &samp_buf );
            glXGetFBConfigAttrib( pDisplay, fbc[i], GLX_SAMPLES       , &samples  );
 
            printf( "  Matching fbconfig %d, visual ID 0lx%2lx: SAMPLE_BUFFERS = %d,"
                    " SAMPLES = %d\n", 
                    i, vi -> visualid, samp_buf, samples );
 
            if ( best_fbc < 0 || samp_buf && samples > best_num_samp ) {
                best_fbc = i, best_num_samp = samples;
            }
            if ( worst_fbc < 0 || !samp_buf || samples < worst_num_samp ) {
                worst_fbc = i, worst_num_samp = samples;
            }
        }
        XFree( vi );
    }
    
    GLXFBConfig bestFbc = fbc[ best_fbc ];
 
    // Be sure to free the FBConfig list allocated by glXChooseFBConfig()
    XFree( fbc );
    
    // Get a visual
    XVisualInfo *vi = glXGetVisualFromFBConfig( pDisplay, bestFbc );
    printf( "Chosen visual ID = 0x%lx\n", vi->visualid );
 
    printf( "Creating colormap\n" );
    XSetWindowAttributes swa;
    swa.colormap = XCreateColormap(pDisplay,
                                          RootWindow(pDisplay, vi->screen), 
                                          vi->visual, AllocNone );
    swa.background_pixmap = None ;
    swa.border_pixel      = 0;
    swa.event_mask        = ExposureMask | Button1MotionMask | ButtonPressMask | ButtonReleaseMask | KeyPressMask | KeyReleaseMask | StructureNotifyMask;
    
    printf( "Creating window\n" );
    win = XCreateWindow( pDisplay, RootWindow(pDisplay, vi->screen ), 
                        0, 0, windowWidth, windowHeight, 0, vi->depth, InputOutput, 
                        vi->visual, 
                        CWBorderPixel | CWColormap | CWEventMask, &swa );
    if ( !win )
    {
        printf( "Failed to create window.\n" );
        exit(1);
    }

    // Done with the visual info data
    XFree( vi );
 
    // register interest in the delete window message
    wmDeleteMessage = XInternAtom(pDisplay, "WM_DELETE_WINDOW", False);
    XSetWMProtocols(pDisplay, win, &wmDeleteMessage, 1);
   
    XStoreName( pDisplay, win, "GL 4.0 Window" );
    
    printf( "Mapping window\n" );
    XMapWindow( pDisplay, win );
 
    // Get the default screen's GLX extension list
    const char *glxExts = glXQueryExtensionsString(pDisplay,
                                                   DefaultScreen( pDisplay ) );
 
    // NOTE: It is not necessary to create or make current to a context before
    // calling glXGetProcAddressARB
    glXCreateContextAttribsARBProc glXCreateContextAttribsARB = 0;
    glXCreateContextAttribsARB = (glXCreateContextAttribsARBProc)
                                  glXGetProcAddressARB( (const GLubyte *) "glXCreateContextAttribsARB" );
 
    ctx = 0;
    
    // Install an X error handler so the application won't exit if GL 3.0
    // context allocation fails.
    //
    // Note this error handler is global.  All display connections in all threads
    // of a process use the same error handler, so be sure to guard against other
    // threads issuing X commands while this code is running.
    ctxErrorOccurred = false;
    int (*oldHandler)(Display*, XErrorEvent*) =
         XSetErrorHandler(&ctxErrorHandler);
 
    // Check for the GLX_ARB_create_context extension string and the function.
    // If either is not present, use GLX 1.3 context creation method.
    if (!isExtensionSupported( glxExts, "GLX_ARB_create_context" ) ||
        !glXCreateContextAttribsARB )
    {
        printf("glXCreateContextAttribsARB() not found"
               " ... using old-style GLX context\n" );
        ctx = glXCreateNewContext( pDisplay, bestFbc, GLX_RGBA_TYPE, 0, True );
    }
    
    // If it does, try to get a GL 3.0 context!
    else
    {
        int context_attribs[] =
        {
            GLX_CONTEXT_MAJOR_VERSION_ARB, 4,
            GLX_CONTEXT_MINOR_VERSION_ARB, 1,
            GLX_CONTEXT_FLAGS_ARB        , GLX_CONTEXT_DEBUG_BIT_ARB,
            None
        };
 
        printf( "Creating context %d.%d\n",  4, 1);
        ctx = glXCreateContextAttribsARB(pDisplay, bestFbc, 0,
                                         True, context_attribs );
 
        // Sync to ensure any errors generated are processed.
        XSync( pDisplay, False );
        if ( !ctxErrorOccurred && ctx ) {
            printf( "Created GL 3.2 context\n" );
        }
        else
        {
            // Couldn't create GL 3.0 context.  Fall back to old-style 2.x context.
            // When a context version below 3.0 is requested, implementations will
            // return the newest context version compatible with OpenGL versions less
            // than version 3.0.
            // GLX_CONTEXT_MAJOR_VERSION_ARB = 1
            context_attribs[1] = 1;
            // GLX_CONTEXT_MINOR_VERSION_ARB = 0
            context_attribs[3] = 0;
 
            ctxErrorOccurred = false;
 
            printf( "Failed to create GL 3.0 context"
                    " ... using old-style GLX context\n" );
 //           ctx = glXCreateContextAttribsARB( pDisplay, bestFbc, 0, 
   //                                           True, context_attribs );
        }
    }
 
    // Sync to ensure any errors generated are processed.
    XSync( pDisplay, False );
 
    // Restore the original error handler
    XSetErrorHandler( oldHandler );
    
    if ( ctxErrorOccurred || !ctx )
    {
        printf( "Failed to create an OpenGL context\n" );
        exit(1);
    }
 
    // Verifying that context is a direct context
    if ( ! glXIsDirect ( pDisplay, ctx ) )
    {
        printf( "Indirect GLX rendering context obtained\n" );
    }
    else
    {
        printf( "Direct GLX rendering context obtained\n" );
    }
    
    printf( "Making context current\n" );
    glXMakeCurrent( pDisplay, win, ctx );

    glewExperimental=true;
    GLenum err = glewInit();
    if (GLEW_OK != err)
    {
        /* Problem: glewInit failed, something is seriously wrong. */
        fprintf(stderr, "Error: %s\n", glewGetErrorString(err));
    }
    
    // glewInit can generate an error which is apparently innocuous. Clear it out here.
    // http://www.opengl.org/wiki/OpenGL_Loading_Library on 2/20/13
    glGetError();
    
    fprintf(stdout, "Status: Using GLEW %s\n", glewGetString(GLEW_VERSION));
    
    glClearColor ( 0, 0.5, 1, 1 );
    glClear ( GL_COLOR_BUFFER_BIT );
    glXSwapBuffers ( pDisplay, win );
    sleep( 1 );
 
    glClearColor ( 1, 0.5, 0, 1 );
    glClear ( GL_COLOR_BUFFER_BIT );
    glXSwapBuffers ( pDisplay, win );
 
    sleep( 1 );

    printf("GL Version: %s\n", glGetString(GL_VERSION));
    
    if (GLEW_ARB_vertex_array_object) {
        /* It is safe to use the ARB_vertex_program extension here. */
        printf("VAOs are supported\n");
    } else {
        printf("VAOs are NOT supported\n");    
    }
    
    if (GLEW_VERSION_4_0)
    {
        printf("OpenGL version 4.0 supported\n");
    } else {
        printf("OpenGL version 4.0 NOT supported\n");
    }
    
    mCPUT = (CPUT*) cput;
    
    /*
    if(mhWnd)
    {
        return CPUT_ERROR_WINDOW_ALREADY_EXISTS;
    }

    ASSERT( (windowX < GetSystemMetrics(SM_CXFULLSCREEN) && (windowX>=-1)), _L("You are attempting to create a window outside the desktop coordinates.  Check your CPUTWindowCreationParams"));
    ASSERT( (windowY < GetSystemMetrics(SM_CYFULLSCREEN) && (windowY>=-1)), _L("You are attempting to create a window outside the desktop coordinates.  Check your CPUTWindowCreationParams"));

    // get the hInstance of this executable
    mhInst = GetModuleHandle(NULL);
    if(NULL==mhInst)
    {
        return CPUT_ERROR_CANNOT_GET_WINDOW_INSTANCE;
    }

    // set up app title (if not specified)
    mAppTitle = WindowTitle;

    if(0==mAppTitle.compare(_L("")))
    {
        mAppTitle = _L("CPUT Sample");
    }

    // Register the Win32 class for this app
    WNDCLASS wc;
    if(TRUE == GetClassInfo(mhInst, mAppTitle.c_str(), &wc))
    {
        // point to the existing one
        mhInst = wc.hInstance;
    }
    else
    {
        // register a new windows class
        ATOM classID;
        classID = MyRegisterClass(mhInst);
        if(0==classID)
        {
			HandleWin32Error();
            return CPUT_ERROR_WINDOW_CANNOT_REGISTER_APP;
        }
    }


	// Perform Win32 instance initialization
    const int nCmdShow = SW_SHOWNORMAL;
	if (false == InitInstance(nCmdShow, windowWidth, windowHeight, windowX, windowY))
	{
		return CPUT_ERROR_CANNOT_GET_WINDOW_INSTANCE;
	}

    // store the CPUT pointer
    mCPUT = (CPUT*) cput;
*/
    return CPUT_SUCCESS;
}
コード例 #26
0
const GrGLInterface* SkNativeGLContext::createGLContext(GrGLStandard forcedGpuAPI) {
    fDisplay = XOpenDisplay(0);

    if (!fDisplay) {
        SkDebugf("Failed to open X display.\n");
        this->destroyGLContext();
        return NULL;
    }

    // Get a matching FB config
    static int visual_attribs[] = {
        GLX_X_RENDERABLE    , True,
        GLX_DRAWABLE_TYPE   , GLX_PIXMAP_BIT,
        None
    };

    int glx_major, glx_minor;

    // FBConfigs were added in GLX version 1.3.
    if (!glXQueryVersion(fDisplay, &glx_major, &glx_minor) ||
            ((glx_major == 1) && (glx_minor < 3)) || (glx_major < 1)) {
        SkDebugf("GLX version 1.3 or higher required.\n");
        this->destroyGLContext();
        return NULL;
    }

    //SkDebugf("Getting matching framebuffer configs.\n");
    int fbcount;
    GLXFBConfig *fbc = glXChooseFBConfig(fDisplay, DefaultScreen(fDisplay),
                                          visual_attribs, &fbcount);
    if (!fbc) {
        SkDebugf("Failed to retrieve a framebuffer config.\n");
        this->destroyGLContext();
        return NULL;
    }
    //SkDebugf("Found %d matching FB configs.\n", fbcount);

    // Pick the FB config/visual with the most samples per pixel
    //SkDebugf("Getting XVisualInfos.\n");
    int best_fbc = -1, best_num_samp = -1;

    int i;
    for (i = 0; i < fbcount; ++i) {
        XVisualInfo *vi = glXGetVisualFromFBConfig(fDisplay, fbc[i]);
        if (vi) {
            int samp_buf, samples;
            glXGetFBConfigAttrib(fDisplay, fbc[i], GLX_SAMPLE_BUFFERS, &samp_buf);
            glXGetFBConfigAttrib(fDisplay, fbc[i], GLX_SAMPLES, &samples);

            //SkDebugf("  Matching fbconfig %d, visual ID 0x%2x: SAMPLE_BUFFERS = %d,"
            //       " SAMPLES = %d\n",
            //        i, (unsigned int)vi->visualid, samp_buf, samples);

            if (best_fbc < 0 || (samp_buf && samples > best_num_samp))
                best_fbc = i, best_num_samp = samples;
        }
        XFree(vi);
    }

    GLXFBConfig bestFbc = fbc[best_fbc];

    // Be sure to free the FBConfig list allocated by glXChooseFBConfig()
    XFree(fbc);

    // Get a visual
    XVisualInfo *vi = glXGetVisualFromFBConfig(fDisplay, bestFbc);
    //SkDebugf("Chosen visual ID = 0x%x\n", (unsigned int)vi->visualid);

    fPixmap = XCreatePixmap(fDisplay, RootWindow(fDisplay, vi->screen), 10, 10, vi->depth);

    if (!fPixmap) {
        SkDebugf("Failed to create pixmap.\n");
        this->destroyGLContext();
        return NULL;
    }

    fGlxPixmap = glXCreateGLXPixmap(fDisplay, vi, fPixmap);

    // Done with the visual info data
    XFree(vi);

    // Create the context

    // Install an X error handler so the application won't exit if GL 3.0
    // context allocation fails.
    //
    // Note this error handler is global.
    // All display connections in all threads of a process use the same
    // error handler, so be sure to guard against other threads issuing
    // X commands while this code is running.
    ctxErrorOccurred = false;
    int (*oldHandler)(Display*, XErrorEvent*) =
        XSetErrorHandler(&ctxErrorHandler);

    // Get the default screen's GLX extension list
    const char *glxExts = glXQueryExtensionsString(
        fDisplay, DefaultScreen(fDisplay)
    );


    // Check for the GLX_ARB_create_context extension string and the function.
    // If either is not present, use GLX 1.3 context creation method.
    if (!gluCheckExtension(reinterpret_cast<const GLubyte*>("GLX_ARB_create_context"),
                           reinterpret_cast<const GLubyte*>(glxExts))) {
        if (kGLES_GrGLStandard != forcedGpuAPI) {
            fContext = glXCreateNewContext(fDisplay, bestFbc, GLX_RGBA_TYPE, 0, True);
        }
    } else {
        //SkDebugf("Creating context.\n");
        PFNGLXCREATECONTEXTATTRIBSARBPROC glXCreateContextAttribsARB =
            (PFNGLXCREATECONTEXTATTRIBSARBPROC) glXGetProcAddressARB((GrGLubyte*)"glXCreateContextAttribsARB");

        if (kGLES_GrGLStandard == forcedGpuAPI) {
            if (gluCheckExtension(
                    reinterpret_cast<const GLubyte*>("GLX_EXT_create_context_es2_profile"),
                    reinterpret_cast<const GLubyte*>(glxExts))) {
                static const int context_attribs_gles[] = {
                    GLX_CONTEXT_MAJOR_VERSION_ARB, 3,
                    GLX_CONTEXT_MINOR_VERSION_ARB, 0,
                    GLX_CONTEXT_PROFILE_MASK_ARB, GLX_CONTEXT_ES2_PROFILE_BIT_EXT,
                    None
                };
                fContext = glXCreateContextAttribsARB(fDisplay, bestFbc, 0, True,
                                                      context_attribs_gles);
            }
        } else {
            // Well, unfortunately GLX will not just give us the highest context so instead we have
            // to do this nastiness
            for (i = NUM_GL_VERSIONS - 2; i > 0 ; i--) {
                /* don't bother below GL 3.0 */
                if (gl_versions[i].major == 3 && gl_versions[i].minor == 0) {
                    break;
                }
                // On Nvidia GPUs, to use Nv Path rendering we need a compatibility profile for the
                // time being.
                // TODO when Nvidia implements NVPR on Core profiles, we should start requesting
                // core here
                static const int context_attribs_gl[] = {
                      GLX_CONTEXT_MAJOR_VERSION_ARB, gl_versions[i].major,
                      GLX_CONTEXT_MINOR_VERSION_ARB, gl_versions[i].minor,
                      GLX_CONTEXT_PROFILE_MASK_ARB, GLX_CONTEXT_COMPATIBILITY_PROFILE_BIT_ARB,
                      None
                };
                fContext =
                        glXCreateContextAttribsARB(fDisplay, bestFbc, 0, True, context_attribs_gl);

                // Sync to ensure any errors generated are processed.
                XSync(fDisplay, False);

                if (!ctxErrorOccurred && fContext) {
                    break;
                }
                // try again
                ctxErrorOccurred = false;
            }

            // Couldn't create GL 3.0 context.
            // Fall back to old-style 2.x context.
            // When a context version below 3.0 is requested,
            // implementations will return the newest context version
            // compatible with OpenGL versions less than version 3.0.
            if (ctxErrorOccurred || !fContext) {
                static const int context_attribs_gl_fallback[] = {
                    GLX_CONTEXT_MAJOR_VERSION_ARB, 1,
                    GLX_CONTEXT_MINOR_VERSION_ARB, 0,
                    None
                };

                ctxErrorOccurred = false;

                fContext = glXCreateContextAttribsARB(fDisplay, bestFbc, 0, True,
                                                      context_attribs_gl_fallback);
            }
        }
    }

    // Sync to ensure any errors generated are processed.
    XSync(fDisplay, False);

    // Restore the original error handler
    XSetErrorHandler(oldHandler);

    if (ctxErrorOccurred || !fContext) {
        SkDebugf("Failed to create an OpenGL context.\n");
        this->destroyGLContext();
        return NULL;
    }

    // Verify that context is a direct context
    if (!glXIsDirect(fDisplay, fContext)) {
        //SkDebugf("Indirect GLX rendering context obtained.\n");
    } else {
        //SkDebugf("Direct GLX rendering context obtained.\n");
    }

    //SkDebugf("Making context current.\n");
    if (!glXMakeCurrent(fDisplay, fGlxPixmap, fContext)) {
      SkDebugf("Could not set the context.\n");
        this->destroyGLContext();
        return NULL;
    }

    const GrGLInterface* interface = GrGLCreateNativeInterface();
    if (!interface) {
        SkDebugf("Failed to create gl interface");
        this->destroyGLContext();
        return NULL;
    }
    return interface;
}
コード例 #27
0
ファイル: depthmapRenderer.cpp プロジェクト: Cerarus/v4r
DepthmapRenderer::DepthmapRenderer(int resx, int resy)
{
    //First of all: create opengl context:
    //res=glm::ivec2(resx,resy);
    res=Eigen::Vector2i(resx,resy);

    if(counter==0){
        //BEGIN OF COPYCAT CODE
        static int visual_attribs[] = {
                None
        };
        int context_attribs[] = {
                GLX_CONTEXT_MAJOR_VERSION_ARB, 3,
                GLX_CONTEXT_MINOR_VERSION_ARB, 0,
                None
        };

        dpy = XOpenDisplay(0);
        int fbcount = 0;
        GLXFBConfig* fbc = NULL;

        GLXPbuffer pbuf;

        /* open display */
        if ( ! (dpy = XOpenDisplay(0)) ){
                fprintf(stderr, "Failed to open display\n");
                exit(1);
        }

        /* get framebuffer configs, any is usable (might want to add proper attribs) */
        if ( !(fbc = glXChooseFBConfig(dpy, DefaultScreen(dpy), visual_attribs, &fbcount) ) ){
                fprintf(stderr, "Failed to get FBConfig\n");
                exit(1);
        }

        /* get the required extensions */
        glXCreateContextAttribsARB = (glXCreateContextAttribsARBProc)glXGetProcAddressARB( (const GLubyte *) "glXCreateContextAttribsARB");
        glXMakeContextCurrentARB = (glXMakeContextCurrentARBProc)glXGetProcAddressARB( (const GLubyte *) "glXMakeContextCurrent");
        if ( !(glXCreateContextAttribsARB && glXMakeContextCurrentARB) ){
                fprintf(stderr, "missing support for GLX_ARB_create_context\n");
                XFree(fbc);
                exit(1);
        }

        /* create a context using glXCreateContextAttribsARB */
        if ( !( ctx = glXCreateContextAttribsARB(dpy, fbc[0], 0, True, context_attribs)) ){
                fprintf(stderr, "Failed to create opengl context\n");
                XFree(fbc);
                exit(1);
        }

        /* create temporary pbuffer */
        int pbuffer_attribs[] = {
                GLX_PBUFFER_WIDTH, 800,
                GLX_PBUFFER_HEIGHT, 600,
                None
        };
        pbuf = glXCreatePbuffer(dpy, fbc[0], pbuffer_attribs);

        XFree(fbc);
        XSync(dpy, False);

        /* try to make it the current context */
        if ( !glXMakeContextCurrent(dpy, pbuf, pbuf, ctx) ){
            /* some drivers does not support context without default framebuffer, so fallback on
             * using the default window.
             */
            if ( !glXMakeContextCurrent(dpy, DefaultRootWindow(dpy), DefaultRootWindow(dpy), ctx) ){
                fprintf(stderr, "failed to make current\n");
                exit(1);
            }
        }


        /* try it out */
        // printf("vendor: %s\n", (const char*)glGetString(GL_VENDOR));
        //END OF COPYCATCODE
    }
    counter++;


    GLenum err=glewInit();

    if(err!=GLEW_OK){
        std::stringstream s; s << "glewInit failed, aborting. " << err;
        throw std::runtime_error(s.str());
    }

    glGetError();
    //create framebuffer:

    //Hardcoded shader:
    const char *vertex=
            "#version 450 \n\
            in vec4 pos;\n\
            out vec4 colorIn;\n\
            void main(){\n\
               gl_Position=vec4(pos.xyz,1);\n\
               colorIn=unpackUnorm4x8(floatBitsToUint(pos.w));\n\
            }";
コード例 #28
0
static gboolean
gst_gl_context_glx_create_context (GstGLContext * context,
    GstGLAPI gl_api, GstGLContext * other_context, GError ** error)
{
  GstGLContextGLX *context_glx;
  GstGLWindow *window;
  GstGLWindowX11 *window_x11;
  GstGLDisplay *display;
  gboolean create_context;
  const char *glx_exts;
  int x_error = 0;
  Display *device;
  guintptr external_gl_context = 0;

  context_glx = GST_GL_CONTEXT_GLX (context);
  window = gst_gl_context_get_window (context);
  window_x11 = GST_GL_WINDOW_X11 (window);
  display = gst_gl_context_get_display (context);

  if (other_context) {
    if (gst_gl_context_get_gl_platform (other_context) != GST_GL_PLATFORM_GLX) {
      g_set_error (error, GST_GL_CONTEXT_ERROR,
          GST_GL_CONTEXT_ERROR_WRONG_CONFIG,
          "Cannot share context with non-GLX context");
      goto failure;
    }

    external_gl_context = gst_gl_context_get_gl_context (other_context);
  }

  device = (Display *) gst_gl_display_get_handle (display);
  glx_exts = glXQueryExtensionsString (device, DefaultScreen (device));

  create_context = gst_gl_check_extension ("GLX_ARB_create_context", glx_exts);
  context_glx->priv->glXCreateContextAttribsARB =
      (gpointer) glXGetProcAddressARB ((const GLubyte *)
      "glXCreateContextAttribsARB");

  if (create_context && context_glx->priv->glXCreateContextAttribsARB) {
    int context_attribs_3[] = {
      GLX_CONTEXT_MAJOR_VERSION_ARB, 3,
      GLX_CONTEXT_MINOR_VERSION_ARB, 1,
      GLX_CONTEXT_FLAGS_ARB, GLX_CONTEXT_FORWARD_COMPATIBLE_BIT_ARB,
#if !defined(GST_DISABLE_GST_DEBUG)
      GLX_CONTEXT_FLAGS_ARB, GLX_CONTEXT_DEBUG_BIT_ARB,
#endif
      None
    };

    int context_attribs_pre_3[] = {
      GLX_CONTEXT_MAJOR_VERSION_ARB, 1,
      GLX_CONTEXT_MINOR_VERSION_ARB, 4,
      None
    };

    if (gl_api & GST_GL_API_OPENGL3) {
      GST_DEBUG_OBJECT (window, "trying to create a GL 3.1 core context");
      gst_gl_window_x11_trap_x_errors ();
      context_glx->glx_context =
          context_glx->priv->glXCreateContextAttribsARB (device,
          context_glx->priv->fbconfigs[0], (GLXContext) external_gl_context,
          True, context_attribs_3);

      x_error = gst_gl_window_x11_untrap_x_errors ();

      if (x_error != 0)
        context_glx->glx_context = NULL;
      context_glx->priv->context_api = GST_GL_API_OPENGL3;
    }

    if (gl_api & GST_GL_API_OPENGL && context_glx->glx_context == NULL) {
      GST_DEBUG_OBJECT (window, "trying to create a GL 1.4 context");

      gst_gl_window_x11_trap_x_errors ();
      context_glx->glx_context =
          context_glx->priv->glXCreateContextAttribsARB (device,
          context_glx->priv->fbconfigs[0], (GLXContext) external_gl_context,
          True, context_attribs_pre_3);

      x_error = gst_gl_window_x11_untrap_x_errors ();

      if (x_error != 0)
        context_glx->glx_context = NULL;
      context_glx->priv->context_api = GST_GL_API_OPENGL;
    }

  } else {
    context_glx->glx_context =
        glXCreateContext (device, window_x11->visual_info,
        (GLXContext) external_gl_context, TRUE);
    context_glx->priv->context_api = GST_GL_API_OPENGL;
  }

  if (context_glx->priv->fbconfigs)
    XFree (context_glx->priv->fbconfigs);

  if (!context_glx->glx_context) {
    g_set_error (error, GST_GL_CONTEXT_ERROR,
        GST_GL_CONTEXT_ERROR_CREATE_CONTEXT, "Failed to create opengl context");
    goto failure;
  }

  GST_LOG ("gl context id: %ld", (gulong) context_glx->glx_context);

  gst_object_unref (window);
  gst_object_unref (display);

  return TRUE;

failure:
  if (window)
    gst_object_unref (window);
  gst_object_unref (display);

  return FALSE;
}
コード例 #29
0
ファイル: gl_hwdec_vaglx.c プロジェクト: AoD314/mpv
static int create(struct gl_hwdec *hw)
{
    if (hw->hwctx)
        return -1;
    Display *x11disp = glXGetCurrentDisplay();
    if (!x11disp)
        return -1;
    int x11scr = DefaultScreen(x11disp);
    struct priv *p = talloc_zero(hw, struct priv);
    hw->priv = p;
    p->log = hw->log;
    p->xdisplay = x11disp;
    const char *glxext = glXQueryExtensionsString(x11disp, x11scr);
    if (!glxext || !strstr(glxext, "GLX_EXT_texture_from_pixmap"))
        return -1;
    p->glXBindTexImage =
        (void*)glXGetProcAddressARB((void*)"glXBindTexImageEXT");
    p->glXReleaseTexImage =
        (void*)glXGetProcAddressARB((void*)"glXReleaseTexImageEXT");
    if (!p->glXBindTexImage || !p->glXReleaseTexImage)
        return -1;
    p->display = vaGetDisplay(x11disp);
    if (!p->display)
        return -1;
    p->ctx = va_initialize(p->display, p->log);
    if (!p->ctx) {
        vaTerminate(p->display);
        return -1;
    }
    if (hw->reject_emulated && va_guess_if_emulated(p->ctx)) {
        destroy(hw);
        return -1;
    }

    int attribs[] = {
        GLX_BIND_TO_TEXTURE_RGBA_EXT, True,
        GLX_DRAWABLE_TYPE, GLX_PIXMAP_BIT,
        GLX_BIND_TO_TEXTURE_TARGETS_EXT, GLX_TEXTURE_2D_BIT_EXT,
        GLX_Y_INVERTED_EXT, True,
        GLX_DOUBLEBUFFER, False,
        GLX_RED_SIZE, 8,
        GLX_GREEN_SIZE, 8,
        GLX_BLUE_SIZE, 8,
        GLX_ALPHA_SIZE, 0,
        None
    };

    int fbcount;
    GLXFBConfig *fbc = glXChooseFBConfig(x11disp, x11scr, attribs, &fbcount);
    if (fbcount)
        p->fbc = fbc[0];
    if (fbc)
        XFree(fbc);
    if (!fbcount) {
        MP_VERBOSE(p, "No texture-from-pixmap support.\n");
        destroy(hw);
        return -1;
    }

    hw->hwctx = &p->ctx->hwctx;
    hw->converted_imgfmt = IMGFMT_RGB0;
    return 0;
}
コード例 #30
0
ファイル: x11argb_opengl.c プロジェクト: hammackj/playground
static void createTheRenderContext()
{
	int dummy;
	if (!glXQueryExtension(Xdisplay, &dummy, &dummy)) {
		fatalError("OpenGL not supported by X server\n");
	}

#if USE_GLX_CREATE_CONTEXT_ATTRIB
	#define GLX_CONTEXT_MAJOR_VERSION_ARB       0x2091
	#define GLX_CONTEXT_MINOR_VERSION_ARB       0x2092
	render_context = NULL;
	if( isExtensionSupported( glXQueryExtensionsString(Xdisplay, DefaultScreen(Xdisplay)), "GLX_ARB_create_context" ) ) {
		typedef GLXContext (*glXCreateContextAttribsARBProc)(Display*, GLXFBConfig, GLXContext, Bool, const int*);
		glXCreateContextAttribsARBProc glXCreateContextAttribsARB = (glXCreateContextAttribsARBProc)glXGetProcAddressARB( (const GLubyte *) "glXCreateContextAttribsARB" );
		if( glXCreateContextAttribsARB ) {
			int context_attribs[] =
			{
				GLX_CONTEXT_MAJOR_VERSION_ARB, 3,
				GLX_CONTEXT_MINOR_VERSION_ARB, 0,
				//GLX_CONTEXT_FLAGS_ARB        , GLX_CONTEXT_FORWARD_COMPATIBLE_BIT_ARB,
				None
			};

			int (*oldHandler)(Display*, XErrorEvent*) = XSetErrorHandler(&ctxErrorHandler);
			
			render_context = glXCreateContextAttribsARB( Xdisplay, fbconfig, 0, True, context_attribs );

			XSync( Xdisplay, False );
			XSetErrorHandler( oldHandler );

			fputs("glXCreateContextAttribsARB failed", stderr);
		} else {
			fputs("glXCreateContextAttribsARB could not be retrieved", stderr);
		}
	} else {
			fputs("glXCreateContextAttribsARB not supported", stderr);
	}

	if(!render_context)
	{
#else
	{
#endif
		render_context = glXCreateNewContext(Xdisplay, fbconfig, GLX_RGBA_TYPE, 0, True);
		if (!render_context) {
			fatalError("Failed to create a GL context\n");
		}
	}

	if (!glXMakeContextCurrent(Xdisplay, glX_window_handle, glX_window_handle, render_context)) {
		fatalError("glXMakeCurrent failed for window\n");
	}
}

static int updateTheMessageQueue()
{
	XEvent event;
	XConfigureEvent *xc;

	while (XPending(Xdisplay))
	{
		XNextEvent(Xdisplay, &event);
		switch (event.type)
		{
		case ClientMessage:
			if (event.xclient.data.l[0] == del_atom)
			{
				return 0;
			}
		break;

		case ConfigureNotify:
			xc = &(event.xconfigure);
			width = xc->width;
			height = xc->height;
			break;
		}
	}
	return 1;
}