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

First of all modern Intel CPU does not care about 2/4/8 whatever alignment for regular instructions. That maybe was true 10 or 15 years ago. But nowadays you can read/write integer on 3-aligned address just fine without any performance penalty. For ARM CPUs its a bit more complicated, it depends on architecture. ARMv6 requires 4-aligned reads/writes (this is Raspberry 1 or Zero). By "requires" I mean it cannot do otherwise, it will fault if you will try it. But ARMv7 and up (Raspberry Pi 2/3, all smartphones) don't care about it same as Intel.

That said there can be performance penalty if read/write crosses cache line. But this penalty comes not because of unaligned read/write. It can happen if memory cache line is not cached - the CPU needs to fetch it from main memory. If it is already cached, then no problems.

Also i know that some data-structures needs to be specially aligned to make it work (Mat4 multiply on a struct with SIMD).
Not true for CPUs released in last 5 years or more. Starting with Sandy Bridge there is only a very tiny performance penalty when reading/writing unaligned memory. And for most ARM implementations it can read/write NEON registers from unaligned memory exactly with same speed.

And anyways, if you care about performance, you would load matrix into SSE registers and not access it from memory when doing your multiplies. So alignment for "matrix multiply" does not matter.

What does malloc() internally do, to not guarantee that the memory is aligned??
The docs says: "The malloc() and calloc() functions return a pointer to the allocated memory, which is suitably aligned for any built-in type.". Meaning that alignment may be 8-bytes, due to the fact that the greatest built-in type is double or what???
Yes, you understand correctly. It guarantees 8-alignment doe to max size type in C standard is "double". Actually glibc switched to 16-byte alignment at some point, but this is not documented and not guaranteed by standard.

