Exemplo n.º 1
1
int main(int argc, char** argv)
{
	// Create display.
	Display* dpy = CreateDisplay();
	int screen = XDefaultScreen(dpy);
	int depth = XDefaultDepth(dpy, screen);
	Window root_win = XDefaultRootWindow(dpy);
	int numScreens = 1;
	Drawable screens[] = { root_win };
	axRect dpy_rect = axRect(0, 0, XDisplayWidth(dpy, screen),
                   			 XDisplayHeight(dpy, screen));

	// Setup GLX.
	XVisualInfo* v_info = GetGLXVisualInfo(dpy);
	Visual* visual = v_info->visual;

	Colormap colormap = XCreateColormap(dpy, root_win, visual, AllocNone);
	glEnable(GL_TEXTURE_2D);

	// Create window.
	axRect window_rect(0, 0, 500, 500);
	
	Window win = CreateWindow(dpy, window_rect, root_win, colormap, v_info);
	
	// Pixmap back_buffer = XCreatePixmap(dpy, win,
 //                                       window_rect.size.x, window_rect.size.y,
 //                                       screen);
	
	GLXContext glx_context = glXCreateContext(dpy, v_info, NULL, GL_TRUE);
	//GC gc;
	glXMakeCurrent(dpy, win, glx_context);
	//glXMakeCurrent( AX_GLOBAL_DISPLAY, win, gc->GetGLX_GC() );

	//Window win = XCreateSimpleWindow(dpy, RootWindow(dpy, s), 10, 10, 660, 200, 1,
	//                               BlackPixel(dpy, s), WhitePixel(dpy, s));

    XSelectInput(dpy, win,
             	 StructureNotifyMask |
             	 ExposureMask        |
             	 ButtonPressMask     |
             	 ButtonReleaseMask   |
             	 PointerMotionMask   |
             	 EnterWindowMask     |
             	 LeaveWindowMask     |
             	 FocusChangeMask );

    // Show window.
    XMapWindow(dpy, win);
    //XFlush(dpy);

	XStoreName(dpy, win, "axLib");


  //XSelectInput(dpy, win, ExposureMask | KeyPressMask);
  //XMapWindow(dpy, win);
 
// #if defined(__APPLE_CC__)  
//   XStoreName(dpy, win, "Geeks3D.com - X11 window under Mac OS X (Lion)");
// #else
//   XStoreName(dpy, win, "Geeks3D.com - X11 window under Linux (Mint 10)");
// #endif  
 
  
 
  MainLoop(dpy, win, window_rect);
 
  XDestroyWindow(dpy, win);
  XCloseDisplay(dpy);
  return 0;
}
Exemplo n.º 2
0
bool QGLContext::chooseContext(const QGLContext* shareContext)
{
    Q_D(QGLContext);
    const QX11Info *xinfo = qt_x11Info(d->paintDevice);

    Display* disp = xinfo->display();
    d->vi = chooseVisual();
    if (!d->vi)
        return false;

    if (deviceIsPixmap() &&
         (((XVisualInfo*)d->vi)->depth != xinfo->depth() ||
          ((XVisualInfo*)d->vi)->screen != xinfo->screen()))
    {
        XFree(d->vi);
        XVisualInfo appVisInfo;
        memset(&appVisInfo, 0, sizeof(XVisualInfo));
        appVisInfo.visualid = XVisualIDFromVisual((Visual *) xinfo->visual());
        appVisInfo.screen = xinfo->screen();
        int nvis;
        d->vi = XGetVisualInfo(disp, VisualIDMask | VisualScreenMask, &appVisInfo, &nvis);
        if (!d->vi)
            return false;

        int useGL;
        glXGetConfig(disp, (XVisualInfo*)d->vi, GLX_USE_GL, &useGL);
        if (!useGL)
            return false;        //# Chickening out already...
    }
    int res;
    glXGetConfig(disp, (XVisualInfo*)d->vi, GLX_LEVEL, &res);
    d->glFormat.setPlane(res);
    glXGetConfig(disp, (XVisualInfo*)d->vi, GLX_DOUBLEBUFFER, &res);
    d->glFormat.setDoubleBuffer(res);
    glXGetConfig(disp, (XVisualInfo*)d->vi, GLX_DEPTH_SIZE, &res);
    d->glFormat.setDepth(res);
    if (d->glFormat.depth())
        d->glFormat.setDepthBufferSize(res);
    glXGetConfig(disp, (XVisualInfo*)d->vi, GLX_RGBA, &res);
    d->glFormat.setRgba(res);
    glXGetConfig(disp, (XVisualInfo*)d->vi, GLX_RED_SIZE, &res);
    d->glFormat.setRedBufferSize(res);
    glXGetConfig(disp, (XVisualInfo*)d->vi, GLX_GREEN_SIZE, &res);
    d->glFormat.setGreenBufferSize(res);
    glXGetConfig(disp, (XVisualInfo*)d->vi, GLX_BLUE_SIZE, &res);
    d->glFormat.setBlueBufferSize(res);
    glXGetConfig(disp, (XVisualInfo*)d->vi, GLX_ALPHA_SIZE, &res);
    d->glFormat.setAlpha(res);
    if (d->glFormat.alpha())
        d->glFormat.setAlphaBufferSize(res);
    glXGetConfig(disp, (XVisualInfo*)d->vi, GLX_ACCUM_RED_SIZE, &res);
    d->glFormat.setAccum(res);
    if (d->glFormat.accum())
        d->glFormat.setAccumBufferSize(res);
    glXGetConfig(disp, (XVisualInfo*)d->vi, GLX_STENCIL_SIZE, &res);
    d->glFormat.setStencil(res);
    if (d->glFormat.stencil())
        d->glFormat.setStencilBufferSize(res);
    glXGetConfig(disp, (XVisualInfo*)d->vi, GLX_STEREO, &res);
    d->glFormat.setStereo(res);
    glXGetConfig(disp, (XVisualInfo*)d->vi, GLX_SAMPLE_BUFFERS_ARB, &res);
    d->glFormat.setSampleBuffers(res);
    if (d->glFormat.sampleBuffers()) {
        glXGetConfig(disp, (XVisualInfo*)d->vi, GLX_SAMPLES_ARB, &res);
        d->glFormat.setSamples(res);
    }

    Bool direct = format().directRendering() ? True : False;

    if (shareContext &&
         (!shareContext->isValid() || !shareContext->d_func()->cx)) {
            qWarning("QGLContext::chooseContext(): Cannot share with invalid context");
            shareContext = 0;
    }

    // 1. Sharing between rgba and color-index will give wrong colors.
    // 2. Contexts cannot be shared btw. direct/non-direct renderers.
    // 3. Pixmaps cannot share contexts that are set up for direct rendering.
    // 4. If the contexts are not created on the same screen, they can't be shared

    if (shareContext
        && (format().rgba() != shareContext->format().rgba()
            || (deviceIsPixmap() && glXIsDirect(disp, (GLXContext)shareContext->d_func()->cx))
            || (shareContext->d_func()->screen != xinfo->screen())))
    {
        shareContext = 0;
    }

    d->cx = 0;
    if (shareContext) {
        d->cx = glXCreateContext(disp, (XVisualInfo *)d->vi,
                               (GLXContext)shareContext->d_func()->cx, direct);
        d->screen = ((XVisualInfo*)d->vi)->screen;
        if (d->cx) {
            QGLContext *share = const_cast<QGLContext *>(shareContext);
            d->sharing = true;
            share->d_func()->sharing = true;
        }
    }
    if (!d->cx) {
        d->cx = glXCreateContext(disp, (XVisualInfo *)d->vi, NULL, direct);
        d->screen = ((XVisualInfo*)d->vi)->screen;
    }
    if (!d->cx)
        return false;
    d->glFormat.setDirectRendering(glXIsDirect(disp, (GLXContext)d->cx));
    if (deviceIsPixmap()) {
#if defined(GLX_MESA_pixmap_colormap) && defined(QGL_USE_MESA_EXT)
        d->gpm = glXCreateGLXPixmapMESA(disp, (XVisualInfo *)d->vi,
                                        qt_x11Handle(d->paintDevice),
                                        qt_gl_choose_cmap(disp, (XVisualInfo *)d->vi));
#else
        d->gpm = (quint32)glXCreateGLXPixmap(disp, (XVisualInfo *)d->vi,
                                              qt_x11Handle(d->paintDevice));
#endif
        if (!d->gpm)
            return false;
    }
    QString glxExt = QString(QLatin1String(glXGetClientString(QX11Info::display(), GLX_EXTENSIONS)));
    if (glxExt.contains(QLatin1String("GLX_SGI_video_sync"))) {
        if (d->glFormat.swapInterval() == -1)
            d->glFormat.setSwapInterval(0);
    } else {
        d->glFormat.setSwapInterval(-1);
    }
    return true;
}
Exemplo n.º 3
0
bool fxwt::init_graphics(GraphicsInitParameters *gparams) {
	Display *dpy;
	Window win;
	info("Initializing GLX");

	if(!(dpy = XOpenDisplay(0))) {
		error("Could not connect to the X server");
		return false;
	}

	int screen = DefaultScreen(dpy);
	Window root_win = RootWindow(dpy, screen);

	info("Trying to set video mode %dx%dx%d, d:%d s:%d %s", gparams->x, gparams->y, gparams->bpp, gparams->depth_bits, gparams->stencil_bits, gparams->fullscreen ? "fullscreen" : "windowed");
	
	// determine color bits
	int color_bits = 1;
	if(!(gparams->dont_care_flags & DONT_CARE_BPP)) {
		switch(gparams->bpp) {
		case 32:
		case 24:
			color_bits = 8;
			break;

		case 16:
		case 15:
			color_bits = 5;
			break;

		case 12:
			color_bits = 4;
			break;

		default:
			error("%s: Tried to set unsupported pixel format: %d bpp", __func__, gparams->bpp);
		}
	}

	// determine stencil bits
	int stencil_bits = gparams->stencil_bits;
	if(gparams->dont_care_flags & DONT_CARE_STENCIL) {
		stencil_bits = 1;
	}

	// determine zbuffer bits
	int zbits = gparams->depth_bits == 32 ? 24 : gparams->depth_bits;
	if(gparams->dont_care_flags & DONT_CARE_BPP) {
		zbits = 1;
	}
	
	int glx_attrib[] = {
		GLX_RGBA, GLX_DOUBLEBUFFER,
		GLX_RED_SIZE, color_bits,
		GLX_GREEN_SIZE, color_bits,
		GLX_BLUE_SIZE, color_bits,
		GLX_DEPTH_SIZE, zbits,
		GLX_STENCIL_SIZE, stencil_bits,
		None
	};

	XVisualInfo *vis_info;
	if(!(vis_info = glXChooseVisual(dpy, screen, glx_attrib))) {
		error("%s: Could not set requested video mode", __func__);
		XCloseDisplay(dpy);
		return false;
	}

	// check the video mode we got
	int arbits, agbits, abbits, azbits, astencilbits;
	glXGetConfig(dpy, vis_info, GLX_RED_SIZE, &arbits);
	glXGetConfig(dpy, vis_info, GLX_GREEN_SIZE, &agbits);
	glXGetConfig(dpy, vis_info, GLX_BLUE_SIZE, &abbits);
	glXGetConfig(dpy, vis_info, GLX_DEPTH_SIZE, &azbits);
	glXGetConfig(dpy, vis_info, GLX_STENCIL_SIZE, &astencilbits);

	info("Initialized video mode:");
	info("    bpp: %d (%d%d%d)", arbits + agbits + abbits, arbits, agbits, abbits);
	info("zbuffer: %d", azbits);
	info("stencil: %d", astencilbits);

	/* if the dont_care_flags does not contain DONT_CARE_BPP and our color bits
	 * does not match, we should return failure, however we test against
	 * the difference allowing a +/-1 difference in order to allow for 16bpp
	 * formats of either 565 or 555 and consider them equal.
	 */
	if(!(gparams->dont_care_flags & DONT_CARE_BPP) && abs(arbits - color_bits) > 1 && abs(agbits - color_bits) > 1 && abs(abbits - color_bits) > 1) {
		error("%s: Could not set requested exact bpp mode", __func__);
		XFree(vis_info);
		XCloseDisplay(dpy);
		return false;
	}

	// now if we don't have DONT_CARE_DEPTH in the dont_care_flags check for 
	// exact depth buffer format, however consider 24 and 32 bit the same
	if(!(gparams->dont_care_flags & DONT_CARE_DEPTH) && azbits != zbits) {
		if(!(zbits == 32 && azbits == 24 || zbits == 24 && azbits == 32)) {
			error("%s: Could not set requested exact zbuffer depth", __func__);
			XFree(vis_info);
			XCloseDisplay(dpy);
			return false;
		}
	}

	// if we don't have DONT_CARE_STENCIL make sure we have the stencil format
	// that was asked.
	if(!(gparams->dont_care_flags & DONT_CARE_STENCIL) && astencilbits != gparams->stencil_bits) {
		error("%s: Could not set exact stencil format", __func__);
		XFree(vis_info);
		XCloseDisplay(dpy);
		return false;
	}

	// everything is ok, create the context
	if(!(glx_ctx = glXCreateContext(dpy, vis_info, 0, True))) {
		error("%s: Failed to create GLX context", __func__);
		XFree(vis_info);
		XCloseDisplay(dpy);
		return false;
	}

	XSetWindowAttributes xattr;
	xattr.background_pixel = xattr.border_pixel = BlackPixel(dpy, screen);
	xattr.colormap = XCreateColormap(dpy, root_win, vis_info->visual, AllocNone);

	if(gparams->fullscreen) {
		// TODO: also test for "XFree86-VidModeExtension"
#ifdef USE_XF86VIDMODE
		info("Using XF86VidMode extension for fullscreen resolution switch.");
		
		XF86VidModeModeInfo **modes;
		XF86VidModeModeInfo *vid_mode = 0;
		int mode_count;
		
		XF86VidModeGetAllModeLines(dpy, screen, &mode_count, &modes);
		orig_mode = *modes[0];

		for(int i=0; i<mode_count; i++) {
			if(modes[i]->hdisplay == gparams->x && modes[i]->vdisplay == gparams->y) {
				vid_mode = modes[i];
			}
		}
		if(!vid_mode) {
			error("Could not set requested video mode");
			XFree(modes);
			XFree(vis_info);
			XCloseDisplay(dpy);
			return -1;
		}
		
		XF86VidModeSwitchToMode(dpy, screen, vid_mode);
		XF86VidModeSetViewPort(dpy, screen, 0, 0);
		XFree(modes);

		xattr.override_redirect = True;
		win = XCreateWindow(dpy, root_win, 0, 0, gparams->x, gparams->y, 0, vis_info->depth,
				InputOutput, vis_info->visual, CWColormap | CWBackPixel | CWBorderPixel | CWOverrideRedirect, &xattr);

		XWarpPointer(dpy, None, win, 0, 0, 0, 0, 0, 0);
		XMapRaised(dpy, win);
        XGrabKeyboard(dpy, win, True, GrabModeAsync, GrabModeAsync, CurrentTime);
        XGrabPointer(dpy, win, True, ButtonPressMask, GrabModeAsync, GrabModeAsync, win, None, CurrentTime);
#else
		info("Resolution switching is not compiled or not supported by the X server, using a full-screen window.");

		XWindowAttributes root_attr;
		XGetWindowAttributes(dpy, root_win, &root_attr);

		gparams->x = root_attr.width;
		gparams->y = root_attr.height;
		xattr.override_redirect = True;
		win = XCreateWindow(dpy, root_win, 0, 0, gparams->x, gparams->y, 0, vis_info->depth,
				InputOutput, vis_info->visual, CWColormap | CWBackPixel | CWBorderPixel | CWOverrideRedirect, &xattr);

		XWarpPointer(dpy, None, win, 0, 0, 0, 0, 0, 0);
		XMapRaised(dpy, win);
        XGrabKeyboard(dpy, win, True, GrabModeAsync, GrabModeAsync, CurrentTime);
        XGrabPointer(dpy, win, True, ButtonPressMask, GrabModeAsync, GrabModeAsync, win, None, CurrentTime);
#endif	// USE_XF86VIDMODE

		fullscreen = true;
	} else {
		win = XCreateWindow(dpy, root_win, 0, 0, gparams->x, gparams->y, 0, vis_info->depth,
				InputOutput, vis_info->visual, CWColormap | CWBackPixel | CWBorderPixel, &xattr);
	}

	long events = ExposureMask | StructureNotifyMask | KeyPressMask;	// expose and key events
	events |= ButtonPressMask | ButtonReleaseMask | PointerMotionMask;	// mouse events
	XSelectInput(dpy, win, events);
		
	// set WM cooperation settings
	Atom wm_delete = XInternAtom(dpy, "WM_DELETE_WINDOW", True);
	XSetWMProtocols(dpy, win, &wm_delete, 1);

	XTextProperty tp_wname;
	static char *win_title = "3dengfx/X";
	XStringListToTextProperty(&win_title, 1, &tp_wname);
	XSetWMName(dpy, win, &tp_wname);
	XFree(tp_wname.value);

	XClassHint class_hint;
	class_hint.res_name = "3dengfx";
	class_hint.res_class = "3dengfx_graphics";
	XSetClassHint(dpy, win, &class_hint);

	XFree(vis_info);

	if(glXMakeCurrent(dpy, win, glx_ctx) == False) {
		error("%s: Failed to make the GLX context current", __func__);
		glXDestroyContext(dpy, glx_ctx);
		XDestroyWindow(dpy, win);
		XCloseDisplay(dpy);
		return false;
	}

	if(!glXIsDirect(dpy, glx_ctx)) {
		warning("using indirect rendering, which might be slow...");
	}

	XMapWindow(dpy, win);
	XFlush(dpy);

	fxwt_x_dpy = dpy;
	fxwt_x_win = win;
	
	return true;
}
Exemplo n.º 4
0
int
main (void)
{
        Display *dpy;
        Window window;

        dpy = XOpenDisplay (NULL);

        if (dpy == NULL) {
                fprintf(stderr, "Failed to open display %s\n",
                        XDisplayName(NULL));
                return 1;
        }

        int visual_attr[] = {
                GLX_RGBA,
                GLX_RED_SIZE,		8,
                GLX_GREEN_SIZE, 	8,
                GLX_BLUE_SIZE,		8,
                GLX_ALPHA_SIZE, 	8,
                GLX_DOUBLEBUFFER,
                GLX_DEPTH_SIZE,		24,
                GLX_STENCIL_SIZE,	8,
                None
        };

        int screen = DefaultScreen(dpy);

	/* Window and context setup. */
        XVisualInfo *visual_info = glXChooseVisual(dpy, screen, visual_attr);

	Window root = DefaultRootWindow (dpy);

	/* window attributes */
	XSetWindowAttributes attr;
	attr.background_pixel = BlackPixel(dpy, screen);
	attr.border_pixel = BlackPixel(dpy, screen);
	attr.colormap = XCreateColormap(dpy, root, visual_info->visual, AllocNone);
	attr.event_mask = KeyPressMask | StructureNotifyMask | ExposureMask;

	unsigned long mask;
	mask = CWBackPixel | CWBorderPixel | CWColormap | CWEventMask;

	window = XCreateWindow(
		dpy, root,
		0, 0, width, height,
		0,
		visual_info->depth,
		InputOutput,
		visual_info->visual,
		mask,
		&attr);

        XMapWindow (dpy, window);

        GLXContext ctx = glXCreateContext(dpy, visual_info, NULL, True);
        glXMakeCurrent(dpy, window, ctx);

        handle_events (dpy, window, width, height);

	/* Cleanup */
        glXDestroyContext (dpy, ctx);

        XDestroyWindow (dpy, window);
        XCloseDisplay (dpy);

        return 0;
}
Exemplo n.º 5
0
Error ContextGL_X11::initialize() {

	
	GLXCREATECONTEXTATTRIBSARBPROC glXCreateContextAttribsARB = NULL;
	
//	const char *extensions = glXQueryExtensionsString(x11_display, DefaultScreen(x11_display));
	
	glXCreateContextAttribsARB = (GLXCREATECONTEXTATTRIBSARBPROC)glXGetProcAddress((const GLubyte*)"glXCreateContextAttribsARB");
	
	ERR_FAIL_COND_V( !glXCreateContextAttribsARB, ERR_UNCONFIGURED );


	static int visual_attribs[] = {
	    GLX_RENDER_TYPE, GLX_RGBA_BIT,
	    GLX_DRAWABLE_TYPE, GLX_WINDOW_BIT,
	    GLX_DOUBLEBUFFER, true,
	    GLX_RED_SIZE, 1,
	    GLX_GREEN_SIZE, 1,
	    GLX_BLUE_SIZE, 1,
	    GLX_DEPTH_SIZE, 24,
	    None 
	};

	int fbcount;
	GLXFBConfig *fbc = glXChooseFBConfig(x11_display, DefaultScreen(x11_display), visual_attribs, &fbcount);
	ERR_FAIL_COND_V(!fbc,ERR_UNCONFIGURED);
	
	XVisualInfo *vi = glXGetVisualFromFBConfig(x11_display, fbc[0]);

	XSetWindowAttributes swa;

	swa.colormap = XCreateColormap(x11_display, RootWindow(x11_display, vi->screen), vi->visual, AllocNone);
	swa.border_pixel = 0;
	swa.event_mask = StructureNotifyMask;

	/*
	char* windowid = getenv("GODOT_WINDOWID");
	if (windowid) {

		//freopen("/home/punto/stdout", "w", stdout);
		//reopen("/home/punto/stderr", "w", stderr);
		x11_window = atol(windowid);
	} else {
	*/

    x11MotivHints.flags         = 2;
    x11MotivHints.decorations   = 0;
    xiaNewProperty              = XInternAtom( x11_display,"_MOTIF_WM_HINTS", True );
    vidModeBest                 = 0;
    vidModeCount                = 0;
    windowWidth                 = 1024;
    windowHeight                = 768;
    dpyWidth                    = 0;
    dpyHeight                   = 0;
    screenBackup                = vi->screen;

    XF86VidModeGetAllModeLines( x11_display, vi->screen, &vidModeCount, &vidModes );

    printf("Debug: vidModeCount=%d\n", vidModeCount );

    desktopMode = *vidModes[ 0 ];

    for ( int i = 0; i < vidModeCount; i++ ){

        if (( vidModes[i]->hdisplay == windowWidth) && ( vidModes[i]->vdisplay == windowHeight ))
                    vidModeBest = i;

    }

    printf("vidModeBest=%d\n",vidModeBest);

    glXQueryVersion(    x11_display, &glxMajor, &glxMinor                 );
    printf(             "Debug: GLX-Version %d.%d\n", glxMajor, glxMinor  );

    context                 = glXCreateContext( x11_display, vi, 0, GL_TRUE                                                 );
    cmap                    = XCreateColormap(  x11_display, RootWindow( x11_display, vi->screen ), vi->visual, AllocNone   );
    winAttr.colormap        = cmap;
    winAttr.border_pixel    = 0;

    XChangeProperty(            x11_display, RootWindow( x11_display, vi->screen ), xiaNewProperty, xiaNewProperty, 32, PropModeReplace, ( unsigned char * ) &x11MotivHints, 5        );
    XF86VidModeSwitchToMode(    x11_display, vi->screen, vidModes[ vidModeBest ]                                                                                                        );
    XF86VidModeSetViewPort(     x11_display, vi->screen, 0, 0                                                                                                                         );
    XMoveResizeWindow(          x11_display, RootWindow( x11_display, vi->screen ), 0, 0, OS::get_singleton()->get_video_mode().width, OS::get_singleton()->get_video_mode().height   );
    XMapRaised(                 x11_display, RootWindow( x11_display, vi->screen )                                                                                                    );

    dpyWidth    = vidModes[vidModeBest]->hdisplay;
    dpyHeight   = vidModes[vidModeBest]->vdisplay;

    XFree(vidModes);

    winAttr.override_redirect   = True;
    winAttr.event_mask          = ExposureMask | KeyPressMask | ButtonPressMask | StructureNotifyMask;

    x11_window = XCreateWindow( x11_display,
                                RootWindow( x11_display, vi->screen ),
                                0, 0,
                                dpyWidth, dpyHeight,
                                0,
                                vi->depth,
                                InputOutput,
                                vi->visual,
                                CWBorderPixel | CWColormap | CWEventMask | CWOverrideRedirect, &winAttr );
    XWarpPointer(               x11_display,
                                None,
                                x11_window,
                                0, 0, 0, 0, 0, 0                                                        );
    XMapRaised(                 x11_display, x11_window                                                 );
    XGrabKeyboard(              x11_display, x11_window,
                                True,
                                GrabModeAsync, GrabModeAsync,
                                CurrentTime                                                             );
    XGrabPointer(               x11_display, x11_window,
                                True, ButtonPressMask,
                                GrabModeAsync, GrabModeAsync,
                                x11_window,
                                None,
                                CurrentTime                                                             );

        //x11_window = XCreateWindow(x11_display, RootWindow(x11_display, vi->screen), 0, 0, OS::get_singleton()->get_video_mode().width, OS::get_singleton()->get_video_mode().height, 0, vi->depth, InputOutput, vi->visual, CWBorderPixel|CWColormap|CWEventMask, &swa);
		ERR_FAIL_COND_V(!x11_window,ERR_UNCONFIGURED);
		XMapWindow(x11_display, x11_window);
		while(true) {
			// wait for mapnotify (window created)
			XEvent e;
			XNextEvent(x11_display, &e);
			if (e.type == MapNotify)
				break;
		}
		//};

	if (!OS::get_singleton()->get_video_mode().resizable) {
		XSizeHints *xsh;
		xsh = XAllocSizeHints();
		xsh->flags = PMinSize | PMaxSize;
		xsh->min_width = OS::get_singleton()->get_video_mode().width;
		xsh->max_width = OS::get_singleton()->get_video_mode().width;
		xsh->min_height = OS::get_singleton()->get_video_mode().height;
		xsh->max_height = OS::get_singleton()->get_video_mode().height;
		XSetWMNormalHints(x11_display, x11_window, xsh);
	}


	if (!opengl_3_context) {
		//oldstyle context:
		p->glx_context = glXCreateContext(x11_display, vi, 0, GL_TRUE);
	} else {
		static int context_attribs[] = {
			GLX_CONTEXT_MAJOR_VERSION_ARB, 3,
			GLX_CONTEXT_MINOR_VERSION_ARB, 0,
			None
		};
	
		p->glx_context = glXCreateContextAttribsARB(x11_display, fbc[0], NULL, true, context_attribs);
		ERR_FAIL_COND_V(!p->glx_context,ERR_UNCONFIGURED);
	}

	glXMakeCurrent(x11_display, x11_window, p->glx_context);

	/*
	glWrapperInit(wrapper_get_proc_address);
	glFlush();
	
	glXSwapBuffers(x11_display,x11_window);
*/
	//glXMakeCurrent(x11_display, None, NULL);

	return OK;
}
Exemplo n.º 6
0
Arquivo: ogl.cpp Projeto: keithw/ahab
void OpenGLDisplay::init_context( void ) {
  int attributes[] = { GLX_RGBA,
		       GLX_DOUBLEBUFFER, True,
		       GLX_RED_SIZE, 8,
		       GLX_GREEN_SIZE, 8,
		       GLX_BLUE_SIZE, 8,
		       None };

  XVisualInfo *visual = glXChooseVisual( state.display, 0, attributes );
  if ( visual == NULL ) {
    fprintf( stderr, "Could not open glX visual.\n" );
    throw DisplayError();
  }

  state.context = glXCreateContext( state.display, visual, NULL, True );
  if ( state.context == NULL ) {
    fprintf( stderr, "No glX context.\n" );
    throw DisplayError();
  }

  XFree( visual );

  if ( !glXMakeCurrent( state.display, state.window, state.context ) ) {
    fprintf( stderr, "Could not reactivate OpenGL.\n" );
    throw DisplayError();
  }

  GLcheck( "glXMakeCurrent" );

  /* initialize textures */
  init_tex( GL_TEXTURE0, GL_LUMINANCE8, &state.Y_tex,
	    state.framewidth, state.frameheight, GL_LINEAR );
  init_tex( GL_TEXTURE1, GL_LUMINANCE8, &state.Cb_tex,
	    state.framewidth/2, state.frameheight/2, GL_LINEAR );
  init_tex( GL_TEXTURE2, GL_LUMINANCE8, &state.Cr_tex,
	    state.framewidth/2, state.frameheight/2, GL_LINEAR );

  /* load the shader */
  GLint errorloc;  
  glEnable( GL_FRAGMENT_PROGRAM_ARB );
  glGenProgramsARB( 1, &shader );
  glBindProgramARB( GL_FRAGMENT_PROGRAM_ARB, shader );
  glProgramStringARB( GL_FRAGMENT_PROGRAM_ARB, GL_PROGRAM_FORMAT_ASCII_ARB,
		      strlen( ahab_fragment_program ),
		      ahab_fragment_program );
  glGetIntegerv( GL_PROGRAM_ERROR_POSITION_ARB, &errorloc );
  if ( errorloc != -1 ) {
    fprintf( stderr, "Error in fragment shader at position %d.\n", errorloc );
    fprintf( stderr, "Error string: %s\n",
	     glGetString( GL_PROGRAM_ERROR_STRING_ARB ) );
    throw DisplayError();
  }

  GLcheck( "glProgramString" );

  /* guess colors */
  if ( state.frameheight <= 480 ) {
    smpte170m.execute( state );
  } else {
    itu709.execute( state );
  }
}
Exemplo n.º 7
0
/* Stereo thread - For GL_STEREO  */
static void * nvstusb_stereo_thread(void * in_pv_arg)
{
  struct nvstusb_context *ctx = (struct nvstusb_context *) in_pv_arg;
  Display *dpy;
  Window win;

  /* Openning X display */
  dpy = XOpenDisplay(0);

  /* Preparing new X window */
  Window s_window;
  static int attributeList[] =
  { GLX_RGBA,
    GLX_DOUBLEBUFFER,
    GLX_RED_SIZE,
    1,
    GLX_GREEN_SIZE,
    1,
    GLX_BLUE_SIZE,
    1,
    None };
  XVisualInfo *vi = glXChooseVisual(dpy, DefaultScreen(dpy), attributeList);
  s_window = RootWindow(dpy, vi->screen);
  XSetWindowAttributes swa;
  swa.colormap = XCreateColormap(dpy, s_window, vi->visual, AllocNone);
  swa.override_redirect = true;

  /* Create X window 1x1 top left of screen */
  win = XCreateWindow(dpy,
      s_window ,
      0,
      0,
      1,
      1,
      0,
      vi->depth,
      InputOutput,
      vi->visual,
      CWColormap|CWOverrideRedirect,
      &swa);

  XMapWindow(dpy, win);

  /* Create glX context */
  GLXContext glx_ctx = glXCreateContext(dpy, vi, 0, true);
  glXMakeCurrent(dpy, win, glx_ctx);

  /* Loop until stop */
  while (ctx->b_thread_running) {
    /* Send swap to usb controler */
    nvstusb_swap(ctx, nvstusb_quad, NULL /*f_swap*/);

    /* Read status from usb controler */
    struct nvstusb_keys k;
    nvstusb_get_keys(ctx, &k);
    if (k.toggled3D) {
      nvstusb_invert_eyes(ctx);
    }
  }
  /* Destroy context */
  glx_ctx = glXGetCurrentContext();
  glXDestroyContext(dpy, glx_ctx);

  return NULL;
}
Exemplo n.º 8
0
OpenGLContext::OpenGLContext(uint _screenNum) : screenNum(_screenNum){

    contextInfo = new OpenGLContextInfo();

    contextInfo->display = XOpenDisplay(NULL);

    if((int)screenNum+1 > ScreenCount(contextInfo->display))
        throw "Could not create OpenGLContext. Screen not available!";

    Screen *xScreen = ScreenOfDisplay(contextInfo->display, screenNum);

    screenResX = xScreen->width;
    screenResY = xScreen->height;

    // Create a OpenGL OpenGLContext on the specified X screen
    contextInfo->window = RootWindow(contextInfo->display, screenNum);

    int attrListDbl[] = {
        GLX_RGBA, GLX_DOUBLEBUFFER,
        GLX_RED_SIZE, 0,
        GLX_GREEN_SIZE, 0,
        GLX_BLUE_SIZE, 0,
        GLX_ALPHA_SIZE, 0,
        GLX_DEPTH_SIZE, 0,
        GLX_STENCIL_SIZE, 0,
        None
    };

    XVisualInfo *visualInfo = glXChooseVisual(contextInfo->display, screenNum, attrListDbl);

    int glxMajor, glxMinor = 0;
    glXQueryVersion(contextInfo->display, &glxMajor, &glxMinor);
    std::cout << "GLX-Version " << glxMajor << "." << glxMinor << std::endl;

    int glMajor, glMinor = 0;
    glGetIntegerv(GL_MAJOR_VERSION, &glMajor);
    glGetIntegerv(GL_MINOR_VERSION, &glMinor);
    std::cout << "GL-Version " << glMajor << "." << glMinor << std::endl;

    // Create a GLX OpenGLContext
    bool directRendering = GL_TRUE;
    contextInfo->context = glXCreateContext(contextInfo->display, visualInfo,  NULL, directRendering);

    // Create colormap
    Colormap colormap = XCreateColormap(contextInfo->display,contextInfo->window,visualInfo->visual,AllocNone);

    // Create the actual window
    unsigned long wamask = CWColormap;

    XSetWindowAttributes wa;
    wa.colormap = colormap;
    wa.border_pixel = 50;
    wa.event_mask = 0;

    // bypass window manager (does not have effect)
    wa.override_redirect = True;

    // show no cursor
    wa.cursor = 0;

    contextInfo->window = XCreateWindow(contextInfo->display, contextInfo->window, 0, 0, screenResX, screenResY, 0, visualInfo->depth, InputOutput, visualInfo->visual, wamask, &wa);

    if(!contextInfo->window)
        std::cerr << "Failed to create X window!" << std::endl;

    // bypass window manager (actually effects here)
    XSetWindowAttributes attributes;
    attributes.override_redirect = True;
    XChangeWindowAttributes(contextInfo->display, contextInfo->window, CWOverrideRedirect, &attributes);

    // Raise window (necessary)
    XMapWindow(contextInfo->display, contextInfo->window);

    // Connect the glx-OpenGLContext to the window
    glXMakeCurrent(contextInfo->display, contextInfo->window, contextInfo->context);

    //XSaveOpenGLContext
    XFlush(contextInfo->display);

    // Check if OpenGLContext is direct
    if (glXIsDirect(contextInfo->display, contextInfo->context))
        std::cout << "OpenGLContext is direct\n";
    else
        std::cout << "OpenGLContext is not direct\n";

    // Set swap interval to 1 for standard vsync
    typedef GLvoid (*glXSwapIntervalSGIFunc) (GLint);
    const char *glx_extensions = glXQueryExtensionsString(contextInfo->display, screenNum);
    if (strstr(glx_extensions, "GLX_SGI_swap_control")) {
        PFNGLXSWAPINTERVALSGIPROC SwapIntervalSGI = (PFNGLXSWAPINTERVALSGIPROC)glXGetProcAddressARB((const GLubyte*)"glXSwapIntervalSGI");
        SwapIntervalSGI(1);
    } else if (strstr(glx_extensions, "GLX_EXT_swap_control")) {
        PFNGLXSWAPINTERVALEXTPROC SwapIntervalEXT = (PFNGLXSWAPINTERVALEXTPROC)glXGetProcAddressARB((const GLubyte*)"glXSwapIntervalEXT");
        SwapIntervalEXT(contextInfo->display, contextInfo->window, 1);
    } else {
        std::cerr << "OpenGLContext.Unix Error: Could not access swap interval extension!" << std::endl;
    }

    // Adjust gamma to one
    //setGamma(1.0);
}
Exemplo n.º 9
0
bool CVDPAU::MakePixmapGL()
{
  int num=0;
  int fbConfigIndex = 0;

  int doubleVisAttributes[] = {
    GLX_RENDER_TYPE, GLX_RGBA_BIT,
    GLX_RED_SIZE, 8,
    GLX_GREEN_SIZE, 8,
    GLX_BLUE_SIZE, 8,
    GLX_ALPHA_SIZE, 8,
    GLX_DEPTH_SIZE, 8,
    GLX_DRAWABLE_TYPE, GLX_PIXMAP_BIT,
    GLX_BIND_TO_TEXTURE_RGBA_EXT, True,
    GLX_DOUBLEBUFFER, True,
    GLX_Y_INVERTED_EXT, True,
    GLX_X_RENDERABLE, True,
    None
  };

  int pixmapAttribs[] = {
    GLX_TEXTURE_TARGET_EXT, GLX_TEXTURE_2D_EXT,
    GLX_TEXTURE_FORMAT_EXT, GLX_TEXTURE_FORMAT_RGBA_EXT,
    None
  };

  GLXFBConfig *fbConfigs;
  fbConfigs = glXChooseFBConfig(m_Display, DefaultScreen(m_Display), doubleVisAttributes, &num);
  if (fbConfigs==NULL)
  {
    CLog::Log(LOGERROR, "GLX Error: MakePixmap: No compatible framebuffers found");
    return false;
  }
  CLog::Log(LOGDEBUG, "Found %d fbconfigs.", num);
  fbConfigIndex = 0;
  CLog::Log(LOGDEBUG, "Using fbconfig index %d.", fbConfigIndex);

  m_glPixmap = glXCreatePixmap(m_Display, fbConfigs[fbConfigIndex], m_Pixmap, pixmapAttribs);

  if (!m_glPixmap)
  {
    CLog::Log(LOGINFO, "GLX Error: Could not create Pixmap");
    XFree(fbConfigs);
    return false;
  }

  /* to make the pixmap usable, it needs to have any context associated with it */
  GLXContext  lastctx = glXGetCurrentContext();
  GLXDrawable lastdrw = glXGetCurrentDrawable();

  XVisualInfo *visInfo;
  visInfo = glXGetVisualFromFBConfig(m_Display, fbConfigs[fbConfigIndex]);
  if (!visInfo)
  {
    CLog::Log(LOGINFO, "GLX Error: Could not obtain X Visual Info for pixmap");
    XFree(fbConfigs);
    return false;
  }
  XFree(fbConfigs);

  CLog::Log(LOGINFO, "GLX: Creating Pixmap context");
  m_glContext = glXCreateContext(m_Display, visInfo, NULL, True);
  XFree(visInfo);

  if (!glXMakeCurrent(m_Display, m_glPixmap, m_glContext))
  {
    CLog::Log(LOGINFO, "GLX Error: Could not make Pixmap current");
    return false;
  }

  /* restore what thread had before */
  glXMakeCurrent(m_Display, lastdrw, lastctx);

  return true;

}
Exemplo n.º 10
0
void ShivaVGWindowSurfacePrivate::ensureContext(QWidget *widget)
{
#if defined(Q_WS_X11)
    Window win = widget->winId();
    if (win != drawable) {
        if (context)
            glXDestroyContext(X11->display, context);
        drawable = win;
    }
    if (context == 0) {
        const QX11Info *xinfo = qt_x11Info(widget);
        int spec[64];
        int i = 0;
        spec[i++] = GLX_DOUBLEBUFFER;
        spec[i++] = GLX_DEPTH_SIZE;
        spec[i++] = 1;
        spec[i++] = GLX_STENCIL_SIZE;
        spec[i++] = 1;
        spec[i++] = GLX_RGBA;
        spec[i++] = GLX_RED_SIZE;
        spec[i++] = 1;
        spec[i++] = GLX_GREEN_SIZE;
        spec[i++] = 1;
        spec[i++] = GLX_BLUE_SIZE;
        spec[i++] = 1;
        spec[i++] = GLX_SAMPLE_BUFFERS_ARB;
        spec[i++] = 1;
        spec[i++] = GLX_SAMPLES_ARB;
        spec[i++] = 4;
        spec[i] = XNone;
        XVisualInfo *visual = glXChooseVisual
            (xinfo->display(), xinfo->screen(), spec);
        context = glXCreateContext(X11->display, visual, 0, True);
        if (!context)
            qWarning("glXCreateContext: could not create GL context for VG rendering");
    }
#else
    Q_UNUSED(widget);
#endif
#if defined(QVG_USE_FBO)
    if (needsResize && fbo) {
#if defined(Q_WS_X11)
        glXMakeCurrent(X11->display, drawable, context);
#endif
        glDeleteTextures(1, &texture);
        glDeleteFramebuffersEXT(1, &fbo);
#if defined(Q_WS_X11)
        glXMakeCurrent(X11->display, 0, 0);
#endif
        fbo = 0;
        texture = 0;
    }
    if (!fbo) {
#if defined(Q_WS_X11)
        glXMakeCurrent(X11->display, drawable, context);
#endif
        glGenFramebuffersEXT(1, &fbo);
        glBindFramebufferEXT(GL_FRAMEBUFFER_EXT, fbo);

        glGenTextures(1, &texture);
        glBindTexture(GL_TEXTURE_2D, texture);
        glTexImage2D(GL_TEXTURE_2D, 0, GL_RGBA8, size.width(), size.height(), 0,
                     GL_RGBA, GL_UNSIGNED_BYTE, NULL);
        glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_NEAREST);
        glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_NEAREST);
        glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE);
        glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_EDGE);
        glFramebufferTexture2DEXT
            (GL_FRAMEBUFFER_EXT, GL_COLOR_ATTACHMENT0_EXT, GL_TEXTURE_2D,
             texture, 0);

        glBindFramebufferEXT(GL_FRAMEBUFFER_EXT, 0);
