2 MiniGLUT - minimal GLUT subset without dependencies
3 Copyright (C) 2020 John Tsiombikas <nuclear@member.fsf.org>
5 This program is free software: you can redistribute it and/or modify
6 it under the terms of the GNU General Public License as published by
7 the Free Software Foundation, either version 3 of the License, or
8 (at your option) any later version.
10 This program is distributed in the hope that it will be useful,
11 but WITHOUT ANY WARRANTY; without even the implied warranty of
12 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
13 GNU General Public License for more details.
15 You should have received a copy of the GNU General Public License
16 along with this program. If not, see <https://www.gnu.org/licenses/>.
18 #ifdef MINIGLUT_USE_LIBC
24 #define PI 3.1415926536f
29 #include <X11/cursorfont.h>
33 #ifndef GLX_SAMPLE_BUFFERS_ARB
34 #define GLX_SAMPLE_BUFFERS_ARB 100000
35 #define GLX_SAMPLES_ARB 100001
37 #ifndef GLX_FRAMEBUFFER_SRGB_CAPABLE_ARB
38 #define GLX_FRAMEBUFFER_SRGB_CAPABLE_ARB 0x20b2
42 static Window win, root;
44 static GLXContext ctx;
45 static Atom xa_wm_proto, xa_wm_del_win;
46 static unsigned int evmask;
58 #error unsupported platform
65 int rsize, gsize, bsize, asize;
73 static void create_window(const char *title);
74 static void get_window_pos(Window win, int *x, int *y);
75 static void get_window_size(Window win, int *w, int *h);
76 static void get_screen_size(Window win, int *scrw, int *scrh);
78 static long get_msec(void);
79 static void panic(const char *msg);
80 static void sys_exit(int status);
81 static int sys_write(int fd, const void *buf, int count);
84 static int init_x, init_y, init_width = 256, init_height = 256;
85 static unsigned int init_mode;
87 static struct ctx_info ctx_info;
88 static int cur_cursor = GLUT_CURSOR_INHERIT;
90 static glut_cb cb_display;
91 static glut_cb cb_idle;
92 static glut_cb_reshape cb_reshape;
93 static glut_cb_state cb_vis, cb_entry;
94 static glut_cb_keyb cb_keydown, cb_keyup;
95 static glut_cb_special cb_skeydown, cb_skeyup;
96 static glut_cb_mouse cb_mouse;
97 static glut_cb_motion cb_motion, cb_passive;
98 static glut_cb_sbmotion cb_sball_motion, cb_sball_rotate;
99 static glut_cb_sbbutton cb_sball_button;
101 static int win_width, win_height;
104 static int upd_pending, reshape_pending;
108 void glutInit(int *argc, char **argv)
111 if(!(dpy = XOpenDisplay(0))) {
112 panic("Failed to connect to the X server\n");
114 scr = DefaultScreen(dpy);
115 root = RootWindow(dpy, scr);
116 xa_wm_proto = XInternAtom(dpy, "WM_PROTOCOLS", False);
117 xa_wm_del_win = XInternAtom(dpy, "WM_DELETE_WINDOW", False);
119 evmask = ExposureMask | StructureNotifyMask;
123 void glutInitWindowPosition(int x, int y)
129 void glutInitWindowSize(int xsz, int ysz)
135 void glutInitDisplayMode(unsigned int mode)
140 void glutCreateWindow(const char *title)
142 create_window(title);
150 void glutMainLoop(void)
157 void glutPostRedisplay(void)
162 #define UPD_EVMASK(x) \
169 if(win) XSelectInput(dpy, win, evmask); \
173 void glutIdleFunc(glut_cb func)
178 void glutDisplayFunc(glut_cb func)
183 void glutReshapeFunc(glut_cb_reshape func)
188 void glutVisibilityFunc(glut_cb_state func)
192 UPD_EVMASK(VisibilityChangeMask);
196 void glutEntryFunc(glut_cb_state func)
200 UPD_EVMASK(EnterWindowMask | LeaveWindowMask);
204 void glutKeyboardFunc(glut_cb_keyb func)
208 UPD_EVMASK(KeyPressMask);
212 void glutKeyboardUpFunc(glut_cb_keyb func)
216 UPD_EVMASK(KeyReleaseMask);
220 void glutSpecialFunc(glut_cb_special func)
224 UPD_EVMASK(KeyPressMask);
228 void glutSpecialUpFunc(glut_cb_special func)
232 UPD_EVMASK(KeyReleaseMask);
236 void glutMouseFunc(glut_cb_mouse func)
240 UPD_EVMASK(ButtonPressMask | ButtonReleaseMask);
244 void glutMotionFunc(glut_cb_motion func)
248 UPD_EVMASK(ButtonMotionMask);
252 void glutPassiveMotionFunc(glut_cb_motion func)
256 UPD_EVMASK(PointerMotionMask);
260 void glutSpaceballMotionFunc(glut_cb_sbmotion func)
262 cb_sball_motion = func;
265 void glutSpaceballRotateFunc(glut_cb_sbmotion func)
267 cb_sball_rotate = func;
270 void glutSpaceballBittonFunc(glut_cb_sbbutton func)
272 cb_sball_button = func;
275 int glutGet(unsigned int s)
280 get_window_pos(win, &x, &y);
283 get_window_pos(win, &x, &y);
285 case GLUT_WINDOW_WIDTH:
286 get_window_size(win, &x, &y);
288 case GLUT_WINDOW_HEIGHT:
289 get_window_size(win, &x, &y);
291 case GLUT_WINDOW_BUFFER_SIZE:
292 return ctx_info.rsize + ctx_info.gsize + ctx_info.bsize + ctx_info.asize;
293 case GLUT_WINDOW_STENCIL_SIZE:
294 return ctx_info.ssize;
295 case GLUT_WINDOW_DEPTH_SIZE:
296 return ctx_info.zsize;
297 case GLUT_WINDOW_RED_SIZE:
298 return ctx_info.rsize;
299 case GLUT_WINDOW_GREEN_SIZE:
300 return ctx_info.gsize;
301 case GLUT_WINDOW_BLUE_SIZE:
302 return ctx_info.bsize;
303 case GLUT_WINDOW_ALPHA_SIZE:
304 return ctx_info.asize;
305 case GLUT_WINDOW_DOUBLEBUFFER:
306 return ctx_info.dblbuf;
307 case GLUT_WINDOW_RGBA:
309 case GLUT_WINDOW_NUM_SAMPLES:
310 return ctx_info.samples;
311 case GLUT_WINDOW_STEREO:
312 return ctx_info.stereo;
313 case GLUT_WINDOW_SRGB:
314 return ctx_info.srgb;
315 case GLUT_WINDOW_CURSOR:
317 case GLUT_SCREEN_WIDTH:
318 get_screen_size(win, &x, &y);
320 case GLUT_SCREEN_HEIGHT:
321 get_screen_size(win, &x, &y);
323 case GLUT_INIT_DISPLAY_MODE:
325 case GLUT_INIT_WINDOW_X:
327 case GLUT_INIT_WINDOW_Y:
329 case GLUT_INIT_WINDOW_WIDTH:
331 case GLUT_INIT_WINDOW_HEIGHT:
333 case GLUT_ELAPSED_TIME:
341 int glutGetModifiers(void)
346 static int is_space(int c)
348 return c == ' ' || c == '\t' || c == '\v' || c == '\n' || c == '\r';
351 static const char *skip_space(const char *s)
353 while(*s && is_space(*s)) s++;
357 int glutExtensionSupported(char *ext)
359 const char *str, *eptr;
361 if(!(str = (const char*)glGetString(GL_EXTENSIONS))) {
366 str = skip_space(str);
367 eptr = skip_space(ext);
368 while(*str && !is_space(*str) && *eptr && *str == *eptr) {
372 if((!*str || is_space(*str)) && !*eptr) {
375 while(*str && !is_space(*str)) str++;
382 void glutSolidSphere(float rad, int slices, int stacks)
385 float x, y, z, s, t, u, v, phi, theta, sintheta, costheta, sinphi, cosphi;
386 float du = 1.0f / (float)slices;
387 float dv = 1.0f / (float)stacks;
390 for(i=0; i<stacks; i++) {
392 for(j=0; j<slices; j++) {
396 s = gray & 1 ? u + du : u;
397 t = gray & 2 ? v + dv : v;
398 theta = s * PI * 2.0f;
400 sincosf(theta, &sintheta, &costheta);
401 sincosf(phi, &sinphi, &cosphi);
402 x = sintheta * sinphi;
403 y = costheta * sinphi;
409 glVertex3f(x * rad, y * rad, z * rad);
416 void glutWireSphere(float rad, int slices, int stacks)
418 glPushAttrib(GL_POLYGON_BIT);
419 glPolygonMode(GL_FRONT_AND_BACK, GL_LINE);
420 glutSolidSphere(rad, slices, stacks);
424 void glutSolidCube(float sz)
426 int i, j, idx, gray, flip, rotx;
427 float vpos[3], norm[3];
428 float rad = sz * 0.5f;
434 idx = (~i & 2) - rotx;
435 norm[0] = norm[1] = norm[2] = 0.0f;
436 norm[idx] = flip ^ ((i >> 1) & 1) ? -1 : 1;
438 vpos[idx] = norm[idx] * rad;
441 vpos[i & 2] = (gray ^ flip) & 1 ? rad : -rad;
442 vpos[rotx + 1] = (gray ^ (rotx << 1)) & 2 ? rad : -rad;
443 glTexCoord2f(gray & 1, gray >> 1);
450 void glutWireCube(float sz)
452 glPushAttrib(GL_POLYGON_BIT);
453 glPolygonMode(GL_FRONT_AND_BACK, GL_LINE);
458 static void draw_cylinder(float rbot, float rtop, float height, int slices, int stacks)
461 float x, y, z, s, t, u, v, theta, phi, sintheta, costheta, sinphi, cosphi, rad;
462 float du = 1.0f / (float)slices;
463 float dv = 1.0f / (float)stacks;
465 phi = atan(fabs(rbot - rtop) / height);
466 sincosf(phi, &sinphi, &cosphi);
469 for(i=0; i<stacks; i++) {
471 for(j=0; j<slices; j++) {
475 s = gray & 2 ? u + du : u;
476 t = gray & 1 ? v + dv : v;
477 rad = rbot + (rtop - rbot) * t;
478 theta = s * PI * 2.0f;
479 sincosf(theta, &sintheta, &costheta);
481 x = sintheta * cosphi;
482 y = costheta * cosphi;
488 glVertex3f(sintheta * rad, costheta * rad, t * height);
495 void glutSolidCone(float base, float height, int slices, int stacks)
497 draw_cylinder(base, 0, height, slices, stacks);
500 void glutWireCone(float base, float height, int slices, int stacks)
502 glPushAttrib(GL_POLYGON_BIT);
503 glPolygonMode(GL_FRONT_AND_BACK, GL_LINE);
504 glutSolidCone(base, height, slices, stacks);
508 void glutSolidCylinder(float rad, float height, int slices, int stacks)
510 draw_cylinder(rad, rad, height, slices, stacks);
513 void glutWireCylinder(float rad, float height, int slices, int stacks)
515 glPushAttrib(GL_POLYGON_BIT);
516 glPolygonMode(GL_FRONT_AND_BACK, GL_LINE);
517 glutSolidCylinder(rad, height, slices, stacks);
521 void glutSolidTorus(float inner_rad, float outer_rad, int sides, int rings)
524 float x, y, z, s, t, u, v, phi, theta, sintheta, costheta, sinphi, cosphi;
525 float du = 1.0f / (float)rings;
526 float dv = 1.0f / (float)sides;
529 for(i=0; i<rings; i++) {
531 for(j=0; j<sides; j++) {
535 s = gray & 1 ? u + du : u;
536 t = gray & 2 ? v + dv : v;
537 theta = s * PI * 2.0f;
539 sincosf(theta, &sintheta, &costheta);
540 sincosf(phi, &sinphi, &cosphi);
541 x = sintheta * sinphi;
542 y = costheta * sinphi;
549 x = x * inner_rad + sintheta * outer_rad;
550 y = y * inner_rad + costheta * outer_rad;
559 void glutWireTorus(float inner_rad, float outer_rad, int sides, int rings)
561 glPushAttrib(GL_POLYGON_BIT);
562 glPolygonMode(GL_FRONT_AND_BACK, GL_LINE);
563 glutSolidTorus(inner_rad, outer_rad, sides, rings);
567 void glutSolidTeapot(float size)
571 void glutWireTeapot(float size)
577 static void handle_event(XEvent *ev);
579 void glutMainLoopEvent(void)
584 panic("display callback not set");
588 if(!upd_pending && !cb_idle) {
589 XNextEvent(dpy, &ev);
593 while(XPending(dpy)) {
594 XNextEvent(dpy, &ev);
603 if(upd_pending && mapped) {
610 static KeySym translate_keysym(KeySym sym)
631 static void handle_event(XEvent *ev)
642 case ConfigureNotify:
643 if(cb_reshape && (ev->xconfigure.width != win_width || ev->xconfigure.height != win_height)) {
644 win_width = ev->xconfigure.width;
645 win_height = ev->xconfigure.height;
646 cb_reshape(ev->xconfigure.width, ev->xconfigure.height);
651 if(ev->xclient.message_type == xa_wm_proto) {
652 if(ev->xclient.data.l[0] == xa_wm_del_win) {
664 modstate = ev->xkey.state & (ShiftMask | ControlMask | Mod1Mask);
665 if(!(sym = XLookupKeysym(&ev->xkey, 0))) {
668 sym = translate_keysym(sym);
670 if(ev->type == KeyPress) {
671 if(cb_keydown) cb_keydown((unsigned char)sym, ev->xkey.x, ev->xkey.y);
673 if(cb_keyup) cb_keyup((unsigned char)sym, ev->xkey.x, ev->xkey.y);
676 if(ev->type == KeyPress) {
677 if(cb_skeydown) cb_skeydown(sym, ev->xkey.x, ev->xkey.y);
679 if(cb_skeyup) cb_skeyup(sym, ev->xkey.x, ev->xkey.y);
686 modstate = ev->xbutton.state & (ShiftMask | ControlMask | Mod1Mask);
688 int bn = ev->xbutton.button - Button1;
689 cb_mouse(bn, ev->type == ButtonPress ? GLUT_DOWN : GLUT_UP,
690 ev->xbutton.x, ev->xbutton.y);
695 if(ev->xmotion.state & (Button1Mask | Button2Mask | Button3Mask | Button4Mask | Button5Mask)) {
696 if(cb_motion) cb_motion(ev->xmotion.x, ev->xmotion.y);
698 if(cb_passive) cb_passive(ev->xmotion.x, ev->xmotion.y);
702 case VisibilityNotify:
704 cb_vis(ev->xvisibility.state == VisibilityFullyObscured ? GLUT_NOT_VISIBLE : GLUT_VISIBLE);
708 if(cb_entry) cb_entry(GLUT_ENTERED);
711 if(cb_entry) cb_entry(GLUT_LEFT);
716 void glutSwapBuffers(void)
718 glXSwapBuffers(dpy, win);
721 void glutPositionWindow(int x, int y)
723 XMoveWindow(dpy, win, x, y);
726 void glutReshapeWindow(int xsz, int ysz)
728 XResizeWindow(dpy, win, xsz, ysz);
731 void glutFullScreen(void)
736 void glutSetWindowTitle(const char *title)
739 if(!XStringListToTextProperty((char**)&title, 1, &tprop)) {
742 XSetWMName(dpy, win, &tprop);
746 void glutSetIconTitle(const char *title)
749 if(!XStringListToTextProperty((char**)&title, 1, &tprop)) {
752 XSetWMIconName(dpy, win, &tprop);
756 void glutSetCursor(int cidx)
761 case GLUT_CURSOR_LEFT_ARROW:
762 cur = XCreateFontCursor(dpy, XC_left_ptr);
764 case GLUT_CURSOR_INHERIT:
766 case GLUT_CURSOR_NONE:
772 XDefineCursor(dpy, win, cur);
776 static XVisualInfo *choose_visual(unsigned int mode)
786 int *aptr = attr + 8;
789 if(mode & GLUT_ALPHA) {
790 *aptr++ = GLX_ALPHA_SIZE;
793 if(mode & GLUT_DEPTH) {
794 *aptr++ = GLX_DEPTH_SIZE;
797 if(mode & GLUT_STENCIL) {
798 *aptr++ = GLX_STENCIL_SIZE;
801 if(mode & GLUT_ACCUM) {
802 *aptr++ = GLX_ACCUM_RED_SIZE; *aptr++ = 1;
803 *aptr++ = GLX_ACCUM_GREEN_SIZE; *aptr++ = 1;
804 *aptr++ = GLX_ACCUM_BLUE_SIZE; *aptr++ = 1;
806 if(mode & GLUT_STEREO) {
807 *aptr++ = GLX_STEREO;
809 if(mode & GLUT_SRGB) {
810 *aptr++ = GLX_FRAMEBUFFER_SRGB_CAPABLE_ARB;
812 if(mode & GLUT_MULTISAMPLE) {
813 *aptr++ = GLX_SAMPLE_BUFFERS_ARB;
815 *aptr++ = GLX_SAMPLES_ARB;
822 return glXChooseVisual(dpy, scr, attr);
824 while(!(vi = glXChooseVisual(dpy, scr, attr)) && *samples) {
833 static void create_window(const char *title)
835 XSetWindowAttributes xattr;
837 unsigned int xattr_mask;
838 unsigned int mode = init_mode;
840 if(!(vi = choose_visual(mode))) {
842 if(!(vi = choose_visual(mode))) {
843 panic("Failed to find compatible visual\n");
847 if(!(ctx = glXCreateContext(dpy, vi, 0, True))) {
849 panic("Failed to create OpenGL context\n");
852 glXGetConfig(dpy, vi, GLX_RED_SIZE, &ctx_info.rsize);
853 glXGetConfig(dpy, vi, GLX_GREEN_SIZE, &ctx_info.gsize);
854 glXGetConfig(dpy, vi, GLX_BLUE_SIZE, &ctx_info.bsize);
855 glXGetConfig(dpy, vi, GLX_ALPHA_SIZE, &ctx_info.asize);
856 glXGetConfig(dpy, vi, GLX_DEPTH_SIZE, &ctx_info.zsize);
857 glXGetConfig(dpy, vi, GLX_STENCIL_SIZE, &ctx_info.ssize);
858 glXGetConfig(dpy, vi, GLX_DOUBLEBUFFER, &ctx_info.dblbuf);
859 glXGetConfig(dpy, vi, GLX_STEREO, &ctx_info.stereo);
860 glXGetConfig(dpy, vi, GLX_SAMPLES_ARB, &ctx_info.samples);
861 glXGetConfig(dpy, vi, GLX_FRAMEBUFFER_SRGB_CAPABLE_ARB, &ctx_info.srgb);
863 xattr.background_pixel = BlackPixel(dpy, scr);
864 xattr.colormap = XCreateColormap(dpy, root, vi->visual, AllocNone);
865 xattr_mask = CWBackPixel | CWColormap;
866 if(!(win = XCreateWindow(dpy, root, init_x, init_y, init_width, init_height, 0,
867 vi->depth, InputOutput, vi->visual, xattr_mask, &xattr))) {
869 glXDestroyContext(dpy, ctx);
870 panic("Failed to create window\n");
874 XSelectInput(dpy, win, evmask);
876 glutSetWindowTitle(title);
877 glutSetIconTitle(title);
878 XSetWMProtocols(dpy, win, &xa_wm_del_win, 1);
879 XMapWindow(dpy, win);
881 glXMakeCurrent(dpy, win, ctx);
884 static void get_window_pos(Window win, int *x, int *y)
886 XWindowAttributes wattr;
887 XGetWindowAttributes(dpy, win, &wattr);
892 static void get_window_size(Window win, int *w, int *h)
894 XWindowAttributes wattr;
895 XGetWindowAttributes(dpy, win, &wattr);
900 static void get_screen_size(Window win, int *scrw, int *scrh)
902 XWindowAttributes wattr;
903 XGetWindowAttributes(dpy, root, &wattr);
905 *scrh = wattr.height;
909 #if defined(__unix__) || defined(__APPLE__)
910 #include <sys/time.h>
912 static long get_msec(void)
914 static struct timeval tv0;
917 gettimeofday(&tv, 0);
918 if(tv0.tv_sec == 0 && tv0.tv_usec == 0) {
922 return (tv.tv_sec - tv0.tv_sec) * 1000 + (tv.tv_usec - tv0.tv_usec) / 1000;
926 static long get_msec(void)
934 return timeGetTime() - t0;
938 static void panic(const char *msg)
940 const char *end = msg;
942 sys_write(2, msg, end - msg);
947 #ifdef MINIGLUT_USE_LIBC
948 static void sys_exit(int status)
953 static int sys_write(int fd, const void *buf, int count)
955 return write(fd, buf, count);
957 #else /* !MINIGLUT_USE_LIBC */
962 static void sys_exit(int status)
966 :: "a"(60), "D"(status)
969 static int sys_write(int fd, const void *buf, int count)
975 : "a"(1), "D"(fd), "S"(buf), "d"(count)
981 static void sys_exit(int status)
990 static int sys_write(int fd, const void *buf, int count)
996 :: "b"(fd), "c"(buf), "d"(count));
1001 #endif /* __linux__ */
1004 static int sys_exit(int status)
1006 ExitProcess(status);
1008 static int sys_write(int fd, const void *buf, int count)
1012 HANDLE out = GetStdHandle(fd == 1 ? STD_OUTPUT_HANDLE : STD_ERROR_HANDLE);
1013 if(!WriteFile(out, buf, count, &wrsz, 0)) {
1020 #endif /* !MINIGLUT_USE_LIBC */