FPL - A C99 Single-Header-File Platform Abstraction Library

Thread solidify and prepare for X11 update

I changed the thread api to make it compatible with pthread.
In addition posix threading is now fully implemented and seem to work fine, but needs more further testing.
To compile all demo projects in linux as well, i added a "Makefile" for each one.

Also i fixed some bugs, updated the documentation and made a lot of internal changes.

Oh and i replaced the visual studio unit-test project with a normal project, so i can test all the features on linux as well - in a unit-test like way. And lastly i finally submitted this project as a official handmade-project and i really hope that it gets approved. I really think this project is well suited for being "handmade".

Here is the changelog since last version:

## v0.6.0.0 beta:
- Changed: Documentation changed a bit
- Changed: Renamed SignalWakeUp() to SignalSet()
- Changed: [Win32] Start thread always immediatly
- Changed: Included "Windows" prefix for output path in visual studio projects
- Changed: Moved opengl settings into graphics union
- Changed: All global functions use :: as a prefix
- Deleted: Removed ThreadSuspend() -> Not complaint with pthread
- Deleted: Removed ThreadResume() -> Not complaint with pthread
- Deleted: Removed SignalReset() -> Not complaint with pthread
- Fixed: Resize video backbuffer was not working anymore
- Fixed: [Win32] Some _Interlocked* functions was not existing on x86
- New: Introduced PrepareWindowForVideoAfter() so we can setup a video context after the window has been created
- New: Introduced PrepareWindowForVideoBefore() so we can setup any window before initializing the video context
- New: Added timings::GetTimeInMilliseconds() with [Win32] and [POSIX] implementation
- New: [POSIX] Implemented all threading functions
- New: [Linux] Added a makefile for each demo project
- New: Added files::FileMove
You can suspend threads on Linux. You do that by raising signal. For example, mono garbage collector used to do this when it needed to run (suspends all other threads). Now they do that differently for better performance when running GC.
mmozeiko
You can suspend threads on Linux. You do that by raising signal. For example, mono garbage collector used to do this when it needed to run (suspends all other threads). Now they do that differently for better performance when running GC.


Sure but the caller has to wait on that signal, not the system managing the threads.
On Win32 this works without any caller interaction (ResumeThread/SuspendThread).

The main problem is, i need to know the state of any given thread when WaitFor*() or ThreadDestroy() is called, but the data pointer for the native thread proc is just one data pointer, so need to decide: Use the user pointer or my internal state. In FPL the internal state is passed and the actual user-code is a passed to a function pointer.

But this has the downside that after the user function is called - you cannot have any way of part-automatic suspend/resume. The caller has to be check and wait for a signal by hisself.

One thing which may works, if i introduce a callback the user has to call regurly to check and wait on a signal, when it is suspended. But for the moment its simply removed, due to the fact that the caller can implement resume/suspend very easiely.

But thanks for the tip!

Edited by Finalspace on
Just a short update about the current state:

The X11/GLX/POSIX/Linux implementation goes very well and very soon i have a full working solution.
After that i will implement the ALSA audio driver, so that i have all the features for POSIX based systems as well.
Also i decided to add more video drivers (D2D, D3D, Vulkan) when the linux implementation is fully complete.

Stay tuned.
I got X11 with GLX working, but as soon as the application exits, there is a segfault coming from the nvidia driver always -.- I am pretty sure that i did something wrong in initializing GLX or the window.

Does someone know how to program X11/GLX properly?
Or does one know how to find out what is wrong, the stacktrace i got from GDB is just useless.
Or know at least a forum i can ask for help?