#if defined(Q_WS_X11)
        glXMakeCurrent(X11->display, 0, 0);
#endif
    }
#endif
    needsResize = false;
}
Exemplo n.º 11
0
static int oil_backend_opengl_initialize(void) {
    static int initialized = 0;
    static int initialization_result = 0;
    Display *dpy;
    Window root;
    GLint attr[] = { GLX_RGBA, GLX_DEPTH_SIZE, 24, GLX_DOUBLEBUFFER, None };
    XVisualInfo *vi;
    GLXContext glc;
    int tmp;
    GLuint vshader, fshader;
    GLuint shader;
    char infolog[1024];
    
    /* only run this once, ever */
    if (initialized)
        return initialization_result;
    initialized = 1;
    
    /* open display */
    if (!(dpy = XOpenDisplay(NULL))) {
        return 0;
    }
    
    /* get root window */
    root = DefaultRootWindow(dpy);
    
    /* get visual matching attr */
    if (!(vi = glXChooseVisual(dpy, 0, attr))) { 
        return 0;
    }
    
    /* create a context */
    if (!(glc = glXCreateContext(dpy, vi, NULL, GL_TRUE))) {
        return 0;
    }
    
    glXMakeCurrent(dpy, root, glc);
    
    if (glewInit() != GLEW_OK) {
        return 0;
    }
    
    glEnable(GL_BLEND);
    glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA);
    glEnable(GL_CULL_FACE);
    glCullFace(GL_BACK);
    glFrontFace(GL_CW);
    
    glEnable(GL_ALPHA_TEST);
    glAlphaFunc(GL_GREATER, 0.0f);
    
    glEnable(GL_DEPTH_TEST);
    glEnable(GL_TEXTURE_2D);
        
    /* set up the texture matrix to handle our flipped images */
    glMatrixMode(GL_TEXTURE);
    glScalef(1.0, -1.0, 1.0);
    glTranslatef(0.0, 1.0, 0.0);
    glMatrixMode(GL_MODELVIEW);
    
    vshader = glCreateShader(GL_VERTEX_SHADER);
    tmp = strlen(vshadersrc);
    glShaderSource(vshader, 1, &vshadersrc, &tmp);
    glCompileShader(vshader);
    glGetShaderiv(vshader, GL_COMPILE_STATUS, &tmp);
    if (tmp == GL_FALSE) {
        glGetShaderInfoLog(vshader, 1024, &tmp, infolog);
        infolog[tmp] = 0;
        printf("%s", infolog);
        return 0;
    }
    
    fshader = glCreateShader(GL_FRAGMENT_SHADER);
    tmp = strlen(fshadersrc);
    glShaderSource(fshader, 1, &fshadersrc, &tmp);
    glCompileShader(fshader);
    glGetShaderiv(fshader, GL_COMPILE_STATUS, &tmp);
    if (tmp == GL_FALSE) {
        glGetShaderInfoLog(fshader, 1024, &tmp, infolog);
        infolog[tmp] = 0;
        printf("%s", infolog);
        return 0;
    }
    
    shader = glCreateProgram();
    glAttachShader(shader, vshader);
    glAttachShader(shader, fshader);
    glLinkProgram(shader);
    glGetProgramiv(shader, GL_LINK_STATUS, &tmp);
    if (tmp == GL_FALSE) {
        glGetProgramInfoLog(shader, 1024, &tmp, infolog);
        infolog[tmp] = 0;
        printf("%s", infolog);
        return 0;
    }
    
    glUseProgram(shader);

    /* printf("vendor: %s\n", (const char*)glGetString(GL_VENDOR)); */
    
    initialization_result = 1;
    return 1;
}
Exemplo n.º 12
0
void GlxContext::createContext(GlxContext* shared, unsigned int bitsPerPixel, const ContextSettings& settings)
{
    // Save the creation settings
    m_settings = settings;

    // Get the attributes of the target window
    XWindowAttributes windowAttributes;
    if (XGetWindowAttributes(m_display, m_window, &windowAttributes) == 0)
    {
        err() << "Failed to get the window attributes" << std::endl;
        return;
    }

    // Setup the visual infos to match
    XVisualInfo tpl;
    tpl.depth    = windowAttributes.depth;
    tpl.visualid = XVisualIDFromVisual(windowAttributes.visual);
    tpl.screen   = DefaultScreen(m_display);

    // Get all the visuals matching the template
    int nbVisuals = 0;
    XVisualInfo* visuals = XGetVisualInfo(m_display, VisualDepthMask | VisualIDMask | VisualScreenMask, &tpl, &nbVisuals);
    if (!visuals || (nbVisuals == 0))
    {
        if (visuals)
            XFree(visuals);
        err() << "There is no valid visual for the selected screen" << std::endl;
        return;
    }

    // Find the best visual
    int          bestScore  = 0xFFFF;
    XVisualInfo* bestVisual = NULL;
    for (int i = 0; i < nbVisuals; ++i)
    {
        // Get the current visual attributes
        int RGBA, doubleBuffer, red, green, blue, alpha, depth, stencil, multiSampling, samples;
        glXGetConfig(m_display, &visuals[i], GLX_RGBA,               &RGBA);
        glXGetConfig(m_display, &visuals[i], GLX_DOUBLEBUFFER,       &doubleBuffer); 
        glXGetConfig(m_display, &visuals[i], GLX_RED_SIZE,           &red);
        glXGetConfig(m_display, &visuals[i], GLX_GREEN_SIZE,         &green); 
        glXGetConfig(m_display, &visuals[i], GLX_BLUE_SIZE,          &blue); 
        glXGetConfig(m_display, &visuals[i], GLX_ALPHA_SIZE,         &alpha); 
        glXGetConfig(m_display, &visuals[i], GLX_DEPTH_SIZE,         &depth);        
        glXGetConfig(m_display, &visuals[i], GLX_STENCIL_SIZE,       &stencil);
        glXGetConfig(m_display, &visuals[i], GLX_SAMPLE_BUFFERS_ARB, &multiSampling);        
        glXGetConfig(m_display, &visuals[i], GLX_SAMPLES_ARB,        &samples);

        // First check the mandatory parameters
        if ((RGBA == 0) || (doubleBuffer == 0))
            continue;

        // Evaluate the current configuration
        int color = red + green + blue + alpha;
        int score = evaluateFormat(bitsPerPixel, m_settings, color, depth, stencil, multiSampling ? samples : 0);

        // Keep it if it's better than the current best
        if (score < bestScore)
        {
            bestScore  = score;
            bestVisual = &visuals[i];
        }
    }

    // Make sure that we have found a visual
    if (!bestVisual)
    {
        err() << "Failed to find a suitable pixel format for the window -- cannot create OpenGL context" << std::endl;
        return;
    }

    // Get the context to share display lists with
    GLXContext toShare = shared ? shared->m_context : NULL;

    // Create the OpenGL context -- first try context versions >= 3.0 if it is requested (they require special code)
    while (!m_context && (m_settings.majorVersion >= 3))
    {
        const GLubyte* name = reinterpret_cast<const GLubyte*>("glXCreateContextAttribsARB");
        PFNGLXCREATECONTEXTATTRIBSARBPROC glXCreateContextAttribsARB = reinterpret_cast<PFNGLXCREATECONTEXTATTRIBSARBPROC>(glXGetProcAddress(name));
        if (glXCreateContextAttribsARB)
        {
            int nbConfigs = 0;
            GLXFBConfig* configs = glXChooseFBConfig(m_display, DefaultScreen(m_display), NULL, &nbConfigs);
            if (configs && nbConfigs)
            {
                // Create the context
                int attributes[] =
                {
                    GLX_CONTEXT_MAJOR_VERSION_ARB, static_cast<int>(m_settings.majorVersion),
                    GLX_CONTEXT_MINOR_VERSION_ARB, static_cast<int>(m_settings.minorVersion),
                    GLX_CONTEXT_PROFILE_MASK_ARB, GLX_CONTEXT_COMPATIBILITY_PROFILE_BIT_ARB,
                    0, 0
                };
                m_context = glXCreateContextAttribsARB(m_display, configs[0], toShare, true, attributes);
            }

            if (configs)
                XFree(configs);
        }

        // If we couldn't create the context, lower the version number and try again -- stop at 3.0
        // Invalid version numbers will be generated by this algorithm (like 3.9), but we really don't care
        if (!m_context)
        {
            if (m_settings.minorVersion > 0)
            {
                // If the minor version is not 0, we decrease it and try again
                m_settings.minorVersion--;
            }
            else
            {
                // If the minor version is 0, we decrease the major version
                m_settings.majorVersion--;
                m_settings.minorVersion = 9;
            }
        }
    }

    // If the OpenGL >= 3.0 context failed or if we don't want one, create a regular OpenGL 1.x/2.x context
    if (!m_context)
    {
        // set the context version to 2.0 (arbitrary)
        m_settings.majorVersion = 2;
        m_settings.minorVersion = 0;

        m_context = glXCreateContext(m_display, bestVisual, toShare, true);
        if (!m_context)
        {
            err() << "Failed to create an OpenGL context for this window" << std::endl;
            return;
        }
    }

    // Update the creation settings from the chosen format
    int depth, stencil, multiSampling, samples;
    glXGetConfig(m_display, bestVisual, GLX_DEPTH_SIZE,         &depth);
    glXGetConfig(m_display, bestVisual, GLX_STENCIL_SIZE,       &stencil);
    glXGetConfig(m_display, bestVisual, GLX_SAMPLE_BUFFERS_ARB, &multiSampling);        
    glXGetConfig(m_display, bestVisual, GLX_SAMPLES_ARB,        &samples);
    m_settings.depthBits         = static_cast<unsigned int>(depth);
    m_settings.stencilBits       = static_cast<unsigned int>(stencil);
    m_settings.antialiasingLevel = multiSampling ? samples : 0;

    // Change the target window's colormap so that it matches the context's one
    ::Window root = RootWindow(m_display, DefaultScreen(m_display));
    Colormap colorMap = XCreateColormap(m_display, root, bestVisual->visual, AllocNone);
    XSetWindowColormap(m_display, m_window, colorMap);

    // Free the temporary visuals array
    XFree(visuals);
}
Exemplo n.º 13
0
	Window::Window(std::string const& title,
	               etc::size_type const width,
	               etc::size_type const height,
	               gl::renderer::Name const renderer_name)
		: cube::system::window::Window{title, width, height, renderer_name}
		, _glx_impl{new Impl{}}
	{
		if ((_glx_impl->display = ::XOpenDisplay(0)) == nullptr)
			throw Exception("Cannot connect to the X server");
		_glx_impl->root = DefaultRootWindow(_glx_impl->display);

		if (!::glXQueryExtension(_glx_impl->display, nullptr, nullptr))
			throw Exception{"X Server has no OpenGL GLX extension"};

		static ::GLint double_buffered_attrs[] = {
			GLX_RGBA,
			GLX_RED_SIZE, 8,
			GLX_GREEN_SIZE, 8,
			GLX_BLUE_SIZE, 8,
			GLX_DEPTH_SIZE, 16,
			GLX_DOUBLEBUFFER,
			None,
		};

		static ::GLint single_buffered_attrs[] = {
			GLX_RGBA,
			GLX_RED_SIZE, 8,
			GLX_GREEN_SIZE, 8,
			GLX_BLUE_SIZE, 8,
			GLX_DEPTH_SIZE, 16,
			GLX_DOUBLEBUFFER,
			None,
		};

		_glx_impl->visual_info = ::glXChooseVisual(
			_glx_impl->display, 0, double_buffered_attrs
		);
		if (_glx_impl->visual_info != nullptr)
		{
			_glx_impl->double_buffered = true;
		}
		else
		{
			_glx_impl->double_buffered = false;
			_glx_impl->visual_info = ::glXChooseVisual(
				_glx_impl->display, 0, single_buffered_attrs
			);
		}

		if (_glx_impl->visual_info == nullptr)
			throw Exception{"Cannot choose GLX visual info"};

		_glx_impl->colormap = ::XCreateColormap(
			_glx_impl->display,
			_glx_impl->root,
			_glx_impl->visual_info->visual,
			AllocNone
		);

		_glx_impl->set_window_attributes.colormap = _glx_impl->colormap;
		_glx_impl->set_window_attributes.event_mask =
			ExposureMask |
			KeyPressMask |
			StructureNotifyMask | //ResizeRedirectMask |
			ButtonReleaseMask | ButtonPressMask |
			PointerMotionMask;
		_glx_impl->window = ::XCreateWindow(
			_glx_impl->display,
			_glx_impl->root,
			40, 40, width, height,
			0, _glx_impl->visual_info->depth,
			InputOutput,
			_glx_impl->visual_info->visual,
			CWColormap | CWEventMask,
			&_glx_impl->set_window_attributes
		);

		::XMapWindow(_glx_impl->display, _glx_impl->window);
		::XStoreName(_glx_impl->display, _glx_impl->window, title.c_str());
		_glx_impl->gl_context = glXCreateContext(
			_glx_impl->display,
			_glx_impl->visual_info,
			NULL, GL_TRUE
		);
		::glXMakeCurrent(
			_glx_impl->display,
			_glx_impl->window,
			_glx_impl->gl_context
		);
		Atom wmDelete = ::XInternAtom(
			_glx_impl->display, "WM_DELETE_WINDOW", True
		);
		::XSetWMProtocols(
			_glx_impl->display, _glx_impl->window, &wmDelete, 1
		);
	}
