1 /* nuklear - v1.32.0 - public domain */
2 #include <stdio.h>
3 #include <stdlib.h>
4 #include <stdint.h>
5 #include <stdarg.h>
6 #include <string.h>
7 #include <math.h>
8 #include <assert.h>
9 #include <time.h>
10 #include <limits.h>
11 
12 #define NK_INCLUDE_FIXED_TYPES
13 #define NK_INCLUDE_STANDARD_IO
14 #define NK_INCLUDE_STANDARD_VARARGS
15 #define NK_INCLUDE_DEFAULT_ALLOCATOR
16 #define NK_INCLUDE_VERTEX_BUFFER_OUTPUT
17 #define NK_INCLUDE_FONT_BAKING
18 #define NK_INCLUDE_DEFAULT_FONT
19 #define NK_IMPLEMENTATION
20 #define NK_XLIB_GL3_IMPLEMENTATION
21 #define NK_XLIB_LOAD_OPENGL_EXTENSIONS
22 #include "../../nuklear.h"
23 #include "nuklear_xlib_gl3.h"
24 
25 #define WINDOW_WIDTH 1200
26 #define WINDOW_HEIGHT 800
27 
28 #define MAX_VERTEX_BUFFER 512 * 1024
29 #define MAX_ELEMENT_BUFFER 128 * 1024
30 
31 /* ===============================================================
32  *
33  *                          EXAMPLE
34  *
35  * ===============================================================*/
36 /* This are some code examples to provide a small overview of what can be
37  * done with this library. To try out an example uncomment the defines */
38 /*#define INCLUDE_ALL */
39 /*#define INCLUDE_STYLE */
40 /*#define INCLUDE_CALCULATOR */
41 /*#define INCLUDE_CANVAS */
42 /*#define INCLUDE_OVERVIEW */
43 /*#define INCLUDE_NODE_EDITOR */
44 
45 #ifdef INCLUDE_ALL
46   #define INCLUDE_STYLE
47   #define INCLUDE_CALCULATOR
48   #define INCLUDE_CANVAS
49   #define INCLUDE_OVERVIEW
50   #define INCLUDE_NODE_EDITOR
51 #endif
52 
53 #ifdef INCLUDE_STYLE
54   #include "../style.c"
55 #endif
56 #ifdef INCLUDE_CALCULATOR
57   #include "../calculator.c"
58 #endif
59 #ifdef INCLUDE_CANVAS
60   #include "../canvas.c"
61 #endif
62 #ifdef INCLUDE_OVERVIEW
63   #include "../overview.c"
64 #endif
65 #ifdef INCLUDE_NODE_EDITOR
66   #include "../node_editor.c"
67 #endif
68 
69 /* ===============================================================
70  *
71  *                          DEMO
72  *
73  * ===============================================================*/
74 struct XWindow {
75     Display *dpy;
76     Window win;
77     XVisualInfo *vis;
78     Colormap cmap;
79     XSetWindowAttributes swa;
80     XWindowAttributes attr;
81     GLXFBConfig fbc;
82     Atom wm_delete_window;
83     int width, height;
84 };
85 static int gl_err = nk_false;
gl_error_handler(Display * dpy,XErrorEvent * ev)86 static int gl_error_handler(Display *dpy, XErrorEvent *ev)
87 {NK_UNUSED(dpy); NK_UNUSED(ev); gl_err = nk_true;return 0;}
88 
89 static void
die(const char * fmt,...)90 die(const char *fmt, ...)
91 {
92     va_list ap;
93     va_start(ap, fmt);
94     vfprintf(stderr, fmt, ap);
95     va_end(ap);
96     fputs("\n", stderr);
97     exit(EXIT_FAILURE);
98 }
99 
100 static int
has_extension(const char * string,const char * ext)101 has_extension(const char *string, const char *ext)
102 {
103     const char *start, *where, *term;
104     where = strchr(ext, ' ');
105     if (where || *ext == '\0')
106         return nk_false;
107 
108     for (start = string;;) {
109         where = strstr((const char*)start, ext);
110         if (!where) break;
111         term = where + strlen(ext);
112         if (where == start || *(where - 1) == ' ') {
113             if (*term == ' ' || *term == '\0')
114                 return nk_true;
115         }
116         start = term;
117     }
118     return nk_false;
119 }
120 
main(void)121 int main(void)
122 {
123     /* Platform */
124     int running = 1;
125     struct XWindow win;
126     GLXContext glContext;
127     struct nk_context *ctx;
128     struct nk_colorf bg;
129 
130     memset(&win, 0, sizeof(win));
131     win.dpy = XOpenDisplay(NULL);
132     if (!win.dpy) die("Failed to open X display\n");
133     {
134         /* check glx version */
135         int glx_major, glx_minor;
136         if (!glXQueryVersion(win.dpy, &glx_major, &glx_minor))
137             die("[X11]: Error: Failed to query OpenGL version\n");
138         if ((glx_major == 1 && glx_minor < 3) || (glx_major < 1))
139             die("[X11]: Error: Invalid GLX version!\n");
140     }
141     {
142         /* find and pick matching framebuffer visual */
143         int fb_count;
144         static GLint attr[] = {
145             GLX_X_RENDERABLE,   True,
146             GLX_DRAWABLE_TYPE,  GLX_WINDOW_BIT,
147             GLX_RENDER_TYPE,    GLX_RGBA_BIT,
148             GLX_X_VISUAL_TYPE,  GLX_TRUE_COLOR,
149             GLX_RED_SIZE,       8,
150             GLX_GREEN_SIZE,     8,
151             GLX_BLUE_SIZE,      8,
152             GLX_ALPHA_SIZE,     8,
153             GLX_DEPTH_SIZE,     24,
154             GLX_STENCIL_SIZE,   8,
155             GLX_DOUBLEBUFFER,   True,
156             None
157         };
158         GLXFBConfig *fbc;
159         fbc = glXChooseFBConfig(win.dpy, DefaultScreen(win.dpy), attr, &fb_count);
160         if (!fbc) die("[X11]: Error: failed to retrieve framebuffer configuration\n");
161         {
162             /* pick framebuffer with most samples per pixel */
163             int i;
164             int fb_best = -1, best_num_samples = -1;
165             for (i = 0; i < fb_count; ++i) {
166                 XVisualInfo *vi = glXGetVisualFromFBConfig(win.dpy, fbc[i]);
167                 if (vi) {
168                     int sample_buffer, samples;
169                     glXGetFBConfigAttrib(win.dpy, fbc[i], GLX_SAMPLE_BUFFERS, &sample_buffer);
170                     glXGetFBConfigAttrib(win.dpy, fbc[i], GLX_SAMPLES, &samples);
171                     if ((fb_best < 0) || (sample_buffer && samples > best_num_samples))
172                         fb_best = i, best_num_samples = samples;
173                 }
174             }
175             win.fbc = fbc[fb_best];
176             XFree(fbc);
177             win.vis = glXGetVisualFromFBConfig(win.dpy, win.fbc);
178         }
179     }
180     {
181         /* create window */
182         win.cmap = XCreateColormap(win.dpy, RootWindow(win.dpy, win.vis->screen), win.vis->visual, AllocNone);
183         win.swa.colormap =  win.cmap;
184         win.swa.background_pixmap = None;
185         win.swa.border_pixel = 0;
186         win.swa.event_mask =
187             ExposureMask | KeyPressMask | KeyReleaseMask |
188             ButtonPress | ButtonReleaseMask| ButtonMotionMask |
189             Button1MotionMask | Button3MotionMask | Button4MotionMask | Button5MotionMask|
190             PointerMotionMask| StructureNotifyMask;
191         win.win = XCreateWindow(win.dpy, RootWindow(win.dpy, win.vis->screen), 0, 0,
192             WINDOW_WIDTH, WINDOW_HEIGHT, 0, win.vis->depth, InputOutput,
193             win.vis->visual, CWBorderPixel|CWColormap|CWEventMask, &win.swa);
194         if (!win.win) die("[X11]: Failed to create window\n");
195         XFree(win.vis);
196         XStoreName(win.dpy, win.win, "Demo");
197         XMapWindow(win.dpy, win.win);
198         win.wm_delete_window = XInternAtom(win.dpy, "WM_DELETE_WINDOW", False);
199         XSetWMProtocols(win.dpy, win.win, &win.wm_delete_window, 1);
200     }
201     {
202         /* create opengl context */
203         typedef GLXContext(*glxCreateContext)(Display*, GLXFBConfig, GLXContext, Bool, const int*);
204         int(*old_handler)(Display*, XErrorEvent*) = XSetErrorHandler(gl_error_handler);
205         const char *extensions_str = glXQueryExtensionsString(win.dpy, DefaultScreen(win.dpy));
206         glxCreateContext create_context = (glxCreateContext)
207             glXGetProcAddressARB((const GLubyte*)"glXCreateContextAttribsARB");
208 
209         gl_err = nk_false;
210         if (!has_extension(extensions_str, "GLX_ARB_create_context") || !create_context) {
211             fprintf(stdout, "[X11]: glXCreateContextAttribARB() not found...\n");
212             fprintf(stdout, "[X11]: ... using old-style GLX context\n");
213             glContext = glXCreateNewContext(win.dpy, win.fbc, GLX_RGBA_TYPE, 0, True);
214         } else {
215             GLint attr[] = {
216                 GLX_CONTEXT_MAJOR_VERSION_ARB, 3,
217                 GLX_CONTEXT_MINOR_VERSION_ARB, 0,
218                 None
219             };
220             glContext = create_context(win.dpy, win.fbc, 0, True, attr);
221             XSync(win.dpy, False);
222             if (gl_err || !glContext) {
223                 /* Could not create GL 3.0 context. Fallback to old 2.x context.
224                  * If a version below 3.0 is requested, implementations will
225                  * return the newest context version compatible with OpenGL
226                  * version less than version 3.0.*/
227                 attr[1] = 1; attr[3] = 0;
228                 gl_err = nk_false;
229                 fprintf(stdout, "[X11] Failed to create OpenGL 3.0 context\n");
230                 fprintf(stdout, "[X11] ... using old-style GLX context!\n");
231                 glContext = create_context(win.dpy, win.fbc, 0, True, attr);
232             }
233         }
234         XSync(win.dpy, False);
235         XSetErrorHandler(old_handler);
236         if (gl_err || !glContext)
237             die("[X11]: Failed to create an OpenGL context\n");
238         glXMakeCurrent(win.dpy, win.win, glContext);
239     }
240 
241     ctx = nk_x11_init(win.dpy, win.win);
242     /* Load Fonts: if none of these are loaded a default font will be used  */
243     {struct nk_font_atlas *atlas;
244     nk_x11_font_stash_begin(&atlas);
245     /*struct nk_font *droid = nk_font_atlas_add_from_file(atlas, "../../../extra_font/DroidSans.ttf", 14, 0);*/
246     /*struct nk_font *roboto = nk_font_atlas_add_from_file(atlas, "../../../extra_font/Roboto-Regular.ttf", 14, 0);*/
247     /*struct nk_font *future = nk_font_atlas_add_from_file(atlas, "../../../extra_font/kenvector_future_thin.ttf", 13, 0);*/
248     /*struct nk_font *clean = nk_font_atlas_add_from_file(atlas, "../../../extra_font/ProggyClean.ttf", 12, 0);*/
249     /*struct nk_font *tiny = nk_font_atlas_add_from_file(atlas, "../../../extra_font/ProggyTiny.ttf", 10, 0);*/
250     /*struct nk_font *cousine = nk_font_atlas_add_from_file(atlas, "../../../extra_font/Cousine-Regular.ttf", 13, 0);*/
251     nk_x11_font_stash_end();
252     /*nk_style_load_all_cursors(ctx, atlas->cursors);*/
253     /*nk_style_set_font(ctx, &droid->handle);*/}
254 
255     #ifdef INCLUDE_STYLE
256     /*set_style(ctx, THEME_WHITE);*/
257     /*set_style(ctx, THEME_RED);*/
258     /*set_style(ctx, THEME_BLUE);*/
259     /*set_style(ctx, THEME_DARK);*/
260     #endif
261 
262     bg.r = 0.10f, bg.g = 0.18f, bg.b = 0.24f, bg.a = 1.0f;
263     while (running)
264     {
265         /* Input */
266         XEvent evt;
267         nk_input_begin(ctx);
268         while (XPending(win.dpy)) {
269             XNextEvent(win.dpy, &evt);
270             if (evt.type == ClientMessage) goto cleanup;
271             if (XFilterEvent(&evt, win.win)) continue;
272             nk_x11_handle_event(&evt);
273         }
274         nk_input_end(ctx);
275 
276         /* GUI */
277         if (nk_begin(ctx, "Demo", nk_rect(50, 50, 200, 200),
278             NK_WINDOW_BORDER|NK_WINDOW_MOVABLE|NK_WINDOW_SCALABLE|
279             NK_WINDOW_CLOSABLE|NK_WINDOW_MINIMIZABLE|NK_WINDOW_TITLE))
280         {
281             enum {EASY, HARD};
282             static int op = EASY;
283             static int property = 20;
284 
285             nk_layout_row_static(ctx, 30, 80, 1);
286             if (nk_button_label(ctx, "button"))
287                 fprintf(stdout, "button pressed\n");
288             nk_layout_row_dynamic(ctx, 30, 2);
289             if (nk_option_label(ctx, "easy", op == EASY)) op = EASY;
290             if (nk_option_label(ctx, "hard", op == HARD)) op = HARD;
291             nk_layout_row_dynamic(ctx, 25, 1);
292             nk_property_int(ctx, "Compression:", 0, &property, 100, 10, 1);
293 
294             nk_layout_row_dynamic(ctx, 20, 1);
295             nk_label(ctx, "background:", NK_TEXT_LEFT);
296             nk_layout_row_dynamic(ctx, 25, 1);
297             if (nk_combo_begin_color(ctx, nk_rgb_cf(bg), nk_vec2(nk_widget_width(ctx),400))) {
298                 nk_layout_row_dynamic(ctx, 120, 1);
299                 bg = nk_color_picker(ctx, bg, NK_RGBA);
300                 nk_layout_row_dynamic(ctx, 25, 1);
301                 bg.r = nk_propertyf(ctx, "#R:", 0, bg.r, 1.0f, 0.01f,0.005f);
302                 bg.g = nk_propertyf(ctx, "#G:", 0, bg.g, 1.0f, 0.01f,0.005f);
303                 bg.b = nk_propertyf(ctx, "#B:", 0, bg.b, 1.0f, 0.01f,0.005f);
304                 bg.a = nk_propertyf(ctx, "#A:", 0, bg.a, 1.0f, 0.01f,0.005f);
305                 nk_combo_end(ctx);
306             }
307         }
308         nk_end(ctx);
309 
310         /* -------------- EXAMPLES ---------------- */
311         #ifdef INCLUDE_CALCULATOR
312           calculator(ctx);
313         #endif
314         #ifdef INCLUDE_CANVAS
315           canvas(ctx);
316         #endif
317         #ifdef INCLUDE_OVERVIEW
318           overview(ctx);
319         #endif
320         #ifdef INCLUDE_NODE_EDITOR
321           node_editor(ctx);
322         #endif
323         /* ----------------------------------------- */
324 
325         /* Draw */
326         XGetWindowAttributes(win.dpy, win.win, &win.attr);
327         glViewport(0, 0, win.width, win.height);
328         glClear(GL_COLOR_BUFFER_BIT);
329         glClearColor(bg.r, bg.g, bg.b, bg.a);
330         /* IMPORTANT: `nk_x11_render` modifies some global OpenGL state
331          * with blending, scissor, face culling, depth test and viewport and
332          * defaults everything back into a default state.
333          * Make sure to either a.) save and restore or b.) reset your own state after
334          * rendering the UI. */
335         nk_x11_render(NK_ANTI_ALIASING_ON, MAX_VERTEX_BUFFER, MAX_ELEMENT_BUFFER);
336         glXSwapBuffers(win.dpy, win.win);
337     }
338 
339 cleanup:
340     nk_x11_shutdown();
341     glXMakeCurrent(win.dpy, 0, 0);
342     glXDestroyContext(win.dpy, glContext);
343     XUnmapWindow(win.dpy, win.win);
344     XFreeColormap(win.dpy, win.cmap);
345     XDestroyWindow(win.dpy, win.win);
346     XCloseDisplay(win.dpy);
347     return 0;
348 
349 }
350