Malloc internally maintains heap (that's why its called heap allocations). Special data structure that allows it to return memory much quicker (multiple orders of magnitude) than going to system memory allocator (VirtualAlloc/mmap). Also it does not waste much space. Each VirtualAlloc/mmap is returning 4kb multiple of memory. If you ask it to "allocate" 1 byte, it will still allocate 4kb. And return 4k aligned memory. Always. 4kb is a minimum, depending on OS it can be bigger. Not sure about Windows, but on Linux kernel can be easily configured to use 16kb or 32kb pages, or whatever power-of-two size page size: https://elixir.bootlin.com/linux/...ce/include/asm-generic/page.h#L14

Here's simple implementation of heap allocator: https://github.com/mattconte/tlsf You provide it space (from system allocator or just global .bss), and it will split it to support smaller and faster allocations.

C aligned_malloc does pretty much same thing as your code (or your pascal fragment). Allocate a bit more to fit extra headers, and return aligned pointer.

Here's simple implementation in musl C library: https://git.musl-libc.org/cgit/musl/tree/src/malloc/memalign.c
glibc aligned malloc is here: https://github.com/bminor/glibc/blob/master/malloc/malloc.c#L3260 A bit more code, but same thing.
MSVC implementation is in "C:\Program Files (x86)\Windows Kits\10\Source\10.0.16299.0\ucrt\heap\align.cpp" file, look for _aligned_offset_malloc_base function.

Edited by Mārtiņš Možeiko on
mmozeiko
First of all modern Intel CPU does not care about 2/4/8 whatever alignment for regular instructions. That maybe was true 10 or 15 years ago. But nowadays you can read/write integer on 3-aligned address just fine without any performance penalty. For ARM CPUs its a bit more complicated, it depends on architecture. ARMv6 requires 4-aligned reads/writes (this is Raspberry 1 or Zero). By "requires" I mean it cannot do otherwise, it will fault if you will try it. But ARMv7 and up (Raspberry Pi 2/3, all smartphones) don't care about it same as Intel.

That said there can be performance penalty if read/write crosses cache line. But this penalty comes not because of unaligned read/write. It can happen if memory cache line is not cached - the CPU needs to fetch it from main memory. If it is already cached, then no problems.

Also i know that some data-structures needs to be specially aligned to make it work (Mat4 multiply on a struct with SIMD).
Not true for CPUs released in last 5 years or more. Starting with Sandy Bridge there is only a very tiny performance penalty when reading/writing unaligned memory. And for most ARM implementations it can read/write NEON registers from unaligned memory exactly with same speed.

And anyways, if you care about performance, you would load matrix into SSE registers and not access it from memory when doing your multiplies. So alignment for "matrix multiply" does not matter.

What does malloc() internally do, to not guarantee that the memory is aligned??
The docs says: "The malloc() and calloc() functions return a pointer to the allocated memory, which is suitably aligned for any built-in type.". Meaning that alignment may be 8-bytes, due to the fact that the greatest built-in type is double or what???
Yes, you understand correctly. It guarantees 8-alignment doe to max size type in C standard is "double". Actually glibc switched to 16-byte alignment at some point, but this is not documented and not guaranteed by standard.

Malloc internally maintains heap (that's why its called heap allocations). Special data structure that allows it to return memory much quicker (multiple orders of magnitude) than going to system memory allocator (VirtualAlloc/mmap). Also it does not waste much space. Each VirtualAlloc/mmap is returning 4kb multiple of memory. If you ask it to "allocate" 1 byte, it will still allocate 4kb. And return 4k aligned memory. Always. 4kb is a minimum, depending on OS it can be bigger. Not sure about Windows, but on Linux kernel can be easily configured to use 16kb or 32kb pages, or whatever power-of-two size page size: https://elixir.bootlin.com/linux/...ce/include/asm-generic/page.h#L14

Here's simple implementation of heap allocator: https://github.com/mattconte/tlsf You provide it space (from system allocator or just global .bss), and it will split it to support smaller and faster allocations.

C aligned_malloc does pretty much same thing as your code (or your pascal fragment). Allocate a bit more to fit extra headers, and return aligned pointer.

Here's simple implementation in musl C library: https://git.musl-libc.org/cgit/musl/tree/src/malloc/memalign.c
glibc aligned malloc is here: https://github.com/bminor/glibc/blob/master/malloc/malloc.c#L3260 A bit more code, but same thing.
MSVC implementation is in "C:\Program Files (x86)\Windows Kits\10\Source\10.0.16299.0\ucrt\heap\align.cpp" file, look for _aligned_offset_malloc_base function.


Okay thanks for finding out the sources. That clears it up for the most port.

Regarding the matrix multiply and SSE registers. I actually do this. I have a float array in my struct then i load it into a register using _mm_load_ps() and then work with it and then store it back to the float array.

Without defining any struct alignment this crashes immediatly on my machine. So i had to do this:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
__declspec(align(16)) union Mat4f {
	struct {
		Vec4f col1;
		Vec4f col2;
		Vec4f col3;
		Vec4f col4;
	};
	struct {
		f32 elements[4][4];
	};
	f32 m[16];
};


I think that if you use VirtualAlloc to get some memory, windows uses 64 KB chunks. If you ask for 4K, there will be 60 KB of unused memory. Those videos cover the memory management of Windows and may give you additional information.
You can use _mm_loadu_ps to load them without any alignment requirements. On modern machine you won't notice any significant performance penalty.

Be careful with unions though. Compilers tend to generate suboptimial code when you stick SSE types and regular types in same union. Here's one way how to deal with them (with C++ templates): http://codrspace.com/t0rakka/simd-scalar-accessor/


Yeah, totally forgot 64KB for VirtualAlloc. That's even more wasted space if you don't implement some kind of allocator (heap/stack/arena/whatever) on top of it.

Edited by Mārtiņš Možeiko on
mrmixer
I think that if you use VirtualAlloc to get some memory, windows uses 64 KB chunks. If you ask for 4K, there will be 60 KB of unused memory. Those videos cover the memory management of Windows and may give you additional information.


Thanks for that resource, i will definitly check that out.

Now regarding FPL:

I fixed compiler-errors on the x11linux branch, seems that i broke something....
The X11 GLX segfault still happens, but i am planning to rewrite the X11/GLX implementation completely with a much more sane Visual and XVisualInfo cache. Hopefully then it wont segfault.

Also i highly changed the way FPL handles memory, now there is only two memory allocations which happens inside FPL: The app state structure and the pixels for the software pixel buffer.

Regarding the MemoryAlignedAllocate, i will leave it in there, it does not hurt, isnt´t it?

*Edit: Oh and one last question, does someone have experience with CLion from Jetbrains?
My last attempt was rather failure, due to the fact that CLion had no way to search for a function/type at all. It seems to can only search for classes and shit. Also i didnt´t like that it forces me to use CMake :-(

Right know i am using KDevelop, but i am really unhappy with it because it has several issues: The search for functions of types is pretty much useless - as soon as i rename something the parser wont catch up and does not find anything at all. So i can just use basic string search using Ctrl+F etc.

Really want i want is a GExperts extreme fast filter which i had 15 years ago, when i was programming in borland delphi 5. Visual studio has something similar, but there is a bug that the filter cannot search in the open document only and its much much slower :-(

Edited by Finalspace on
Bad news:

It still does not work, i have rewritten the X11/GLX implementation in a slightly different way buts its still segfaulting :-(

What the hell is wrong? I still havent figured it out yet, i debugged it for hours and havent found anything which looks like a culprit.

I really need some help.

I x11linux branch has the broken implementation. Just compile the FPL_ImGUI demo which is stripped down to just initialize and finalization.

Edited by Finalspace on
Your branch works fine on two of my machines. No crash, no error. Just bunch of log when excuting imgui demo. Demo exits cleanly.

1) desktop with NVidia Quadro 4000

2) laptop with NVidia GTX 1060

Both on ArchLinux. Linux kernel version 4.15.10, nvidia driver version 390.42. Mesa version (probably not relevant) 17.3.6.
Code compiled with gcc 7.3.1 (20180312).

What hw/OS are you running on?

Edited by Mārtiņš Možeiko on
mmozeiko
Your branch works fine on two of my machines. No crash, no error. Just bunch of log when excuting imgui demo. Demo exits cleanly.

1) desktop with NVidia Quadro 4000

2) laptop with NVidia GTX 1060

Both on ArchLinux. Linux kernel version 4.15.10, nvidia driver version 390.42. Mesa version (probably not relevant) 17.3.6.
Code compiled with gcc 7.3.1 (20180312).

What hw/OS are you running on?


I am running ubuntu 17.10. Thats the only linux distro which works on my machine (i7 4790k, GTX 970).
Every other binary distro i tried crashes while booting the live or installer cd/dvd (ACPI issue). Which GCC or driver i cannot look right know, because i am at work. Gentoo and arch booted just fine, but i dont want to spend many evenings just to get a linux up and running.

Weirdly enough your snipped you uploaded works without a crash on my machine O_o

Edited by Finalspace on
I removed the caching of the XVisualInfo and release the visual info immediatly after it was used.
The only which i need to cache is the GLXFBConfig - which is cached in all major platform libraries as well (SDL, SFML, GLUT, GLFW, etc.).

Branch is updated.

Also my linux system is very unstable, sometimes i get random kernel crashes - without any way to recover.
But all the simple X11/GLX implementation/amples i tested work without any problems. Glut/SDL/GLFW works as well.

There is something special in my implementation which crashes my opengl driver :-(
So i expect this may crash on other drivers/systems as well, but i want this thing to be stable rock solid, so i cannot leave it like this.

Regarding the nvidia driver version:

glxinfo:

 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
name of display: :1
display: :1  screen: 0
direct rendering: Yes
server glx vendor string: NVIDIA Corporation
server glx version string: 1.4
server glx extensions:
    GLX_ARB_context_flush_control, GLX_ARB_create_context,
    GLX_ARB_create_context_profile, GLX_ARB_create_context_robustness,
    GLX_ARB_fbconfig_float, GLX_ARB_multisample, GLX_EXT_buffer_age,
    GLX_EXT_create_context_es2_profile, GLX_EXT_create_context_es_profile,
    GLX_EXT_framebuffer_sRGB, GLX_EXT_import_context, GLX_EXT_libglvnd,
    GLX_EXT_stereo_tree, GLX_EXT_swap_control, GLX_EXT_swap_control_tear,
    GLX_EXT_texture_from_pixmap, GLX_EXT_visual_info, GLX_EXT_visual_rating,
    GLX_NV_copy_image, GLX_NV_delay_before_swap, GLX_NV_float_buffer,
    GLX_NV_robustness_video_memory_purge, GLX_SGIX_fbconfig, GLX_SGIX_pbuffer,
    GLX_SGI_swap_control, GLX_SGI_video_sync
client glx vendor string: NVIDIA Corporation
client glx version string: 1.4
client glx extensions:
    GLX_ARB_context_flush_control, GLX_ARB_create_context,
    GLX_ARB_create_context_profile, GLX_ARB_create_context_robustness,
    GLX_ARB_fbconfig_float, GLX_ARB_get_proc_address, GLX_ARB_multisample,
    GLX_EXT_buffer_age, GLX_EXT_create_context_es2_profile,
    GLX_EXT_create_context_es_profile, GLX_EXT_fbconfig_packed_float,
    GLX_EXT_framebuffer_sRGB, GLX_EXT_import_context, GLX_EXT_stereo_tree,
    GLX_EXT_swap_control, GLX_EXT_swap_control_tear,
    GLX_EXT_texture_from_pixmap, GLX_EXT_visual_info, GLX_EXT_visual_rating,
    GLX_NV_copy_buffer, GLX_NV_copy_image, GLX_NV_delay_before_swap,
    GLX_NV_float_buffer, GLX_NV_multisample_coverage, GLX_NV_present_video,
    GLX_NV_robustness_video_memory_purge, GLX_NV_swap_group,
    GLX_NV_video_capture, GLX_NV_video_out, GLX_SGIX_fbconfig,
    GLX_SGIX_pbuffer, GLX_SGI_swap_control, GLX_SGI_video_sync
GLX version: 1.4
GLX extensions:
    GLX_ARB_context_flush_control, GLX_ARB_create_context,
    GLX_ARB_create_context_profile, GLX_ARB_create_context_robustness,
    GLX_ARB_fbconfig_float, GLX_ARB_get_proc_address, GLX_ARB_multisample,
    GLX_EXT_buffer_age, GLX_EXT_create_context_es2_profile,
    GLX_EXT_create_context_es_profile, GLX_EXT_framebuffer_sRGB,
    GLX_EXT_import_context, GLX_EXT_stereo_tree, GLX_EXT_swap_control,
    GLX_EXT_swap_control_tear, GLX_EXT_texture_from_pixmap,
    GLX_EXT_visual_info, GLX_EXT_visual_rating, GLX_NV_copy_image,
    GLX_NV_delay_before_swap, GLX_NV_float_buffer,
    GLX_NV_robustness_video_memory_purge, GLX_SGIX_fbconfig, GLX_SGIX_pbuffer,
    GLX_SGI_swap_control, GLX_SGI_video_sync


Any other idea?

Edited by Finalspace on
That's glxinfo. For nvidia driver info try "nvidia-smi".
You nave name of display ":1" ? What happened to :0 ? Are you running multiple X11 servers? Wayland?

Edited by Mārtiņš Možeiko on
mmozeiko
That's glxinfo. For nvidia driver info try "nvidia-smi".
You nave name of display ":1" ? What happened to :0 ? Are you running multiple X11 servers? Wayland?


No idea, its a default ubuntu 17.10 installation.

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
final@final-i7:~$ nvidia-smi 
Thu Mar 22 19:39:12 2018       
+-----------------------------------------------------------------------------+
| NVIDIA-SMI 384.111                Driver Version: 384.111                   |
|-------------------------------+----------------------+----------------------+
| GPU  Name        Persistence-M| Bus-Id        Disp.A | Volatile Uncorr. ECC |
| Fan  Temp  Perf  Pwr:Usage/Cap|         Memory-Usage | GPU-Util  Compute M. |
|===============================+======================+======================|
|   0  GeForce GTX 970     Off  | 00000000:01:00.0  On |                  N/A |
|  0%   32C    P0    50W / 200W |    336MiB /  4034MiB |      0%      Default |
+-------------------------------+----------------------+----------------------+
                                                                               
+-----------------------------------------------------------------------------+
| Processes:                                                       GPU Memory |
|  GPU       PID   Type   Process name                             Usage      |
|=============================================================================|
|    0       988      G   /usr/lib/xorg/Xorg                            16MiB |
|    0      1043      G   /usr/bin/gnome-shell                          52MiB |
|    0      1305      G   /usr/lib/xorg/Xorg                           111MiB |
|    0      1433      G   /usr/bin/gnome-shell                          76MiB |
|    0      1819      G   ...-token=80B7115FD44AA707D1FBCFCDFDE322BE    75MiB |
+-----------------------------------------------------------------------------+

Edited by Finalspace on
Oh i may have found the issue. One or more function prototypes for X11/GLX seems to be wrong (I load X11 and GLX dynamically). Or i load the wrong library.

I changed it to static linking and it works without crashing!

Edited by Finalspace on
Right. That could be an issue.
NVidia has super hacky OpenGL implementation on Linux. That's why this video exists :)

Normally glx is in /usr/lib/libGLX.so. But nvidia's one is /usr/lib/nvidia/xorg/libglx.so (at least on my Arch).
So they do a lot of hacks to redirect it to correct one. This is what I have on my Arch:
1
2
3
4
/usr/lib/libGLX_nvidia.so
/usr/lib/libGLX_mesa.so.0
/usr/lib/libGLX_indirect.so.0
/usr/lib/libGLX.so


It gets even more complicated if you are on "Optimus" laptop where nvidia GPU can be disabled to save power. I'm not sure how GL/GLX libraries work in this case, but I suspect they get preloaded into your process with optirun/primusrun. So dynamically loading will mess up everything.

Recently it got a bit better with GLVND infrastructure:
https://devtalk.nvidia.com/defaul...a-linux-driver-installer-package/
https://www.x.org/wiki/Events/XDC...Program/xdc-2016-glvnd-status.pdf
But its a mess nonetheless.



Edited by Mārtiņš Možeiko on
I finally found the issue. I was loading the wrong opengl driver!

- libGLX.so is wrong on my machine
- libGL.so does not work on my machine

The only library which works is "libGL.so.1".

Finally...

Is there a way to detect such crappy drivers, so i can try the next one in the list?

Edited by Finalspace on
Short update

Good news people, i am switching to C99. I got sick of all the namespace typing nonsense.

The only thing i am unsure of how to name the internal types and functions.
I cannot begin any type or function name with an underscore, this is reserved for the compiler.
But i dont want people to accidentally call the internal function. So it should be marked clearly.

What about fpl__NameOfInternalTypeOrFunction?

Here is my current public api C99 draft:

   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
 823
 824
 825
 826
 827
 828
 829
 830
 831
 832
 833
 834
 835
 836
 837
 838
 839
 840
 841
 842
 843
 844
 845
 846
 847
 848
 849
 850
 851
 852
 853
 854
 855
 856
 857
 858
 859
 860
 861
 862
 863
 864
 865
 866
 867
 868
 869
 870
 871
 872
 873
 874
 875
 876
 877
 878
 879
 880
 881
 882
 883
 884
 885
 886
 887
 888
 889
 890
 891
 892
 893
 894
 895
 896
 897
 898
 899
 900
 901
 902
 903
 904
 905
 906
 907
 908
 909
 910
 911
 912
 913
 914
 915
 916
 917
 918
 919
 920
 921
 922
 923
 924
 925
 926
 927
 928
 929
 930
 931
 932
 933
 934
 935
 936
 937
 938
 939
 940
 941
 942
 943
 944
 945
 946
 947
 948
 949
 950
 951
 952
 953
 954
 955
 956
 957
 958
 959
 960
 961
 962
 963
 964
 965
 966
 967
 968
 969
 970
 971
 972
 973
 974
 975
 976
 977
 978
 979
 980
 981
 982
 983
 984
 985
 986
 987
 988
 989
 990
 991
 992
 993
 994
 995
 996
 997
 998
 999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
2181
2182
2183
2184
2185
2186
2187
2188
2189
2190
2191
2192
2193
2194
2195
2196
2197
2198
2199
2200
2201
2202
2203
2204
2205
2206
2207
2208
2209
2210
2211
2212
2213
2214
2215
2216
2217
2218
2219
2220
2221
2222
2223
2224
2225
2226
2227
2228
2229
2230
2231
2232
2233
2234
2235
2236
2237
2238
2239
2240
2241
2242
2243
2244
2245
2246
2247
2248
2249
2250
2251
2252
2253
2254
2255
2256
2257
2258
2259
2260
2261
2262
2263
2264
2265
2266
2267
2268
2269
2270
2271
2272
2273
2274
2275
2276
2277
2278
2279
2280
2281
2282
2283
2284
2285
2286
2287
2288
2289
2290
2291
2292
2293
2294
2295
2296
2297
2298
2299
2300
2301
2302
2303
2304
2305
2306
2307
2308
2309
2310
2311
2312
2313
2314
2315
2316
2317
2318
2319
2320
2321
2322
2323
2324
2325
2326
2327
2328
2329
2330
2331
2332
2333
2334
2335
2336
2337
2338
2339
2340
2341
2342
2343
2344
2345
2346
2347
2348
2349
2350
2351
2352
2353
2354
2355
2356
2357
2358
2359
2360
2361
2362
2363
2364
2365
2366
2367
2368
2369
2370
2371
2372
2373
2374
2375
2376
2377
2378
2379
2380
2381
2382
2383
2384
2385
2386
2387
2388
2389
2390
2391
2392
2393
2394
2395
2396
2397
2398
2399
2400
2401
2402
2403
2404
2405
2406
2407
2408
2409
2410
2411
2412
2413
2414
2415
2416
2417
2418
2419
2420
2421
2422
2423
2424
2425
2426
2427
2428
2429
2430
2431
2432
2433
2434
2435
2436
2437
2438
2439
2440
2441
2442
2443
2444
2445
2446
2447
2448
2449
2450
2451
2452
2453
2454
2455
2456
2457
2458
2459
2460
2461
2462
2463
2464
2465
2466
2467
2468
2469
2470
2471
2472
2473
2474
2475
2476
2477
2478
2479
2480
2481
2482
2483
2484
2485
2486
2487
2488
2489
2490
2491
2492
2493
2494
2495
2496
2497
2498
2499
2500
2501
2502
2503
2504
2505
2506
2507
2508
2509
2510
2511
2512
2513
2514
2515
2516
2517
2518
2519
2520
2521
2522
2523
2524
2525
2526
2527
2528
2529
2530
2531
2532
2533
2534
2535
2536
2537
2538
2539
2540
2541
2542
2543
2544
2545
2546
2547
2548
2549
2550
2551
2552
2553
2554
2555
2556
2557
2558
2559
2560
2561
2562
2563
2564
2565
2566
2567
2568
2569
2570
2571
2572
2573
2574
2575
2576
2577
2578
2579
2580
2581
2582
2583
2584
2585
2586
2587
2588
2589
2590
2591
2592
2593
2594
2595
2596
2597
2598
2599
2600
2601
2602
2603
2604
2605
2606
2607
2608
2609
2610
2611
2612
2613
2614
2615
2616
2617
2618
2619
2620
2621
2622
2623
2624
2625
2626
2627
2628
2629
2630
2631
2632
2633
2634
2635
2636
2637
2638
2639
2640
2641
2642
2643
2644
2645
2646
2647
2648
2649
2650
2651
2652
2653
2654
2655
2656
2657
2658
2659
2660
2661
2662
// ****************************************************************************
//
// > HEADER
//
// ****************************************************************************
#ifndef FPL_INCLUDE_H
#define FPL_INCLUDE_H

// C99 detection
#if defined(__cplusplus) || (defined(__cplusplus) && defined(_MSC_VER) && _MSC_VER >= 1900)
#	define FPL_IS_CPP
#elif (defined(__STDC_VERSION__) && (__STDC_VERSION__ >= 199901L)) || (defined(_MSC_VER) && _MSC_VER >= 1900)
#	define FPL_IS_C99
#else
#	error "This C/C++ compiler is not supported!"
#endif

//
// Platform detection
//
// https://sourceforge.net/p/predef/wiki/OperatingSystems/
#if defined(_WIN32) || defined(_WIN64)
#	define FPL_PLATFORM_WIN32
#	define FPL_PLATFORM_NAME "Windows"
#	define FPL_SUBPLATFORM_STD_CONSOLE
#elif defined(__linux__) || defined(__gnu_linux__)
#	define FPL_PLATFORM_LINUX
#	define FPL_PLATFORM_NAME "Linux"
#	define FPL_SUBPLATFORM_POSIX
#	define FPL_SUBPLATFORM_X11
#	define FPL_SUBPLATFORM_STD_STRINGS
#	define FPL_SUBPLATFORM_STD_CONSOLE
#elif defined(__FreeBSD__) || defined(__NetBSD__) || defined(__OpenBSD__) || defined(__DragonFly__) || defined(__bsdi__)
#	define FPL_PLATFORM_BSD
#	define FPL_PLATFORM_NAME "BSD"
#	define FPL_SUBPLATFORM_POSIX
#	define FPL_SUBPLATFORM_X11
#	define FPL_SUBPLATFORM_STD_STRINGS
#	define FPL_SUBPLATFORM_STD_CONSOLE
#	error "Not implemented yet!"
#elif defined(unix) || defined(__unix) || defined(__unix__)
#	define FPL_PLATFORM_UNIX
#	define FPL_PLATFORM_NAME "Unix"
#	define FPL_SUBPLATFORM_POSIX
#	define FPL_SUBPLATFORM_X11
#	define FPL_SUBPLATFORM_STD_STRINGS
#	define FPL_SUBPLATFORM_STD_CONSOLE
#	error "Not implemented yet!"
#else
#	error "This platform is not supported!"
#endif // FPL_PLATFORM

//
// Architecture detection (x86, x64)
// See: https://sourceforge.net/p/predef/wiki/Architectures/
//
#if defined(_M_X64) || defined(__x86_64__) || defined(__amd64__)
#	define FPL_ARCH_X64
#elif defined(_M_IX86) || defined(__i386__) || defined(__X86__) || defined(_X86_)
#	define FPL_ARCH_X86
#elif defined(__arm__) || defined(_M_ARM)
#	if defined(__aarch64__)
#		define FPL_ARCH_ARM64
#	else	
#		define FPL_ARCH_ARM32
#	endif
#else
#	error "This architecture is not supported!"
#endif // FPL_ARCH

//
// Build configuration and compilers
// See: http://beefchunk.com/documentation/lang/c/pre-defined-c/precomp.html
// See: http://nadeausoftware.com/articles/2012/10/c_c_tip_how_detect_compiler_name_and_version_using_compiler_predefined_macros
//
#if defined(__clang__)
	//! CLANG compiler detected
#	define FPL_COMPILER_CLANG
#elif defined(__llvm__)
	//! LLVM compiler detected
#	define FPL_COMPILER_LLVM
#elif defined(__INTEL_COMPILER)
	//! Intel compiler detected
#	define FPL_COMPILER_INTEL
#elif defined(__MINGW32__)
	//! MingW compiler detected
#	define FPL_COMPILER_MINGW
#elif defined(__GNUC__) && !defined(__clang__)
	//! GCC compiler detected
#	define FPL_COMPILER_GCC
#elif defined(_MSC_VER)
	//! Visual studio compiler detected
#	define FPL_COMPILER_MSVC
#else
	//! No compiler detected
#	define FPL_COMPILER_UNKNOWN
#endif // FPL_COMPILER

//
// Compiler depended settings and detections
//
#if defined(FPL_COMPILER_MSVC)
	//! Disable noexcept compiler warning for C++
#	pragma warning( disable : 4577 )
	//! Disable "switch statement contains 'default' but no 'case' labels" compiler warning for C++
#	pragma warning( disable : 4065 )

#	if defined(_DEBUG) || (!defined(NDEBUG))
		//! Debug mode detected
#		define FPL_ENABLE_DEBUG
#	else
		//! Non-debug (Release) mode detected
#		define FPL_ENABLE_RELEASE
#	endif

	//! Function name macro (Win32)
#   define FPL_FUNCTION_NAME __FUNCTION__
#else
	// @NOTE(final): Expect all other compilers to pass in FPL_DEBUG manually
#	if defined(FPL_DEBUG)
		//! Debug mode detected
#		define FPL_ENABLE_DEBUG
#	else
		//! Non-debug (Release) mode detected
#		define FPL_ENABLE_RELEASE
#	endif

	//! Function name macro (Other compilers)
#   define FPL_FUNCTION_NAME __FUNCTION__
#endif // FPL_COMPILER

//
// Options & Feature detection
//

// Assertions
#if !defined(FPL_NO_ASSERTIONS)
#	if !defined(FPL_FORCE_ASSERTIONS)
#		if defined(FPL_ENABLE_DEBUG)
			//! Enable Assertions in Debug Mode by default
#			define FPL_ENABLE_ASSERTIONS
#		endif
#	else
		//! Enable Assertions always
#		define FPL_ENABLE_ASSERTIONS
#	endif
#endif // !FPL_NO_ASSERTIONS
#if defined(FPL_ENABLE_ASSERTIONS)
#	if !defined(FPL_NO_C_ASSERT)
		//! Enable C-Runtime Assertions by default
#		define FPL_ENABLE_C_ASSERT
#	endif
#endif // FPL_ENABLE_ASSERTIONS

// Window
#if !defined(FPL_NO_WINDOW)
	//! Window support enabled by default
#	define FPL_SUPPORT_WINDOW
#endif

// Video
#if !defined(FPL_NO_VIDEO)
	//! Video support
#	define FPL_SUPPORT_VIDEO
#endif
#if defined(FPL_SUPPORT_VIDEO)
#	if !defined(FPL_NO_VIDEO_OPENGL)
		//! OpenGL support enabled by default
#		define FPL_SUPPORT_VIDEO_OPENGL
#	endif
#	if !defined(FPL_NO_VIDEO_SOFTWARE)
		//! Software rendering support enabled by default
#		define FPL_SUPPORT_VIDEO_SOFTWARE
#	endif
#endif // FPL_SUPPORT_VIDEO

// Audio
#if !defined(FPL_NO_AUDIO)
	//! Audio support
#	define FPL_SUPPORT_AUDIO
#endif
#if defined(FPL_SUPPORT_AUDIO)
#	if !defined(FPL_NO_AUDIO_DIRECTSOUND) && defined(FPL_PLATFORM_WIN32)
		//! DirectSound support is only available on Win32
#		define FPL_SUPPORT_AUDIO_DIRECTSOUND
#	endif
#endif // FPL_SUPPORT_AUDIO

// Remove video support when window is disabled
#if !defined(FPL_SUPPORT_WINDOW)
#	if defined(FPL_SUBPLATFORM_X11)
#		undef FPL_SUBPLATFORM_X11
#	endif

#	if defined(FPL_SUPPORT_VIDEO)
#		undef FPL_SUPPORT_VIDEO
#	endif
#	if defined(FPL_SUPPORT_VIDEO_OPENGL)
#		undef FPL_SUPPORT_VIDEO_OPENGL
#	endif
#	if defined(FPL_SUPPORT_VIDEO_SOFTWARE)
#		undef FPL_SUPPORT_VIDEO_SOFTWARE
#	endif
#endif // !FPL_SUPPORT_WINDOW

//
// Enable supports (FPL uses _ENABLE_ internally only)
//
#if defined(FPL_SUPPORT_WINDOW)
	//! Enable Window
#	define FPL_ENABLE_WINDOW
#endif
#if defined(FPL_SUPPORT_VIDEO)
	//! Enable Video
#	define FPL_ENABLE_VIDEO
#	if defined(FPL_SUPPORT_VIDEO_OPENGL)
		//! Enable OpenGL Video
#		define FPL_ENABLE_VIDEO_OPENGL
#	endif
#	if defined(FPL_SUPPORT_VIDEO_SOFTWARE)
		//! Enable Software Rendering Video
#		define FPL_ENABLE_VIDEO_SOFTWARE
#	endif
#endif // FPL_SUPPORT_VIDEO
#if defined(FPL_SUPPORT_AUDIO)
	//! Enable Audio
#	define FPL_ENABLE_AUDIO
#	if defined(FPL_SUPPORT_AUDIO_DIRECTSOUND)
		//! Enable DirectSound Audio
#		define FPL_ENABLE_AUDIO_DIRECTSOUND
#	endif
#endif // FPL_SUPPORT_AUDIO

#if !defined(FPL_NO_ERROR_IN_CONSOLE)
	//! Write errors in console
#	define FPL_ENABLE_ERROR_IN_CONSOLE
#endif
#if !defined(FPL_NO_MULTIPLE_ERRORSTATES)
	//! Allow multiple error states
#	define FPL_ENABLE_MULTIPLE_ERRORSTATES
#endif
#if defined(FPL_AUTO_NAMESPACE)
	//! Expand namespaces at the header end always
#	define FPL_ENABLE_AUTO_NAMESPACE
#endif

//
// Static/Inline/Extern/Internal
//
//! Global persistent variable
#define fpl_globalvar static
//! Local persistent variable
#define fpl_localvar static
//! Private/Internal function
#define fpl_internal static
//! Inline function
#define fpl_inline inline
//! Internal inlined function
#define fpl_internal_inline inline
//! Null
#define fpl_null '\0'

#if defined(FPL_API_AS_PRIVATE)
	//! Private api call
#	define fpl_api static
#else
	//! Public api call
#	define fpl_api extern
#endif // FPL_API_AS_PRIVATE

//! Platform api definition
#define fpl_platform_api fpl_api
//! Common api definition
#define fpl_common_api fpl_api
//! Main entry point api definition
#define fpl_main

//
// Assertions
//
#if defined(FPL_ENABLE_ASSERTIONS)
#	if defined(FPL_ENABLE_C_ASSERT) && !defined(FPL_FORCE_ASSERTIONS)
#		include <assert.h>
		//! Runtime assert (C Runtime)
#		define FPL_ASSERT(exp) assert(exp)
		//! Compile error assert (C Runtime)
#		define FPL_STATICASSERT(exp) static_assert(exp, "static_assert")
#	else
		//! Runtime assert
#		define FPL_ASSERT(exp) if(!(exp)) {*(int *)0 = 0;}
		//! Compile error assert
#		define FPL_STATICASSERT_(exp, line) \
			int fpl_static_assert_##line(int static_assert_failed[(exp)?1:-1])
#		define FPL_STATICASSERT(exp) \
			FPL_STATICASSERT_(exp, __LINE__)
#	endif // FPL_ENABLE_C_ASSERT
#else
	//! Runtime assertions disabled
#	define FPL_ASSERT(exp)
	//! Compile time assertions disabled
#	define FPL_STATICASSERT(exp)
#endif // FPL_ENABLE_ASSERTIONS

//! This will full-on crash when something is not implemented always.
#define FPL_NOT_IMPLEMENTED {*(int *)0 = 0xBAD;}

//
// Logging
//
#if defined(FPL_LOGGING)
	//! Enable logging
#   define FPL_ENABLE_LOGGING
#endif

//
// Types & Limits
//
#include <stdint.h> // uint32_t, ...
#include <stddef.h> // size_t
#include <stdlib.h> // UINT32_MAX, ...
#include <stdbool.h> // bool

//
// Macro functions
//
//! Macro for initialize a struct to zero
#if defined(FPL_IS_C99)
#	define FPL_STRUCT_ZERO {0}
#else
#	define FPL_STRUCT_ZERO {}
#endif


//! Returns the element count from a static array,
#define FPL_ARRAYCOUNT(arr) (sizeof(arr) / sizeof((arr)[0]))

//! Returns the offset in bytes to a field in a structure
#define FPL_OFFSETOF(type, field) ((size_t)(&(((type*)(0))->field)))

//! Returns the offset for the value to satisfy the given alignment boundary
#define FPL_ALIGNMENT_OFFSET(value, alignment) ( (((alignment) > 1) && (((value) & ((alignment) - 1)) != 0)) ? ((alignment) - ((value) & (alignment - 1))) : 0)           
//! Returns the given size extended o to satisfy the given alignment boundary
#define FPL_ALIGNED_SIZE(size, alignment) (((size) > 0 && (alignment) > 0) ? ((size) + FPL_ALIGNMENT_OFFSET(size, alignment)) : (size))
//! Returns true when the given pointer address is aligned to the given alignment
#define FPL_IS_ALIGNED(ptr, alignment) (((uintptr_t)(const void *)(ptr)) % (alignment) == 0)

//! Returns the smallest value
#define FPL_MIN(a, b) ((a) < (b)) ? (a) : (b)
//! Returns the biggest value
#define FPL_MAX(a, b) ((a) > (b)) ? (a) : (b)

//! Returns the number of bytes for the given kilobytes
#define FPL_KILOBYTES(value) (((value) * 1024ull))
//! Returns the number of bytes for the given megabytes
#define FPL_MEGABYTES(value) ((FPL_KILOBYTES(value) * 1024ull))
//! Returns the number of bytes for the given gigabytes
#define FPL_GIGABYTES(value) ((FPL_MEGABYTES(value) * 1024ull))
//! Returns the number of bytes for the given terabytes
#define FPL_TERABYTES(value) ((FPL_GIGABYTES(value) * 1024ull))

//! Manually allocate memory on the stack (Use this with care!)
#define FPL_STACKALLOCATE(size) _alloca(size)

// ****************************************************************************
// ****************************************************************************
//
// Platform includes
//
// ****************************************************************************
// ****************************************************************************
#if defined(FPL_PLATFORM_WIN32)
// @NOTE(final): windef.h defines min/max macros defined in lowerspace, this will break for example std::min/max so we have to tell the header we dont want this!
#	if !defined(NOMINMAX)
#		define NOMINMAX
#	endif
// @NOTE(final): For now we dont want any network, com or gdi stuff at all, maybe later who knows.
#	if !defined(WIN32_LEAN_AND_MEAN)
#		define WIN32_LEAN_AND_MEAN 1
#	endif
#	include <windows.h>		// Win32 api, its unfortunate we have to include this in the header as well, but there are structures
#endif // FPL_PLATFORM_WIN32

#if defined(FPL_SUBPLATFORM_POSIX)
#	include <pthread.h> // pthread_t, pthread_mutex_, pthread_cond_, pthread_barrier_
#endif // FPL_SUBPLATFORM_POSIX

#if defined(FPL_SUBPLATFORM_X11)
#   include <X11/X.h> // Window
#   include <X11/Xlib.h> // Display
#   undef None
#   undef Success
#endif // FPL_SUBPLATFORM_X11

// ****************************************************************************
// ****************************************************************************
//
// API Declaration
//
// ****************************************************************************
// ****************************************************************************

// ----------------------------------------------------------------------------
/**
  * \defgroup Atomics Atomic functions
  * \brief Atomic functions, like AtomicCompareAndExchange, AtomicReadFence, etc.
  * \{
  */
// ----------------------------------------------------------------------------

/**
  * \brief Insert a memory read fence/barrier.
  *
  * This will complete previous reads before future reads and prevents the compiler from reordering memory reads across this fence.
  */
fpl_platform_api void fplAtomicReadFence();
/**
  * \brief Insert a memory write fence/barrier.
  * This will complete previous writes before future writes and prevents the compiler from reordering memory writes across this fence.
  */
fpl_platform_api void fplAtomicWriteFence();
/**
  * \brief Insert a memory read/write fence/barrier.
  * This will complete previous reads/writes before future reads/writes and prevents the compiler from reordering memory access across this fence.
  */
fpl_platform_api void fplAtomicReadWriteFence();

/**
  * \brief Replace a 32-bit unsigned integer with the given value atomically.
  * Ensures that memory operations are completed in order.
  * \param target The target value to write into.
  * \param value The source value used for exchange.
  * \return Returns the initial value before the replacement.
  */
fpl_platform_api uint32_t fplAtomicExchangeU32(volatile uint32_t *target, const uint32_t value);
/**
  * \brief Replace a 64-bit unsigned integer with the given value atomically.
  * Ensures that memory operations are completed in order.
  * \param target The target value to write into.
  * \param value The source value used for exchange.
  * \return Returns the initial value before the replacement.
  */
fpl_platform_api uint64_t fplAtomicExchangeU64(volatile uint64_t *target, const uint64_t value);
/**
  * \brief Replace a 32-bit signed integer with the given value atomically.
  * Ensures that memory operations are completed in order.
  * \param target The target value to write into.
  * \param value The source value used for exchange.
  * \return Returns the initial value before the replacement.
  */
fpl_platform_api int32_t fplAtomicExchangeS32(volatile int32_t *target, const int32_t value);
/**
  * \brief Replace a 64-bit signed integer with the given value atomically.
  * Ensures that memory operations are completed in order.
  * \param target The target value to write into.
  * \param value The source value used for exchange.
  * \return Returns the initial value before the replacement.
  */
fpl_platform_api int64_t fplAtomicExchangeS64(volatile int64_t *target, const int64_t value);
/**
  * \brief Replace a pointer with the given value atomically.
  * Ensures that memory operations are completed in order.
  * \param target The target value to write into.
  * \param value The source value used for exchange.
  * \return Returns the initial value before the replacement.
  */
fpl_common_api void *fplAtomicExchangePtr(volatile void **target, const void *value);

/**
  * \brief Adds a 32-bit unsigned integer to the value by the given addend atomically.
  * Ensures that memory operations are completed in order.
  * \param value The target value to append to.
  * \param addend The value used for adding.
  * \return Returns the initial value before the append.
  */
fpl_platform_api uint32_t fplAtomicAddU32(volatile uint32_t *value, const uint32_t addend);
/**
  * \brief Adds a 64-bit unsigned integer to the value by the given addend atomically.
  * Ensures that memory operations are completed in order.
  * \param value The target value to append to.
  * \param addend The value used for adding.
  * \return Returns the initial value before the append.
  */
fpl_platform_api uint64_t fplAtomicAddU64(volatile uint64_t *value, const uint64_t addend);
/**
  * \brief Adds a 32-bit signed integer to the value by the given addend atomically.
  * Ensures that memory operations are completed in order.
  * \param value The target value to append to.
  * \param addend The value used for adding.
  * \return Returns the initial value before the append.
  */
fpl_platform_api int32_t fplAtomicAddS32(volatile int32_t *value, const int32_t addend);
/**
  * \brief Adds a 64-bit signed integer to the value by the given addend atomically.
  * Ensures that memory operations are completed in order.
  * \param value The target value to append to.
  * \param addend The value used for adding.
  * \return Returns the initial value before the append.
  */
fpl_platform_api int64_t fplAtomicAddS64(volatile int64_t *value, const int64_t addend);

/**
  * \brief Compares a 32-bit unsigned integer with a comparand and exchange it when comparand matches destination.
  * Ensures that memory operations are completed in order.
  * \param dest The target value to write into.
  * \param comparand The value to compare with.
  * \param exchange The value to exchange with.
  * \note Use \ref fplIsAtomicCompareAndExchangeU32() when you want to check if the exchange has happened or not.
  * \return Returns the dest before the exchange, regardless of the result.
  */
fpl_platform_api uint32_t fplAtomicCompareAndExchangeU32(volatile uint32_t *dest, const uint32_t comparand, const uint32_t exchange);
/**
  * \brief Compares a 64-bit unsigned integer with a comparand and exchange it when comparand matches destination.
  * Ensures that memory operations are completed in order.
  * \param dest The target value to write into.
  * \param comparand The value to compare with.
  * \param exchange The value to exchange with.
  * \note Use \ref fplIsAtomicCompareAndExchangeU64() when you want to check if the exchange has happened or not.
  * \return Returns the value of the destination before the exchange, regardless of the result.
  */
fpl_platform_api uint64_t fplAtomicCompareAndExchangeU64(volatile uint64_t *dest, const uint64_t comparand, const uint64_t exchange);
/**
  * \brief Compares a 32-bit signed integer with a comparand and exchange it when comparand matches destination.
  * Ensures that memory operations are completed in order.
  * \param dest The target value to write into.
  * \param comparand The value to compare with.
  * \param exchange The value to exchange with.
  * \note Use \ref fplIsAtomicCompareAndExchangeS32() when you want to check if the exchange has happened or not.
  * \return Returns the value of the destination before the exchange, regardless of the result.
  */
fpl_platform_api int32_t fplAtomicCompareAndExchangeS32(volatile int32_t *dest, const int32_t comparand, const int32_t exchange);
/**
  * \brief Compares a 64-bit signed integer with a comparand and exchange it when comparand matches destination.
  * Ensures that memory operations are completed in order.
  * \param dest The target value to write into.
  * \param comparand The value to compare with.
  * \param exchange The value to exchange with.
  * \note Use \ref fplIsAtomicCompareAndExchangeS64() when you want to check if the exchange has happened or not.
  * \return Returns the value of the destination before the exchange, regardless of the result.
  */
fpl_platform_api int64_t fplAtomicCompareAndExchangeS64(volatile int64_t *dest, const int64_t comparand, const int64_t exchange);
/**
  * \brief Compares a pointer with a comparand and exchange it when comparand matches destination.
  * Ensures that memory operations are completed in order.
  * \param dest The target value to write into.
  * \param comparand The value to compare with.
  * \param exchange The value to exchange with.
  * \note Use \ref fplIsAtomicCompareAndExchangePtr() when you want to check if the exchange has happened or not.
  * \return Returns the value of the destination before the exchange, regardless of the result.
  */
fpl_common_api void *fplAtomicCompareAndExchangePtr(volatile void **dest, const void *comparand, const void *exchange);

/**
  * \brief Compares a 32-bit unsigned integer with a comparand and exchange it when comparand matches destination and returns a bool indicating the result.
  * Ensures that memory operations are completed in order.
  * \param dest The target value to write into.
  * \param comparand The value to compare with.
  * \param exchange The value to exchange with.
  * \return Returns true when the exchange happened, otherwise false.
  */
fpl_platform_api bool fplIsAtomicCompareAndExchangeU32(volatile uint32_t *dest, const uint32_t comparand, const uint32_t exchange);
/**
  * \brief Compares a 64-bit unsigned integer with a comparand and exchange it when comparand matches destination and returns a bool indicating the result.
  * Ensures that memory operations are completed in order.
  * \param dest The target value to write into.
  * \param comparand The value to compare with.
  * \param exchange The value to exchange with.
  * \return Returns true when the exchange happened, otherwise false.
  */
fpl_platform_api bool fplIsAtomicCompareAndExchangeU64(volatile uint64_t *dest, const uint64_t comparand, const uint64_t exchange);
/**
  * \brief Compares a 32-bit signed integer with a comparand and exchange it when comparand matches destination and returns a bool indicating the result.
  * Ensures that memory operations are completed in order.
  * \param dest The target value to write into.
  * \param comparand The value to compare with.
  * \param exchange The value to exchange with.
  * \return Returns true when the exchange happened, otherwise false.
  */
fpl_platform_api bool fplIsAtomicCompareAndExchangeS32(volatile int32_t *dest, const int32_t comparand, const int32_t exchange);
/**
  * \brief Compares a 64-bit signed integer with a comparand and exchange it when comparand matches destination and returns a bool indicating the result.
  * Ensures that memory operations are completed in order.
  * \param dest The target value to write into.
  * \param comparand The value to compare with.
  * \param exchange The value to exchange with.
  * \return Returns true when the exchange happened, otherwise false.
  */
fpl_platform_api bool fplIsAtomicCompareAndExchangeS64(volatile int64_t *dest, const int64_t comparand, const int64_t exchange);
/**
  * \brief Compares a pointer with a comparand and exchange it when comparand matches destination and returns a bool indicating the result.
  * Ensures that memory operations are completed in order.
  * \param dest The target value to write into.
  * \param comparand The value to compare with.
  * \param exchange The value to exchange with.
  * \return Returns true when the exchange happened, otherwise false.
  */
fpl_common_api bool fplIsAtomicCompareAndExchangePtr(volatile void **dest, const void *comparand, const void *exchange);

/**
  * \brief Loads the 32-bit unsigned value atomically and returns the value.
  * Ensures that memory operations are completed before the read.
  * \param source The source value to read from.
  * \note This may use a CAS instruction when there is no suitable compiler intrinsics found.
  * \return Returns the source value.
  */
fpl_platform_api uint32_t fplAtomicLoadU32(volatile uint32_t *source);
/**
  * \brief Loads the 64-bit unsigned value atomically and returns the value.
  * Ensures that memory operations are completed before the read.
  * \param source The source value to read from.
  * \note This may use a CAS instruction when there is no suitable compiler intrinsics found.
  * \return Returns the source value.
  */
fpl_platform_api uint64_t fplAtomicLoadU64(volatile uint64_t *source);
/**
  * \brief Loads the 32-bit signed value atomically and returns the value.
  * Ensures that memory operations are completed before the read.
  * \param source The source value to read from.
  * \note This may use a CAS instruction when there is no suitable compiler intrinsics found.
  * \return Returns the source value.
  */
fpl_platform_api int32_t fplAtomicLoadS32(volatile int32_t *source);
/**
  * \brief Loads the 64-bit signed value atomically and returns the value.
  * Ensures that memory operations are completed before the read.
  * \param source The source value to read from.
  * \note This may use a CAS instruction when there is no suitable compiler intrinsics found.
  * \return Returns the source value.
  */
fpl_platform_api int64_t fplAtomicLoadS64(volatile int64_t *source);
/**
  * \brief Loads the pointer value atomically and returns the value.
  * Ensures that memory operations are completed before the read.
  * \param source The source value to read from.
  * \note This may use a CAS instruction when there is no suitable compiler intrinsics found.
  * \return Returns the source value.
  */
fpl_common_api void *fplAtomicLoadPtr(volatile void **source);

/**
  * \brief Overwrites the 32-bit unsigned value atomically.
  * Ensures that memory operations are completed before the write.
  * \param dest The destination to write to.
  * \param value The value to exchange with.
  * \return Returns the source value.
  */
fpl_platform_api void fplAtomicStoreU32(volatile uint32_t *dest, const uint32_t value);
/**
  * \brief Overwrites the 64-bit unsigned value atomically.
  * Ensures that memory operations are completed before the write.
  * \param dest The destination to write to.
  * \param value The value to exchange with.
  * \return Returns the source value.
  */
fpl_platform_api void fplAtomicStoreU64(volatile uint64_t *dest, const uint64_t value);
/**
  * \brief Overwrites the 32-bit signed value atomically.
  * Ensures that memory operations are completed before the write.
  * \param dest The destination to write to.
  * \param value The value to exchange with.
  * \return Returns the source value.
  */
fpl_platform_api void fplAtomicStoreS32(volatile int32_t *dest, const int32_t value);
/**
  * \brief Overwrites the 64-bit signed value atomically.
  * Ensures that memory operations are completed before the write.
  * \param dest The destination to write to.
  * \param value The value to exchange with.
  * \return Returns the source value.
  */
fpl_platform_api void fplAtomicStoreS64(volatile int64_t *dest, const int64_t value);
/**
  * \brief Overwrites the pointer value atomically.
  * Ensures that memory operations are completed before the write.
  * \param dest The destination to write to.
  * \param value The value to exchange with.
  * \return Returns the source value.
  */
fpl_common_api void fplAtomicStorePtr(volatile void **dest, const void *value);

/** \}*/

/**
  * \defgroup Hardware Hardware functions
  * \brief Hardware functions, like GetProcessorCoreCount, GetProcessorName, etc.
  * \{
  */

//! Memory informations
typedef struct fplMemoryInfos {
	//! Total size of physical memory in bytes (Amount of RAM installed)
	uint64_t totalPhysicalSize;
	//! Available size of physical memory in bytes (May be less than the amount of RAM installed)
	uint64_t availablePhysicalSize;
	//! Free size of physical memory in bytes
	uint64_t usedPhysicalSize;
	//! Total size of virtual memory in bytes
	uint64_t totalVirtualSize;
	//! Used size of virtual memory in bytes
	uint64_t usedVirtualSize;
	//! Total page size in bytes
	uint64_t totalPageSize;
	//! Used page size in bytes
	uint64_t usedPageSize;
} fplMemoryInfos;

/**
  * \brief Returns the total number of processor cores.
  * \return Number of processor cores.
  */
fpl_platform_api uint32_t fplGetProcessorCoreCount();
/**
  * \brief Returns the name of the processor.
  * The processor name is written in the destination buffer.
  * \param destBuffer The character buffer to write the processor name into.
  * \param maxDestBufferLen The total number of characters available in the destination character buffer.
  * \return Name of the processor.
  */
fpl_platform_api char *fplGetProcessorName(char *destBuffer, const uint32_t maxDestBufferLen);
/**
  * \brief Returns the current system memory informations.
  * \return Current system memory informations.
  */
fpl_platform_api fplMemoryInfos fplGetSystemMemoryInfos();

/** \}*/

/**
  * \defgroup Settings Settings and configurations
  * \brief Video/audio/window settings
  * \{
  */

//! Initialization flags (Window, Video, etc.)
typedef enum fplInitFlags {
	//! No init flags
	fplInitFlags_None = 0,
	//! Create a single window
	fplInitFlags_Window = 1 << 0,
	//! Use a video backbuffer (This flag ensures that \ref fplInitFlags_Window is included always)
	fplInitFlags_Video = 1 << 1,
	//! Use asyncronous audio playback
	fplInitFlags_Audio = 1 << 2,
	//! Default init flags for initializing everything
	fplInitFlags_All = fplInitFlags_Window | fplInitFlags_Video | fplInitFlags_Audio
} fplInitFlags;

//! Video driver type
typedef enum fplVideoDriverType {
	//! No video driver
	fplVideoDriverType_None = 0,
	//! OpenGL
	fplVideoDriverType_OpenGL,
	//! Software
	fplVideoDriverType_Software
} fplVideoDriverType;

#if defined(FPL_ENABLE_VIDEO_OPENGL)
//! OpenGL compability flags
typedef enum fplOpenGLCompabilityFlags {
	//! Use legacy context
	fplOpenGLCompabilityFlags_Legacy = 0,
	//! Use core profile
	fplOpenGLCompabilityFlags_Core = 1 << 1,
	//! Use compability profile
	fplOpenGLCompabilityFlags_Compability = 1 << 2,
	//! Remove features marked as deprecated
	fplOpenGLCompabilityFlags_Forward = 1 << 3,
} fplOpenGLCompabilityFlags;

//! OpenGL video settings container
typedef struct fplOpenGLVideoSettings {
	//! Compability flags
	fplOpenGLCompabilityFlags compabilityFlags;
	//! Desired major version
	uint32_t majorVersion;
	//! Desired minor version
	uint32_t minorVersion;
} fplOpenGLVideoSettings;
#endif // FPL_ENABLE_VIDEO_OPENGL

	//! Graphics API settings union
typedef union fplGraphicsAPISettings {
#if defined(FPL_ENABLE_VIDEO_OPENGL)
	//! OpenGL settings
	fplOpenGLVideoSettings opengl;
#endif
} fplGraphicsAPISettings;

//! Video settings container (Driver, Flags, Version, VSync, etc.)
typedef struct fplVideoSettings {
	//! Video driver type
	fplVideoDriverType driver;
	//! Vertical syncronisation enabled/disabled
	bool isVSync;
	//! Backbuffer size is automatically resized. Useable only for software rendering!
	bool isAutoSize;
	//! Graphics API settings
	fplGraphicsAPISettings graphics;
} fplVideoSettings;

/**
  * \brief Make default video settings
  * \note This will not change any video settings! To change the actual settings you have to pass the entire \ref fplSettings container to a argument in \ref fplPlatformInit().
  */
fpl_inline fplVideoSettings fplDefaultVideoSettings() {
	fplVideoSettings result = FPL_STRUCT_ZERO;

	result.isVSync = false;
	result.isAutoSize = true;

	// @NOTE(final): Auto detect video driver
#if defined(FPL_ENABLE_VIDEO_OPENGL)
	result.driver = fplVideoDriverType_OpenGL;
	result.graphics.opengl.compabilityFlags = fplOpenGLCompabilityFlags_Legacy;
#elif defined(FPL_ENABLE_VIDEO_SOFTWARE)
	result.driver = VideoDriverType_Software;
#else
	result.driver = VideoDriverType_None;
#endif

	return(result);
}

//! Audio driver type
typedef enum fplAudioDriverType {
	//! No audio driver
	fplAudioDriverType_None = 0,
	//! Auto detection
	fplAudioDriverType_Auto,
	//! DirectSound
	fplAudioDriverType_DirectSound,
} fplAudioDriverType;

//! Audio format type
typedef enum fplAudioFormatType {
	// No audio format
	fplAudioFormatType_None = 0,
	// Unsigned 8-bit integer PCM
	fplAudioFormatType_U8,
	// Signed 16-bit integer PCM
	fplAudioFormatType_S16,
	// Signed 24-bit integer PCM
	fplAudioFormatType_S24,
	// Signed 32-bit integer PCM
	fplAudioFormatType_S32,
	// Signed 64-bit integer PCM
	fplAudioFormatType_S64,
	// 32-bit IEEE_FLOAT
	fplAudioFormatType_F32,
	// 64-bit IEEE_FLOAT
	fplAudioFormatType_F64,
} fplAudioFormatType;

//! Audio device format
typedef struct fplAudioDeviceFormat {
	//! Audio format
	fplAudioFormatType type;
	//! Samples per seconds
	uint32_t sampleRate;
	//! Number of channels
	uint32_t channels;
	//! Number of periods
	uint32_t periods;
	//! Buffer size for the device
	uint32_t bufferSizeInBytes;
	//! Buffer size in frames
	uint32_t bufferSizeInFrames;
} fplAudioDeviceFormat;

//! Audio device id union
typedef union fplAudioDeviceID {
#	if defined(FPL_ENABLE_AUDIO_DIRECTSOUND)
	//! DirectShow Device GUID
	GUID dshow;
#	endif
} fplAudioDeviceID;

//! Audio device info
typedef struct fplAudioDeviceInfo {
	//! Device name
	char name[256];
	//! Device id
	fplAudioDeviceID id;
} fplAudioDeviceInfo;

//! Audio Client Read Callback Function
typedef uint32_t(fpl_audio_client_read_callback)(const fplAudioDeviceFormat deviceFormat, const uint32_t frameCount, void *outputSamples, void *userData);

//! Audio settings
typedef struct fplAudioSettings {
	//! The device format
	fplAudioDeviceFormat deviceFormat;
	//! The device info
	fplAudioDeviceInfo deviceInfo;
	//! The callback for retrieving audio data from the client
	fpl_audio_client_read_callback *clientReadCallback;
	//! The targeted driver
	fplAudioDriverType driver;
	//! Audio buffer in milliseconds
	uint32_t bufferSizeInMilliSeconds;
	//! Is exclude mode prefered
	bool preferExclusiveMode;
	//! User data pointer for client read callback
	void *userData;
} fplAudioSettings;

/**
  * \brief Make default audio settings (S16 PCM, 48 KHz, 2 Channels)
  * \note This will not change any audio settings! To change the actual settings you have to pass the entire \ref fplSettings container to a argument in \ref fplPlatformInit().
  */
fpl_inline fplAudioSettings fplDefaultAudioSettings() {
	fplAudioSettings result = FPL_STRUCT_ZERO;
	result.bufferSizeInMilliSeconds = 25;
	result.preferExclusiveMode = false;
	result.deviceFormat.channels = 2;
	result.deviceFormat.sampleRate = 48000;
	result.deviceFormat.type = fplAudioFormatType_S16;

	result.driver = fplAudioDriverType_None;
#	if defined(FPL_ENABLE_AUDIO_DIRECTSOUND)
	result.driver = fplAudioDriverType_DirectSound;
#	endif
	return(result);
}

//! Window settings (Size, Title etc.)
typedef struct fplWindowSettings {
	//! Window title
	char windowTitle[256];
	//! Window width in screen coordinates
	uint32_t windowWidth;
	//! Window height in screen coordinates
	uint32_t windowHeight;
	//! Fullscreen width in screen coordinates
	uint32_t fullscreenWidth;
	//! Fullscreen height in screen coordinates
	uint32_t fullscreenHeight;
	//! Is window resizable
	bool isResizable;
	//! Is window in fullscreen mode
	bool isFullscreen;
} fplWindowSettings;

/**
  * \brief Make default settings for the window
  * \note This will not change any window settings! To change the actual settings you have to pass the entire \ref fplSettings container to a argument in \ref fplPlatformInit().
  */
fpl_inline fplWindowSettings fplDefaultWindowSettings() {
	fplWindowSettings result = FPL_STRUCT_ZERO;
	result.windowTitle[0] = 0;
	result.windowWidth = 800;
	result.windowHeight = 600;
	result.fullscreenWidth = 0;
	result.fullscreenHeight = 0;
	result.isResizable = true;
	result.isFullscreen = false;
	return(result);
}

//! Input settings
typedef struct fplInputSettings {
	//! Frequency in ms for detecting new or removed controllers (Default: 100 ms)
	uint32_t controllerDetectionFrequency;
} fplInputSettings;

/**
  * \brief Make default settings for input devices.
  * \note This will not change any input settings! To change the actual settings you have to pass the entire \ref fplSettings container to a argument in \ref fplPlatformInit().
  */
fpl_inline fplInputSettings fplDefaultInputSettings() {
	fplInputSettings result = FPL_STRUCT_ZERO;
	result.controllerDetectionFrequency = 100;
	return(result);
}

//! Settings container (Window, Video, etc)
typedef struct fplSettings {
	//! Window settings
	fplWindowSettings window;
	//! Video settings
	fplVideoSettings video;
	//! Audio settings
	fplAudioSettings audio;
	//! Input settings
	fplInputSettings input;
} fplSettings;

/**
  * \brief Make default settings for window, video, audio, etc.
  * \note This will not change any settings! To change the actual settings you have to pass this settings container to a argument in \ref fplPlatformInit().
  */
fpl_inline fplSettings fplDefaultSettings() {
	fplSettings result = FPL_STRUCT_ZERO;
	result.window = fplDefaultWindowSettings();
	result.video = fplDefaultVideoSettings();
	result.audio = fplDefaultAudioSettings();
	result.input = fplDefaultInputSettings();
	return(result);
}

/**
  * \brief Returns the current settings
  */
fpl_common_api const fplSettings *fplGetCurrentSettings();

/** \}*/

/**
  * \defgroup Initialization Initialization functions
  * \brief Initialization and release functions
  * \{
  */

/**
  * \brief Initializes the platform layer.
  * \param initFlags Optional init flags used for enable certain features, like video/audio etc. (Default: \ref fplInitFlags_All)
  * \param initSettings Optional initialization settings which can be passed to control the platform layer behavior or systems. (Default: \ref fplSettings provided by \ref fplDefaultSettings())
  * \note \ref fplPlatformRelease() must be called when you are done! After \ref fplPlatformRelease() has been called you can call this function again if needed.
  * \return Returns true when the initialzation was successful, otherwise false. Will return false when the platform layers is already initialized successfully.
  */
fpl_common_api bool fplPlatformInit(const fplInitFlags initFlags, const fplSettings initSettings);
/**
  * \brief Releases the resources allocated by the platform layer.
  * \note Can only be called when \ref fplPlatformInit() was successful.
  */
fpl_common_api void fplPlatformRelease();

/** \}*/

/**
  * \defgroup ErrorHandling Error Handling
  * \brief Functions for error handling
  * \{
  */

  /**
	* \brief Returns the last internal error string
	* \note This function can be called regardless of the initialization state!
	* \return Last error string or empty string when there was no error.
	*/
fpl_common_api const char *fplGetPlatformError();
/**
  * \brief Returns the last error string from the given index
  * \param index The index
  * \note This function can be called regardless of the initialization state!
  * \return Last error string from the given index or empty when there was no error.
  */
fpl_common_api const char *fplGetPlatformError(const size_t index);
/**
  * \brief Returns the count of total last errors
  * \note This function can be called regardless of the initialization state!
  * \return Number of last errors or zero when there was no error.
  */
fpl_common_api size_t fplGetPlatformErrorCount();
/**
  * \brief Clears all the current errors in the platform
  * \note This function can be called regardless of the initialization state!
  */
fpl_common_api void ClearPlatformErrors();

/** \}*/

/**
  * \defgroup DynamicLibrary Dynamic library loading
  * \brief Loading dynamic libraries and retrieving the procedure addresses.
  * \{
  */

//! Internal library handle union
typedef union fplInternalDynamicLibraryHandle {
#if defined(FPL_PLATFORM_WIN32)
	//! Win32 library handle
	HMODULE win32LibraryHandle;
#elif defined(FPL_SUBPLATFORM_POSIX)
	//! Posix library handle
	void *posixLibraryHandle;
#endif
} fplInternalDynamicLibraryHandle;

  //! Handle to a loaded dynamic library
typedef struct fplDynamicLibraryHandle {
	//! Internal library handle
	fplInternalDynamicLibraryHandle internalHandle;
	//! Library opened successfully
	bool isValid;
} fplDynamicLibraryHandle;

/**
  * \brief Loads a dynamic library and returns the loaded handle for it.
  * \param libraryFilePath The path to the library with included file extension (.dll / .so)
  * \note To check for success, just check the DynamicLibraryHandle.isValid field from the result.
  * \return Handle container of the loaded library.
  */
fpl_platform_api fplDynamicLibraryHandle fplDynamicLibraryLoad(const char *libraryFilePath);
/**
  * \brief Returns the dynamic library procedure address for the given procedure name.
  * \param handle Handle to the loaded library
  * \param name Name of the procedure
  * \return Procedure address for the given procedure name or fpl_null when procedure not found or library is not loaded.
  */
fpl_platform_api void *fplGetDynamicLibraryProc(const fplDynamicLibraryHandle *handle, const char *name);
/**
  * \brief Unloads the loaded library and resets the handle to zero.
  * \param handle Loaded dynamic library handle
  */
fpl_platform_api void fplDynamicLibraryUnload(fplDynamicLibraryHandle *handle);

/** \}*/

/**
  * \defgroup Console Console functions
  * \brief Console out/in functions
  * \{
  */

  /**
	* \brief Writes the given text to the standard output console buffer.
	* \param text The text to write into standard output console.
	* \note This is most likely just a wrapper call to fprintf(stdout)
	*/
fpl_platform_api void fplConsoleOut(const char *text);
/**
  * \brief Writes the given formatted text to the standard output console buffer.
  * \param format The format used for writing into the standard output console.
  * \param ... The dynamic arguments used for formatting the text.
  * \note This is most likely just a wrapper call to vfprintf(stdout)
  */
fpl_platform_api void fplConsoleFormatOut(const char *format, ...);
/**
  * \brief Writes the given text to the standard error console buffer.
  * \param text The text to write into standard error console.
  * \note This is most likely just a wrapper call to fprintf(stderr)
  */
fpl_platform_api void fplConsoleError(const char *text);
/**
  * \brief Writes the given formatted text to the standard error console buffer.
  * \param format The format used for writing into the standard error console.
  * \param ... The dynamic arguments used for formatting the text.
  * \note This is most likely just a wrapper call to vfprintf(stderr)
  */
fpl_platform_api void fplConsoleFormatError(const char *format, ...);
/**
  * \brief Wait for a character to be typed in the console input and return it
  * \note This is most likely just a wrapper call to getchar()
  * \return Character typed in in the console input
  */
fpl_platform_api const char fplConsoleWaitForCharInput();

/** \}*/

/**
  * \defgroup Threading Threading routines
  * \brief Tons of functions for multithreading, mutex and signal creation and handling
  * \{
  */

  //! Thread state
typedef enum fplThreadStates {
	//! Thread is stopped
	fplThreadState_Stopped = 0,
	//! Thread is being started
	fplThreadState_Starting,
	//! Thread is still running
	fplThreadState_Running,
	//! Thread is being stopped
	fplThreadState_Stopping,
} fplThreadStates;
typedef uint32_t fplThreadState;

typedef struct fplThreadHandle fplThreadHandle;
//! Run function type definition for CreateThread
typedef void (fpl_run_thread_function)(const fplThreadHandle *thread, void *data);

#if defined(FPL_SUBPLATFORM_POSIX)
//! Posix internal thread handle
typedef struct fplPosixInternalThreadHandle {
	//! Thread
	pthread_t thread;
	//! Mutex
	pthread_mutex_t mutex;
	//! Stop condition
	pthread_cond_t stopCondition;
} fplPosixInternalThreadHandle;
#endif

//! Internal thread handle union
typedef union fplInternalThreadHandle {
#if defined(FPL_PLATFORM_WIN32)
	//! Win32 thread handle
	HANDLE win32ThreadHandle;
#elif defined(FPL_SUBPLATFORM_POSIX)
	//! Posix thread handle
	fplPosixInternalThreadHandle posix;
#endif
} fplInternalThreadHandle;

//! Thread handle
typedef struct fplThreadHandle {
	//! The internal thread handle
	fplInternalThreadHandle internalHandle;
	//! The identifier of the thread
	uint64_t id;
	//! The stored run function
	fpl_run_thread_function *runFunc;
	//! The user data passed to the run function
	void *data;
	//! Thread state
	volatile fplThreadState currentState;
	//! Is this thread valid
	volatile bool isValid;
	//! Is this thread stopping
	volatile bool isStopping;
} fplThreadHandle;

//! Internal mutex handle union
typedef union fplInternalMutexHandle {
#if defined(FPL_PLATFORM_WIN32)
	//! Win32 mutex handle
	CRITICAL_SECTION win32CriticalSection;
#elif defined(FPL_SUBPLATFORM_POSIX)
	//! Posix mutex handle
	pthread_mutex_t posixMutex;
#endif
} fplInternalMutexHandle;

//! Mutex handle
typedef struct fplMutexHandle {
	//! The internal mutex handle
	fplInternalMutexHandle internalHandle;
	//! Is it valid
	bool isValid;
} fplMutexHandle;

//! Internal signal handle union
typedef union fplInternalSignalHandle {
#if defined(FPL_PLATFORM_WIN32)
	//! Win32 event handle
	HANDLE win32EventHandle;
#elif defined(FPL_SUBPLATFORM_POSIX)
	//! Posix condition
	pthread_cond_t posixCondition;
#endif
} fplInternalSignalHandle;

//! Signal handle
typedef struct fplSignalHandle {
	//! The internal signal handle
	fplInternalSignalHandle internalHandle;
	//! Is it valid
	bool isValid;
} fplSignalHandle;

//! Returns the current thread state from the given thread
fpl_inline fplThreadState GetThreadState(fplThreadHandle *thread) {
	if(thread == fpl_null) {
		return fplThreadState_Stopped;
	}
	fplThreadState result = (fplThreadState)fplAtomicLoadU32((volatile uint32_t *)&thread->currentState);
	return(result);
}

/**
  * \brief Creates a thread and return a handle to it.
  * \param runFunc Function prototype called when this thread starts.
  * \param data User data passed to the run function.
  * \note Use \ref fplThreadDestroy() with this thread context when you dont need this thread anymore. You can only have 64 threads suspended/running at the same time!
  * \warning Do not free this thread context directly! Use \ref fplThreadDestroy() instead.
  * \return Pointer to a internal stored thread-context or return fpl_null when the limit of current threads has been reached.
  */
fpl_platform_api fplThreadHandle *fplThreadCreate(fpl_run_thread_function *runFunc, void *data);
/**
  * \brief Let the current thread sleep for the given amount of milliseconds.
  * \param milliseconds Number of milliseconds to sleep
  * \note There is no guarantee that the OS sleeps for the exact amount of milliseconds! This can vary based on the OS scheduler granularity.
  */
fpl_platform_api void fplThreadSleep(const uint32_t milliseconds);
/**
  * \brief Stop the given thread and release all underlying resources.
  * \param thread Thread
  * \note This thread context may get re-used for another thread in the future!
  * \warning Do not free the given thread context manually!
  */
fpl_platform_api void fplThreadDestroy(fplThreadHandle *thread);
/**
  * \brief Wait until the given thread is done running or the given timeout has been reached.
  * \param thread Thread
  * \param maxMilliseconds Optional number of milliseconds to wait. When this is set to UINT32_MAX it may wait infinitly. (Default: UINT32_MAX)
  * \return Returns true when the thread completes or when the timeout has been reached.
  */
fpl_platform_api bool fplThreadWaitForOne(fplThreadHandle *thread, const uint32_t maxMilliseconds);
/**
  * \brief Wait until all given threads are done running or the given timeout has been reached.
  * \param threads Array of threads
  * \param count Number of threads in the array
  * \param maxMilliseconds Optional number of milliseconds to wait. When this is set to UINT32_MAX it may wait infinitly. (Default: UINT32_MAX)
  * \return Returns true when all threads completes or when the timeout has been reached.
  */
fpl_platform_api bool fplThreadWaitForAll(fplThreadHandle *threads[], const uint32_t count, const uint32_t maxMilliseconds);
/**
  * \brief Wait until one of given threads is done running or the given timeout has been reached.
  * \param threads Array of threads
  * \param count Number of threads in the array
  * \param maxMilliseconds Optional number of milliseconds to wait. When this is set to UINT32_MAX it may wait infinitly. (Default: UINT32_MAX)
  * \return Returns true when one thread completes or when the timeout has been reached.
  */
fpl_platform_api bool fplThreadWaitForAny(fplThreadHandle *threads[], const uint32_t count, const uint32_t maxMilliseconds);

/**
  * \brief Creates a mutex and returns a copy of the handle to it.
  * \note Use \ref fplMutexDestroy() when you are done with this mutex.
  * \return Copy of the handle to the mutex.
  */
fpl_platform_api fplMutexHandle fplMutexCreate();
/**
  * \brief Releases the given mutex and clears the structure to zero.
  * \param mutex The mutex reference to destroy.
  */
fpl_platform_api void fplMutexDestroy(fplMutexHandle *mutex);
/**
  * \brief Locks the given mutex and ensures that other threads will wait until it gets unlocked or the timeout has been reached.
  * \param mutex The mutex reference to lock
  * \param maxMilliseconds Optional number of milliseconds to wait. When this is set to UINT32_MAX it may wait infinitly. (Default: UINT32_MAX)
  * \returns True when mutex was locked or false otherwise.
  */
fpl_platform_api bool fplMutexLock(fplMutexHandle *mutex, const uint32_t maxMilliseconds);
/**
 * \brief Unlocks the given mutex
 * \param mutex The mutex reference to unlock
 * \returns True when mutex was unlocked or false otherwise.
 */
fpl_platform_api bool fplMutexUnlock(fplMutexHandle *mutex);

/**
  * \brief Creates a signal and returns a copy of the handle to it.
  * \note Use \ref fplSignalDestroy() when you are done with this signal.
  * \return Copy of the handle to the signal.
  */
fpl_platform_api fplSignalHandle fplSignalCreate();
/**
  * \brief Releases the given signal and clears the structure to zero.
  * \param signal The signal reference to destroy.
  */
fpl_platform_api void fplSignalDestroy(fplSignalHandle *signal);
/**
  * \brief Waits until the given signal are waked up.
  * \param mutex The mutex reference
  * \param signal The signal reference to signal.
  * \param maxMilliseconds Optional number of milliseconds to wait. When this is set to UINT32_MAX it may wait infinitly. (Default: UINT32_MAX)
  * \return Returns true when the signal woke up or the timeout has been reached, otherwise false.
  */
fpl_platform_api bool fplSignalWaitForOne(fplMutexHandle *mutex, fplSignalHandle *signal, const uint32_t maxMilliseconds);
/**
  * \brief Waits until all the given signal are waked up.
  * \param mutex The mutex reference
  * \param signals Array of signals
  * \param count Number of signals
  * \param maxMilliseconds Optional number of milliseconds to wait. When this is set to UINT32_MAX it may wait infinitly. (Default: UINT32_MAX)
  * \return Returns true when all signals woke up or the timeout has been reached, otherwise false.
  */
fpl_platform_api bool fplSignalWaitForAll(fplMutexHandle *mutex, fplSignalHandle *signals[], const uint32_t count, const uint32_t maxMilliseconds);
/**
  * \brief Waits until any of the given signals wakes up or the timeout has been reached.
  * \param mutex The mutex reference
  * \param signals Array of signals
  * \param count Number of signals
  * \param maxMilliseconds Optional number of milliseconds to wait. When this is set to UINT32_MAX it may wait infinitly. (Default: UINT32_MAX)
  * \return Returns true when any of the signals woke up or the timeout has been reached, otherwise false.
  */
fpl_platform_api bool fplSignalWaitForAny(fplMutexHandle *mutex, fplSignalHandle *signals[], const uint32_t count, const uint32_t maxMilliseconds);
/**
  * \brief Sets the signal and wakes up the given signal.
  * \param signal The reference to the signal
  * \return Returns true when the signal was set and woke up, otherwise false.
  */
fpl_platform_api bool fplSignalSet(fplSignalHandle *signal);

/** \}*/

/**
  * \defgroup Memory Memory functions
  * \brief Memory allocation, clearing and copy functions
  * \{
  */

  /**
	* \brief Clears the given memory by the given size to zero.
	* \param mem Pointer to the memory.
	* \param size Size in bytes to be cleared to zero.
	*/
fpl_common_api void fplMemoryClear(void *mem, const size_t size);
/**
  * \brief Copies the given source memory with its length to the target memory.
  * \param sourceMem Pointer to the source memory to copy from.
  * \param sourceSize Size in bytes to be copied.
  * \param targetMem Pointer to the target memory to copy to.
  */
fpl_common_api void fplMemoryCopy(void *sourceMem, const size_t sourceSize, void *targetMem);
/**
  * \brief Allocates memory from the operating system by the given size.
  * \param size Size to by allocated in bytes.
  * \note The memory is guaranteed to be initialized by zero.
  * \warning Alignment is not ensured here, the OS decides how to handle this. If you want to force a specific alignment use \ref fplMemoryAlignedAllocate() instead.
  * \return Pointer to the new allocated memory.
  */
fpl_platform_api void *fplMemoryAllocate(const size_t size);
/**
  * \brief Releases the memory allocated from the operating system.
  * \param ptr Pointer to the allocated memory.
  * \warning This should never be called with a aligned memory pointer! For freeing aligned memory, use \ref fplMemoryAlignedFree() instead.
  * \return Pointer to the new allocated memory.
  */
fpl_platform_api void fplMemoryFree(void *ptr);
/**
  * \brief Allocates aligned memory from the operating system by the given alignment.
  * \param size Size amount in bytes
  * \param alignment Alignment in bytes (Needs to be a power-of-two!)
  * \note The memory is guaranteed to be initialized by zero.
  * \return Pointer to the new allocated aligned memory.
  */
fpl_common_api void *fplMemoryAlignedAllocate(const size_t size, const size_t alignment);
/**
  * \brief Releases the aligned memory allocated from the operating system.
  * \param ptr Pointer to the aligned allocated memory.
  * \warning This should never be called with a not-aligned memory pointer! For freeing not-aligned memory, use \ref fplMemoryFree() instead.
  * \return Pointer to the new allocated memory.
  */
fpl_common_api void fplMemoryAlignedFree(void *ptr);

/** \}*/

/**
  * \defgroup Timings Timing functions
  * \brief Functions for retrieving timebased informations
  * \{
  */

/**
  * \brief Returns the current system clock in seconds with the highest precision possible.
  * \return Returns number of second since some fixed starting point (OS start, System start, etc).
  * \note Can only be used to calculate a difference in time!
  */
fpl_platform_api double fplGetTimeInSeconds();

/**
  * \brief Returns the current system in milliseconds without deeper precision.
  * \return Returns number of milliseconds since some fixed starting point (OS start, System start, etc).
  * \note Can only be used to calculate a difference in time!
  */
fpl_platform_api uint64_t fplGetTimeInMilliseconds();

/** \}*/

/**
  * \defgroup Strings String manipulation functions
  * \brief Functions for converting/manipulating strings
  * \{
  */

  /**
	* \brief Returns true when both ansi strings are equal with enforcing the given length.
	* \param a First string
	* \param aLen Number of characters for the first string
	* \param b Second string
	* \param bLen Number of characters for the second string
	* \note Len parameters does not include the null-terminator!
	* \return True when strings matches, otherwise false.
	*/
fpl_common_api bool fplIsStringEqualLen(const char *a, const uint32_t aLen, const char *b, const uint32_t bLen);
/**
  * \brief Returns true when both ansi strings are equal.
  * \param a First string
  * \param b Second string
  * \return True when strings matches, otherwise false.
  */
fpl_common_api bool fplIsStringEqual(const char *a, const char *b);
/**
  * \brief Returns the number of characters of the given 8-bit Ansi string.
  * \param str The 8-bit ansi string
  * \note Null terminator is not included!
  * \return Returns the character length or zero when the input string is fpl_null.
  */
fpl_common_api uint32_t fplGetAnsiStringLength(const char *str);
/**
  * \brief Returns the number of characters of the given 16-bit wide string.
  * \param str The 16-bit wide string
  * \note Null terminator is not included!
  * \return Returns the character length or zero when the input string is fpl_null.
  */
fpl_common_api uint32_t fplGetWideStringLength(const wchar_t *str);
/**
  * \brief Copies the given 8-bit source ansi string with a fixed length into a destination ansi string.
  * \param source The 8-bit source ansi string.
  * \param sourceLen The number of characters to copy.
  * \param dest The 8-bit destination ansi string buffer.
  * \param maxDestLen The total number of characters available in the destination buffer.
  * \note Null terminator is included always. Does not allocate any memory.
  * \return Returns the pointer to the first character in the destination buffer or fpl_null when either the dest buffer is too small or the source string is invalid.
  */
fpl_common_api char *fplCopyAnsiStringLen(const char *source, const uint32_t sourceLen, char *dest, const uint32_t maxDestLen);
/**
  * \brief Copies the given 8-bit source ansi string into a destination ansi string.
  * \param source The 8-bit source ansi string.
  * \param dest The 8-bit destination ansi string buffer.
  * \param maxDestLen The total number of characters available in the destination buffer.
  * \note Null terminator is included always. Does not allocate any memory.
  * \return Returns the pointer to the first character in the destination buffer or fpl_null when either the dest buffer is too small or the source string is invalid.
  */
fpl_common_api char *fplCopyAnsiString(const char *source, char *dest, const uint32_t maxDestLen);
/**
  * \brief Copies the given 16-bit source wide string with a fixed length into a destination wide string.
  * \param source The 16-bit source wide string.
  * \param sourceLen The number of characters to copy.
  * \param dest The 16-bit destination wide string buffer.
  * \param maxDestLen The total number of characters available in the destination buffer.
  * \note Null terminator is included always. Does not allocate any memory.
  * \return Returns the pointer to the first character in the destination buffer or fpl_null when either the dest buffer is too small or the source string is invalid.
  */
fpl_common_api wchar_t *fplCopyWideStringLen(const wchar_t *source, const uint32_t sourceLen, wchar_t *dest, const uint32_t maxDestLen);
/**
  * \brief Copies the given 16-bit source wide string into a destination wide string.
  * \param source The 16-bit source wide string.
  * \param dest The 16-bit destination wide string buffer.
  * \param maxDestLen The total number of characters available in the destination buffer.
  * \note Null terminator is included always. Does not allocate any memory.
  * \return Returns the pointer to the first character in the destination buffer or fpl_null when either the dest buffer is too small or the source string is invalid.
  */
fpl_common_api wchar_t *fplCopyWideString(const wchar_t *source, wchar_t *dest, const uint32_t maxDestLen);
/**
  * \brief Converts the given 16-bit source wide string with length in a 8-bit ansi string.
  * \param wideSource The 16-bit source wide string.
  * \param maxWideSourceLen The number of characters of the source wide string.
  * \param ansiDest The 8-bit destination ansi string buffer.
  * \param maxAnsiDestLen The total number of characters available in the destination buffer.
  * \note Null terminator is included always. Does not allocate any memory.
  * \return Returns the pointer to the first character in the destination buffer or fpl_null when either the dest buffer is too small or the source string is invalid.
  */
fpl_platform_api char *fplWideStringToAnsiString(const wchar_t *wideSource, const uint32_t maxWideSourceLen, char *ansiDest, const uint32_t maxAnsiDestLen);
/**
  * \brief Converts the given 16-bit source wide string with length in a 8-bit UTF-8 ansi string.
  * \param wideSource The 16-bit source wide string.
  * \param maxWideSourceLen The number of characters of the source wide string.
  * \param utf8Dest The 8-bit destination ansi string buffer.
  * \param maxUtf8DestLen The total number of characters available in the destination buffer.
  * \note Null terminator is included always. Does not allocate any memory.
  * \return Returns the pointer to the first character in the destination buffer or fpl_null when either the dest buffer is too small or the source string is invalid.
  */
fpl_platform_api char *fplWideStringToUTF8String(const wchar_t *wideSource, const uint32_t maxWideSourceLen, char *utf8Dest, const uint32_t maxUtf8DestLen);
/**
  * \brief Converts the given 8-bit source ansi string with length in a 16-bit wide string.
  * \param ansiSource The 8-bit source ansi string.
  * \param ansiSourceLen The number of characters of the source wide string.
  * \param wideDest The 16-bit destination wide string buffer.
  * \param maxWideDestLen The total number of characters available in the destination buffer.
  * \note Null terminator is included always. Does not allocate any memory.
  * \return Returns the pointer to the first character in the destination buffer or fpl_null when either the dest buffer is too small or the source string is invalid.
  */
fpl_platform_api wchar_t *fplAnsiStringToWideString(const char *ansiSource, const uint32_t ansiSourceLen, wchar_t *wideDest, const uint32_t maxWideDestLen);
/**
  * \brief Converts the given 8-bit UTF-8 source ansi string with length in a 16-bit wide string.
  * \param utf8Source The 8-bit source ansi string.
  * \param utf8SourceLen The number of characters of the source wide string.
  * \param wideDest The 16-bit destination wide string buffer.
  * \param maxWideDestLen The total number of characters available in the destination buffer.
  * \note Null terminator is included always. Does not allocate any memory.
  * \return Returns the pointer to the first character in the destination buffer or fpl_null when either the dest buffer is too small or the source string is invalid.
  */
fpl_platform_api wchar_t *fplUTF8StringToWideString(const char *utf8Source, const uint32_t utf8SourceLen, wchar_t *wideDest, const uint32_t maxWideDestLen);
/**
  * \brief Fills out the given destination ansi string buffer with a formatted string, using the format specifier and variable arguments.
  * \param ansiDestBuffer The 8-bit destination ansi string buffer.
  * \param maxAnsiDestBufferLen The total number of characters available in the destination buffer.
  * \param format The string format.
  * \param ... Variable arguments.
  * \note This is most likely just a wrapper call to vsnprintf()
  * \return Pointer to the first character in the destination buffer or fpl_null.
  */
fpl_platform_api char *fplFormatAnsiString(char *ansiDestBuffer, const uint32_t maxAnsiDestBufferLen, const char *format, ...);

/** \}*/

/**
  * \defgroup Files Files/IO functions
  * \brief Tons of file and directory IO functions
  * \{
  */

//! Internal file handle union
typedef union fplInternalFileHandle {
#if defined(FPL_PLATFORM_WIN32)
	//! Win32 file handle
	HANDLE win32FileHandle;
#elif defined(FPL_SUBPLATFORM_POSIX)
	//! Posix file handle
	int posixFileHandle;
#endif
} fplInternalFileHandle;

//! Handle to a loaded/created file
typedef struct fplFileHandle {
	//! Internal file handle
	fplInternalFileHandle internalHandle;
	//! File opened successfully
	bool isValid;
} fplFileHandle;

//! File position mode (Beginning, Current, End)
typedef enum fplFilePositionMode {
	//! Starts from the beginning
	fplFilePositionMode_Beginning = 0,
	//! Starts from the current position
	fplFilePositionMode_Current,
	//! Starts from the end
	fplFilePositionMode_End
} fplFilePositionMode;

//! File entry type (File, Directory, etc.)
typedef enum fplFileEntryType {
	//! Unknown entry type
	fplFileEntryType_Unknown = 0,
	//! Entry is a file
	fplFileEntryTypeFile,
	//! Entry is a directory
	fplFileEntryTypeDirectory
} fplFileEntryType;

//! File attribute flags (Normal, Readonly, Hidden, etc.)
typedef enum fplFileAttributeFlags {
	//! No attributes
	fplFileAttributeFlags_None = 0,
	//! Normal
	fplFileAttributeFlags_Normal = 1 << 0,
	//! Readonly
	fplFileAttributeFlags_ReadOnly = 1 << 1,
	//! Hidden
	fplFileAttributeFlags_Hidden = 1 << 2,
	//! Archive
	fplFileAttributeFlags_Archive = 1 << 3,
	//! System
	fplFileAttributeFlags_System = 1 << 4
} fplFileAttributeFlags;

//! Maximum length of a file entry path
#define FPL_MAX_FILEENTRY_PATH_LENGTH 1024

//! Internal file entry handle
typedef struct fplInternalFileEntryHandle {
#if defined(FPL_PLATFORM_WIN32)
	//! Win32 file handle
	HANDLE win32FileHandle;
#elif defined(FPL_SUBPLATFORM_POSIX)
	//! Posix file handle
	int posixFileHandle;
#endif
} fplInternalFileEntryHandle;

//! Entry for storing current file informations (path, type, attributes, etc.)
typedef struct fplFileEntry {
	//! File path
	char path[FPL_MAX_FILEENTRY_PATH_LENGTH];
	//! Internal file handle
	fplInternalFileEntryHandle internalHandle;
	//! Entry type
	fplFileEntryType type;
	//! File attributes
	fplFileAttributeFlags attributes;
} fplFileEntry;

/**
  * \brief Opens a binary file for reading from a ansi string path and returns the handle of it.
  * \param filePath Ansi file path.
  * \param handle Pointer to the file handle
  * \return True when binary ansi file was opened, false otherwise
  */
fpl_platform_api bool fplOpenAnsiBinaryFile(const char *filePath, fplFileHandle *handle);
/**
  * \brief Opens a binary file for reading from a wide string path and returns the handle of it.
  * \param filePath Wide file path.
  * \param handle Pointer to the file handle
  * \return True when binary wide file was opened, false otherwise
  */
fpl_platform_api bool fplOpenWideBinaryFile(const wchar_t *filePath, fplFileHandle *handle);
/**
  * \brief Create a binary file for writing to the given ansi string path and returns the handle of it.
  * \param filePath Ansi file path.
  * \param handle Pointer to the file handle
  * \return True when binary ansi file was created, false otherwise
  */
fpl_platform_api bool fplCreateAnsiBinaryFile(const char *filePath, fplFileHandle *handle);
/**
  * \brief Create a binary file for writing to the given wide string path and returns the handle of it.
  * \param filePath Wide file path.
  * \param handle Pointer to the file handle
  * \return True when binary wide file was created, false otherwise
  */
fpl_platform_api bool CreateWideBinaryFile(const wchar_t *filePath, fplFileHandle *handle);
/**
  * \brief Reads a block from the given file handle and returns the number of bytes read.
  * \param fileHandle Reference to the file handle.
  * \param sizeToRead Number of bytes to read.
  * \param targetBuffer Target memory to write into.
  * \param maxTargetBufferSize Total number of bytes available in the target buffer.
  * \note Its limited to files < 2 GB.
  * \return Number of bytes read or zero.
  */
fpl_platform_api uint32_t fplReadFileBlock32(const fplFileHandle *fileHandle, const uint32_t sizeToRead, void *targetBuffer, const uint32_t maxTargetBufferSize);
/**
  * \brief Writes a block to the given file handle and returns the number of bytes written.
  * \param fileHandle Reference to the file handle.
  * \param sourceBuffer Source memory to read from.
  * \param sourceSize Number of bytes to write.
  * \note Its limited to files < 2 GB.
  * \return Number of bytes written or zero.
  */
fpl_platform_api uint32_t fplWriteFileBlock32(const fplFileHandle *fileHandle, void *sourceBuffer, const uint32_t sourceSize);
/**
  * \brief Sets the current file position by the given position, depending on the mode its absolute or relative.
  * \param fileHandle Reference to the file handle.
  * \param position Position in bytes
  * \param mode Position mode
  * \note Its limited to files < 2 GB.
  */
fpl_platform_api void fplSetFilePosition32(const fplFileHandle *fileHandle, const int32_t position, const fplFilePositionMode mode);
/**
  * \brief Returns the current file position in bytes.
  * \param fileHandle Reference to the file handle.
  * \note Its limited to files < 2 GB.
  * \return Current file position in bytes.
  */
fpl_platform_api uint32_t fplGetFilePosition32(const fplFileHandle *fileHandle);
/**
  * \brief Closes the given file and releases the underlying resources and clears the handle to zero.
  * \param fileHandle Reference to the file handle.
  */
fpl_platform_api void CloseFile(fplFileHandle *fileHandle);

// @TODO(final): Add 64-bit file operations
// @TODO(final): Add wide file operations

/**
  * \brief Returns the 32-bit file size in bytes for the given file.
  * \param filePath Ansi path to the file.
  * \note Its limited to files < 2 GB.
  * \return File size in bytes or zero.
  */
fpl_platform_api uint32_t fplGetFileSizeFromPath32(const char *filePath);
/**
  * \brief Returns the 32-bit file size in bytes for a opened file.
  * \param fileHandle Reference to the file handle.
  * \note Its limited to files < 2 GB.
  * \return File size in bytes or zero.
  */
fpl_platform_api uint32_t fplGetFileSizeFromHandle32(const fplFileHandle *fileHandle);
/**
  * \brief Returns true when the given file physically exists.
  * \param filePath Ansi path to the file.
  * \return True when the file exists, otherwise false.
  */
fpl_platform_api bool fplFileExists(const char *filePath);
/**
  * \brief Copies the given source file to the target path and returns true when copy was successful.
  * \param sourceFilePath Ansi source file path.
  * \param targetFilePath Ansi target file path.
  * \param overwrite When true the target file always be overwritten, otherwise it will return false when file already exists.
  * \return True when the file was copied, otherwise false.
  */
fpl_platform_api bool fplFileCopy(const char *sourceFilePath, const char *targetFilePath, const bool overwrite);
/**
  * \brief Movies the given source file to the target file and returns true when the move was successful.
  * \param sourceFilePath Ansi source file path.
  * \param targetFilePath Ansi target file path.
  * \return True when the file was moved, otherwise false.
  */
fpl_platform_api bool fplFileMove(const char *sourceFilePath, const char *targetFilePath);
/**
  * \brief Deletes the given file without confirmation and returns true when the deletion was successful.
  * \param filePath Ansi path to the file.
  * \return True when the file was deleted, otherwise false.
  */
fpl_platform_api bool fplFileDelete(const char *filePath);

/**
  * \brief Creates all the directories in the given path.
  * \param path Ansi path to the directory.
  * \return True when at least one directory was created, otherwise false.
  */
fpl_platform_api bool fplDirectoriesCreate(const char *path);
/**
  * \brief Returns true when the given directory physically exists.
  * \param path Ansi path to the directory.
  * \return True when the directory exists, otherwise false.
  */
fpl_platform_api bool fplDirectoryExists(const char *path);
/**
  * \brief Deletes the given empty directory without confirmation and returns true when the deletion was successful.
  * \param path Ansi path to the directory.
  * \return True when the empty directory was deleted, otherwise false.
  */
fpl_platform_api bool fplDirectoryRemove(const char *path);
/**
  * \brief Iterates through files / directories in the given directory.
  * \param pathAndFilter The path with its included after the path separator.
  * \param firstEntry The reference to a file entry.
  * \note The path must contain the filter as well.
  * \return Returns true when there was a first entry found otherwise false.
  */
fpl_platform_api bool fplListFilesBegin(const char *pathAndFilter, fplFileEntry *firstEntry);
/**
  * \brief Gets the next file entry from iterating through files / directories.
  * \param nextEntry The reference to the current file entry.
  * \return Returns true when there was a next file otherwise false if not.
  */
fpl_platform_api bool fplListFilesNext(fplFileEntry *nextEntry);
/**
  * \brief Releases opened resources from iterating through files / directories.
  * \param lastEntry The reference to the last file entry.
  */
fpl_platform_api void fplListFilesEnd(fplFileEntry *lastEntry);

/** \}*/

/**
  * \defgroup Paths Path functions
  * \brief Functions for retrieving paths like HomePath, ExecutablePath, etc.
  * \{
  */

// @TODO(final): Support wide path for 'paths' as well

/**
  * \brief Returns the full path to this executable, including the executable file name.
  * \param destPath Destination buffer
  * \param maxDestLen Total number of characters available in the destination buffer.
  * \note Result is written in the destination buffer.
  * \return Returns the pointer to the first character in the destination buffer or fpl_null.
  */
fpl_platform_api char *fplGetExecutableFilePath(char *destPath, const uint32_t maxDestLen);
/**
  * \brief Returns the full path to your home directory.
  * \param destPath Destination buffer
  * \param maxDestLen Total number of characters available in the destination buffer.
  * \note Result is written in the destination buffer.
  * \return Returns the pointer to the first character in the destination buffer or fpl_null.
  */
fpl_platform_api char *fplGetHomePath(char *destPath, const uint32_t maxDestLen);
/**
  * \brief Returns the path from the given source path.
  * \param sourcePath Source path to extract from.
  * \param destPath Destination buffer
  * \param maxDestLen Total number of characters available in the destination buffer.
  * \note Result is written in the destination buffer.
  * \return Returns the pointer to the first character in the destination buffer or fpl_null.
  */
fpl_common_api char *fplExtractFilePath(const char *sourcePath, char *destPath, const uint32_t maxDestLen);
/**
  * \brief Returns the file extension from the given source path.
  * \param sourcePath Source path to extract from.
  * \return Returns the pointer to the first character of the extension.
  */
fpl_common_api const char *fplExtractFileExtension(const char *sourcePath);
/**
  * \brief Returns the file name including the file extension from the given source path.
  * \param sourcePath Source path to extract from.
  * \return Returns the pointer to the first character of the filename.
  */
fpl_common_api const char *fplExtractFileName(const char *sourcePath);
/**
  * \brief Changes the file extension on the given source path and writes the result into the destination path.
  * \param filePath File path to search for the extension.
  * \param newFileExtension New file extension.
  * \param destPath Destination buffer
  * \param maxDestLen Total number of characters available in the destination buffer.
  * \note Result is written in the destination buffer.
  * \return Returns the pointer to the first character in the destination buffer or fpl_null.
  */
fpl_common_api char *fplChangeFileExtension(const char *filePath, const char *newFileExtension, char *destPath, const uint32_t maxDestLen);
/**
  * \brief Combines all included path by the systems path separator.
  * \param destPath Destination buffer
  * \param maxDestPathLen Total number of characters available in the destination buffer.
  * \param pathCount Number of dynamic path arguments.
  * \param ... Dynamic path arguments.
  * \note Result is written in the destination buffer.
  * \return Returns the pointer to the first character in the destination buffer or fpl_null.
  */
fpl_common_api char *fplPathCombine(char *destPath, const uint32_t maxDestPathLen, const uint32_t pathCount, ...);

/** \}*/

#if defined(FPL_ENABLE_WINDOW)
/**
* \defgroup WindowEvents Window events
* \brief Window event structures
* \{
*/

//! Mapped keys (Based on MS Virtual-Key-Codes, mostly directly mapped from ASCII)
typedef enum fplKey {
	fplKey_None = 0,

	// 0x07: Undefined

	fplKey_Backspace = 0x08,
	fplKey_Tab = 0x09,

	// 0x0A-0x0B: Reserved

	fplKey_Clear = 0x0C,
	fplKey_Enter = 0x0D,

	// 0x0E-0x0F: Undefined

	fplKey_Shift = 0x10,
	fplKey_Control = 0x11,
	fplKey_Alt = 0x12,
	fplKey_Pause = 0x13,
	fplKey_CapsLock = 0x14,

	// 0x15: IME-fplKeys
	// 0x16: Undefined
	// 0x17-0x19 IME-fplKeys
	// 0x1A: Undefined

	fplKey_Escape = 0x1B,

	// 0x1C - 0x1F: IME-fplKeys

	fplKey_Space = 0x20,
	fplKey_PageUp = 0x21,
	fplKey_PageDown = 0x22,
	fplKey_End = 0x23,
	fplKey_Home = 0x24,
	fplKey_Left = 0x25,
	fplKey_Up = 0x26,
	fplKey_Right = 0x27,
	fplKey_Down = 0x28,
	fplKey_Select = 0x29,
	fplKey_Print = 0x2A,
	fplKey_Execute = 0x2B,
	fplKey_Snapshot = 0x2C,
	fplKey_Insert = 0x2D,
	fplKey_Delete = 0x2E,
	fplKey_Help = 0x2F,

	fplKey_0 = 0x30,
	fplKey_1 = 0x31,
	fplKey_2 = 0x32,
	fplKey_3 = 0x33,
	fplKey_4 = 0x34,
	fplKey_5 = 0x35,
	fplKey_6 = 0x36,
	fplKey_7 = 0x37,
	fplKey_8 = 0x38,
	fplKey_9 = 0x39,

	// 0x3A-0x40: Undefined

	fplKey_A = 0x41,
	fplKey_B = 0x42,
	fplKey_C = 0x43,
	fplKey_D = 0x44,
	fplKey_E = 0x45,
	fplKey_F = 0x46,
	fplKey_G = 0x47,
	fplKey_H = 0x48,
	fplKey_I = 0x49,
	fplKey_J = 0x4A,
	fplKey_K = 0x4B,
	fplKey_L = 0x4C,
	fplKey_M = 0x4D,
	fplKey_N = 0x4E,
	fplKey_O = 0x4F,
	fplKey_P = 0x50,
	fplKey_Q = 0x51,
	fplKey_R = 0x52,
	fplKey_S = 0x53,
	fplKey_T = 0x54,
	fplKey_U = 0x55,
	fplKey_V = 0x56,
	fplKey_W = 0x57,
	fplKey_X = 0x58,
	fplKey_Y = 0x59,
	fplKey_Z = 0x5A,

	fplKey_LeftWin = 0x5B,
	fplKey_RightWin = 0x5C,
	fplKey_Apps = 0x5D,

	// 0x5E: Reserved

	fplKey_Sleep = 0x5F,
	fplKey_NumPad0 = 0x60,
	fplKey_NumPad1 = 0x61,
	fplKey_NumPad2 = 0x62,
	fplKey_NumPad3 = 0x63,
	fplKey_NumPad4 = 0x64,
	fplKey_NumPad5 = 0x65,
	fplKey_NumPad6 = 0x66,
	fplKey_NumPad7 = 0x67,
	fplKey_NumPad8 = 0x68,
	fplKey_NumPad9 = 0x69,
	fplKey_Multiply = 0x6A,
	fplKey_Add = 0x6B,
	fplKey_Separator = 0x6C,
	fplKey_Substract = 0x6D,
	fplKey_Decimal = 0x6E,
	fplKey_Divide = 0x6F,
	fplKey_F1 = 0x70,
	fplKey_F2 = 0x71,
	fplKey_F3 = 0x72,
	fplKey_F4 = 0x73,
	fplKey_F5 = 0x74,
	fplKey_F6 = 0x75,
	fplKey_F7 = 0x76,
	fplKey_F8 = 0x77,
	fplKey_F9 = 0x78,
	fplKey_F10 = 0x79,
	fplKey_F11 = 0x7A,
	fplKey_F12 = 0x7B,
	fplKey_F13 = 0x7C,
	fplKey_F14 = 0x7D,
	fplKey_F15 = 0x7E,
	fplKey_F16 = 0x7F,
	fplKey_F17 = 0x80,
	fplKey_F18 = 0x81,
	fplKey_F19 = 0x82,
	fplKey_F20 = 0x83,
	fplKey_F21 = 0x84,
	fplKey_F22 = 0x85,
	fplKey_F23 = 0x86,
	fplKey_F24 = 0x87,

	// 0x88-8F: Unassigned

	fplKey_NumLock = 0x90,
	fplKey_Scroll = 0x91,

	// 0x92-9x96: OEM specific
	// 0x97-0x9F: Unassigned

	fplKey_LeftShift = 0xA0,
	fplKey_RightShift = 0xA1,
	fplKey_LeftControl = 0xA2,
	fplKey_RightControl = 0xA3,
	fplKey_LeftAlt = 0xA4,
	fplKey_RightAlt = 0xA5,

	// 0xA6-0xFE: Dont care
} fplKey;

//! Window event type (Resized, PositionChanged, etc.)
typedef enum fplWindowEventType {
	//! None window event type
	fplWindowEventType_None = 0,
	//! Window has been resized
	fplWindowEventType_Resized,
	//! Window got focus
	fplWindowEventType_GotFocus,
	//! Window lost focus
	fplWindowEventType_LostFocus,
} fplWindowEventType;

//! Window event data (Size, Position, etc.)
typedef struct fplWindowEvent {
	//! Window event type
	fplWindowEventType type;
	//! Window width in screen coordinates
	uint32_t width;
	//! Window height in screen coordinates
	uint32_t height;
} fplWindowEvent;

//! Keyboard event type (KeyDown, KeyUp, Char, ...)
typedef enum fplKeyboardEventType {
	//! None key event type
	fplKeyboardEventType_None = 0,
	//! Key is down
	fplKeyboardEventType_KeyDown,
	//! Key was released
	fplKeyboardEventType_KeyUp,
	//! Character was entered
	fplKeyboardEventType_CharInput,
} fplKeyboardEventType;

//! Keyboard modifier flags (Alt, Ctrl, ...)
typedef enum fplKeyboardModifierFlags {
	//! No modifiers
	fplKeyboardModifierFlags_None = 0,
	//! Alt key is down
	fplKeyboardModifierFlags_Alt = 1 << 0,
	//! Ctrl key is down
	fplKeyboardModifierFlags_Ctrl = 1 << 1,
	//! Shift key is down
	fplKeyboardModifierFlags_Shift = 1 << 2,
	//! Super key is down
	fplKeyboardModifierFlags_Super = 1 << 3,
} fplKeyboardModifierFlags;

//! Keyboard event data (Type, Keycode, Mapped key, etc.)
typedef struct fplKeyboardEvent {
	//! Keyboard event type
	fplKeyboardEventType type;
	//! Raw key code
	uint64_t keyCode;
	//! Mapped key
	fplKey mappedKey;
	//! Keyboard modifiers
	fplKeyboardModifierFlags modifiers;
} fplKeyboardEvent;

//! Mouse event type (Move, ButtonDown, ...)
typedef enum fplMouseEventType {
	//! No mouse event type
	fplMouseEventType_None,
	//! Mouse position has been changed
	fplMouseEventType_Move,
	//! Mouse button is down
	fplMouseEventType_ButtonDown,
	//! Mouse button was released
	fplMouseEventType_ButtonUp,
	//! Mouse wheel up/down
	fplMouseEventType_Wheel,
} fplMouseEventType;

//! Mouse button type (Left, Right, ...)
typedef enum fplMouseButtonType {
	//! No mouse button
	fplMouseButtonType_None = -1,
	//! Left mouse button
	fplMouseButtonType_Left = 0,
	//! Right mouse button
	fplMouseButtonType_Right = 1,
	//! Middle mouse button
	fplMouseButtonType_Middle = 2,
} fplMouseButtonType;

//! Mouse event data (Type, Button, Position, etc.)
typedef struct fplMouseEvent {
	//! Mouse event type
	fplMouseEventType type;
	//! Mouse button
	fplMouseButtonType mouseButton;
	//! Mouse X-Position
	int32_t mouseX;
	//! Mouse Y-Position
	int32_t mouseY;
	//! Mouse wheel delta
	float wheelDelta;
} fplMouseEvent;

//! Gamepad event type (Connected, Disconnected, StateChanged, etc.)
typedef enum fplGamepadEventType {
	//! No gamepad event
	fplGamepadEventType_None = 0,
	//! Gamepad connected
	fplGamepadEventType_Connected,
	//! Gamepad disconnected
	fplGamepadEventType_Disconnected,
	//! Gamepad state updated
	fplGamepadEventType_StateChanged,
} fplGamepadEventType;

//! Gamepad button (IsDown, etc.)
typedef struct fplGamepadButton {
	//! Is button down
	bool isDown;
} fplGamepadButton;

//! Gamepad state data
typedef struct fplGamepadState {
	union {
		struct {
			//! Digital button up
			fplGamepadButton dpadUp;
			//! Digital button right
			fplGamepadButton dpadRight;
			//! Digital button down
			fplGamepadButton dpadDown;
			//! Digital button left
			fplGamepadButton dpadLeft;

			//! Action button A
			fplGamepadButton actionA;
			//! Action button B
			fplGamepadButton actionB;
			//! Action button X
			fplGamepadButton actionX;
			//! Action button Y
			fplGamepadButton actionY;

			//! Start button
			fplGamepadButton start;
			//! Back button
			fplGamepadButton back;

			//! Analog left thumb button
			fplGamepadButton leftThumb;
			//! Analog right thumb button
			fplGamepadButton rightThumb;

			//! Left shoulder button
			fplGamepadButton leftShoulder;
			//! Right shoulder button
			fplGamepadButton rightShoulder;
		};
		//! All gamepad buttons
		fplGamepadButton buttons[14];
	};

	//! Analog left thumb X in range (-1.0 to 1.0f)
	float leftStickX;
	//! Analog left thumb Y in range (-1.0 to 1.0f)
	float leftStickY;
	//! Analog right thumb X in range (-1.0 to 1.0f)
	float rightStickX;
	//! Analog right thumb Y in range (-1.0 to 1.0f)
	float rightStickY;

	//! Analog left trigger in range (-1.0 to 1.0f)
	float leftTrigger;
	//! Analog right trigger in range (-1.0 to 1.0f)
	float rightTrigger;
} fplGamepadState;

//! Gamepad event data (Type, Device, State, etc.)
typedef struct fplGamepadEvent {
	//! Gamepad event type
	fplGamepadEventType type;
	//! Gamepad device index
	uint32_t deviceIndex;
	//! Full gamepad state
	fplGamepadState state;
} fplGamepadEvent;

//! Event type (Window, Keyboard, Mouse, ...)
typedef enum fplEventType {
	//! None event type
	fplEventType_None = 0,
	//! Window event
	fplEventType_Window,
	//! Keyboard event
	fplEventType_Keyboard,
	//! Mouse event
	fplEventType_Mouse,
	//! Gamepad event
	fplEventType_Gamepad,
} fplEventType;

//! Event data (Type, Window, Keyboard, Mouse, etc.)
typedef struct fplEvent {
	//! Event type
	fplEventType type;
	union {
		//! Window event data
		fplWindowEvent window;
		//! Keyboard event data
		fplKeyboardEvent keyboard;
		//! Mouse event data
		fplMouseEvent mouse;
		//! Gamepad event data
		fplGamepadEvent gamepad;
	};
} fplEvent;

/**
  * \brief Gets the top event from the internal event queue and removes it.
  * \param ev Reference to an event
  * \return Returns false when there are no events left, otherwise true.
  */
fpl_common_api bool fplPollEvent(fplEvent *ev);
/**
  * \brief Removes all the events from the internal event queue.
  * \note Dont call when you care about any event!
  */
fpl_common_api void fplClearEvents();
/**
  * \brief Reads the next window event from the OS and pushes it into the internal queue.
  * \return Returns true when there was a event from the OS, otherwise true.
  * \note Use this only if dont use \ref fplWindowUpdate() and want to handle the events more granular!
  */
fpl_platform_api bool fplPushEvent();
/**
  * \brief Updates the game controller states and detects new and disconnected devices.
  * \note Use this only if dont use \ref fplWindowUpdate() and want to handle the events more granular!
  */
fpl_platform_api void fplUpdateGameControllers();

/*\}*/

/**
  * \defgroup WindowBase Window functions
  * \brief Functions for reading/setting/handling the window
  * \{
  */

  //! Window size in screen coordinates
typedef struct fplWindowSize {
	//! Width in screen coordinates
	uint32_t width;
	//! Height in screen coordinates
	uint32_t height;
} fplWindowSize;

//! Window position in screen coordinates
typedef struct fplWindowPosition {
	//! Left position in screen coordinates
	int32_t left;
	//! Top position in screen coordinates
	int32_t top;
} fplWindowPosition;

/**
  * \brief Returns true when the window is active.
  * \return True when the window is active, otherwise false.
  */
fpl_platform_api bool fplIsWindowRunning();
/**
  * \brief Processes the message queue of the window.
  * \note This will update the game controller states as well.
  * \return True when the window is still active, otherwise false.
  */
fpl_platform_api bool fplWindowUpdate();
/**
  * \brief Enables or disables the window cursor.
  * \param value Set this to true for enabling the cursor or false for disabling the cursor.
  */
fpl_platform_api void fplSetWindowCursorEnabled(const bool value);
/**
  * \brief Returns the inner window area.
  * \return Window area size
  */
fpl_platform_api fplWindowSize GetWindowArea();
/**
  * \brief Resizes the window to fit the inner area to the given size.
  * \param width Width in screen units
  * \param height Height in screen units
  */
fpl_platform_api void fplSetWindowArea(const uint32_t width, const uint32_t height);
/**
  * \brief Returns true when the window is resizable.
  * \return True when the window resizable, otherwise false.
  */
fpl_platform_api bool fplIsWindowResizable();
/**
  * \brief Enables or disables the ability to resize the window.
  * \param value Set this to true for making the window resizable or false for making it static
  */
fpl_platform_api void fplSetWindowResizeable(const bool value);
/**
  * \brief Enables or disables fullscreen mode.
  * \param value Set this to true for changing the window to fullscreen or false for switching it back to window mode.
  * \param fullscreenWidth Optional fullscreen width in screen units. When set to zero the desktop default is being used. (Default: 0)
  * \param fullscreenHeight Optional fullscreen height in screen units. When set to zero the desktop default is being used. (Default: 0)
  * \param refreshRate Optional refresh rate in screen units. When set to zero the desktop default is being used. (Default: 0)
  * \return True when the window was changed to the desire fullscreen mode, false when otherwise.
  */
fpl_platform_api bool fplSetWindowFullscreen(const bool value, const uint32_t fullscreenWidth, const uint32_t fullscreenHeight, const uint32_t refreshRate);
/**
  * \brief Returns true when the window is in fullscreen mode
  * \return True when the window is in fullscreen mode, otherwise false.
  */
fpl_platform_api bool fplIsWindowFullscreen();
/**
  * \brief Returns the absolute window position.
  * \return Window position in screen units
  */
fpl_platform_api fplWindowPosition fplGetWindowPosition();
/**
  * \brief Sets the window absolut position to the given coordinates.
  * \param left Left position in screen units.
  * \param top Top position in screen units.
  */
fpl_platform_api void fplSetWindowPosition(const int32_t left, const int32_t top);
/**
  * \brief Sets the window title.
  * \param title New title ansi string
  */
fpl_platform_api void fplSetWindowTitle(const char *title);

/*\}*/

/**
  * \defgroup WindowClipboard Clipboard functions
  * \brief Functions for reading/writing clipboard data
  * \{
  */

  /**
	* \brief Returns the current clipboard ansi text.
	* \param dest The destination ansi string buffer to write the clipboard text into.
	* \param maxDestLen The total number of characters available in the destination buffer.
	* \return Pointer to the first character in the clipboard text or fpl_null otherwise.
	*/
fpl_platform_api char *fplGetClipboardAnsiText(char *dest, const uint32_t maxDestLen);
/**
  * \brief Returns the current clipboard wide text.
  * \param dest The destination wide string buffer to write the clipboard text into.
  * \param maxDestLen The total number of characters available in the destination buffer.
  * \return Pointer to the first character in the clipboard text or fpl_null otherwise.
  */
fpl_platform_api wchar_t *fplGetClipboardWideText(wchar_t *dest, const uint32_t maxDestLen);
/**
  * \brief Overwrites the current clipboard ansi text with the given one.
  * \param ansiSource The new clipboard ansi string.
  * \return Returns true when the text in the clipboard was changed, otherwise false.
  */
fpl_platform_api bool fplSetClipboardAnsiText(const char *ansiSource);
/**
  * \brief Overwrites the current clipboard wide text with the given one.
  * \param wideSource The new clipboard wide string.
  * \return Returns true when the text in the clipboard was changed, otherwise false.
  */
fpl_platform_api bool fplSetClipboardWideText(const wchar_t *wideSource);

/** \}*/
#endif // FPL_ENABLE_WINDOW

#if defined(FPL_ENABLE_VIDEO)
/**
  * \defgroup Video Video functions
  * \brief Functions for retrieving or resizing the video buffer
  * \{
  */

//! Video rectangle
typedef struct fplVideoRect {
	//! Left position in pixels
	int32_t x;
	//! Top position in pixels
	int32_t y;
	//! Width in pixels
	int32_t width;
	//! Height in pixels
	int32_t height;
} fplVideoRect;

/**
  * \brief Makes a video rectangle from a LT-RB rectangle
  * \param left Left position in screen units.
  * \param top Top position in screen units.
  * \param right Right position in screen units.
  * \param bottom Bottom position in screen units.
  * \return Computed video rectangle
  */
fpl_inline fplVideoRect fplCreateVideoRectFromLTRB(int32_t left, int32_t top, int32_t right, int32_t bottom) {
	fplVideoRect result = { left, top, (right - left) + 1, (bottom - top) + 1 };
	return(result);
}

/**
  * \brief Returns the string for the given video driver
  * \param driver The audio driver
  * \return String for the given audio driver
  */
fpl_inline const char *fplGetVideoDriverString(fplVideoDriverType driver) {
	const char *VIDEO_DRIVER_TYPE_STRINGS[] = {
		"None",
		"OpenGL",
		"Software",
	};
	uint32_t index = (uint32_t)driver;
	FPL_ASSERT(index < FPL_ARRAYCOUNT(VIDEO_DRIVER_TYPE_STRINGS));
	const char *result = VIDEO_DRIVER_TYPE_STRINGS[index];
	return(result);
}


//! Video backbuffer container. Use this for accessing the pixels directly. Use with care!
typedef struct fplVideoBackBuffer {
	//! The 32-bit pixel top-down array, format: 0xAABBGGRR. Do not modify before WindowUpdate
	uint32_t *pixels;
	//! The width of the backbuffer in pixels. Do not modify, it will be set automatically.
	uint32_t width;
	//! The height of the backbuffer in pixels. Do not modify, it will be set automatically.
	uint32_t height;
	//! The size of one entire pixel with all 4 components in bytes. Do not modify, it will be set automatically.
	size_t pixelStride;
	//! The width of one line in bytes. Do not modify, it will be set automatically.
	size_t lineWidth;
	//! The output rectangle for displaying the backbuffer (Size may not match backbuffer size!)
	fplVideoRect outputRect;
	//! Set this to true to actually use the output rectangle
	bool useOutputRect;
} fplVideoBackBuffer;

/**
  * \brief Returns the pointer to the video software context.
  * \warning Do not release this memory by any means, otherwise you will corrupt heap memory!
  * \return Pointer to the video backbuffer.
  */
fpl_common_api fplVideoBackBuffer *fplGetVideoBackBuffer();
/**
  * \brief Resizes the current video backbuffer.
  * \param width Width in pixels.
  * \param height Height in pixels.
  * \return Returns true when video back buffer could be resized or false otherwise.
  */
fpl_common_api bool fplResizeVideoBackBuffer(const uint32_t width, const uint32_t height);
/**
  * \brief Returns the current video driver type used.
  * \return The current video driver type used.
  */
fpl_common_api fplVideoDriverType fplGetVideoDriver();

/**
  * \brief Forces the window to redraw or to swap the back/front buffer.
  */
fpl_common_api void fplVideoFlip();

/** \}*/
#endif // FPL_ENABLE_VIDEO

#if defined(FPL_ENABLE_AUDIO)
/**
  * \defgroup Audio Audio functions
  * \brief Functions for start/stop playing audio and retrieving/changing some audio related settings.
  * \{
  */

//! Audio result
typedef enum fplAudioResult {
	fplAudioResult_None = 0,
	fplAudioResult_Success,
	fplAudioResult_DeviceNotInitialized,
	fplAudioResult_DeviceAlreadyStopped,
	fplAudioResult_DeviceAlreadyStarted,
	fplAudioResult_DeviceBusy,
	fplAudioResult_Failed,
} fplAudioResult;

/**
  * \brief Start playing asyncronous audio.
  * \return Audio result code.
  */
fpl_common_api fplAudioResult fplPlayAudio();
/**
  * \brief Stop playing asyncronous audio.
  * \return Audio result code.
  */
fpl_common_api fplAudioResult fplStopAudio();
/**
  * \brief Returns the native format for the current audio device.
  * \return Copy fo the audio device format.
  */
fpl_common_api fplAudioDeviceFormat fplGetAudioHardwareFormat();
/**
  * \brief Overwrites the audio client read callback.
  * \param newCallback Pointer to the client read callback.
  * \param userData Pointer to the client/user data.
  * \note This has no effect when audio is already playing, you have to call it when audio is in a stopped state!
  */
fpl_common_api void fplSetAudioClientReadCallback(fpl_audio_client_read_callback *newCallback, void *userData);
/**
  * \brief Gets all playback audio devices.
  * \param devices Target device id array.
  * \param maxDeviceCount Total number of devices available in the devices array.
  * \return Number of devices found.
  */
fpl_common_api uint32_t fplGetAudioDevices(fplAudioDeviceInfo *devices, uint32_t maxDeviceCount);

/**
  * \brief Returns the number of bytes required to write one sample with one channel
  * \param format The audio format
  * \return Number of bytes for one sample with one channel
  */
fpl_inline uint32_t fplGetAudioSampleSizeInBytes(const fplAudioFormatType format) {
	switch(format) {
		case fplAudioFormatType_U8:
			return 1;
		case fplAudioFormatType_S16:
			return 2;
		case fplAudioFormatType_S24:
			return 3;
		case fplAudioFormatType_S32:
		case fplAudioFormatType_F32:
			return 4;
		case fplAudioFormatType_S64:
		case fplAudioFormatType_F64:
			return 8;
		default:
			return 0;
	}
}

/**
  * \brief Returns the string for the given format type
  * \param format The audio format
  * \return String for the given format type
  */
fpl_inline const char *fplGetAudioFormatString(const fplAudioFormatType format) {
	// @NOTE(final): Order must be equal to the AudioFormatType enum!
	const char *AUDIO_FORMAT_TYPE_STRINGS[] = {
		"None",
		"U8",
		"S16",
		"S24",
		"S32",
		"S64",
		"F32",
		"F64",
	};
	uint32_t index = (uint32_t)format;
	FPL_ASSERT(index < FPL_ARRAYCOUNT(AUDIO_FORMAT_TYPE_STRINGS));
	const char *result = AUDIO_FORMAT_TYPE_STRINGS[index];
	return(result);
}

/**
  * \brief Returns the string for the given audio driver
  * \param driver The audio driver
  * \return String for the given audio driver
  */
fpl_inline const char *fplGetAudioDriverString(fplAudioDriverType driver) {
	const char *AUDIO_DRIVER_TYPE_STRINGS[] = {
		"None",
		"Auto",
		"DirectSound",
	};
	uint32_t index = (uint32_t)driver;
	FPL_ASSERT(index < FPL_ARRAYCOUNT(AUDIO_DRIVER_TYPE_STRINGS));
	const char *result = AUDIO_DRIVER_TYPE_STRINGS[index];
	return(result);
}

/**
  * \brief Returns the total frame count for given sample rate and buffer size in milliseconds
  * \param sampleRate The sample rate in Hz
  * \param bufferSizeInMilliSeconds The buffer size in number of milliseconds
  * \return Number of frames
  */
fpl_inline uint32_t fplGetAudioBufferSizeInFrames(uint32_t sampleRate, uint32_t bufferSizeInMilliSeconds) {
	uint32_t result = (sampleRate / 1000) * bufferSizeInMilliSeconds;
	return(result);
}

/**
  * \brief Returns the number of bytes required for one interleaved audio frame - containing all the channels
  * \param format The audio format
  * \param channelCount The number of channels
  * \return Number of bytes for one frame in bytes
  */
fpl_inline uint32_t fplGetAudioFrameSizeInBytes(const fplAudioFormatType format, const uint32_t channelCount) {
	uint32_t result = fplGetAudioSampleSizeInBytes(format) * channelCount;
	return(result);
}

/**
  * \brief Returns the total number of bytes for the buffer and the given parameters
  * \param format The audio format
  * \param channelCount The number of channels
  * \param frameCount The number of frames
  * \return Total number of bytes for the buffer
  */
fpl_inline uint32_t fplGetAudioBufferSizeInBytes(const fplAudioFormatType format, const uint32_t channelCount, const uint32_t frameCount) {
	uint32_t frameSize = fplGetAudioFrameSizeInBytes(format, channelCount);
	uint32_t result = frameSize * frameCount;
	return(result);
}

/** \}*/
#endif // FPL_ENABLE_AUDIO

#endif // FPL_INCLUDE_H

Edited by Finalspace on