Exemplo n.º 14
0
int CreateWindow(int display)
{
  int err = 0;
  glutDisplay *glut_dpy = (glutDisplay *)display;
  glutWindow *glut_win = NULL;
  XVisualInfo *glx_visual = NULL;
  int glx_visual_attr[5];
  int i = 0;

  glut_win = calloc(1, sizeof(glutWindow));
  FIU_CHECK(glut_win);
  if (!glut_win) {
    printf("glut_win calloc error\n");
    return 0;
  }

  memcpy(&glut_win->attribs, &glut_dpy->attribs, sizeof(struct attributes));

  memset(glx_visual_attr, 0, sizeof(glx_visual_attr));
  glx_visual_attr[i++] = GLX_RGBA;
  if (glut_win->attribs.double_buffer) {
    glx_visual_attr[i++] = GLX_DOUBLEBUFFER;
  }
  if (glut_win->attribs.depth_size) {
    glx_visual_attr[i++] = GLX_DEPTH_SIZE;
    glx_visual_attr[i++] = glut_win->attribs.depth_size;
  }
  glx_visual_attr[i] = None;
  glx_visual = glXChooseVisual(glut_dpy->x11_dpy, 0, glx_visual_attr);
  if (!glx_visual) {
    printf("glXChooseVisual error\n");
    goto error;
  }

  glut_win->x11_win = create_window((int)glut_dpy->x11_dpy, glut_win->attribs.win_posx, glut_win->attribs.win_posy, glut_win->attribs.win_width, glut_win->attribs.win_height, 0, &err);
  if (err == -1) {
    goto error;
  }

  glut_win->glx_ctx = glXCreateContext(glut_dpy->x11_dpy, glx_visual, NULL, True);
  if (!glut_win->glx_ctx) {
    printf("glXCreateContext error\n");
    goto error;
  }

  if (glut_win->attribs.depth_size) {
    err = glXGetConfig(glut_dpy->x11_dpy, glx_visual, GLX_DEPTH_SIZE, &glut_win->attribs.depth_size);
    if (err) {
      printf("glXCreateContext error\n");
      goto error;
    }
  }

  free(glx_visual);

  return (int)glut_win;

error:
  if (glut_win->glx_ctx) {
    glXDestroyContext(glut_dpy->x11_dpy, glut_win->glx_ctx);
  }
  if (glut_win->x11_win) {
    destroy_window((int)glut_dpy->x11_dpy, glut_win->x11_win);
  }
  if (glx_visual) {
    free(glx_visual);
  }
  free(glut_win);
  return 0;
}
Exemplo n.º 15
0
/* ARGSUSED5 */  /* Only Win32 uses gameMode parameter. */
GLUTwindow *
__glutCreateWindow(GLUTwindow * parent,
  int x, int y, int width, int height, int gameMode)
{
  GLUTwindow *window;
  XSetWindowAttributes wa;
  unsigned long attribMask;
  int winnum;
  int i;
#if defined(GLX_VERSION_1_1) && defined(GLX_SGIX_fbconfig)
  GLXFBConfigSGIX fbc;
#else
  void *fbc;
#endif

#if defined(__OS2PM__)
 {
    extern HAB   hab;      /* PM anchor block handle         */
    CLASSINFO classinfo;

    if(!WinQueryClassInfo(hab,"GLUT", &classinfo) )
                               __glutOpenOS2Connection(NULL);
  }
#elif defined(_WIN32)
  WNDCLASS wc;
  int style;

  if (!GetClassInfo(GetModuleHandle(NULL), "GLUT", &wc)) {
    __glutOpenWin32Connection(NULL);
  }
#else
  if (!__glutDisplay) {
    __glutOpenXConnection(NULL);
  }
#endif

#ifndef __OS2PM__
  if (__glutGameModeWindow) {
    __glutFatalError("cannot create windows in game mode.");
  }
#endif

  winnum = getUnusedWindowSlot();
  window = (GLUTwindow *) malloc(sizeof(GLUTwindow));
  if (!window) {
    __glutFatalError("out of memory.");
  }
  window->num = winnum;

#if defined(__OS2PM__)
  /* Add this new window to the window list. */
  __glutWindowList[winnum] = window;
  window->shownState = -1;
#endif

#if !defined(_WIN32)  && !defined(__OS2PM__)
  window->vis = __glutDetermineWindowVisual(&window->treatAsSingle,
    &window->visAlloced, (void**) &fbc);
  if (!window->vis) {
    __glutFatalError(
      "visual with necessary capabilities not found.");
  }
  __glutSetupColormap(window->vis, &window->colormap, &window->cmap);
#endif
  window->eventMask = StructureNotifyMask | ExposureMask;

  attribMask = CWBackPixmap | CWBorderPixel | CWColormap | CWEventMask;
  wa.background_pixmap = None;
  wa.border_pixel = 0;
  wa.colormap = window->cmap;
  wa.event_mask = window->eventMask;
  if (parent) {
    if (parent->eventMask & GLUT_HACK_STOP_PROPAGATE_MASK)
      wa.event_mask |= GLUT_HACK_STOP_PROPAGATE_MASK;
    attribMask |= CWDontPropagate;
    wa.do_not_propagate_mask = parent->eventMask & GLUT_DONT_PROPAGATE_FILTER_MASK;
  } else {
    wa.do_not_propagate_mask = 0;
  }

  /* Stash width and height before Win32's __glutAdjustCoords
     possibly overwrites the values. */
  window->width = width;
  window->height = height;
  window->forceReshape = True;
  window->ignoreKeyRepeat = False;

#if defined(__OS2PM__)

 {  ULONG flStyle=0;
    int ii;
    ERRORID  erridErrorCode;/* last error id code */
    extern HAB   hab;      /* PM anchor block handle         */

  if (parent) {
    flStyle = WS_CLIPCHILDREN|WS_VISIBLE;
  } else {
    if (gameMode) {
      /* Game mode window should be a WS_POPUP window to
         ensure that the taskbar is hidden by it.  A standard
         WS_OVERLAPPEDWINDOW does not hide the task bar. */
      flStyle = FCF_STANDARD |  WS_MAXIMIZED;
    } else {
      /* A standard toplevel window with borders and such. */
      flStyle = FCF_STANDARD | WS_CLIPCHILDREN;
//      flStyle = WS_OVERLAPPEDWINDOW;
    }
  }
{
 HWND  hwnd;                           /* Window     */
 ULONG ListBoxId;                      /* Window id  */
                                       /* (supplied by application) */


 HWND hwndClient;        /* handle to the client                 */
 HWND hwndFrame;         /* handle to the frame                  */
 PFNWP GenericWndProc;
 FRAMECDATA  fcd;
 RECTL  rect;     /* Boundary rectangle                   */



/************************************************/
// flCreate = (FCF_STANDARD) & ~FCF_TASKLIST;
/**********************************/
  if (parent)
  {   window->frame = NULL;

 hwnd = WinCreateWindow(parent->win,  /* Parent window             */
                        "GLUTCHILD",        /* Class name                */
                        "",    /* Window text               */
                        flStyle,       /* Window style              */
                        x, y,          /* Position (x,y)            */
                        width, height,      /* Size (width,height)       */
                        parent->win,    /* Owner window              */
                        HWND_TOP,      /* Sibling window            */
                        0,             /* Window id                 */
                        NULL,          /* Control data              */
                        NULL);         /* Pres parameters           */

 erridErrorCode = WinGetLastError(hab);
    window->win = hwnd;

  window->hdc = WinOpenWindowDC(window->win);
  window->hpsBuffer = hpsCurrent;


 rect.xLeft = x;
 rect.xRight = x+width;
 rect.yBottom = y;
 rect.yTop = y + height;

/***** else parent *****************************/
  } else {
        hwnd = WinCreateStdWindow(HWND_DESKTOP,
           0,       /* WS_VISIBLE frame-window style        */
           &flStyle,        /* window style                 */
           "GLUT",          /* class name                   */
           "GLUT",/* window title                  */
            0L,                  /* default client style          */
            NULLHANDLE,          /* resource in executable file   */
            ID_WINDOW,           /* resource id                   */
            &hwndClient);        /* receives client window handle */

 erridErrorCode = WinGetLastError(hab);
       window->win = hwndClient;
       window->frame = hwnd;
  window->hdc = WinOpenWindowDC(window->win);

  window->hpsBuffer = hpsCurrent;


/* converts a client window's boundaries into  an equivalent frame rectangle */
 rect.xLeft = x;
 rect.xRight = x+width;
 rect.yBottom = y;
 rect.yTop = y + height;

 /* calculate equivalent frame boundary from boundary data */
  WinCalcFrameRect(window->frame, &rect, FALSE);
 }
/***** endof if(parent) *****************************/

  /* Must set the XHDC for fake glXChooseVisual & fake
     glXCreateContext & fake XAllocColorCells. */
  XHDC = window->hdc;
  XHWND = window->win;
  window->vis = __glutDetermineWindowVisual(&window->treatAsSingle,
    &window->visAlloced, &fbc);
    if (!window->vis)
    {   __glutFatalError(
        "pixel format with necessary capabilities not found.");
    }
    { int rc;
      rc = wglChoosePixelFormat(window->hdc, window->vis),

//     evglSetPixelFormat(2); /* int iPixelFormat 1 - doublebuffer/2 - single buffer ??*/
      wglSetPixelFormat(window->hdc,rc,window->vis);
    }
   __glutSetupColormap(window->vis, &window->colormap, &window->cmap);

  window->ctx = glXCreateContext(window->hpsBuffer, window->vis,
    None, __glutTryDirect);

  WinSetWindowPos(hwnd,
                  HWND_TOP,rect.xLeft,rect.yBottom,
                  rect.xRight-rect.xLeft, rect.yTop-rect.yBottom,
      SWP_ACTIVATE | SWP_MOVE | SWP_SIZE | SWP_SHOW|SWP_ZORDER); /* flags*/

  /* Make sure subwindows get a windowStatus callback. */
  if (parent)
       WinPostMsg(parent->win, WM_ACTIVATE, 0, 0);

  }
}

#elif defined(_WIN32)

  __glutAdjustCoords(parent ? parent->win : NULL,
    &x, &y, &width, &height);
  if (parent) {
    style = WS_CHILD;
  } else {
    if (gameMode) {
      /* Game mode window should be a WS_POPUP window to
         ensure that the taskbar is hidden by it.  A standard
         WS_OVERLAPPEDWINDOW does not hide the task bar. */
      style = WS_POPUP | WS_MAXIMIZE;
    } else {
      /* A standard toplevel window with borders and such. */
      style = WS_OVERLAPPEDWINDOW;
    }
  }
  window->win = CreateWindow("GLUT", "GLUT",
    WS_CLIPSIBLINGS | WS_CLIPCHILDREN | style,
    x, y, width, height, parent ? parent->win : __glutRoot,
    NULL, GetModuleHandle(NULL), 0);
  window->hdc = GetDC(window->win);
  /* Must set the XHDC for fake glXChooseVisual & fake
     glXCreateContext & fake XAllocColorCells. */
  XHDC = window->hdc;
  window->vis = __glutDetermineWindowVisual(&window->treatAsSingle,
    &window->visAlloced, &fbc);
  if (!window->vis) {
    __glutFatalError(
      "pixel format with necessary capabilities not found.");
  }
  if (!SetPixelFormat(window->hdc,
      ChoosePixelFormat(window->hdc, window->vis),
      window->vis)) {
    __glutFatalError("SetPixelFormat failed during window create.");
  }
  __glutSetupColormap(window->vis, &window->colormap, &window->cmap);
  /* Make sure subwindows get a windowStatus callback. */
  if (parent) {
    PostMessage(parent->win, WM_ACTIVATE, 0, 0);
  }
  window->renderDc = window->hdc;
#else
  window->win = XCreateWindow(__glutDisplay,
    parent == NULL ? __glutRoot : parent->win,
    x, y, width, height, 0,
    window->vis->depth, InputOutput, window->vis->visual,
    attribMask, &wa);
#endif
  window->renderWin = window->win;
#if defined(GLX_VERSION_1_1) && defined(GLX_SGIX_fbconfig)
  if (fbc) {
    window->ctx = __glut_glXCreateContextWithConfigSGIX(__glutDisplay, fbc,
      GLX_RGBA_TYPE_SGIX, None, __glutTryDirect);
  } else
#endif
#if defined(__OS2PM__)
//    window->ctx = glXCreateContext(window->hpsBuffer, window->vis,
//      None, __glutTryDirect);
#else
    window->ctx = glXCreateContext(__glutDisplay, window->vis,
      None, __glutTryDirect);
#endif
  if (!window->ctx) {
    __glutFatalError(
      "failed to create OpenGL rendering context.");
  }
  window->renderCtx = window->ctx;
#if !defined(_WIN32) && !defined(__OS2PM__)
  window->isDirect = glXIsDirect(__glutDisplay, window->ctx);
  if (__glutForceDirect) {
    if (!window->isDirect)
      __glutFatalError("direct rendering not possible.");
  }
#endif

  window->parent = parent;
  if (parent) {
    window->siblings = parent->children;
    parent->children = window;
  } else {
    window->siblings = NULL;
  }
  window->overlay = NULL;
  window->children = NULL;
  window->display = __glutDefaultDisplay;
  window->reshape = __glutDefaultReshape;
  window->mouse = NULL;
  window->motion = NULL;
  window->passive = NULL;
  window->entry = NULL;
  window->keyboard = NULL;
  window->keyboardUp = NULL;
  window->windowStatus = NULL;
  window->visibility = NULL;
  window->special = NULL;
  window->specialUp = NULL;
  window->buttonBox = NULL;
  window->dials = NULL;
  window->spaceMotion = NULL;
  window->spaceRotate = NULL;
  window->spaceButton = NULL;
  window->tabletMotion = NULL;
  window->tabletButton = NULL;
#ifdef _WIN32
  window->joystick = NULL;
  window->joyPollInterval = 0;
#endif

#if defined(__OS2PM__)
  window->wm_command = NULL;
#endif

  window->tabletPos[0] = -1;
  window->tabletPos[1] = -1;
#if defined(__OS2PM__)
  if(window->shownState == -1)
           window->shownState = 0;
   window->visState =  window->shownState;
#else
  window->shownState = 0;
  window->visState = -1;  /* not VisibilityUnobscured,
                             VisibilityPartiallyObscured, or
                             VisibilityFullyObscured */
#endif
  window->entryState = -1;  /* not EnterNotify or LeaveNotify */

  window->desiredConfMask = 0;
  window->buttonUses = 0;
  window->cursor = GLUT_CURSOR_INHERIT;

  /* Setup window to be mapped when glutMainLoop starts. */
  window->workMask = GLUT_MAP_WORK;
#ifdef _WIN32
  if (gameMode) {
    /* When mapping a game mode window, just show
       the window.  We have already created the game
       mode window with a maximize flag at creation
       time.  Doing a ShowWindow(window->win, SW_SHOWNORMAL)
       would be wrong for a game mode window since it
       would unmaximize the window. */
    window->desiredMapState = GameModeState;
  } else {
    window->desiredMapState = NormalState;
  }
#else
  window->desiredMapState = NormalState;
#endif
  window->prevWorkWin = __glutWindowWorkList;
  __glutWindowWorkList = window;

  /* Initially, no menus attached. */
  for (i = 0; i < GLUT_MAX_MENUS; i++) {
    window->menu[i] = 0;
  }

  /* Add this new window to the window list. */
  __glutWindowList[winnum] = window;

  /* Make the new window the current window. */
  __glutSetWindow(window);

  __glutDetermineMesaSwapHackSupport();

  if (window->treatAsSingle) {
    /* We do this because either the window really is single
       buffered (in which case this is redundant, but harmless,
       because this is the initial single-buffered context
       state); or we are treating a double buffered window as a
       single-buffered window because the system does not appear
       to export any suitable single- buffered visuals (in which
       the following are necessary). */
    glDrawBuffer(GL_FRONT);
    glReadBuffer(GL_FRONT);
  }
  return window;
}
Exemplo n.º 16
0
int main() {
    Engine = new LinuxEngine;

    display = XOpenDisplay(NULL);
    if (!display) {
        LOG("Couldn't open display, terminating.");
        delete Engine;
        return 1;
    }

    root = DefaultRootWindow(display);
    XVisualInfo *visualInfo = glXChooseVisual(display, 0, att);
    if (!visualInfo) {
        LOG("FATAL: Unable to acquire visual!");
        delete Engine;
        return 1;
    }

    cmap = XCreateColormap(display, root, visualInfo->visual, AllocNone);
    swa.colormap = cmap;
    swa.event_mask = ExposureMask | KeyPressMask;// | ResizeRedirectMask;
    Window win = XCreateWindow(display, root, 0, 0, 1024, 600, 0, visualInfo->depth, InputOutput, visualInfo->visual, CWColormap | CWEventMask, &swa);


    XMapWindow(display, win);
    XStoreName(display, win, "tenn0");
    GLXContext context = glXCreateContext(display, visualInfo, NULL, GL_TRUE);
    glXMakeCurrent(display, win, context);

    if (glewInit()) {
        LOG("FATAL! glewInit failed!\n");
        return 0;
    }

    if (!glewIsSupported("GL_VERSION_2_0")) {
        LOG("FATAL! Needs OpenGL 2.0 or later!");
        return 255;
    }
    //if (!glewIsSupported("GL_EXT_geometry_shader4")) {
    //    LOG("FATAL! Needs geometry shader support!");
    //    return 255;
    //}


    Engine->initRender();
    Engine->setViewport(1024,768);

    XEvent xev;
    while (1) {
        Engine->drawFrame();
        glXSwapBuffers(display, win);

        if (!XPending(display))
            continue;

        XNextEvent(display, &xev);

        //XResizeRequestEvent *rev = reinterpret_cast<XResizeRequestEvent*>(&xev);
        switch (xev.type) {
        case Expose:
            XGetWindowAttributes(display, win, &gwa);
            Engine->setViewport(gwa.width, gwa.height);
            Engine->drawFrame();
            glXSwapBuffers(display, win);
            break;

        case KeyPress:
            switch (XLookupKeysym(&xev.xkey, 0)) {
            case XK_Escape:
            case XK_space:
                glXMakeCurrent(display, None, NULL);
                glXDestroyContext(display, context);
                XDestroyWindow(display, win);
                XCloseDisplay(display);
                delete Engine;
                return(1);
            case XK_F2:
                Engine->toggleFrame();
                break;
            case XK_F3:
                Engine->reloadShaders();
                break;
            default:
                continue;
            }
        default:
            break;
        }
    }
}
Exemplo n.º 17
0
mitk::GPGPU::GPGPU()
{

#ifdef _WIN32
               /*
	WNDCLASSEX wcx;

	// Fill in the window class structure with parameters
	// that describe the main window.

	wcx.cbSize = sizeof(wcx);          // size of structure
	wcx.style = CS_HREDRAW |
		CS_VREDRAW;                    // redraw if size changes
	wcx.lpfnWndProc = MainWndProc;     // points to window procedure
	wcx.cbClsExtra = 0;                // no extra class memory
	wcx.cbWndExtra = 0;                // no extra window memory
	wcx.hInstance = GetModuleHandle(NULL);         // handle to inst ance
	wcx.hIcon = LoadIcon(NULL,
		IDI_APPLICATION);              // predefined app. icon
	wcx.hCursor = LoadCursor(NULL,
		IDC_ARROW);                    // predefined arrow
	wcx.hbrBackground = NULL;                  // white background brush
	wcx.lpszMenuName = (LPCSTR) "MainMenu";    // name of menu resource
	wcx.lpszClassName = (LPCSTR) "MainWClass";  // name of window class
	wcx.hIconSm = LoadIcon(NULL, IDI_APPLICATION);

	// Register the window class.

	if(!RegisterClassEx(&wcx))
		std::cout << "failed registering window class\n";

	HWND desktopWindow=CreateWindowEx(
		WS_EX_CLIENTEDGE,
		(LPCSTR)"MainWClass",
		(LPCSTR)"Anatomy of a Window",
		WS_OVERLAPPEDWINDOW,
		CW_USEDEFAULT, CW_USEDEFAULT, 240, 120,
		NULL,
		NULL,
		GetModuleHandle(NULL),
		NULL);
	windowHandle = desktopWindow;
  ShowWindow(desktopWindow, SW_RESTORE);

  if(desktopWindow==0)
	  std::cout << "failed creating window\n";
                 */

	HWND desktopWindow=QApplication::topLevelWidgets().at(0)->winId();

  windowsContext = GetDC(desktopWindow);

  if(windowsContext==0)
	  std::cout << "failed getting window device context\n";
                 
	static PIXELFORMATDESCRIPTOR pfd =// pfd Tells Windows How We Want Things To Be
	{
		sizeof(PIXELFORMATDESCRIPTOR),	// Size Of This Pixel Format Descriptor
		1,								              // Version Number
		PFD_DRAW_TO_WINDOW |						// Format Must Support Window
		PFD_SUPPORT_OPENGL |						// Format Must Support OpenGL
		PFD_DOUBLEBUFFER |
		PFD_SWAP_EXCHANGE ,					    // Must Support Double Buffering
		PFD_TYPE_RGBA,							    // Request An RGBA Format
		24,								              // Select Our Color Depth
		0, 0, 0, 0, 0, 0,						    // Color Bits Ignored  if(openGLContext==0)
		0,								              // No Alpha Buffer
		0,								              // Shift Bit Ignored
		0,								              // No Accumulation Buffer
		0, 0, 0, 0,							        // Accumulation Bits Ignored
		0,								              // 16Bit Z-Buffer (Depth Buffer)
		0,								              // No Stencil Buffer
		0,								              // No Auxiliary Buffer
		PFD_MAIN_PLANE,							    // Main Drawing Layer
		0,								              // Reserved
		0, 0, 0								          // Layer Masks Ignored
	};


  // Sonstiges einstellen
  int iFormat = ChoosePixelFormat(windowsContext,&pfd);
  SetPixelFormat(windowsContext,iFormat,&pfd);


  openGLContext = wglCreateContext(windowsContext);

  int errw=GetLastError();

  if(openGLContext==0)
	  std::cout << "failed creating openGL context "<<errw<<"\n";

#else

  X_display = XOpenDisplay(NULL);

  GPGPU_ERROR( !X_display ) << "cant open X display";

  GLX_drawable = QApplication::topLevelWidgets().at(0)->winId();

  GPGPU_ERROR( !GLX_drawable ) << "cant get toplevel widget from QT";

  static int visAttributes[] = {
    GLX_RGBA,
    GLX_RED_SIZE, 1,
    GLX_GREEN_SIZE, 1,
    GLX_BLUE_SIZE, 1,
    GLX_DOUBLEBUFFER,
    None
  };

  XVisualInfo *visinfo = glXChooseVisual(X_display, 0, visAttributes);

  GPGPU_ERROR(!visinfo) << "Unable to choose specified visual!";

  openGLContext = glXCreateContext(X_display, visinfo, 0, true);

  if(visinfo)
     XFree(visinfo);

  GPGPU_ERROR(!openGLContext) << "cant create GLX context";

#endif

  Activate();

  GPGPU_INFO << "initializing glew";

  int err=glewInit();

  GPGPU_CHECKGLERR << "initializing glew";
  GPGPU_ERROR(GLEW_OK != err) << "glewInit() fails with " << err << " as text: " << glewGetErrorString(err);

  glMatrixMode(GL_PROJECTION);
  glLoadIdentity();
  glOrtho(0,1,0,1,-1,1);
  glMatrixMode(GL_MODELVIEW);
  glLoadIdentity();

  GPGPU_CHECKGLERR << "intializing projection&modelview matrix";

  glDisable(GL_CULL_FACE);
	glShadeModel(GL_SMOOTH);							// Enable Smooth Shading
	glClearColor(0.0f, 0.0f, 0.0f, 0.0f);				// Black Background
	glClearDepth(1.0f);									// Depth Buffer Setup
  glDisable(GL_DEPTH_TEST);							// Enables Depth Testing
	glHint(GL_PERSPECTIVE_CORRECTION_HINT, GL_NICEST);	// Really Nice Perspective Calculations
  glHint(GL_TEXTURE_COMPRESSION_HINT, GL_NICEST);
  glDepthMask(false);

  GPGPU_CHECKGLERR << "setting up openGL context";
}
Exemplo n.º 18
0
Arquivo: glx.c Projeto: ssvb/glshim
GLXContext glXCreateNewContext(Display *display, GLXFBConfig config,
                               int render_type, GLXContext share_list,
                               Bool is_direct) {
    return glXCreateContext(display, 0, share_list, is_direct);
}
Exemplo n.º 19
0
int main(int argc, char *argv[])
{

    i=0.0;
    numPlotPoints=0;

    //Allocate memory for the plot
    plot = (DATA_POINT**)calloc( MAX_PLOTS, sizeof(DATA_POINT*));

#ifdef seawolf
    Seawolf_loadConfig("../../conf/seawolf.conf");
    Seawolf_init("HUD");
#endif

    currentDepth=0;

    dpy = XOpenDisplay(NULL);

    if(dpy == NULL)
        {
            printf("\n\tcannot connect to X server\n\n");
            exit(0);
        }

    root = DefaultRootWindow(dpy);

    vi = glXChooseVisual(dpy, 0, att);

    if(vi == NULL)
        {
            printf("\n\tno appropriate visual found\n\n");
            exit(0);
        }
    else
        {
            //printf("\n\tvisual %p selected\n", vi->visualid);
        }/* %p creates hexadecimal output like in glxinfo */


    cmap = XCreateColormap(dpy, root, vi->visual, AllocNone);

    swa.colormap = cmap;
    swa.event_mask = ExposureMask | KeyPressMask;

    win = XCreateWindow(dpy, root, (SCREEN_X-WINDOW_X)/2,(SCREEN_Y-WINDOW_Y)/2 , WINDOW_X, WINDOW_Y, 0, vi->depth, InputOutput, vi->visual, CWColormap | CWEventMask, &swa);

    XMapWindow(dpy, win);
    XStoreName(dpy, win, "Seawolf HUD");

    glc = glXCreateContext(dpy, vi, NULL, GL_TRUE);
    glXMakeCurrent(dpy, win, glc);

    glEnable(GL_DEPTH_TEST);

#ifdef seawolf
    Var_bind("Depth", &currentDepth);
    Var_bind("DepthPID.Heading", &desiredDepth);
    Var_bind("SEA.Roll", &currentRoll);
    Var_bind("SEA.Pitch", &currentPitch);
    Var_bind("SEA.Yaw", &currentYaw);
#endif

    while(1)
        {

#ifdef seawolf
            Util_usleep(0.02);
#else
            currentDepth=10.0*sin(i*PI/180.0);
            currentRoll =180.0*cos(i*PI/180.0) ;
            currentPitch=10.0*sin(i*PI/180.0);
            currentYaw = 180.0*cos((i+90.0)*PI/180.0);

            desiredDepth=4*cos(i*PI/180.0);
            desiredPitch=180.0*sin((i+30.0f)*PI/180.0);
            desiredYaw = 180.0*cos((i+90.0)*PI/180.0);
#endif


            //Initialize the plots you want to see
            UpdatePlot(CUR_DEPTH, currentDepth);
            UpdatePlot(SET_DEPTH, desiredDepth);
            UpdatePlot(CUR_ROLL, currentRoll);
            UpdatePlot(SET_ROLL, desiredDepth);
            UpdatePlot(CUR_PITCH, currentPitch);
            UpdatePlot(SET_PITCH, desiredPitch);
            UpdatePlot(CUR_YAW, currentYaw);
            UpdatePlot(SET_YAW, desiredYaw);
            //Incriment the number of points in the buffer
            numPlotPoints++;

            i+=0.1;

            XGetWindowAttributes(dpy, win, &gwa);
            //glViewport(0, 0, gwa.width, gwa.height);
            glViewport(0,0, WINDOW_X, WINDOW_Y);
            Render();
            glXSwapBuffers(dpy, win);

        }
}
Exemplo n.º 20
0
GLXContext *
init_GL(ModeInfo * mi)
{
  Display *dpy = mi->dpy;
  Window window = mi->window;
  Screen *screen = mi->xgwa.screen;
  Visual *visual = mi->xgwa.visual;
  XVisualInfo vi_in, *vi_out;
  int out_count;

  if (mi->glx_context) {
    glXMakeCurrent (dpy, window, mi->glx_context);
    return &mi->glx_context;
  }

# ifdef HAVE_JWZGLES
  jwzgles_make_current(jwzgles_make_state(state));
# endif

  vi_in.screen = screen_number (screen);
  vi_in.visualid = XVisualIDFromVisual (visual);
  vi_out = XGetVisualInfo (dpy, VisualScreenMask|VisualIDMask,
			   &vi_in, &out_count);
  if (! vi_out) abort ();

  {
    XSync (dpy, False);
    orig_ehandler = XSetErrorHandler (BadValue_ehandler);
    mi->glx_context = glXCreateContext (dpy, vi_out, 0, GL_TRUE);
    XSync (dpy, False);
    XSetErrorHandler (orig_ehandler);
    if (got_error)
      mi->glx_context = 0;
  }

  XFree((char *) vi_out);

  if (!mi->glx_context)
    {
      fprintf(stderr, "%s: couldn't create GL context for visual 0x%x.\n",
	      progname, (unsigned int) XVisualIDFromVisual (visual));
      exit(1);
    }

  glXMakeCurrent (dpy, window, mi->glx_context);

  {
    GLboolean rgba_mode = 0;
    glGetBooleanv(GL_RGBA_MODE, &rgba_mode);
    if (!rgba_mode)
      {
	glIndexi (WhitePixelOfScreen (screen));
	glClearIndex (BlackPixelOfScreen (screen));
      }
  }


  /* jwz: the doc for glDrawBuffer says "The initial value is GL_FRONT
     for single-buffered contexts, and GL_BACK for double-buffered
     contexts."  However, I find that this is not always the case,
     at least with Mesa 3.4.2 -- sometimes the default seems to be
     GL_FRONT even when glGet(GL_DOUBLEBUFFER) is true.  So, let's
     make sure.

     Oh, hmm -- maybe this only happens when we are re-using the
     xscreensaver window, and the previous GL hack happened to die with
     the other buffer selected?  I'm not sure.  Anyway, this fixes it.
   */
  {
    GLboolean d = False;
    glGetBooleanv (GL_DOUBLEBUFFER, &d);
    if (d)
      glDrawBuffer (GL_BACK);
    else
      glDrawBuffer (GL_FRONT);
  }

  /* Sometimes glDrawBuffer() throws "invalid op". Dunno why. Ignore. */
  clear_gl_error ();

  /* Process the -background argument. */
  {
    char *s = get_string_resource(mi->dpy, "background", "Background");
    XColor c = { 0, };
    if (! XParseColor (dpy, mi->xgwa.colormap, s, &c))
      fprintf (stderr, "%s: can't parse color %s; using black.\n", 
               progname, s);
    glClearColor (c.red   / 65535.0,
                  c.green / 65535.0,
                  c.blue  / 65535.0,
                  1.0);
  }

  glClear (GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);

  /* GLXContext is already a pointer type.
     Why this function returns a pointer to a pointer, I have no idea...
   */
  return &mi->glx_context;
}
Exemplo n.º 21
0
/* FIXME: bits is currently unused */
Bool createGLWindow(char* title, int width, int height, int bits,
                    Bool fullscreenflag)
{
    XVisualInfo *vi;
    Colormap cmap;
    int dpyWidth, dpyHeight;
    int i;
    int glxMajorVersion, glxMinorVersion;
    int vidModeMajorVersion, vidModeMinorVersion;
    XF86VidModeModeInfo **modes;
    int modeNum;
    int bestMode;
    Atom wmDelete;
    Window winDummy;
    unsigned int borderDummy;
    
    GLWin.fs = fullscreenflag;
    /* set best mode to current */
    bestMode = 0;
    /* get a connection */
    GLWin.dpy = XOpenDisplay(0);
    GLWin.screen = DefaultScreen(GLWin.dpy);
    XF86VidModeQueryVersion(GLWin.dpy, &vidModeMajorVersion,
        &vidModeMinorVersion);
    printf("XF86VidModeExtension-Version %d.%d\n", vidModeMajorVersion,
        vidModeMinorVersion);
    XF86VidModeGetAllModeLines(GLWin.dpy, GLWin.screen, &modeNum, &modes);
    /* save desktop-resolution before switching modes */
    GLWin.deskMode = *modes[0];
    /* look for mode with requested resolution */
    for (i = 0; i < modeNum; i++)
    {
        if ((modes[i]->hdisplay == width) && (modes[i]->vdisplay == height))
        {
            bestMode = i;
        }
    }
    /* get an appropriate visual */
    vi = glXChooseVisual(GLWin.dpy, GLWin.screen, attrListDbl);
    if (vi == NULL)
    {
        vi = glXChooseVisual(GLWin.dpy, GLWin.screen, attrListSgl);
        printf("Only Singlebuffered Visual!\n");
    }
    else
    {
        printf("Got Doublebuffered Visual!\n");
    }
    glXQueryVersion(GLWin.dpy, &glxMajorVersion, &glxMinorVersion);
    printf("glX-Version %d.%d\n", glxMajorVersion, glxMinorVersion);
    /* create a GLX context */
    GLWin.ctx = glXCreateContext(GLWin.dpy, vi, 0, GL_TRUE);
    /* create a color map */
    cmap = XCreateColormap(GLWin.dpy, RootWindow(GLWin.dpy, vi->screen),
        vi->visual, AllocNone);
    GLWin.attr.colormap = cmap;
    GLWin.attr.border_pixel = 0;

    if (GLWin.fs)
    {
        XF86VidModeSwitchToMode(GLWin.dpy, GLWin.screen, modes[bestMode]);
        XF86VidModeSetViewPort(GLWin.dpy, GLWin.screen, 0, 0);
        dpyWidth = modes[bestMode]->hdisplay;
        dpyHeight = modes[bestMode]->vdisplay;
        printf("Resolution %dx%d\n", dpyWidth, dpyHeight);
        XFree(modes);
    
        /* create a fullscreen window */
        GLWin.attr.override_redirect = True;
        GLWin.attr.event_mask = ExposureMask | KeyPressMask | ButtonPressMask |
            StructureNotifyMask;
        GLWin.win = XCreateWindow(GLWin.dpy, RootWindow(GLWin.dpy, vi->screen),
            0, 0, dpyWidth, dpyHeight, 0, vi->depth, InputOutput, vi->visual,
            CWBorderPixel | CWColormap | CWEventMask | CWOverrideRedirect,
            &GLWin.attr);
        XWarpPointer(GLWin.dpy, None, GLWin.win, 0, 0, 0, 0, 0, 0);
		XMapRaised(GLWin.dpy, GLWin.win);
        XGrabKeyboard(GLWin.dpy, GLWin.win, True, GrabModeAsync,
            GrabModeAsync, CurrentTime);
        XGrabPointer(GLWin.dpy, GLWin.win, True, ButtonPressMask,
            GrabModeAsync, GrabModeAsync, GLWin.win, None, CurrentTime);
    }
    else
    {
        /* create a window in window mode*/
        GLWin.attr.event_mask = ExposureMask | KeyPressMask | ButtonPressMask |
            StructureNotifyMask;
        GLWin.win = XCreateWindow(GLWin.dpy, RootWindow(GLWin.dpy, vi->screen),
            0, 0, width, height, 0, vi->depth, InputOutput, vi->visual,
            CWBorderPixel | CWColormap | CWEventMask, &GLWin.attr);
        /* only set window title and handle wm_delete_events if in windowed mode */
        wmDelete = XInternAtom(GLWin.dpy, "WM_DELETE_WINDOW", True);
        XSetWMProtocols(GLWin.dpy, GLWin.win, &wmDelete, 1);
        XSetStandardProperties(GLWin.dpy, GLWin.win, title,
            title, None, NULL, 0, NULL);
        XMapRaised(GLWin.dpy, GLWin.win);
    }       
    /* connect the glx-context to the window */
    glXMakeCurrent(GLWin.dpy, GLWin.win, GLWin.ctx);
    XGetGeometry(GLWin.dpy, GLWin.win, &winDummy, &GLWin.x, &GLWin.y,
        &GLWin.width, &GLWin.height, &borderDummy, &GLWin.depth);
    printf("Depth %d\n", GLWin.depth);
    if (glXIsDirect(GLWin.dpy, GLWin.ctx)) 
        printf("Congrats, you have Direct Rendering!\n");
    else
        printf("Sorry, no Direct Rendering possible!\n");
    initGL();
    return True;    
}
Exemplo n.º 22
0
bool CreateWindowGL (GL_Window* window) {
	XVisualInfo *vi;
	Colormap cmap;
	int dpyWidth, dpyHeight;
	int i;
	int glxMajorVersion, glxMinorVersion;
	int vidModeMajorVersion, vidModeMinorVersion;
	XF86VidModeModeInfo **modes;
	int modeNum;
	int bestMode;
	Atom wmDelete;
	Window winDummy;
	unsigned int borderDummy;
	int x, y;

	bestMode = 0;

	window->init.dpy = XOpenDisplay( NULL );
	window->init.screen = DefaultScreen( window->init.dpy );
	XF86VidModeQueryVersion( window->init.dpy, &vidModeMajorVersion,
													 &vidModeMinorVersion );
	
	printf( "XF86VMExt-Version %d.%d\n",
					vidModeMajorVersion, vidModeMinorVersion );
	XF86VidModeGetAllModeLines( window->init.dpy, window->init.screen,
															&modeNum, &modes );
	window->init.deskMode = *modes[0];

	for( i=0;i<modeNum;i++ ) {
		if( (modes[i]->hdisplay == window->init.width) &&
				(modes[i]->vdisplay == window->init.height) )
			bestMode = i;
	}

	vi = glXChooseVisual( window->init.dpy, window->init.screen, attrListDbl );
	if( vi == NULL ) {
		vi = glXChooseVisual( window->init.dpy, window->init.screen, attrListSgl );
		window->init.doubleBuffered = false;
		printf( "Single Buffered visual\n" );
	} else {
		window->init.doubleBuffered = true;
		printf( "Double Buffered visual\n" );
	}

	glXQueryVersion( window->init.dpy, &glxMajorVersion, &glxMinorVersion );
	printf( "glx-version %d.%d\n", glxMajorVersion, glxMinorVersion );

	window->init.ctx = glXCreateContext( window->init.dpy, vi, 0, GL_TRUE );

	cmap = XCreateColormap( window->init.dpy,
													RootWindow( window->init.dpy, vi->screen ),
													vi->visual, AllocNone );
	window->init.attr.colormap = cmap;
	window->init.attr.border_pixel = 0;

	if( window->init.isFullScreen ) {
		XF86VidModeSwitchToMode( window->init.dpy, window->init.screen,
														 modes[bestMode] );
		XF86VidModeSetViewPort( window->init.dpy, window->init.screen, 0, 0 );
		dpyWidth = modes[bestMode]->hdisplay;
		dpyHeight = modes[bestMode]->vdisplay;
		XFree( modes );

		window->init.attr.override_redirect = true;
		window->init.attr.event_mask =
			ExposureMask | KeyPressMask | KeyReleaseMask | ButtonPressMask |
			ButtonReleaseMask | StructureNotifyMask | PointerMotionMask;
		window->init.win =
			XCreateWindow( window->init.dpy,
										 RootWindow( window->init.dpy, vi->screen ),
										 0, 0, dpyWidth, dpyHeight, 0, vi->depth, InputOutput,
										 vi->visual, CWBorderPixel | CWColormap | CWEventMask |
										 CWOverrideRedirect, &window->init.attr );
		XWarpPointer( window->init.dpy, None, window->init.win, 0, 0, 0, 0, 0, 0 );
		XMapRaised( window->init.dpy, window->init.win );
		XGrabKeyboard( window->init.dpy, window->init.win, True, GrabModeAsync,
									 GrabModeAsync, CurrentTime );
		XGrabPointer( window->init.dpy, window->init.win, True, ButtonPressMask,
									GrabModeAsync, GrabModeAsync, window->init.win, None,
									CurrentTime );
	} else {
		window->init.attr.event_mask =
			ExposureMask | KeyPressMask | KeyReleaseMask | ButtonPressMask |
			ButtonReleaseMask | StructureNotifyMask | PointerMotionMask;
		window->init.win =
			XCreateWindow( window->init.dpy,
										 RootWindow( window->init.dpy, vi->screen ),
										 0, 0, window->init.width, window->init.height,
										 0, vi->depth, InputOutput, vi->visual,
										 CWBorderPixel | CWColormap | CWEventMask,
										 &window->init.attr );
		wmDelete = XInternAtom( window->init.dpy, "WM_DELETE_WINDOW", True );
		XSetWMProtocols( window->init.dpy, window->init.win, &wmDelete, 1 );
		XSetStandardProperties( window->init.dpy, window->init.win,
														window->init.title, window->init.title, None, NULL,
														0, NULL );
		XMapRaised( window->init.dpy, window->init.win );
	}

	glXMakeCurrent( window->init.dpy, window->init.win, window->init.ctx );
	XGetGeometry( window->init.dpy, window->init.win, &winDummy, &x, &y,
								&window->init.width, &window->init.height, &borderDummy,
								&window->init.depth );
	
	if( glXIsDirect( window->init.dpy, window->init.ctx ) )
		printf( "Direct rendering\n" );
	else
		printf( "Not Direct rendering\n" );

	return true;
}
Exemplo n.º 23
0
int geCreateMainWindow(const char* title, int Width, int Height, int flags){
	initializing = true;
	XInitThreads();

	LibGE_LinuxContext* context = (LibGE_LinuxContext*)geMalloc(sizeof(LibGE_LinuxContext));
	libge_context->syscontext = (unsigned long)context;


	win_hints = XAllocWMHints();
	win_size_hints = XAllocSizeHints();

	libge_context->width = Width;
	libge_context->height = Height;
	context->fs = flags & GE_WINDOW_FULLSCREEN;

	int nSamples = 1;
	if(flags & GE_WINDOW_MSAA2X){
		nSamples = 2;
	}
	if(flags & GE_WINDOW_MSAA4X){
		nSamples = 4;
	}
	if(flags & GE_WINDOW_MSAA8X){
		nSamples = 8;
	}

	Colormap cmap;
	Window winDummy;
	unsigned int borderDummy;

	context->dpy = XOpenDisplay(0);
	context->screen = DefaultScreen(context->dpy);

	// get an appropriate visual
	context->vi = glXChooseVisual(context->dpy, context->screen, attributes);
	context->doubleBuffered = True;

	// create a color map
	cmap = XCreateColormap(context->dpy, RootWindow(context->dpy, context->vi->screen), context->vi->visual, AllocNone);
	context->attr.colormap = cmap;
	context->attr.border_pixel = 0;
	context->attr.background_pixmap = None;

	win_size_hints->flags = PSize;
	if(!(flags & GE_WINDOW_RESIZABLE)){
		win_size_hints->flags = PSize | PMinSize | PMaxSize;
		win_size_hints->min_width = libge_context->width;
		win_size_hints->min_height = libge_context->height;
		win_size_hints->max_width = libge_context->width;
		win_size_hints->max_height = libge_context->height;
		win_size_hints->base_width = libge_context->width;
		win_size_hints->base_height = libge_context->height;
	}

	XWindowAttributes attribs;
	XGetWindowAttributes(context->dpy, RootWindow(context->dpy, context->vi->screen), &attribs);
	if(Width < 0){
		libge_context->width = attribs.width;
	}
	if(Height < 0){
		libge_context->height = attribs.height;
	}

	context->attr.override_redirect = false;
	context->attr.event_mask = event_mask;
	context->win = XCreateWindow(context->dpy, RootWindow(context->dpy, context->vi->screen), 0, 0, libge_context->width, libge_context->height, 0, context->vi->depth, InputOutput, context->vi->visual, CWBorderPixel | CWBackPixmap | CWColormap | CWEventMask | CWOverrideRedirect, &context->attr);

	XSetStandardProperties(context->dpy, context->win, title, title, None, NULL, 0, NULL);
	XMapRaised(context->dpy, context->win);

	if(context->fs){
		Atom wm_fullscreen = XInternAtom(context->dpy, "_NET_WM_STATE_FULLSCREEN", true);
		XChangeProperty(context->dpy, context->win, XInternAtom(context->dpy, "_NET_WM_STATE", true), XA_ATOM, 32, PropModeReplace, (unsigned char *)&wm_fullscreen, 1);
	}

	// create a GLX context
	context->ctx = glXCreateContext(context->dpy, context->vi, 0, true);

	Atom wmDelete = XInternAtom(context->dpy, "WM_DELETE_WINDOW", True);
	XSetWMProtocols(context->dpy, context->win, &wmDelete, 1);

	Pixmap bm_no; XColor black;
	static char bm_no_data[] = {0, 0, 0, 0, 0, 0, 0, 0};
	bm_no = XCreateBitmapFromData(context->dpy, context->win, bm_no_data, 8, 8);
	invisible_cursor = XCreatePixmapCursor(context->dpy, bm_no, bm_no, &black, &black, 0, 0);
	if (bm_no!=None)XFreePixmap(context->dpy, bm_no);

	XSetWMNormalHints(context->dpy, context->win, win_size_hints);
	XSetWMHints(context->dpy, context->win, win_hints);
	XSelectInput(context->dpy, context->win, event_mask);

	// connect the glx-context to the window
	glXMakeCurrent(context->dpy, context->win, context->ctx);
	XGetGeometry(context->dpy, context->win, &winDummy, &context->x, &context->y, (u32*)&libge_context->width, (u32*)&libge_context->height, &borderDummy, (u32*)&context->depth);
	gePrintDebug(0x100, "X11 Window: %dx%d	depth:%d	Direct rendering: %s\n", libge_context->width, libge_context->height, context->depth, glXIsDirect(context->dpy, context->ctx)?"yes":"no");

	LinuxInit();
	geWaitVsync(true);

	gePrintDebug(0x100, "Current OpenGL version: %s\n", (const char*)glGetString(GL_VERSION));
	geInitVideo();
	geInitShaders();
	geGraphicsInit();
	geDrawingMode(GE_DRAWING_MODE_2D);
	
	atexit(_ge_exit);

	initializing = false;
	return 0;
}
Exemplo n.º 24
0
void
dev_open(
	char  *id
)
{
	extern char	*getenv();
	static RGBPRIMS	myprims = STDPRIMS;
	static int	atlBest[] = {GLX_RGBA, GLX_RED_SIZE,8,
				GLX_GREEN_SIZE,8, GLX_BLUE_SIZE,8,
				GLX_DEPTH_SIZE,15, None};
	char	*ev;
	double	gamval = GAMMA;
	RGBPRIMP	dpri = stdprims;
	XSetWindowAttributes	ourwinattr;
	XWMHints	ourxwmhints;
	XSizeHints	oursizhints;
					/* set quadtree globals */
	qtMinNodesiz = 3;
	qtDepthEps = 0.07;
					/* open display server */
	ourdisplay = XOpenDisplay(NULL);
	if (ourdisplay == NULL)
		error(USER, "cannot open X-windows; DISPLAY variable set?\n");
					/* find a usable visual */
	ourvinf = glXChooseVisual(ourdisplay, ourscreen, atlBest);
	if (ourvinf == NULL)
		error(USER, "no suitable visuals available");
					/* get a context */
	gctx = glXCreateContext(ourdisplay, ourvinf, NULL, GL_TRUE);
					/* set gamma and tone mapping */
	if ((ev = XGetDefault(ourdisplay, "radiance", "gamma")) != NULL
			|| (ev = getenv("DISPLAY_GAMMA")) != NULL)
		gamval = atof(ev);
	if ((ev = getenv("DISPLAY_PRIMARIES")) != NULL &&
			sscanf(ev, "%f %f %f %f %f %f %f %f",
				&myprims[RED][CIEX],&myprims[RED][CIEY],
				&myprims[GRN][CIEX],&myprims[GRN][CIEY],
				&myprims[BLU][CIEX],&myprims[BLU][CIEY],
				&myprims[WHT][CIEX],&myprims[WHT][CIEY]) >= 6)
		dpri = myprims;
	tmGlobal = tmInit(mytmflags(), dpri, gamval);
	if (tmGlobal == NULL)
		error(SYSTEM, "not enough memory in dev_open");
					/* open window */
	ourwinattr.background_pixel = ourblack;
	ourwinattr.border_pixel = ourblack;
	ourwinattr.event_mask = ourmask;
					/* this is stupid */
	ourwinattr.colormap = XCreateColormap(ourdisplay, ourroot,
				ourvinf->visual, AllocNone);
	gwind = XCreateWindow(ourdisplay, ourroot, 0, 0,
		DisplayWidth(ourdisplay,ourscreen)-2*BORWIDTH,
		DisplayHeight(ourdisplay,ourscreen)-2*BORWIDTH,
		BORWIDTH, ourvinf->depth, InputOutput, ourvinf->visual,
		CWBackPixel|CWBorderPixel|CWColormap|CWEventMask, &ourwinattr);
	if (gwind == 0)
		error(SYSTEM, "cannot create window\n");
   	XStoreName(ourdisplay, gwind, id);
					/* set window manager hints */
	ourxwmhints.flags = InputHint|IconPixmapHint;
	ourxwmhints.input = True;
	ourxwmhints.icon_pixmap = XCreateBitmapFromData(ourdisplay,
			gwind, x11icon_bits, x11icon_width, x11icon_height);
	XSetWMHints(ourdisplay, gwind, &ourxwmhints);
	oursizhints.min_width = MINWIDTH;
	oursizhints.min_height = MINHEIGHT;
	oursizhints.flags = PMinSize;
	XSetNormalHints(ourdisplay, gwind, &oursizhints);
					/* set GLX context */
	glXMakeCurrent(ourdisplay, gwind, gctx);
	glEnable(GL_DEPTH_TEST);
	glDepthFunc(GL_LEQUAL);
	glShadeModel(GL_FLAT);
	glDisable(GL_DITHER);
	glDisable(GL_CULL_FACE);
	glMatrixMode(GL_PROJECTION);
	glOrtho(0., 1., 0., 1., -.01, 1.01);
	glTranslated(0., 0., -1.01);
					/* figure out sensible view */
	pwidth = (double)DisplayWidthMM(ourdisplay, ourscreen) /
			DisplayWidth(ourdisplay, ourscreen);
	pheight = (double)DisplayHeightMM(ourdisplay, ourscreen) /
			DisplayHeight(ourdisplay, ourscreen);
	odev.v = stdview;
	odev.v.type = VT_PER;
					/* map the window */
	XMapWindow(ourdisplay, gwind);
	dev_input();			/* sets size and view angles */
					/* allocate our leaf pile */
	if (!qtAllocLeaves(DisplayWidth(ourdisplay,ourscreen) *
			DisplayHeight(ourdisplay,ourscreen) * 3 /
			(qtMinNodesiz*qtMinNodesiz*2)))
		error(SYSTEM, "insufficient memory for value storage");
	odev.name = id;
	odev.ifd = ConnectionNumber(ourdisplay);
					/* initialize cone array */
	initcones();
}
Exemplo n.º 25
0
int main(int argc, char **argv)
{
	struct engine *engine = NULL;
	Display *dpy;
	int num;
	XSetWindowAttributes attr;
	unsigned long mask;
	Window root;
	Window win;
	XVisualInfo *info = NULL;
	GLXContext ctx  = NULL;
	int conf[] = { GLX_RGBA,
		GLX_RED_SIZE, 1,
		GLX_GREEN_SIZE, 1,
		GLX_BLUE_SIZE, 1,
		GLX_DOUBLEBUFFER, GL_FALSE,
		GLX_DEPTH_SIZE, 1,
		None,
	};

	dpy = XOpenDisplay(NULL);
	if (!dpy) {
		_err("failed to open X display\n");
		return 1;
	}

	num = DefaultScreen(dpy);
	_inf("use GLX_SGIX_pbuffer on screen %d\n", num);

	root = RootWindow(dpy, num);
	info = glXChooseVisual(dpy, num, conf);
	if (!info) {
		_err("glXChooseVisual() failed\n");
		goto out;
	}

	/* window attributes */
	attr.border_pixel = 0;
	attr.colormap = XCreateColormap(dpy, root, info->visual, AllocNone);
	attr.event_mask = ButtonPressMask | ExposureMask | KeyPressMask;
	mask = CWBorderPixel | CWColormap | CWEventMask;

	win = XCreateWindow(dpy, root, 0, 0, DISPLAY_WIDTH, DISPLAY_HEIGHT,
		0, info->depth, InputOutput, info->visual, mask, &attr);

	ctx = glXCreateContext(dpy, info, NULL, GL_TRUE);
	if (!ctx) {
		_err("glXCreateContext() failed\n");
		goto out;
	}

	XFree(info);
	info = NULL;
	XMapWindow(dpy, win);

	_msg("call glXMakeCurrent()\n");
	glXMakeCurrent(dpy, win, ctx);

	_inf("GL_RENDERER   = %s\n", (char *) glGetString(GL_RENDERER));
	_inf("GL_VERSION    = %s\n", (char *) glGetString(GL_VERSION));
	_inf("GL_VENDOR     = %s\n", (char *) glGetString(GL_VENDOR));
	_inf("GL_EXTENSIONS = %s\n", (char *) glGetString(GL_EXTENSIONS));
	_inf("GL_SHADING_LANGUAGE_VERSION = %s\n",
		(char *) glGetString(GL_SHADING_LANGUAGE_VERSION));

	_msg("clear window\n");
	glClearColor(0, 0, 0, 1);
	glClear(GL_COLOR_BUFFER_BIT);
	glXSwapBuffers(dpy, win);

	_msg("init engine\n");
	if (engine_init(&engine, argc, argv) < 0) {
		_err("engine_init() failed\n");
		goto out;
	}

	_msg("start engine\n");
	engine_start(engine);

	glXSwapBuffers(dpy, win);

	engine_stop(engine);
	event_loop(dpy);

	_msg("exit engine\n");
	engine_exit(&engine);

out:
	glXMakeCurrent(dpy, 0, 0);

	if (info)
		XFree(info);

	if (ctx)
		glXDestroyContext(dpy, ctx);

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

	return 0;
}
Exemplo n.º 26
0
bool QGLContext::chooseContext( const QGLContext* shareContext )
{
    Display* disp = d->paintDevice->x11Display();
    vi = chooseVisual();
    if ( !vi )
	return FALSE;

    if ( deviceIsPixmap() &&
	 (((XVisualInfo*)vi)->depth != d->paintDevice->x11Depth() ||
	  ((XVisualInfo*)vi)->screen != d->paintDevice->x11Screen()) )
    {
	XFree( vi );
	XVisualInfo appVisInfo;
	memset( &appVisInfo, 0, sizeof(XVisualInfo) );
	appVisInfo.visualid = XVisualIDFromVisual( (Visual*)d->paintDevice->x11Visual() );
	appVisInfo.screen = d->paintDevice->x11Screen();
	int nvis;
	vi = XGetVisualInfo( disp, VisualIDMask | VisualScreenMask, &appVisInfo, &nvis );
	if ( !vi )
	    return FALSE;

	int useGL;
	glXGetConfig( disp, (XVisualInfo*)vi, GLX_USE_GL, &useGL );
	if ( !useGL )
	    return FALSE;	//# Chickening out already...
    }
    int res;
    glXGetConfig( disp, (XVisualInfo*)vi, GLX_LEVEL, &res );
    glFormat.setPlane( res );
    glXGetConfig( disp, (XVisualInfo*)vi, GLX_DOUBLEBUFFER, &res );
    glFormat.setDoubleBuffer( res );
    glXGetConfig( disp, (XVisualInfo*)vi, GLX_DEPTH_SIZE, &res );
    glFormat.setDepth( res );
    glXGetConfig( disp, (XVisualInfo*)vi, GLX_RGBA, &res );
    glFormat.setRgba( res );
    glXGetConfig( disp, (XVisualInfo*)vi, GLX_ALPHA_SIZE, &res );
    glFormat.setAlpha( res );
    glXGetConfig( disp, (XVisualInfo*)vi, GLX_ACCUM_RED_SIZE, &res );
    glFormat.setAccum( res );
    glXGetConfig( disp, (XVisualInfo*)vi, GLX_STENCIL_SIZE, &res );
    glFormat.setStencil( res );
    glXGetConfig( disp, (XVisualInfo*)vi, GLX_STEREO, &res );
    glFormat.setStereo( res );

    Bool direct = format().directRendering() ? True : False;

    if ( shareContext &&
	 ( !shareContext->isValid() || !shareContext->cx ) ) {
#if defined(QT_CHECK_NULL)
	    qWarning("QGLContext::chooseContext(): Cannot share with invalid context");
#endif
	    shareContext = 0;
    }

    // 1. Sharing between rgba and color-index will give wrong colors.
    // 2. Contexts cannot be shared btw. direct/non-direct renderers.
    // 3. Pixmaps cannot share contexts that are set up for direct rendering.
    if ( shareContext && (format().rgba() != shareContext->format().rgba() ||
			  (deviceIsPixmap() &&
			   glXIsDirect( disp, (GLXContext)shareContext->cx ))))
	shareContext = 0;

    cx = 0;
    if ( shareContext ) {
	cx = glXCreateContext( disp, (XVisualInfo *)vi,
			       (GLXContext)shareContext->cx, direct );
	if ( cx )
	    d->sharing = TRUE;
    }
    if ( !cx )
	cx = glXCreateContext( disp, (XVisualInfo *)vi, None, direct );
    if ( !cx )
	return FALSE;
    glFormat.setDirectRendering( glXIsDirect( disp, (GLXContext)cx ) );
    if ( deviceIsPixmap() ) {
#if defined(GLX_MESA_pixmap_colormap) && defined(QGL_USE_MESA_EXT)
	gpm = glXCreateGLXPixmapMESA( disp, (XVisualInfo *)vi,
				      d->paintDevice->handle(),
				      choose_cmap( disp, (XVisualInfo *)vi ) );
#else
	gpm = (Q_UINT32)glXCreateGLXPixmap( disp, (XVisualInfo *)vi,
					    d->paintDevice->handle() );
#endif
	if ( !gpm )
	    return FALSE;
    }
    return TRUE;
}
const GrGLInterface* SkNativeGLContext::createGLContext() {
    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
    };