Its still the initialization and release i am struggling, i havent even started to implement event handling yet :-(

Seems that it will take a while before linux support is done...

*Edit: Maybe its because i never called XFree for either GLXFBConfig or XVisualInfo pointers...

Edited by Finalspace on
Here's my example that works without segfaults: https://git.handmade.network/snippets/20

Edited by Mārtiņš Možeiko on
mmozeiko
Here's my example that works without segfaults: https://git.handmade.network/snippets/20


Thanks! I compared it with my implementation and there are a few things which are different in my implementation:

Init:
- I search over all FBConfig to look for a config which have the alpha bits test (glXGetFBConfigAttrib / GLX_ALPHA_SIZE)
- I XFree the FBConfig base pointer always when i am done searching
- I use XDefaultScreen directly instead of DefaultScreen macro
- I use XRootWindow directly instead of DefaultRootWindow
- I dont use XSetWMNormalHints
- I dont get/set the atom for WM_DELETE_WINDOW
- I store the window name after i mapped the window

Release:
- I XFree the visual info after i destroyed the rendering context immediatly
- I unmap the window (XUnmapWindow) before i destroy it (XDestroyWindow)
- I call XFlush before i close the display (XCloseDisplay)

Loop:
- I havent done any event handling yet, i just initialize the window + context and then release it immediataly after that

One major difference is the destroying of the visual info happens on your code after you released the colormap. In my implementation its the opposite. Maybe thats the main issue?

Edited by Finalspace on
Not sure, but could be. XCreateColormap accepts pointer to visual, so it could potentially store it and use later (no idea if it really does it). In such case freeing visual info before colormap would lead to errors.

The rest of the stuff does not seem to matter.

Try commenting out "free" functionality for specific objects and see which one "fixes" the issue.

Edited by Mārtiņš Možeiko on
mmozeiko
Not sure, but could be. XCreateColormap accepts pointer to visual, so it could potentially store it and use later (no idea if it really does it). In such case freeing visual info before colormap would lead to errors.

The rest of the stuff does not seem to matter.

Try commenting out "free" functionality for specific objects and see which one "fixes" the issue.


I get home very late today, so i made a simple main.cpp with a allmost identical structure FPL uses. Can you please try to compile and run it? So i know at least that it crashes the same way. (Sorry about the weird architecture, the window system has no access to the video system directly - so i need a callback to access it).

I really need to clean up the window <-> video integration.

  1
  2
  3
  4
  5
  6
  7
  8
  9
 10
 11
 12
 13
 14
 15
 16
 17
 18
 19
 20
 21
 22
 23
 24
 25
 26
 27
 28
 29
 30
 31
 32
 33
 34
 35
 36
 37
 38
 39
 40
 41
 42
 43
 44
 45
 46
 47
 48
 49
 50
 51
 52
 53
 54
 55
 56
 57
 58
 59
 60
 61
 62
 63
 64
 65
 66
 67
 68
 69
 70
 71
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
//#define COMPILE_ON_WIN

#define fpl_internal static
#define fpl_constant constexpr
#define fpl_inline inline

#define FPL_ARRAYCOUNT(arr) (sizeof(arr) / sizeof((arr)[0]))

#include <assert.h>
#define FPL_ASSERT(exp) assert(exp)

#include <stdint.h> // uint32_t, int64_t etc.
#include <stdio.h> // fprintf
#include <string.h> // strcpy
#include <malloc.h> // malloc, free

#define FPL_LOG_FORMAT(what, format) "[" what "] " format "\n"
#define FPL_LOG(what, format, ...) do { \
	::fprintf(stdout, FPL_LOG_FORMAT(what, format), ## __VA_ARGS__); \
} while (0)

// Subplatform POSIX
#if !defined(COMPILE_ON_WIN)
#include <sys/mman.h> // mmap, munmap
#include <sys/types.h> // data types
#include <sys/stat.h> // mkdir
#include <sys/errno.h> // errno
#include <signal.h> // pthread_kill
#include <time.h> // clock_gettime, nanosleep
#include <dlfcn.h> // dlopen, dlclose
#include <fcntl.h> // open
#include <unistd.h> // read, write, close, access, rmdir

// Subplatform X11
#include <X11/X.h> // Window
#include <X11/Xlib.h> // Display
#undef None
#undef Success

// GLX
#include <GL/glx.h> // XVisualInfo, GLXContext, GLXDrawable
#else

// Fake types to get it compile on windows
#define RTLD_NOW 1337
#define AllocNone 0
#define CopyFromParent 0

#define InputOutput 0x4

#define CWEventMask 0x10
#define CWBorderPixel 0x11
#define CWColormap 0x12

#define StructureNotifyMask 0x20

typedef int XID;
typedef XID Colormap;
typedef XID Visual;
struct Display {
	int dummy;
};
struct XVisualInfo {
	int depth;
	Visual *visual;
};
typedef XID Window;
struct XSetWindowAttributes {
	Colormap colormap;
	int event_mask;
};
struct XErrorEvent {
	int type;
	Display *display;			/* Display the event was read from */
	unsigned long serial;		/* serial number of failed request */
	unsigned char error_code;	/* error code of failed request */
	unsigned char request_code;	/* Major op-code of failed request */
	unsigned char minor_code;	/* Minor op-code of failed request */
	XID resourceid;				/* resource id */
};
#define XERRORHANDLER(name) int name(Display *display, XErrorEvent *ev)
typedef XERRORHANDLER(__XErrorHandler);
typedef __XErrorHandler *XErrorHandler;

typedef unsigned char GLubyte;
typedef int GLint;
#define GL_TRUE 1
#define GL_FALSE 0

#ifndef True
#	define True 1
#	define False 0
#endif
#ifndef Bool
#	define Bool int
#endif

#define GLX_VENDOR 1
#define GLX_RGBA_BIT 0x00000001
#define GLX_WINDOW_BIT 0x00000001
#define GLX_DRAWABLE_TYPE 0x8010
#define GLX_RENDER_TYPE	0x8011
#define GLX_RGBA_TYPE 0x8014
#define GLX_DOUBLEBUFFER 5
#define GLX_STEREO 6
#define GLX_AUX_BUFFERS	7
#define GLX_RED_SIZE 8
#define GLX_GREEN_SIZE 9
#define GLX_BLUE_SIZE 10
#define GLX_ALPHA_SIZE 11
#define GLX_DEPTH_SIZE 12
#define GLX_STENCIL_SIZE 13
#define GLX_ACCUM_RED_SIZE 14
#define GLX_ACCUM_GREEN_SIZE 15
#define GLX_ACCUM_BLUE_SIZE	16
#define GLX_ACCUM_ALPHA_SIZE 17
#define GLX_SAMPLES 0x186a1
#define GLX_VISUAL_ID 0x800b

#define GLX_X_VISUAL_TYPE 0x22
#define GLX_TRUE_COLOR 0x8002

typedef XID GLXWindow;
typedef XID GLXDrawable;
struct __GLXFBConfig {
	int dummy;
};
struct __GLXcontext {
	int dummy;
};
typedef __GLXFBConfig* GLXFBConfig;
typedef __GLXcontext* GLXContext;

static void *dlopen(const char *filepath, int loadtype) {
	return nullptr;
}
static void dlclose(void *handle) {
}
static void *dlsym(void *handle, const char *name) {
	return nullptr;
}
static const char *getenv(const char *name) {
	return nullptr;
}
#endif

#define FPL_POSIX_GET_FUNCTION_ADDRESS_BREAK(libHandle, libName, target, type, name) \
	target = (type *)::dlsym(libHandle, name); \
	if (target == nullptr) { \
		break; \
	}

namespace fpl {
	namespace subplatform_posix {
		fpl_constant int DL_LOADTYPE = RTLD_NOW;
	}

	namespace subplatform_x11 {
		//
		// X11 Api
		//
#       define FPL_FUNC_X11_X_FREE(name) int name(void *data)
		typedef FPL_FUNC_X11_X_FREE(fpl_func_x11_XFree);
#       define FPL_FUNC_X11_X_FLUSH(name) void name(Display *display)
		typedef FPL_FUNC_X11_X_FLUSH(fpl_func_x11_XFlush);
#       define FPL_FUNC_X11_X_OPEN_DISPLAY(name) Display *name(char *display_name)
		typedef FPL_FUNC_X11_X_OPEN_DISPLAY(fpl_func_x11_XOpenDisplay);
#       define FPL_FUNC_X11_X_CLOSE_DISPLAY(name) int name(Display *display)
		typedef FPL_FUNC_X11_X_CLOSE_DISPLAY(fpl_func_x11_XCloseDisplay);
#       define FPL_FUNC_X11_X_DEFAULT_SCREEN(name) int name(Display *display)
		typedef FPL_FUNC_X11_X_DEFAULT_SCREEN(fpl_func_x11_XDefaultScreen);
#       define FPL_FUNC_X11_X_ROOT_WINDOW(name) Window name(Display *display, int screen_number)
		typedef FPL_FUNC_X11_X_ROOT_WINDOW(fpl_func_x11_XRootWindow);
#       define FPL_FUNC_X11_X_CREATE_WINDOW(name) Window name(Display *display, Window parent, int x, int y, unsigned int width, unsigned int height, unsigned int border_width, int depth, unsigned int clazz, Visual *visual, unsigned long valuemask, XSetWindowAttributes *attributes)
		typedef FPL_FUNC_X11_X_CREATE_WINDOW(fpl_func_x11_XCreateWindow);
#       define FPL_FUNC_X11_X_DESTROY_WINDOW(name) int name(Display *display, Window w)
		typedef FPL_FUNC_X11_X_DESTROY_WINDOW(fpl_func_x11_XDestroyWindow);
#       define FPL_FUNC_X11_X_CREATE_COLORMAP(name) Colormap name(Display *display, Window w, Visual *visual, int alloc)
		typedef FPL_FUNC_X11_X_CREATE_COLORMAP(fpl_func_x11_XCreateColormap);
#       define FPL_FUNC_X11_X_DEFAULT_COLORMAP(name) Colormap name(Display *display, int screen_number)
		typedef FPL_FUNC_X11_X_DEFAULT_COLORMAP(fpl_func_x11_XDefaultColormap);
#       define FPL_FUNC_X11_X_FREE_COLORMAP(name) void name(Display *display, Colormap colormap)
		typedef FPL_FUNC_X11_X_FREE_COLORMAP(fpl_func_x11_XFreeColormap);
#       define FPL_FUNC_X11_X_MAP_WINDOW(name) void name(Display *display, Window w)
		typedef FPL_FUNC_X11_X_MAP_WINDOW(fpl_func_x11_XMapWindow);
#       define FPL_FUNC_X11_X_UNMAP_WINDOW(name) void name(Display *display, Window w)
		typedef FPL_FUNC_X11_X_UNMAP_WINDOW(fpl_func_x11_XUnmapWindow);
#       define FPL_FUNC_X11_X_STORE_NAME(name) void name(Display *display, Window w, char *windowName)
		typedef FPL_FUNC_X11_X_STORE_NAME(fpl_func_x11_XStoreName);
//#       define FPL_FUNC_X11_X_RENDER_FIND_VISUAL_FORMAT(name) XRenderPictFormat* name(Display* display, Visual const* visual)
//        typedef FPL_FUNC_X11_X_RENDER_FIND_VISUAL_FORMAT(fpl_func_x11_XRenderFindVisualFormat);
#       define FPL_FUNC_X11_X_DEFAULT_VISUAL(name) Visual *name(Display *display, int screen_number)
		typedef FPL_FUNC_X11_X_DEFAULT_VISUAL(fpl_func_x11_XDefaultVisual);
#       define FPL_FUNC_X11_X_SET_ERROR_HANDLER(name) XErrorHandler name(XErrorHandler handler)
		typedef FPL_FUNC_X11_X_SET_ERROR_HANDLER(fpl_func_x11_XSetErrorHandler);

		struct X11Api {
			void *libHandle;
			fpl_func_x11_XFlush *XFlush;
			fpl_func_x11_XFree *XFree;
			fpl_func_x11_XOpenDisplay *XOpenDisplay;
			fpl_func_x11_XCloseDisplay *XCloseDisplay;
			fpl_func_x11_XDefaultScreen *XDefaultScreen;
			fpl_func_x11_XRootWindow *XRootWindow;
			fpl_func_x11_XCreateWindow *XCreateWindow;
			fpl_func_x11_XDestroyWindow *XDestroyWindow;
			fpl_func_x11_XCreateColormap *XCreateColormap;
			fpl_func_x11_XFreeColormap *XFreeColormap;
			fpl_func_x11_XDefaultColormap *XDefaultColormap;
			fpl_func_x11_XMapWindow *XMapWindow;
			fpl_func_x11_XUnmapWindow *XUnmapWindow;
			fpl_func_x11_XStoreName *XStoreName;
			//fpl_func_x11_XRenderFindVisualFormat *XRenderFindVisualFormat;
			fpl_func_x11_XDefaultVisual *XDefaultVisual;
			fpl_func_x11_XSetErrorHandler *XSetErrorHandler;
		};

		fpl_internal void UnloadX11Api(X11Api &x11Api) {
			if (x11Api.libHandle != nullptr) {
				::dlclose(x11Api.libHandle);
			}
			x11Api = {};
		}

		fpl_internal bool LoadX11Api(X11Api &x11Api) {
			const char* libFileNames[] = {
				"libX11.so",
				"libX11.so.7",
				"libX11.so.6",
				"libX11.so.5",
			};
			bool result = false;
			for (uint32_t index = 0; index < FPL_ARRAYCOUNT(libFileNames); ++index) {
				const char *libName = libFileNames[index];
				void *libHandle = x11Api.libHandle = ::dlopen(libName, subplatform_posix::DL_LOADTYPE);
				if (libHandle != nullptr) {
					FPL_POSIX_GET_FUNCTION_ADDRESS_BREAK(libHandle, libName, x11Api.XFlush, fpl_func_x11_XFlush, "XFlush");
					FPL_POSIX_GET_FUNCTION_ADDRESS_BREAK(libHandle, libName, x11Api.XFree, fpl_func_x11_XFree, "XFree");
					FPL_POSIX_GET_FUNCTION_ADDRESS_BREAK(libHandle, libName, x11Api.XOpenDisplay, fpl_func_x11_XOpenDisplay, "XOpenDisplay");
					FPL_POSIX_GET_FUNCTION_ADDRESS_BREAK(libHandle, libName, x11Api.XCloseDisplay, fpl_func_x11_XCloseDisplay, "XCloseDisplay");
					FPL_POSIX_GET_FUNCTION_ADDRESS_BREAK(libHandle, libName, x11Api.XDefaultScreen, fpl_func_x11_XDefaultScreen, "XDefaultScreen");
					FPL_POSIX_GET_FUNCTION_ADDRESS_BREAK(libHandle, libName, x11Api.XRootWindow, fpl_func_x11_XRootWindow, "XRootWindow");
					FPL_POSIX_GET_FUNCTION_ADDRESS_BREAK(libHandle, libName, x11Api.XCreateWindow, fpl_func_x11_XCreateWindow, "XCreateWindow");
					FPL_POSIX_GET_FUNCTION_ADDRESS_BREAK(libHandle, libName, x11Api.XDestroyWindow, fpl_func_x11_XDestroyWindow, "XDestroyWindow");
					FPL_POSIX_GET_FUNCTION_ADDRESS_BREAK(libHandle, libName, x11Api.XCreateColormap, fpl_func_x11_XCreateColormap, "XCreateColormap");
					FPL_POSIX_GET_FUNCTION_ADDRESS_BREAK(libHandle, libName, x11Api.XFreeColormap, fpl_func_x11_XFreeColormap, "XFreeColormap");
					FPL_POSIX_GET_FUNCTION_ADDRESS_BREAK(libHandle, libName, x11Api.XDefaultColormap, fpl_func_x11_XDefaultColormap, "XDefaultColormap");
					FPL_POSIX_GET_FUNCTION_ADDRESS_BREAK(libHandle, libName, x11Api.XMapWindow, fpl_func_x11_XMapWindow, "XMapWindow");
					FPL_POSIX_GET_FUNCTION_ADDRESS_BREAK(libHandle, libName, x11Api.XUnmapWindow, fpl_func_x11_XUnmapWindow, "XUnmapWindow");
					FPL_POSIX_GET_FUNCTION_ADDRESS_BREAK(libHandle, libName, x11Api.XStoreName, fpl_func_x11_XStoreName, "XStoreName");
					//FPL_POSIX_GET_FUNCTION_ADDRESS_BREAK(libHandle, libName, x11Api.XRenderFindVisualFormat, fpl_func_x11_XRenderFindVisualFormat, "XRenderFindVisualFormat");
					FPL_POSIX_GET_FUNCTION_ADDRESS_BREAK(libHandle, libName, x11Api.XDefaultVisual, fpl_func_x11_XDefaultVisual, "XDefaultVisual");
					FPL_POSIX_GET_FUNCTION_ADDRESS_BREAK(libHandle, libName, x11Api.XSetErrorHandler, fpl_func_x11_XSetErrorHandler, "XSetErrorHandler");
					result = true;
					break;
				}
				UnloadX11Api(x11Api);
			}
			return(result);
		}

		struct X11AppState {
			X11Api api;
		};

		struct X11WindowState {
			Window root;
			Window window;
			Colormap colorMap;
			XErrorHandler originalErrorHandler;
			Display *display;
			int32_t screen;
		};

		struct X11WindowAttributesInput {
			X11AppState *appState;
			X11WindowState *windowState;
		};

		struct X11WindowAttributesOutput {
			Colormap colorMap;
			Visual *visual;
			int colorDepth;
		};

	} // subplatform_x11
} // fpl

namespace fpl {
	namespace platform {
		struct PlatformWindowState {
			subplatform_x11::X11WindowState x11;
		};

		struct PlatformVideoState {
			void *mem;
			size_t size;
		};

		struct PlatformAppState {
			subplatform_x11::X11AppState x11;
			PlatformWindowState window;
			PlatformVideoState video;
		};

		struct WindowAttributesInput {
			subplatform_x11::X11WindowAttributesInput x11;
			PlatformVideoState *video;
		};

		struct WindowAttributesOutput {
			subplatform_x11::X11WindowAttributesOutput x11;
		};

#		define FPL_FUNC_GET_WINDOW_ATTRIBUTES(name) bool name(const platform::WindowAttributesInput &input, platform::WindowAttributesOutput &output)
		typedef FPL_FUNC_GET_WINDOW_ATTRIBUTES(GetWindowAttributes_callback);
	}
}

namespace fpl {
	namespace strings {
		char *CopyAnsiString(const char *sourceStr, char *destStr, size_t destLength) {
			char *result = strncpy(destStr, sourceStr, destLength);
			return(result);
		}
	}

	namespace subplatform_x11 {

		fpl_internal void X11ReleaseSubplatform(X11AppState &appState) {
			UnloadX11Api(appState.api);
		}

		fpl_internal bool X11InitSubplatform(X11AppState &appState) {
			if (!LoadX11Api(appState.api)) {
				return false;
			}
			return true;
		}

		fpl_internal void X11ReleaseWindow(const X11AppState &x11AppState, X11WindowState &windowState) {
			const X11Api &x11Api = x11AppState.api;
			if (windowState.window) {
				FPL_LOG("X11", "Unmap Window '%d' on Display '%p'", (int)windowState.window, windowState.display);
				x11Api.XUnmapWindow(windowState.display, windowState.window);
				FPL_LOG("X11", "Destroy Window '%d' on Display '%p'", (int)windowState.window, windowState.display);
				x11Api.XDestroyWindow(windowState.display, windowState.window);
				windowState.window = (Window)0;
			}
			if (windowState.colorMap) {
				FPL_LOG("X11", "Free Colormap '%d' on Display '%p'", (int)windowState.colorMap, windowState.display);
				x11Api.XFreeColormap(windowState.display, windowState.colorMap);
				windowState.colorMap = (Colormap)0;
			}
			if (windowState.display != nullptr) {
				FPL_LOG("X11", "Flush Display '%p'", windowState.display);
				x11Api.XFlush(windowState.display);
				FPL_LOG("X11", "Close Display '%p'", windowState.display);
				x11Api.XCloseDisplay(windowState.display);
				windowState.display = nullptr;
			}
			FPL_LOG("X11", "Clear Window State");
			windowState = {};
		}

		fpl_internal int X11ErrorHandler(Display *display, XErrorEvent *ev) {
			return 0;
		}

		fpl_internal bool X11InitWindow(platform::GetWindowAttributes_callback *getWindowAttributesCallback, const platform::WindowAttributesInput &winAttribInput, X11AppState &x11AppState, X11WindowState &windowState) {
			const X11Api &x11Api = x11AppState.api;

			// @TODO(final): Implement this!
			// See: https://www.khronos.org/opengl/wiki/Programming_OpenGL_in_Linux:_GLX_and_Xlib

			// Get display with fallback from environment variable
			const char *displayStrings[] = {
				nullptr,
				::getenv("DISPLAY")
			};
			char displayStringBuffer[256];
			for (uint32_t displayStringIndex = 0; displayStringIndex < FPL_ARRAYCOUNT(displayStrings); ++displayStringIndex) {
				// @NOTE(final): Nonsense we have to copy the constant display string to a variable buffer to satisfy the compiler
				const char *displayString = displayStrings[displayStringIndex];
				const char *notNullDisplayString = (displayString == nullptr ? "nullptr" : displayString);
				if (displayString != nullptr) {
					strings::CopyAnsiString(displayString, displayStringBuffer, FPL_ARRAYCOUNT(displayStringBuffer));
					windowState.display = x11Api.XOpenDisplay(displayStringBuffer);
				} else {
					windowState.display = x11Api.XOpenDisplay(nullptr);
				}
				FPL_LOG("X11", "Open Display from String '%s'", notNullDisplayString);
				if (windowState.display != nullptr) {
					FPL_LOG("X11", "Successfully opened Display: '%p' from String '%s'", windowState.display, notNullDisplayString);
					break;
				}
				FPL_LOG("X11", "Failed opening Display from String '%s'!", notNullDisplayString);
			}
			if (windowState.display == nullptr) {
				return false;
			}

			// Set error handler
			windowState.originalErrorHandler = x11Api.XSetErrorHandler(X11ErrorHandler);

			// Get screen
			FPL_LOG("X11", "Get Screen from Display '%p'", windowState.display);
			windowState.screen = x11Api.XDefaultScreen(windowState.display);
			FPL_LOG("X11", "Successfully got Screen: '%d' from Display '%p'", windowState.screen, windowState.display);

			// Get root window
			FPL_LOG("X11", "Get Root Window From Display '%p' and Screen '%d'", windowState.display, windowState.screen);
			windowState.root = x11Api.XRootWindow(windowState.display, windowState.screen);
			FPL_LOG("X11", "Successfully got Root Window '%d' from Display '%p' and Screen '%d'", (int)windowState.root, windowState.display, windowState.screen);

			// @TODO(final): This entire thing about getting the visual info is just bullshit and need to replaced by a much more sane implementation!
			FPL_LOG("X11", "Get Window Attributes from Callback '%p':", getWindowAttributesCallback);
			platform::WindowAttributesOutput winAttribOutput = {};
			bool gotWindowAttributes = getWindowAttributesCallback(winAttribInput, winAttribOutput);
			if (!gotWindowAttributes) {
				FPL_LOG("X11", "Failed getting Window Attributes from Callback '%p'!", getWindowAttributesCallback);
			} else {
				FPL_LOG("X11", "Successfully got Window Attributes");
			}

			// Set window attributes
			XSetWindowAttributes swa = {};
			unsigned long valueMask;
			if (gotWindowAttributes) {
				FPL_LOG("X11", "Using Colormap from Window Attributes");
				swa.colormap = winAttribOutput.x11.colorMap;
				valueMask = CWEventMask | CWBorderPixel | CWColormap;
			} else {
				FPL_LOG("X11", "Not using a Colormap");
				winAttribOutput.x11.colorMap = x11Api.XDefaultColormap(windowState.display, windowState.screen);
				winAttribOutput.x11.visual = x11Api.XDefaultVisual(windowState.display, windowState.root);
				winAttribOutput.x11.colorDepth = CopyFromParent;
				valueMask = CWEventMask | CWBorderPixel;
			}
			swa.event_mask = StructureNotifyMask;

			// @TODO(final): Get window width from settings (Either window or fullscreen)
			uint32_t windowWidth = 800;
			uint32_t windowHeight = 600;

			// Create window
			FPL_LOG("X11", "Create Window with Display('%p'), Root('%d'), Dimension(%d x %d), ColorDepth(%d)", windowState.display, (int)windowState.root, windowWidth, windowHeight, winAttribOutput.x11.colorDepth);
			windowState.colorMap = winAttribOutput.x11.colorMap;
			windowState.window = x11Api.XCreateWindow(windowState.display, windowState.root, 0, 0, windowWidth, windowHeight, 0, winAttribOutput.x11.colorDepth, InputOutput, winAttribOutput.x11.visual, valueMask, &swa);
			if (!windowState.window) {
				FPL_LOG("X11", "Failed creating Window from Display '%p' and Root '%d'", windowState.display, (int)windowState.root);
				X11ReleaseWindow(x11AppState, windowState);
				return false;
			}
			FPL_LOG("X11", "Successfully created Window '%d'", (int)windowState.window);

			// Show window
			FPL_LOG("X11", "Map Window '%d' on Display '%p'", (int)windowState.window, windowState.display);
			x11Api.XMapWindow(windowState.display, windowState.window);

			// Set title
			char windowTitleBuffer[256];
			strings::CopyAnsiString("Unnamed FPL X Window", windowTitleBuffer, FPL_ARRAYCOUNT(windowTitleBuffer));
			FPL_LOG("X11", "Set window title to '%s'", windowTitleBuffer);
			x11Api.XStoreName(windowState.display, windowState.window, windowTitleBuffer);

			return true;
		}

	} // subplatform_x11

	namespace drivers {
		// GLX function prototypes
#		define FPL_FUNC_GL_X_CHOOSE_VISUAL(name) XVisualInfo* name(Display *dpy, int screen, int *attribList)
		typedef FPL_FUNC_GL_X_CHOOSE_VISUAL(fpl_func_glx_glXChooseVisual);
#		define FPL_FUNC_GL_X_CREATE_CONTEXT(name) GLXContext name(Display *dpy, XVisualInfo *vis, GLXContext shareList, Bool direct)
		typedef FPL_FUNC_GL_X_CREATE_CONTEXT(fpl_func_glx_glXCreateContext);
#		define FPL_FUNC_GL_X_CREATE_NEW_CONTEXT(name) GLXContext name(Display *dpy, GLXFBConfig config, int render_type, GLXContext share_list, Bool direct)
		typedef FPL_FUNC_GL_X_CREATE_NEW_CONTEXT(fpl_func_glx_glXCreateNewContext);
#		define FPL_FUNC_GL_X_DESTROY_CONTEXT(name) void name(Display *dpy, GLXContext ctx)
		typedef FPL_FUNC_GL_X_DESTROY_CONTEXT(fpl_func_glx_glXDestroyContext);
#		define FPL_FUNC_GL_X_MAKE_CURRENT(name) Bool name(Display *dpy, GLXDrawable drawable, GLXContext ctx)
		typedef FPL_FUNC_GL_X_MAKE_CURRENT(fpl_func_glx_glXMakeCurrent);
#		define FPL_FUNC_GL_X_SWAP_BUFFERS(name) void name(Display *dpy, GLXDrawable drawable)
		typedef FPL_FUNC_GL_X_SWAP_BUFFERS(fpl_func_glx_glXSwapBuffers);
#		define FPL_FUNC_GL_X_GET_PROC_ADDRESS(name) void *name(const GLubyte *procname)
		typedef FPL_FUNC_GL_X_GET_PROC_ADDRESS(fpl_func_glx_glXGetProcAddress);
#		define FPL_FUNC_GL_X_CHOOSE_FB_CONFIG(name) GLXFBConfig *name(Display *dpy, int screen, const int *attrib_list,  int *nelements)
		typedef FPL_FUNC_GL_X_CHOOSE_FB_CONFIG(fpl_func_glx_glXChooseFBConfig);
#		define FPL_FUNC_GL_X_GET_FB_CONFIGS(name) GLXFBConfig *name(Display *dpy, int screen, int *nelements)
		typedef FPL_FUNC_GL_X_GET_FB_CONFIGS(fpl_func_glx_glXGetFBConfigs);
#		define FPL_FUNC_GL_X_GET_VISUAL_FROM_FB_CONFIG(name) XVisualInfo *name(Display *dpy, GLXFBConfig config)
		typedef FPL_FUNC_GL_X_GET_VISUAL_FROM_FB_CONFIG(fpl_func_glx_glXGetVisualFromFBConfig);
#		define FPL_FUNC_GL_X_GET_FB_CONFIG_ATTRIB(name) int name(Display *dpy, GLXFBConfig config, int attribute, int *value)
		typedef FPL_FUNC_GL_X_GET_FB_CONFIG_ATTRIB(fpl_func_glx_glXGetFBConfigAttrib);
#		define FPL_FUNC_GL_X_CREATE_WINDOW(name) GLXWindow name(Display *dpy, GLXFBConfig config, Window win, const int *attrib_list)
		typedef FPL_FUNC_GL_X_CREATE_WINDOW(fpl_func_glx_glXCreateWindow);
#		define FPL_FUNC_GL_X_QUERY_EXTENSION(name) Bool name(Display *dpy,  int *errorBase,  int *eventBase)
		typedef FPL_FUNC_GL_X_QUERY_EXTENSION(fpl_func_glx_glXQueryExtension);

		struct GLXApi {
			void *libHandle;
			fpl_func_glx_glXChooseVisual *glXChooseVisual;
			fpl_func_glx_glXCreateContext *glXCreateContext;
			fpl_func_glx_glXDestroyContext *glXDestroyContext;
			fpl_func_glx_glXCreateNewContext *glXCreateNewContext;
			fpl_func_glx_glXMakeCurrent *glXMakeCurrent;
			fpl_func_glx_glXSwapBuffers *glXSwapBuffers;
			fpl_func_glx_glXGetProcAddress *glXGetProcAddress;
			fpl_func_glx_glXChooseFBConfig *glXChooseFBConfig;
			fpl_func_glx_glXGetFBConfigs *glXGetFBConfigs;
			fpl_func_glx_glXGetVisualFromFBConfig *glXGetVisualFromFBConfig;
			fpl_func_glx_glXGetFBConfigAttrib *glXGetFBConfigAttrib;
			fpl_func_glx_glXCreateWindow *glXCreateWindow;
			fpl_func_glx_glXQueryExtension *glXQueryExtension;
		};

		fpl_internal void UnloadGLXApi(GLXApi &glxApi) {
			if (glxApi.libHandle != nullptr) {
				FPL_LOG("GLX", "Unload Api (Library '%p')", glxApi.libHandle);
				::dlclose(glxApi.libHandle);
			}
			glxApi = {};
		}

		fpl_internal bool LoadGLXApi(GLXApi &glxApi) {
			const char* libFileNames[] = {
				"libGLX.so",
				"libGLX.so.0",
			};
			bool result = false;
			for (uint32_t index = 0; index < FPL_ARRAYCOUNT(libFileNames); ++index) {
				const char *libName = libFileNames[index];
				FPL_LOG("GLX", "Load GLX Api from Library: %s", libName);
				void *libHandle = glxApi.libHandle = ::dlopen(libName, subplatform_posix::DL_LOADTYPE);
				if (libHandle != nullptr) {
					FPL_LOG("GLX", "Library Found: '%s', Resolving Procedures", libName);
					FPL_POSIX_GET_FUNCTION_ADDRESS_BREAK(libHandle, libName, glxApi.glXChooseVisual, fpl_func_glx_glXChooseVisual, "glXChooseVisual");
					FPL_POSIX_GET_FUNCTION_ADDRESS_BREAK(libHandle, libName, glxApi.glXCreateContext, fpl_func_glx_glXCreateContext, "glXCreateContext");
					FPL_POSIX_GET_FUNCTION_ADDRESS_BREAK(libHandle, libName, glxApi.glXDestroyContext, fpl_func_glx_glXDestroyContext, "glXDestroyContext");
					FPL_POSIX_GET_FUNCTION_ADDRESS_BREAK(libHandle, libName, glxApi.glXCreateNewContext, fpl_func_glx_glXCreateNewContext, "glXCreateNewContext");
					FPL_POSIX_GET_FUNCTION_ADDRESS_BREAK(libHandle, libName, glxApi.glXMakeCurrent, fpl_func_glx_glXMakeCurrent, "glXMakeCurrent");
					FPL_POSIX_GET_FUNCTION_ADDRESS_BREAK(libHandle, libName, glxApi.glXSwapBuffers, fpl_func_glx_glXSwapBuffers, "glXSwapBuffers");
					FPL_POSIX_GET_FUNCTION_ADDRESS_BREAK(libHandle, libName, glxApi.glXGetProcAddress, fpl_func_glx_glXGetProcAddress, "glXGetProcAddress");
					FPL_POSIX_GET_FUNCTION_ADDRESS_BREAK(libHandle, libName, glxApi.glXChooseFBConfig, fpl_func_glx_glXChooseFBConfig, "glXChooseFBConfig");
					FPL_POSIX_GET_FUNCTION_ADDRESS_BREAK(libHandle, libName, glxApi.glXGetFBConfigs, fpl_func_glx_glXGetFBConfigs, "glXGetFBConfigs");
					FPL_POSIX_GET_FUNCTION_ADDRESS_BREAK(libHandle, libName, glxApi.glXGetVisualFromFBConfig, fpl_func_glx_glXGetVisualFromFBConfig, "glXGetVisualFromFBConfig");
					FPL_POSIX_GET_FUNCTION_ADDRESS_BREAK(libHandle, libName, glxApi.glXGetFBConfigAttrib, fpl_func_glx_glXGetFBConfigAttrib, "glXGetFBConfigAttrib");
					FPL_POSIX_GET_FUNCTION_ADDRESS_BREAK(libHandle, libName, glxApi.glXCreateWindow, fpl_func_glx_glXCreateWindow, "glXCreateWindow");
					FPL_POSIX_GET_FUNCTION_ADDRESS_BREAK(libHandle, libName, glxApi.glXQueryExtension, fpl_func_glx_glXQueryExtension, "glXQueryExtension");
					FPL_LOG("GLX", "Successfully loaded GLX Api from Library '%s'", libName);
					result = true;
					break;
				}
				UnloadGLXApi(glxApi);
			}
			return (result);
		}

		struct X11VideoOpenGLState {
			GLXApi glxApi;
			XVisualInfo *visualInfo;
			GLXContext glxContext;
			bool isActivated;
		};

		fpl_inline int GLXGetFrameBufferConfigAttrib(const GLXApi &glxApi, Display *display, GLXFBConfig fbConfig, int attrib) {
			int result;
			glxApi.glXGetFBConfigAttrib(display, fbConfig, attrib, &result);
			return(result);
		}

		fpl_internal XVisualInfo *GLXGetVisualInfo(const subplatform_x11::X11AppState &x11AppState, const X11VideoOpenGLState &glState, Display *display, int screen) {
			XVisualInfo *result = nullptr;

			const GLXApi &glxApi = glState.glxApi;
			const subplatform_x11::X11Api &x11Api = x11AppState.api;

			GLint attributes[] = {
				GLX_RENDER_TYPE, GLX_RGBA_BIT,
				GLX_DRAWABLE_TYPE, GLX_WINDOW_BIT,
				GLX_X_VISUAL_TYPE, GLX_TRUE_COLOR,
				GLX_RED_SIZE, 8,
				GLX_GREEN_SIZE, 8,
				GLX_BLUE_SIZE, 8,
				GLX_ALPHA_SIZE, 8,
				GLX_STENCIL_SIZE, 8,
				GLX_DEPTH_SIZE, 24,
				GLX_DOUBLEBUFFER, True,
				0
			};

			// Find all frame buffer configs
			FPL_LOG("GLX", "Get FrameBuffer Configs for Display '%p' and Screen '%d':", display, screen);
			int fbAllConfigCount = 0;
			GLXFBConfig *fbAllConfigs = glxApi.glXChooseFBConfig(display, screen, attributes, &fbAllConfigCount);

			if (!fbAllConfigs || !fbAllConfigCount) {
				FPL_LOG("GLX", "Failed getting FrameBuffer Configs from Display '%p' and Screen '%d'!", display, screen);
				return nullptr;
			}
			FPL_LOG("GLX", "Successfully got '%d' FrameBuffer Configs from Display '%p' and Screen '%d'", fbAllConfigCount, display, screen);

			XVisualInfo *foundVisualInfo = nullptr;
			GLXFBConfig foundFBConfig = nullptr;
			for (int fbConfigIndex = 0; fbConfigIndex < fbAllConfigCount; ++fbConfigIndex) {
				GLXFBConfig testFBConfig = fbAllConfigs[fbConfigIndex];

				// Get visual info from frame buffer config
				XVisualInfo *visualInfo = (XVisualInfo*)glxApi.glXGetVisualFromFBConfig(display, testFBConfig);
				if (!visualInfo) {
					continue;
				}

				// Get alpha bits
				int testAlphaBits = GLXGetFrameBufferConfigAttrib(glxApi, display, testFBConfig, GLX_ALPHA_SIZE);

				// Found a suitable frame buffer config with visual
				if (testAlphaBits > 0) {
					foundFBConfig = testFBConfig;
					foundVisualInfo = visualInfo;
					break;
				}

				// Release unused visual info (Important!)
				x11Api.XFree(visualInfo);
			}

			if (foundFBConfig != nullptr) {
				FPL_ASSERT(foundVisualInfo != nullptr);
				int doubleBuffer = GLXGetFrameBufferConfigAttrib(glxApi, display, foundFBConfig, GLX_DOUBLEBUFFER);
				int redBits = GLXGetFrameBufferConfigAttrib(glxApi, display, foundFBConfig, GLX_RED_SIZE);
				int greenBits = GLXGetFrameBufferConfigAttrib(glxApi, display, foundFBConfig, GLX_GREEN_SIZE);
				int blueBits = GLXGetFrameBufferConfigAttrib(glxApi, display, foundFBConfig, GLX_BLUE_SIZE);
				int alphaBits = GLXGetFrameBufferConfigAttrib(glxApi, display, foundFBConfig, GLX_ALPHA_SIZE);
				int depthBits = GLXGetFrameBufferConfigAttrib(glxApi, display, foundFBConfig, GLX_DEPTH_SIZE);
				int colorDepth = redBits + greenBits + blueBits + alphaBits;
				FPL_LOG("GLX", "Successfully found a suitable Frame Buffer Config (Doublebuffer: %s, Color bits: %d, Depth bits: %d) with Visual '%p'", (doubleBuffer == True ? "Yes" : "No"), colorDepth, depthBits, foundVisualInfo);
				result = foundVisualInfo;
			} else {
				FPL_LOG("GLX", "Failed finding a suitable Frame Buffer Config for Display '%p'!", display);
			}

			// Release frame buffer configs (Important!)
			x11Api.XFree(fbAllConfigs);

			return(result);
		}

		fpl_internal bool GLXGetWindowAttributes(const subplatform_x11::X11AppState &x11AppState, const subplatform_x11::X11WindowState &windowState, X11VideoOpenGLState &glState, subplatform_x11::X11WindowAttributesOutput &outAttributes) {
			const GLXApi &glxApi = glState.glxApi;
			const subplatform_x11::X11Api &x11Api = x11AppState.api;

			Display *display = windowState.display;
			Window root = windowState.root;
			int screen = windowState.screen;

			FPL_LOG("GLX", "Get Visual Info for Display '%p' and Screen '%d':", windowState.display, windowState.screen);
			XVisualInfo *visualInfo = GLXGetVisualInfo(x11AppState, glState, display, screen);
			if (visualInfo == nullptr) {
				FPL_LOG("GLX", "Failed getting Visual Info for Display '%p' and Screen '%d'!", windowState.display, windowState.screen);
				return false;
			}
			FPL_LOG("GLX", "Successfully got Visual Info '%p' for Display '%p' and Screen '%d'", windowState.display, windowState.screen, visualInfo);

			FPL_LOG("GLX", "Create Colormap on Display '%p' and Screen '%d'", display, screen);
			Colormap colorMap = x11Api.XCreateColormap(display, root, visualInfo->visual, AllocNone);

			outAttributes.visual = visualInfo->visual;
			outAttributes.colorMap = colorMap;
			outAttributes.colorDepth = visualInfo->depth;

			// @BAD(final): Really bad design here, a get function should not change anything at all
			glState.visualInfo = visualInfo;

			return(true);
		}

		fpl_internal bool X11InitVideoOpenGL(const subplatform_x11::X11AppState &x11AppState, const subplatform_x11::X11WindowState &windowState, X11VideoOpenGLState &glState) {
			const GLXApi &glxApi = glState.glxApi;

			glState.isActivated = false;

			if (glState.visualInfo == nullptr) {
				FPL_LOG("GLX", "VisualInfo was not set!");
				return false;
			}

			FPL_LOG("GLX", "Create Context for Display '%p' and VisualInfo '%p':", windowState.display, glState.visualInfo);
			glState.glxContext = glxApi.glXCreateContext(windowState.display, glState.visualInfo, nullptr, GL_TRUE);
			if (glState.glxContext == nullptr) {
				FPL_LOG("GLX", "Failed creating Context for Display '%p' and VisualInfo '%p'!", windowState.display, glState.visualInfo);
				return false;
			}
			FPL_LOG("GLX", "Successfully created Context for Display '%p' and VisualInfo '%p': %p", windowState.display, glState.visualInfo, glState.glxContext);

			FPL_LOG("GLX", "Activate Context for Display '%p' and Context '%p':", windowState.display, glState.glxContext);
			if (!glxApi.glXMakeCurrent(windowState.display, windowState.window, glState.glxContext)) {
				FPL_LOG("GLX", "Failed activating Context for Display '%p' and Context '%p'!", windowState.display, glState.glxContext);
				return false;
			}
			FPL_LOG("GLX", "Successfully activated Context for Display '%p' and Context '%p'", windowState.display, glState.glxContext);

			glState.isActivated = true;

			return true;
		}

		fpl_internal void X11ReleaseVideoOpenGL(const subplatform_x11::X11Api &x11Api, const subplatform_x11::X11WindowState &windowState, X11VideoOpenGLState &glState) {
			GLXApi &glxApi = glState.glxApi;
			if (glState.isActivated) {
				FPL_LOG("GLX", "Disable Context for Display '%p'", windowState.display);
				glxApi.glXMakeCurrent(windowState.display, 0L, nullptr);
				glState.isActivated = false;
			}
			if (glState.glxContext != nullptr) {
				FPL_LOG("GLX", "Destroy Context '%p' for Display '%p'", glState.glxContext, windowState.display);
				glxApi.glXDestroyContext(windowState.display, glState.glxContext);
				glState.glxContext = nullptr;
			}
			// @TODO(final): Do we want to free it before we destroy the context???
			if (glState.visualInfo != nullptr) {
				x11Api.XFree(glState.visualInfo);
				glState.visualInfo = nullptr;
			}
		}
	} // drivers

	namespace common_video {
		struct VideoState {
			drivers::X11VideoOpenGLState x11_opengl;
		};

		// @NOTE(final): The window has no access to the video driver directly, so we use callback to access it.
		fpl_internal FPL_FUNC_GET_WINDOW_ATTRIBUTES(DefaultGetWindowAttributes) {
			FPL_ASSERT(input.x11.appState != nullptr);
			FPL_ASSERT(input.x11.windowState != nullptr);
			VideoState *videoState = (VideoState *)input.video->mem;
			bool result = drivers::GLXGetWindowAttributes(*input.x11.appState, *input.x11.windowState, videoState->x11_opengl, output.x11);
			return(result);
		}
	} // common_video
} // fpl

int main(int argc, char *args[]) {
	int retCode = 0;

	// Allocate all state
	fpl::platform::PlatformAppState *appState = (fpl::platform::PlatformAppState *)malloc(sizeof(fpl::platform::PlatformAppState));
	memset(appState, 0, sizeof(fpl::platform::PlatformAppState));

	// Setup get window attributes callback and input
	fpl::platform::GetWindowAttributes_callback *getWinAttribsCallback = fpl::common_video::DefaultGetWindowAttributes;
	fpl::platform::WindowAttributesInput winAttribInput = {};
	winAttribInput.video = &appState->video;
	winAttribInput.x11.appState = &appState->x11;
	winAttribInput.x11.windowState = &appState->window.x11;

	// Init video state
	appState->video.size = sizeof(fpl::common_video::VideoState);
	appState->video.mem = malloc(appState->video.size);
	if (!appState->video.mem) {
		goto failed;
	}
	memset(appState->video.mem, 0, appState->video.size);
	fpl::common_video::VideoState *videoState = (fpl::common_video::VideoState *)appState->video.mem;

	// Load X11 library
	fpl::subplatform_x11::X11AppState &x11AppState = appState->x11;
	if (!fpl::subplatform_x11::X11InitSubplatform(x11AppState)) {
		goto failed;
	}

	// Load OpenGL library
	if (!fpl::drivers::LoadGLXApi(videoState->x11_opengl.glxApi)) {
		goto failed;
	}

	// Create window
	if (!fpl::subplatform_x11::X11InitWindow(getWinAttribsCallback, winAttribInput, appState->x11, appState->window.x11)) {
		goto failed;
	}

	// Create rendering context
	if (!fpl::drivers::X11InitVideoOpenGL(appState->x11, appState->window.x11, videoState->x11_opengl)) {
		goto failed;
	}

	// @TODO(final): Event loop!

	goto success;

failed:
	retCode = -1;
	goto release;

success:
	retCode = 0;
	goto release;

release:
	// Release rendering context
	if (videoState != nullptr) {
		fpl::drivers::X11ReleaseVideoOpenGL(appState->x11.api, appState->window.x11, videoState->x11_opengl);
	}

	// Release window
	fpl::subplatform_x11::X11ReleaseWindow(appState->x11, appState->window.x11);

	// Unload OpenGL library
	if (videoState != nullptr) {
		fpl::drivers::UnloadGLXApi(videoState->x11_opengl.glxApi);
	}

	// Unload X11 library
	fpl::subplatform_x11::UnloadX11Api(appState->x11.api);

	// Free app state
	free(appState);

	return retCode;
}

Edited by Finalspace on
Okay this is really confusing. I put the code into a main.cpp compiled it and it run without any issues - but had to first change the goto shit.

Running my library will compile as well, but segfaults at the end :-(
But more confusely the glGetString(GL_RENDERER) prints my correct graphics card (GeForce GTX 970/PCIe/SSE2) O_o

I put it on pastebin: https://pastebin.com/eCZGyvSr

Sigh, its such a nightmare programming C++ on linux -.-
Useless segfault stack trace, even the X11 error handler wont fire, every call returns proper values.

Here is the stacktrace:
1
2
3
4
5
6
7
8
#0 ??() at 
#1 ??() at /usr/lib/nvidia-384/libGL.so.1
#2 ??() at /usr/lib/nvidia-384/libGL.so.1
#3 _dl_fini() at /build/glibc-itYbWN/glibc-2.26/elf/dl-fini.c:240
#4 __run_exit_handlers() at /build/glibc-itYbWN/glibc-2.26/stdlib/exit.c:83
#5 __GI_exit() at /build/glibc-itYbWN/glibc-2.26/stdlib/exit.c:105
#6 __libc_start_main() at /build/glibc-itYbWN/glibc-2.26/csu/libc-start.c:342
#7 _start() at


If someone knows what this means, please write a post!

*Edit: I added a branch with the current state of the X11 implementation: https://github.com/f1nalspace/final_game_tech/tree/x11linux

Just check it out, go to the demos/FPL_ImGui folder and call make (There is a makefile).

Edited by Finalspace on
This most likely means memory corruption. You (or some library call you called incorrectly) corrupted memory that is used on program exit. Same thing can happen on Windows. This is not a Linux thing. You'll get "usless" stack traces also on Windows in such case. Imho developing on Linux is so much better than Windows. Look at many useful debugging capabilities - strace, ltrace, valgrind + sanitizers, etc...

I'm trying to run your code from pastebin now. Apart from few copy/paste mistakes (wtf on line 50-65) and wrong getenv declaration, I'm getting very weird behavior - dlopen on libX11.so returns NULL. Trying to figure out what is wrong with it.

Branch is not building for me. "make DEBUG=1" gives me "g++: error: fpl_imgui.cpp: No such file or directory"

Edit1: ok, figured out issue with pastebin code - first line should be deleted. COMPILE_ON_WIN should *NOT* be defined.
Edit2: Your pastebin code does not crash for me. On ArchLinux & nvidia.
Edit3: Code crashes on free(appState) when compiled with clang. But it seems clang simply exploited undefined behavior in your code - function ReleaseAppState does not return any value, although it should return int.

So your code does not crash for me with gcc or clang.

Btw your code to call XOpenDisplay is too complex. You don't need to lookup DISPLAY env variable. If you pass NULL to XOpenDisplay, it will do it for you.

Edited by Mārtiņš Možeiko on
mmozeiko

Branch is not building for me. "make DEBUG=1" gives me "g++: error: fpl_imgui.cpp: No such file or directory"


Fixed, please try again. I renamed the files recentnly but missed to add it to git.

No crash for me. Window is opened, closed and app shuts down cleanly.
mmozeiko
No crash for me. Window is opened, closed and app shuts down cleanly.


The FPL branch or the thing i posted on pastebin?
Both.