#ifdef GLX_1_3
    //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);
#else
    int numVisuals;
    XVisualInfo visTemplate, *visReturn;

    visReturn = XGetVisualInfo(fDisplay, VisualNoMask, &visTemplate, &numVisuals);
    if (NULL == visReturn)
    {
        SkDebugf("Failed to get visual information.\n");
        this->destroyGLContext();
        return NULL;
    }

    int best = -1, best_num_samp = -1;

    for (int i = 0; i < numVisuals; ++i)
    {
        int samp_buf, samples;

        glXGetConfig(fDisplay, &visReturn[i], GLX_SAMPLE_BUFFERS, &samp_buf);
        glXGetConfig(fDisplay, &visReturn[i], GLX_SAMPLES, &samples);

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

    XVisualInfo temp = visReturn[best];
    XVisualInfo *vi = &temp;

    XFree(visReturn);
#endif

    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);

#ifdef GLX_1_3
    // Done with the visual info data
    XFree(vi);
#endif

    // 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)))
    {
        //SkDebugf("GLX_ARB_create_context not found."
        //       " Using old-style GLX context.\n");
#ifdef GLX_1_3
        fContext = glXCreateNewContext(fDisplay, bestFbc, GLX_RGBA_TYPE, 0, True);
#else
        fContext = glXCreateContext(fDisplay, vi, 0, True);
#endif

    }
#ifdef GLX_1_3
    else {
        //SkDebugf("Creating context.\n");

        PFNGLXCREATECONTEXTATTRIBSARBPROC glXCreateContextAttribsARB =
            (PFNGLXCREATECONTEXTATTRIBSARBPROC) glXGetProcAddressARB((GrGLubyte*)"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
        };
        fContext = glXCreateContextAttribsARB(
            fDisplay, bestFbc, 0, True, context_attribs
        );

        // Sync to ensure any errors generated are processed.
        XSync(fDisplay, False);
        if (!ctxErrorOccurred && fContext) {
           //SkDebugf( "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;

            //SkDebugf("Failed to create GL 3.0 context."
            //       " Using old-style GLX context.\n");
            fContext = glXCreateContextAttribsARB(
                fDisplay, bestFbc, 0, True, context_attribs
            );
        }
    }
#endif

    // 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;
}
//create gl window
bool openglx_1o5_renderer::makeWindow( char* title, int width, int height, int bits, bool fullscreenflag )
{
    XVisualInfo *vi;
    Colormap cmap;
    Window winDummy;
    unsigned int borderDummy;

    this->gl.fs = fullscreenflag;

    //open display
    this->gl.dpy = XOpenDisplay( 0 );
    this->gl.screen = DefaultScreen( this->gl.dpy );

    //set visual format
    static int attrListSgl[] =
    {
        GLX_RGBA,
        GLX_RED_SIZE, 4,
        GLX_GREEN_SIZE, 4,
        GLX_BLUE_SIZE, 4,
        GLX_DEPTH_SIZE, 16,
        None
    };
    static int attrListDbl[] =
    {
        GLX_RGBA, GLX_DOUBLEBUFFER,
        GLX_RED_SIZE, 4,
        GLX_GREEN_SIZE, 4,
        GLX_BLUE_SIZE, 4,
        GLX_DEPTH_SIZE, 16,
        None
    };
    vi = glXChooseVisual( this->gl.dpy, this->gl.screen, attrListDbl );
    this->gl.doubleBuffered = vi != 0;
    if( !vi )
        vi = glXChooseVisual(this->gl.dpy, this->gl.screen, attrListSgl );
    if( !vi )
    {
        XCloseDisplay( this->gl.dpy );
        this->gl.dpy = 0;
        return 0;
    }

    //create context
    this->gl.ctx = glXCreateContext( this->gl.dpy, vi, 0, GL_TRUE );
    if( !this->gl.ctx )
    {
        XCloseDisplay( this->gl.dpy );
        this->gl.dpy = 0;
        return 0;
    }

    //colormap
    cmap = XCreateColormap( this->gl.dpy, RootWindow( this->gl.dpy, vi->screen ), vi->visual, AllocNone );
    this->gl.attr.colormap = cmap;
    this->gl.attr.border_pixel = 0;

    //create window
    this->gl.attr.event_mask = ExposureMask | KeyPressMask | ButtonPressMask | StructureNotifyMask;
    this->gl.win = XCreateWindow( this->gl.dpy, RootWindow( this->gl.dpy, vi->screen ), 0, 0, width, height, 0, vi->depth, InputOutput, vi->visual, CWBorderPixel | CWColormap | CWEventMask, &this->gl.attr );
    if( !this->gl.win )
    {
        glXDestroyContext( this->gl.dpy, this->gl.ctx );
        XCloseDisplay( this->gl.dpy );
        this->gl.dpy = 0;
        this->gl.ctx = 0;
        return 0;
    }

    //setup close button event
    this->gl.wm_delete_window = XInternAtom( this->gl.dpy, "WM_DELETE_WINDOW", True );
    XSetWMProtocols( this->gl.dpy, this->gl.win, &this->gl.wm_delete_window, 1 );

    //set title
    XSetStandardProperties( this->gl.dpy, this->gl.win, title, title, None, NULL, 0, NULL );
    XMapRaised( this->gl.dpy, this->gl.win );

    //male context active
    glXMakeCurrent( this->gl.dpy, this->gl.win, this->gl.ctx );

    //get window position
    XGetGeometry( this->gl.dpy, this->gl.win, &winDummy, &this->gl.x, &this->gl.y, &this->gl.width, &this->gl.height, &borderDummy, &this->gl.depth );

    glDisable(GL_CULL_FACE);

    glShadeModel( GL_SMOOTH );
    glClearColor( 0.0f, 0.0f, 0.0f, 0.5f );
    glClearDepth( 1.0f );
    glEnable( GL_DEPTH_TEST );
    glDepthFunc( GL_LEQUAL );
    glHint( GL_PERSPECTIVE_CORRECTION_HINT, GL_NICEST );
    glMatrixMode( GL_PROJECTION );
    glLoadIdentity();
    glMatrixMode( GL_MODELVIEW );
    glLoadIdentity();
    glEnable( GL_TEXTURE_2D );

    return 1;
}
Exemplo n.º 29
0
int main(int argc, char *argv[])
{
char*			command_name;
char*			display_name;
Display*		display;
Window			window;
int			scrnum;
Window			root;
int			x, y;
GLXContext		context;
XVisualInfo*		vinfo;
XSetWindowAttributes	winattrs;
XFontStruct*		font;
unsigned long		winmask;
static const char* getopt_string = "sf::ima::r:vh";
static const struct option longopts[] =
{
	{ "full", no_argument, NULL, 's' },
	{ "fps", optional_argument, NULL, 'f' },
	{ "info", no_argument, NULL, 'i' },
	{ "fsaa", no_argument, NULL, 'm' },
	{ "aniso", optional_argument, NULL, 'a' },
	{ "runlength", required_argument, NULL, 'r' },
	{ "version", no_argument, NULL, 'v' },
	{ "help", no_argument, NULL, 'h' },
	{ 0, 0, 0, 0 }
};
static const char* x11font = "-*-courier-bold-r-normal--14-*-*-*-*-*-*-*";
static int		attributes[] = {
					GLX_RGBA,
					GLX_DOUBLEBUFFER,
					GLX_RED_SIZE, 8,
					GLX_GREEN_SIZE, 8,
					GLX_BLUE_SIZE, 8,
					GLX_ALPHA_SIZE, 8,
					GLX_DEPTH_SIZE, 24,
					0
					};

/* Comman line arguments processing */

command_name = basename(argv[0]);

while (1)
{
	int c = getopt_long(argc, argv, getopt_string, longopts, NULL);

	if (c == -1)
		break;

	switch (c)
	{
	case 's':
		full_screen = GL_TRUE;
		break;
	case 'f':
		if( optarg == NULL )
		{
			print_fps = GL_TRUE;
		}
		else
			if( ( Timed = (GLfloat)atof(optarg) ) > 0.0f )
				print_fps = GL_TRUE;
			else
			{
				printf("<!> Time slice for fps computation must be greater than 0\n");
				return 0;
			}

		break;
	case 'i':
		print_info = GL_TRUE;
		break;
	case 'm':
		enable_fsaa = GL_TRUE;
		break;
	case 'a':
		if( optarg == NULL )
		{
			enable_anisotropic = GL_TRUE;
			AnisoLevel = 16.0f;
		}
		else
			if( ( AnisoLevel = (GLfloat)atof(optarg) ) > 0.0f )
				if( 	( AnisoLevel ==  2.0f ) ||
					( AnisoLevel ==  4.0f ) ||
					( AnisoLevel ==  8.0f ) ||
					( AnisoLevel == 16.0f ) )
						enable_anisotropic = GL_TRUE;
				else
				{
					printf("<!> Incorrect anisotropic filtering level specified, must be 2, 4, 8 or 16\n");
					return 0;
				}
			else
			{
				printf("<!> Incorrect anisotropic filtering level specified, must be 2, 4, 8 or 16\n");
				return 0;
			}

		break;
	case 'r':
		if( ( max_timer = (GLfloat)atof(optarg) ) > 0.0f )
			use_timer = GL_TRUE;
		else
		{
			printf("<!> Timer must be greater than 0\n");
			return 0;
		}

		break;
	case 'v':
		printf("Version: " VERSION "\n");
		return 0;
	case 'h':
		printf("Usage: %s [OPTIONS]...\n"
				"%s is an OpenGL rendering demo.\n"
				"   -s, --full         : display full screen\n"
				"   -f[t], --fps[=t]   : display frames per second every t seconds (default 5)\n"
				"   -i, --info         : display X11/OpenGL and program info\n"
				"   -m, --fsaa         : enable anti-aliasing\n"
				"   -a[l], --aniso[=l] : enable xl anisotropic filtering (default 16)\n"
				"   -rL, --runlength=L : run the demo for L secs, then exit\n"
				"   -v, --version      : display version and exit\n",
				"   -h, --help         : display this information\n",
				command_name, command_name
		);
		return 0;
	case '?':
	case ':':
		exit(-1);
	}
}

/* Set signal handlers */

act.sa_handler = signal_handler;
sigemptyset(&act.sa_mask);
act.sa_flags = 0;

if( (sigaction(SIGINT, &act, &oact) < 0)
	|| (sigaction(SIGTERM, &act, &oact) < 0)
	|| (sigaction(SIGHUP, &act, &oact) < 0) )
{
	printf("<!> Setting signal handler failed\n");
	return 1;
}

/* Open the connection to the X server */

display_name = getenv("DISPLAY");
display = XOpenDisplay(display_name);

if (!display)
{
	printf("<!> Couldn't open display %s\n", display_name);
	return 1;
}
else if (print_info)
	printf("<-> Name of display: %s\n", DisplayString(display));

/* Find the proper visual */

scrnum = DefaultScreen( display );
root = RootWindow( display, scrnum );

x = 0; y = 0;

if (full_screen)
{
	width = DisplayWidth( display, scrnum );
	height = DisplayHeight( display, scrnum );
}
else
{
	width = DisplayWidth( display, scrnum )*3/4;
	height = DisplayHeight( display, scrnum )*3/4;
}

vinfo = glXChooseVisual(display, scrnum, attributes);

if (!vinfo)
{
	printf("<!> Couldn't get an RGB, Double-buffered visual\n");
	return 1;
}
else if (print_info)
	printf("<-> Visual ID: %x\n", vinfo->visualid);

/* Create the window */

winattrs.event_mask =	ExposureMask | StructureNotifyMask |
			ButtonPressMask | ButtonReleaseMask |
			PointerMotionMask | KeyPressMask;

winattrs.background_pixel = BlackPixel(display, scrnum);
winattrs.border_pixel = BlackPixel(display, scrnum);
winattrs.bit_gravity = StaticGravity;
winattrs.colormap = XCreateColormap( display, root, vinfo->visual, AllocNone);
winattrs.override_redirect = full_screen;

winmask = CWBitGravity | CWBackPixel | CWBorderPixel | CWColormap | CWEventMask | CWOverrideRedirect;

window = XCreateWindow( display, root,
			x, y, width, height, 0, vinfo->depth, InputOutput,
			vinfo->visual, winmask, &winattrs );

XChangeProperty(display, window, XA_WM_NAME, XA_STRING, 8, 0,
		command_name, strlen(argv[0]));
XChangeProperty(display, window, XA_WM_ICON_NAME, XA_STRING, 8, 0,
		command_name, strlen(argv[0]));

/* Create the OpenGL context */

context = glXCreateContext(display, vinfo, 0, True);

if (!context)
{
	printf("<!> glXCreateContext failed\n");
	return 1;
}

XFree(vinfo);

XMapWindow( display, window );
glXMakeCurrent( display, window, context );

/* Print info */

if (print_info)
{
	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));
}

/* Setup fonts */
if( ( font = XLoadQueryFont(display, x11font) ) == NULL )
{
	//Try fallback first
	if( ( font = XLoadQueryFont(display, "fixed") ) == NULL )
	{
		printf("<!> Can't load font \"%s\"\n", x11font);
		return -1;
	}
	else if (print_info)
		printf("<-> Loaded font \"fixed\"\n");
}
else if (print_info)
	printf("<-> Loaded font \"%s\"\n", x11font);

fps_font = glGenLists(96);
glXUseXFont(font->fid, ' ', 96, fps_font);


/* Setup Rendering Context */

if (setup())
{
	printf("<!> Setup failed, exiting ...\n");
	return 1;
}

/* Event loop */

event_loop( display, window );

/* Print average fps */
printf("Average FPS: %.1f\n", fps_mean);

/* Clean up */

// Delete shader identifiers
glDeleteProgramsARB(NUM_SHADERS, ids);

// Delete shader objects
glDeleteObjectARB(progObj);

//Texture objects
glDeleteTextures( NUM_TEXTURES, texture_id );
if (texture_id)
	free(texture_id);

//Lists
glDeleteLists(fps_font, 96);
glDeleteLists(FList, 1);

//MD2 models
int model_id;

for (model_id = 0; model_id < NUM_MODELS; ++model_id)
	if (md2_model[model_id])
	{
		if (md2_model[model_id]->normal)
		{
			free(md2_model[model_id]->normal);
			md2_model[model_id]->normal = NULL;
		}
		if (md2_model[model_id]->skin)
		{
			free(md2_model[model_id]->skin);
			md2_model[model_id]->skin = NULL;
		}
		free(md2_model[model_id]);
		md2_model[model_id] = NULL;
	}
	
//Floor
if (floor_texture)
{
	free(floor_texture);
	floor_texture = NULL;
}

//Destroy FB objects
glDeleteTextures(1, &shadow_tx);
glDeleteFramebuffersEXT(1, &FBO);

glXDestroyContext( display, context );
XDestroyWindow( display, window );
XCloseDisplay( display );

if( print_info )
	printf("Program exit successfully\n");

return 0;
}
Exemplo n.º 30
0
bool GLContext::create(const Window* window_, const Version& version_,
                              const GLContext* glcxt_)//not copy - share!
{
    glcontext_t res_glcxt = 0;


    glcontext_t origcxt = 0;
    XWindow origDrawWindow = 0;
    //winid_t origReadWindow = 0;
    XDisplay* origDisplay = nullptr;


    glcontext_t tmpglcxt = 0;
    glcontext_t shared = 0;
    
    XVisualInfo visualinfo = {0};
    GLXFBConfig fbconfig = nullptr;
    XWindowAttributes winattribs = {0};


    XWindow window = window_->id();
    
    
    if(glcxt_ != NULL) shared = glcxt_->id();
    
    XGetWindowAttributes(Display::display(), window, &winattribs);
    
    visualinfo.visual = winattribs.visual;
    visualinfo.visualid = XVisualIDFromVisual(winattribs.visual);
    visualinfo.screen = XScreenNumberOfScreen(winattribs.screen);
    visualinfo.depth = winattribs.depth;


    //save current context state
    origcxt = glXGetCurrentContext();
    origDrawWindow = glXGetCurrentDrawable();
    //origReadWindow = glXGetCurrentReadDrawable();
    origDisplay = glXGetCurrentDisplay();
    
    
    //if need CreateContextAttribs
    if(version_.major > 2){
        //if current context == NULL
        if(origcxt == 0){
            //create context
            tmpglcxt = glXCreateContext(Display::display(), &visualinfo, 0, True);
            if(tmpglcxt == 0){
                return false;
            }
            if(!glXMakeCurrent(Display::display(), window, tmpglcxt)){
                glXDestroyContext(Display::display(), tmpglcxt);
                return false;
            }
        }


        if(glXCreateContextAttribsARB == nullptr){
            //get proc address
            if(nullptr == (glXCreateContextAttribsARB =
                reinterpret_cast<PFNGLXCREATECONTEXTATTRIBSARBPROC>(
                    glXGetProcAddress(
                        reinterpret_cast<const GLubyte*>("glXCreateContextAttribsARB")
            )))){
                //OpenGL 3.0 is not supported
                glXMakeCurrent(origDisplay, origDrawWindow, origcxt);
                return false;
            }
        }
        
        if(glXGetFBConfigFromVisualSGIX == nullptr){
            if(NULL == (glXGetFBConfigFromVisualSGIX =
                reinterpret_cast<PFNGLXGETFBCONFIGFROMVISUALSGIXPROC>(
                    glXGetProcAddress(
                        reinterpret_cast<const GLubyte*>("glXGetFBConfigFromVisualSGIX")
            )))){
                glXMakeCurrent(Display::display(), origDrawWindow, origcxt);
                return false;
            }
        }
        
        fbconfig = glXGetFBConfigFromVisualSGIX(Display::display(), &visualinfo);
        
        if(fbconfig == nullptr){
            glXMakeCurrent(Display::display(), origDrawWindow, origcxt);
            return false;
        }


        int context_attribs[]={
            GL_CONTEXT_MAJOR_VERSION, version_.major,
            GL_CONTEXT_MINOR_VERSION, version_.minor,
            //GLX_CONTEXT_FLAGS_ARB        , GLX_CONTEXT_FORWARD_COMPATIBLE_BIT_ARB,
            None
        };


        //if tmpglcxt created
        if(tmpglcxt != 0){
            //destroy tmp context
            glXMakeCurrent(Display::display(), 0, 0);
            glXDestroyContext(Display::display(), tmpglcxt);
        }


        //create new, gl3 context
        res_glcxt = glXCreateContextAttribsARB(Display::display(),
                                fbconfig, shared, True, context_attribs);
        if(!res_glcxt){
            glXMakeCurrent(Display::display(), origDrawWindow, origcxt);
            return false;
        }
        //
    }else{
        //create context
        res_glcxt = glXCreateContext(Display::display(), &visualinfo, shared, True);
        if(res_glcxt == nullptr){
            return false;
        }
    }


    glXMakeCurrent(Display::display(), origDrawWindow, origcxt);

    _shared_id->data = res_glcxt;
    _contexts[_shared_id->data] = this;
    
    return true;
}