-
Notifications
You must be signed in to change notification settings - Fork 79
/
gs.h
9839 lines (8255 loc) · 304 KB
/
gs.h
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
/*==============================================================================================================
* Copyright: 2020 John Jackson
* Gunslinger: A simple, header-only c99 multi-media framework
* File: gs.h
* Github: https://github.com/MrFrenik/gunslinger
All Rights Reserved
BSD 3-Clause License
Copyright (c) 2020 John Jackson
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are met:
1. Redistributions of source code must retain the above copyright notice, this
list of conditions and the following disclaimer.
2. Redistributions in binary form must reproduce the above copyright notice,
this list of conditions and the following disclaimer in the documentation
and/or other materials provided with the distribution.
3. Neither the name of the copyright holder nor the names of its contributors may be used to
endorse or promote products derived from this software without specific prior written permission.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIEDi
WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR
ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
(INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
=================================================================================================================*/
#ifndef GS_H
#define GS_H
/*═█═════════════════════════════════════════════════════════════════════════════════════█═╗
████ ██████╗ ██╗ ██╗███╗ ██╗███████╗██╗ ██╗███╗ ██╗ ██████╗ ███████╗██████╗ ██████═█
█║█ ██╔════╝ ██║ ██║████╗ ██║██╔════╝██║ ██║████╗ ██║██╔════╝ ██╔════╝██╔══██╗ ██═████
███ ██║ ███╗██║ ██║██╔██╗ ██║███████╗██║ ██║██╔██╗ ██║██║ ███╗█████╗ ██████╔╝ █████═██
╚██ ██║ ██║██║ ██║██║╚██╗██║╚════██║██║ ██║██║╚██╗██║██║ ██║██╔══╝ ██╔══██╗ ███ █╝█
█║█ ╚██████╔╝╚██████╔╝██║ ╚████║███████║███████╗██║██║ ╚████║╚██████╔╝███████╗██║ ██║ ██═████
████ ╚═════╝ ╚═════╝ ╚═╝ ╚═══╝╚══════╝╚══════╝╚═╝╚═╝ ╚═══╝ ╚═════╝ ╚══════╝╚═╝ ╚═╝ █═█═██
╚═██════════════════════════════════════════════════════════════════════════════════════██═╝*/
/*
Gunslinger is a header-only, c99 framework for multi-media applications and tools.
USAGE: (IMPORTANT)
=================================================================================================================
Before including, define the gunslinger implementation like this:
#define GS_IMPL
in EXACTLY ONE C or C++ file that includes this header, BEFORE the
include, like this:
#define GS_IMPL
#include "gs.h"
All other files should just #include "gs.h" without the #define.
(Thanks to SB for the template for this instructional message. I was too lazy to come up with my own wording.)
NOTE:
All main interface stuff in here, then system implementations can be in separate header files
All provided implementations will be in impl/xxx.h
This is just to keep everything from being in one huge file
================================================================================================================
Contained within (Contents):
* GS_APPLICATION
* GS_UTIL
* GS_CONTAINERS
* GS_ASSET_TYPES
* GS_MATH
* GS_LEXER
* GS_PLATFORM
* GS_GRAPHICS
* GS_AUDIO
================================================================================================================
GS_APPLICATION:
Gunslinger is a framework that expects to take flow control over your app and calls into your code
at certain sync points. These points are 'init', 'update', and 'shutdown'. When creating your application,
you provide certain information to the framework via a `gs_app_desc_t` descriptor object. Gunslinger acts as the
main entry point to your application, so instead of defining "main" as you typically would for a c/c++ program,
you instead implement the `gs_main` function that will be called by gunslinger. This last bit is optional and
a different method for entry is covered, however this is the most convenient way to use the framework.
Basic Example Application:
#define GS_IMPL
#include "gs.h"
void my_init(void* app) {
// Do your initialization
}
void my_update(void* app) {
// Do your updates
}
void my_shutdown(void* app) {
// Do your shutdown
}
gs_app_desc_t gs_main(int32_t argc, char** argv) {
return (gs_app_desc_t) {
.init = my_init, // Function pointer to call into your init code
.update = my_update, // Function pointer to call into your update code
.shutdown = my_shutdown // Function pointer to call into your shutdown code
};
}
If you do not provide information for any of this information, defaults will be provided by the framework.
Therefore, it is possible to return a completely empty app descriptor back to the framework to run:
gs_app_desc_t gs_main(int32_t argc, char** argv) {
return (gs_app_desc_t){0};
}
NOTE:
In addition to function callbacks, there are quite a few options available to provide for this descriptor,
such as window width, window height, window flags, window title, etc. Refer to the section for gs_app_desc_t
further in the code for all provided options.
It's also possible to define GS_NO_HIJACK_MAIN for your application. This will make it so gunslinger will not be
the main entry point to your application. You will instead be responsible for creating a gunslinger instance and
passing in your application description to it.
#define GS_NO_HIJACK_MAIN
int32_t main(int32_t argv, char** argc)
{
gs_app_desc_t app = {0}; // Fill this with whatever your app needs
gs_create(app); // Create instance of framework and run
while (gs_app()->is_running) {
gs_frame();
}
return 0;
}
NOTE:
Lastly, while it is possible to use gunslinger without it controlling the main application loop, this isn't recommended.
Internally, gunslinger does its best to handle the boiler plate drudge work of implementing (in correct order)
the various layers required for a basic hardware accelerated multi-media application program to work. This involves allocating
memory for internal data structures for these layers as well initializing them in a particular order so they can inter-operate
as expected. If you're interested in taking care of this yourself, look at the `gs_frame()` function to get a feeling
for how this is being handled.
GS_MATH:
Gunslinger includes utilities for common graphics/game related math structures. These aren't required to be used, however they are
used internally for certain function calls in various APIs. Where possible, I've tried to add as much redundancy as possible to
the APIs so that these structures are not required if you prefer.
* common utils:
- interpolation
* Vectors:
- gs_vec2: float[2]
- gs_vec3: float[3]
- gs_vec4: float[4]
* vector ops:
- dot product
- normalize
- add/subtract (component wise)
- multiply
- cross product
- length
*Quaternions:
- gs_quat: float[4]
* quaternion ops:
- add/subtract/multiply
- inverse
- conjugate
- angle/axis | axis/angle
- to euler | from euler
- to mat4
*Mat4x4:
- gs_mat4: float[16]
* mat4 ops:
- add/subtract/multiply
- transpose
- inverse
- homogenous transformations:
- rotation
- scale
- translate
- view:
- lookat
- projection:
- orthographic
- perspective
*VQS:
- gs_vqs: gs_vec3, gs_quat, gs_vec3
(SPECIAL NOTE):
`gs_vqs` is a transform structure that's commonly used in games/physics sims, especially with complex child/parent hierarchies. It stands for
`Vector-Quaternion-Scalar` to denote its internal components. Typically this encodes position, rotation (in quaternion), and a uniform scale
for transformation. Gunslinger uses non-uniform scale in the form of a gs_vec3.
gs_vqs xform = {0};
xform.position = gs_v3(...);
xform.rotation = gs_quat(...);
xform.scale = gs_v3(...);
This structure can then be converted into a final form float[16] mat4x4 for any typical homogenous graphics transformations:
gs_mat4 model = gs_vqs_to_mat4(&xform);
The real power in VQS transforms is the ability to easily encode parent/child hierarchies. This is done using the two functions
`gs_vqs_absolute_transform` and `gs_vqs_relative_transform`:
gs_vqs parent = ...;
gs_vqs child = ...; {
gs_vqs relative = gs_vqs_relative_transform(&child, &parent); // Get relative transform with respect to parent
gs_vqs absolute = gs_vqs_absolute_transform(&local, &parent); // Get absolute transform with respect to local
GS_UTIL:
memory allocation
hashing(32/64 bit)
siphash (hash generic bytes)
string utils
file utils
GS_CONTAINERS:
gs_dyn_array:
Inspired GREATLY from Shawn Barret's "stretchy buffer" implementation. A generic, dynamic array of type T,
which is defined by the user:
gs_dyn_array(float) arr = NULL; // Dynamic array of type float
This works by using the macro `gs_dyn_array(T)`, which evaluates to `T*`. The dynamic array stores a bit of header information
right before the actual array in memory for a table to describe properties of the array:
[header][actual array data]
The header is a structure of uint32_t[2]:
typedef struct gs_array_header_t {
uint32_t size;
uint32_t capacity;
} gs_array_header_t;
The array can be randomly accessed using the [] operator, just like any regular c array. There are also provided functions for accessing
information using this provided table. This dynamic structure is the baseline for all other containers provided in gunslinger.
Array Usage:
gs_dyn_array(float) arr = NULL; // Create dynamic array of type float.
gs_dyn_array_push(arr, 10.f); // Push value into back of array. Will dynamically grow/initialize on demand.
float v = arr[0]; // Gets value of array data at index 0;
float* vp = &arr[0]; // Gets pointer reference of array data at index 0;
uint32_t sz = gs_dyn_array_size(arr); // Gets size of array. Return 0 if NULL.
uint32_t cap = gs_dyn_array_capacity(arr); // Gets capacity of array. Return 0 if NULL.
bool is_empty = gs_dyn_array_empty(arr); // Returns whether array is empty. Return true if NULL.
gs_dyn_array_reserve(arr, 10); // Reserves internal space in the array for N, non-initialized elements.
gs_dyn_array_clear(arr); // Clears all elements. Simply sets array size to 0.
gs_dyn_array_free(arr); // Frees array data calling `gs_free` internally.
gs_hash_table: generic hash table of key:K and val:V
Inspired GREATLY from Shawn Barret's "stb_ds.h" implementation. A generic hash table of K,V which is defined
by the user:
gs_hash_table(uint32_t, float) ht = NULL; // Creates a hash table with K = uint32_t, V = float
Internally, the hash table uses a 64-bit siphash to hash generic byte data to an unsigned 64-bit key. This means it's possible to pass up
arbitrary data to the hash table and it will hash accordingly, such as structures:
typedef struct key_t {
uint32_t id0;
uint64_t id1;
} key_t;
gs_hash_table(key_t, float) ht = NULL; // Create hash table with K = key_t, V = float
Inserting into the array with "complex" types is as simple as:
key_t k = {.ido0 = 5, .id1 = 32}; // Create structure for "key"
gs_hash_table_insert(ht, k, 5.f); // Insert into hash table using key
float v = gs_hash_table_get(ht, k); // Get data at key
It is possible to return a reference to the data using `gs_hash_table_getp()`. However, keep in mind that this comes with the
danger that the reference could be lost IF the internal data array grows or shrinks in between you caching the pointer
and using it.
float* val = gs_hash_table_getp(ht, k); // Cache pointer to internal data. Dangerous game.
gs_hash_table_insert(ht, new_key); // At this point, your pointer could be invalidated due to growing internal array.
Hash tables provide iterators to iterate the data:
for (
gs_hash_table_iter it = 0;
gs_hash_table_iter_valid(ht, it);
gs_hash_table_iter_advance(ht, it)
) {
float v = gs_hash_table_iter_get(ht, it); // Get value using iterator
float* vp = gs_hash_table_iter_getp(ht, it); // Get value pointer using iterator
key_t k = gs_hash_table_iter_getk(ht, it); // Get key using iterator
key_t* kp = gs_hash_table_iter_getkp(ht, it); // Get key pointer using iterator
}
Hash Table Usage:
gs_hash_table(uint32_t, float) ht = NULL; // Create hash table with key = uint32_t, val = float
gs_hash_table_insert(ht, 64, 3.145f); // Insert key/val pair {64, 3.145f} into hash table. Will dynamically grow/init on demand.
bool exists = gs_hash_table_key_exists(ht, 64); // Use to query whether or not a key exists in the table.
float v = gs_hash_table_get(ht, 64); // Get value at key = 64. Will crash if not available.
float* vp = gs_hash_table_get(ht, 64); // Get pointer reference to data at key = 64. Will crash if not available.
bool is_empty = gs_hash_table_empty(ht); // Returns whether hash table is empty. Returns true if NULL.
uint32_t sz = gs_hash_table_size(ht); // Get size of hash table. Returns 0 if NULL.
uint32_t cap = gs_hash_table_capacity(ht); // Get capacity of hash table. Returns 0 if NULL.
gs_hash_table_clear(ht); // Clears all elements. Sets size to 0.
gs_hash_table_free(ht); // Frees hash table internal data calling `gs_free` internally.
gs_slot_array:
Slot arrays are internally just dynamic arrays but alleviate the issue with losing references to internal
data when the arrays grow. Slot arrays therefore hold two internals arrays:
gs_dyn_array(T) your_data;
gs_dyn_array(uint32_t) indirection_array;
The indirection array takes an opaque uint32_t handle and then dereferences it to find the actual index
for the data you're interested in. Just like dynamic arrays, they are NULL initialized and then
allocated/initialized internally upon use:
gs_slot_array(float) arr = NULL; // Slot array with internal 'float' data
uint32_t hndl = gs_slot_array_insert(arr, 3.145f); // Inserts your data into the slot array, returns handle to you
float val = gs_slot_array_get(arr, hndl); // Returns copy of data to you using handle as lookup
It is possible to return a reference to the data using `gs_slot_array_getp()`. However, keep in mind that this comes with the
danger that the reference could be lost IF the internal data array grows or shrinks in between you caching the pointer
and using it.
float* val = gs_slot_array_getp(arr, hndl); // Cache pointer to internal data. Dangerous game.
gs_slot_array_insert(arr, 5.f); // At this point, your pointer could be invalidated due to growing internal array.
Slot arrays provide iterators to iterate the data:
for (
gs_slot_array_iter it = 0;
gs_slot_array_iter_valid(sa, it);
gs_slot_array_iter_advance(sa, it)
) {
float v = gs_slot_array_iter_get(sa, it); // Get value using iterator
float* vp = gs_slot_array_iter_getp(sa, it); // Get value pointer using iterator
}
Slot Array Usage:
gs_slot_array(float) sa = NULL; // Create slot array with internal 'float' data
uint32_t hndl = gs_slot_array_insert(sa, 3.145); // Insert data into slot array. Returns uint32_t handle. Init/Grow on demand.
float v = gs_slot_array_get(sa, hndl); // Get data at hndl.
float* vp = gs_slot_array_getp(sa, hndl); // Get pointer reference at hndl. Dangerous.
uint32_t sz = gs_slot_array_size(sa); // Size of slot array. Returns 0 if NULL.
uint32_t cap = gs_slot_array_capacity(sa); // Capacity of slot array. Returns 0 if NULL.
gs_slot_array_empty(sa); // Returns whether slot array is empty. Returns true if NULL.
gs_slot_array_clear(sa); // Clears array. Sets size to 0.
gs_slot_array_free(sa); // Frees array memory. Calls `gs_free` internally.
gs_slot_map:
Works exactly the same, functionally, as gs_slot_array, however allows the user to use one more layer of indirection by
hashing any data as a key type. Also worth note, the slot map does not return a handle to the user. Instead, the user is
expected to use the key to access data.
gs_slot_map(float, uint64_t) sm = NULL; // Slot map with key = float, val = uint64_t
gs_slot_map_insert(sm, 1.f, 32); // Insert data into slot map.
uint64_t v = gs_slot_map_get(sm, 1.f); // Returns copy of data to you at key `1.f`
Like the slot array, it is possible to return a reference via pointer using `gs_slot_map_getp()`. Again, this comes with the same
danger of losing references if not careful about growing the internal data.
uint64_t* v = gs_slot_map_getp(sm, 1.f); // Cache pointer to data
gs_slot_map_insert(sm, 2.f, 10); // Possibly have just invalidated your previous pointer
Slot maps provide iterators to iterate the data:
for (
gs_slot_map_iter it = 0;
gs_slot_map_iter_valid(sm, it);
gs_slot_map_iter_advance(sm, it)
) {
uint64_t v = gs_slot_map_iter_get(sm, it); // Get value using iterator
uint64_t* vp = gs_slot_map_iter_getp(sm, it); // Get value pointer using iterator
float k = gs_slot_map_iter_get_key(sm, it); // Get key using iterator
float* kp = gs_slot_map_iter_get_keyp(sm, it); // Get key pointer using iterator
}
Slot Map Usage:
gs_slot_map(float, uint64_t) sm = NULL; // Create slot map with K = float, V = uint64_t
uint32_t hndl = gs_slot_map_insert(sm, 3.145f, 32); // Insert data into slot map. Init/Grow on demand.
uint64_t v = gs_slot_map_get(sm, 3.145f); // Get data at key.
uint64_t* vp = gs_slot_map_getp(sm, 3.145f); // Get pointer reference at hndl. Dangerous.
uint32_t sz = gs_slot_map_size(sm); // Size of slot map. Returns 0 if NULL.
uint32_t cap = gs_slot_map_capacity(sm); // Capacity of slot map. Returns 0 if NULL.
gs_slot_map_empty(sm); // Returns whether slot map is empty. Returns true if NULL.
gs_slot_map_clear(sm); // Clears map. Sets size to 0.
gs_slot_map_free(sm); // Frees map memory. Calls `gs_free` internally.
GS_PLATFORM:
By default, Gunslinger supports (via included GLFW) the following platforms:
- Win32
- OSX
- Linux
To define your own custom implementation and not use the included glfw implementation, define GS_PLATFORM_IMPL_CUSTOM in your
project. Gunslinger will see this and leave the implementation of the platform API up to you:
// For custom platform implementation
#define GS_PLATFORM_IMPL_CUSTOM
Internally, the platform interface holds the following data:
gs_platform_settings_t settings; // Settings for platform, including video driver settings
gs_platform_time_t time; // Time structure, used to query frame time, delta time, render time
gs_platform_input_t input; // Input struture, used to query input state for mouse, keyboard, controllers
gs_slot_array(void*) windows; // Slot array of raw platform window data and handles
void* cursors[GS_PLATFORM_CURSOR_COUNT]; // Raw platform cursors
void* user_data; // Specific user data (for custom implementations)
Upon creation, the framework will create a main window for you and then store its handle with slot id 0. All platform related window
query functions require passing in an opaque uint32_t handle to get the actual data internally. There is a convenience function available for
querying the main window handle created for you:
uint32_t main_window_hndl = gs_platform_main_window();
Internally, the platform layer queries the platform backend and updates its exposed gs_platform_input_t data structure for you to use. Several
utility functions exist:
gs_platform_key_down(gs_platform_keycode) // Checks to see if a key is held down (pressed last frame and this frame)
gs_platform_key_released(gs_platform_keycode) // Checks to see if a key was released this frame
gs_platform_key_pressed(gs_platform_keycode) // Checks to see if a key was pressed this frame (not pressed last frame)
gs_platform_mouse_down(gs_platform_mouse_button_code) // Checks to see if mouse button is held down
gs_platform_mouse_pressed(gs_platform_mouse_button_code) // Checks to see if mouse button was pressed this frame (not pressed last frame)
gs_platform_mouse_released(gs_platform_mouse_button_code) // Checks to see if mouse button was released this frame
GS_AUDIO:
By default, Gunslinger includes and uses miniaudio for its audio backend.
To define your own custom implementation and not use the included miniaudio implementation, define GS_AUDIO_IMPL_CUSTOM in your
project. Gunslinger will see this and leave the implementation of the audio API up to you:
// For custom audio implementation
#define GS_AUDIO_IMPL_CUSTOM
GS_GRAPHICS:
// For custom graphics implementation
#define GS_GRAPHICS_IMPL_CUSTOM
*/
/*===== Gunslinger Include ======*/
// #ifdef __cplusplus
// extern "C" {
// #endif
/*========================
// Defines
========================*/
#include <stdarg.h> // valist
#include <stddef.h> // ptrdiff_t
#include <stdlib.h> // malloc, realloc, free
#include <stdint.h> // standard types
#include <limits.h> // INT32_MAX, UINT32_MAX
#include <string.h> // memset
#include <float.h> // FLT_MAX
#include <stdio.h> // FILE
#include <time.h> // time
#include <ctype.h> // tolower
#include <math.h> // floor, acos, sin, sqrt, tan
#include <assert.h> // assert
#include <malloc.h> // alloca/_alloca
/*===========================================================
// gs_inline, gs_global, gs_local_persist, gs_force_inline
===========================================================*/
#ifndef gs_inline
#define gs_inline static inline
#endif
#ifndef gs_local_persist
#define gs_local_persist static
#endif
#ifndef gs_global
#define gs_global static
#endif
#if (defined _WIN32 || defined _WIN64)
#define gs_force_inline gs_inline
#elif (defined __APPLE__ || defined _APPLE)
#define gs_force_inline static __attribute__((always_inline))
#else
#define gs_force_inline gs_inline
#endif
#define GS_INLINE gs_force_inline
#define GS_GLOBAL gs_global
#define GS_LOCAL_PERSIST gs_local_persist
#ifdef __cplusplus
#pragma warning(disable:4996)
#endif
/*===================
// GS_API_DECL
===================*/
#ifdef GS_API_DLL_EXPORT
#ifdef __cplusplus
#define GS_API_EXTERN extern "C" __declspec(dllexport)
#else
#define GS_API_EXTERN extern __declspec(dllexport)
#endif
#else
#ifdef __cplusplus
#define GS_API_EXTERN extern "C"
#else
#define GS_API_EXTERN extern
#endif
#endif
#define GS_API_DECL GS_API_EXTERN
#define GS_API_PRIVATE GS_API_EXTERN
/*===================
// PLATFORM DEFINES
===================*/
/* Platform Android */
#if (defined __ANDROID__)
#define GS_PLATFORM_ANDROID
/* Platform Apple */
#elif (defined __APPLE__ || defined _APPLE)
#define GS_PLATFORM_APPLE
/* Platform Windows */
#elif (defined _WIN32 || defined _WIN64)
#define __USE_MINGW_ANSI_STDIO 1
// Necessary windows defines before including windows.h, because it's retarded.
#define OEMRESOURCE
#define GS_PLATFORM_WIN
#define GS_PLATFORM_WINDOWS
#include <windows.h>
#define WIN32_LEAN_AND_MEAN
/* Platform Linux */
#elif (defined linux || defined _linux || defined __linux__)
#define GS_PLATFORM_LINUX
/* Platform Emscripten */
#elif (defined __EMSCRIPTEN__)
#define GS_PLATFORM_WEB
/* Else - Platform Undefined and Unsupported or custom */
#endif
/*============================================================
// C primitive types
============================================================*/
#ifndef __cplusplus
#define false 0
#define true 1
#endif
#ifdef __cplusplus
typedef bool b8;
#else
#ifndef __bool_true_false_are_defined
typedef _Bool bool;
#endif
typedef bool b8;
#endif
typedef size_t usize;
typedef uint8_t u8;
typedef int8_t s8;
typedef uint16_t u16;
typedef int16_t s16;
typedef uint32_t u32;
typedef int32_t s32;
typedef s32 b32;
typedef uint64_t u64;
typedef int64_t s64;
typedef float f32;
typedef double f64;
typedef const char* const_str;
typedef int32_t bool32_t;
typedef float float32_t;
typedef double float64_t;
typedef bool32_t bool32;
#define uint16_max UINT16_MAX
#define uint32_max UINT32_MAX
#define int32_max INT32_MAX
#define float_max FLT_MAX
#define float_min FLT_MIN
/*============================================================
// gs utils
============================================================*/
/** @defgroup gs_util Common Utils
* Gunslinger Common Utils
* @{
*/
// Helper macro for compiling to nothing
#define gs_empty_instruction(...)
#define gs_array_size(__ARR) sizeof(__ARR) / sizeof(__ARR[0])
#ifndef gs_assert
#define gs_assert assert
#endif
#if defined (__cplusplus)
#define gs_default_val() {}
#else
#define gs_default_val() {0}
#endif
// Helper macro for an in place for-range loop
#define gs_for_range_i(__COUNT)\
for (uint32_t i = 0; i < __COUNT; ++i)
// Helper macro for an in place for-range loop
#define gs_for_range_j(__COUNT)\
for (uint32_t j = 0; j < __COUNT; ++j)
#define gs_for_range(__COUNT)\
for(uint32_t gs_macro_token_paste(__T, __LINE__) = 0;\
gs_macro_token_paste(__T, __LINE__) < __COUNT;\
++(gs_macro_token_paste(__T, __LINE__)))
#define gs_max(A, B) ((A) > (B) ? (A) : (B))
#define gs_min(A, B) ((A) < (B) ? (A) : (B))
#define gs_clamp(V, MIN, MAX) ((V) > (MAX) ? (MAX) : (V) < (MIN) ? (MIN) : (V))
#define gs_is_nan(V) ((V) != (V))
// Helpful macro for casting one type to another
#define gs_cast(A, B) ((A*)(B))
#ifdef __cplusplus
#define gs_ctor(TYPE, ...) (TYPE {__VA_ARGS__})
#else
#define gs_ctor(TYPE, ...) ((TYPE){__VA_ARGS__})
#endif
// Helpful marco for calculating offset (in bytes) of an element from a given structure type
#define gs_offset(TYPE, ELEMENT) ((size_t)(&(((TYPE*)(0))->ELEMENT)))
// macro for turning any given type into a const char* of itself
#define gs_to_str(TYPE) ((const char*)#TYPE)
#define gs_macro_token_paste(X, Y) X##Y
#define gs_macro_cat(X, Y) gs_macro_token_paste(X, Y)
#define gs_timed_action(INTERVAL, ...)\
do {\
static uint32_t gs_macro_cat(gs_macro_cat(__T, __LINE__), t) = 0;\
if (gs_macro_cat(gs_macro_cat(__T, __LINE__), t)++ > INTERVAL) {\
gs_macro_cat(gs_macro_cat(__T, __LINE__), t) = 0;\
__VA_ARGS__\
}\
} while (0)
#define gs_int2voidp(I) (void*)(uintptr_t)(I)
#define gs_if(INIT, CHECK, ...)\
do {\
INIT;\
if (CHECK)\
{\
__VA_ARGS__\
}\
} while (0)
//=== Logging ===//
#define gs_log_info(MESSAGE, ...) gs_println("LOG::%s::%s(%zu)::" MESSAGE, __FILE__, __FUNCTION__, __LINE__, ##__VA_ARGS__)
#define gs_log_success(MESSAGE, ...) gs_println("SUCCESS::%s::%s(%zu)::" MESSAGE, __FILE__, __FUNCTION__, __LINE__, ##__VA_ARGS__)
#define gs_log_warning(MESSAGE, ...) gs_println("WARNING::%s::%s(%zu)::" MESSAGE, __FILE__, __FUNCTION__, __LINE__, ##__VA_ARGS__)
#define gs_log_error(MESSAGE, ...) do {gs_println("ERROR::%s::%s(%zu)::" MESSAGE, __FILE__, __FUNCTION__, __LINE__, ##__VA_ARGS__);\
gs_assert(false);\
} while (0)
/*===================================
// Memory Allocation Utils
===================================*/
// Operating system function pointer
typedef struct gs_os_api_s
{
void* (* malloc)(size_t sz);
void (* free)(void* ptr);
void* (* realloc)(void* ptr, size_t sz);
void* (* calloc)(size_t num, size_t sz);
void* (* alloca)(size_t sz);
void* (* malloc_init)(size_t sz);
char* (* strdup)(const char* str);
} gs_os_api_t;
// TODO(john): Check if all defaults need to be set, in case gs context will not be used
GS_API_DECL
void* _gs_malloc_init_impl(size_t sz);
// Default memory allocations
#ifndef GS_NO_OS_MEMORY_ALLOC_DEFAULT
#define gs_malloc malloc
#define gs_free free
#define gs_realloc realloc
#define gs_calloc calloc
#define gs_alloca malloc
#define gs_malloc_init(__T) (__T*)_gs_malloc_init_impl(sizeof(__T))
#endif
GS_API_DECL gs_os_api_t
gs_os_api_new_default();
#ifndef gs_os_api_new
#define gs_os_api_new gs_os_api_new_default
#endif
#ifndef gs_malloc
#define gs_malloc(__SZ) (gs_ctx()->os.malloc(__SZ))
#endif
#ifndef gs_malloc_init
#define gs_malloc_init(__T) ((__T*)gs_ctx()->os.malloc_init(sizeof(__T)))
#endif
#ifndef gs_free
#define gs_free(__MEM) (gs_ctx()->os.free(__MEM))
#endif
#ifndef gs_realloc
#define gs_realloc(__MEM, __AZ) (gs_ctx()->os.realloc(__MEM, __AZ))
#endif
#ifndef gs_calloc
#define gs_calloc(__NUM, __SZ) (gs_ctx()->os.calloc(__NUM, __SZ))
#endif
#ifndef gs_alloca
#define gs_alloca(__SZ) (gs_ctx()->os.alloca(__SZ))
#endif
#ifndef gs_strdup
#define gs_strdup(__STR) (gs_ctx()->os.strdup(__STR))
#endif
// Modified from: https://stackoverflow.com/questions/11815894/how-to-read-write-arbitrary-bits-in-c-c
#define gs_bit_mask(INDEX, SIZE)\
(((1u << (SIZE)) - 1u) << (INDEX))
#define gs_write_bits(DATA, INDEX, SIZE, VAL)\
((DATA) = (((DATA) & (~BIT_MASK((INDEX), (SIZE)))) | (((VAL) << (INDEX)) & (BIT_MASK((INDEX), (SIZE))))))
#define gs_read_bits(DATA, INDEX, SIZE)\
(((DATA) & BIT_MASK((INDEX), (SIZE))) >> (INDEX))
/*============================================================
// Result
============================================================*/
typedef enum gs_result
{
GS_RESULT_SUCCESS,
GS_RESULT_IN_PROGRESS,
GS_RESULT_INCOMPLETE,
GS_RESULT_FAILURE
} gs_result;
/*===================================
// Resource Handles
===================================*/
// Useful typedefs for typesafe, internal resource handles
#define gs_handle(TYPE)\
gs_handle_##TYPE
#define gs_handle_decl(TYPE)\
typedef struct {uint32_t id;} gs_handle(TYPE);\
gs_inline\
gs_handle(TYPE) gs_handle_invalid_##TYPE()\
{\
gs_handle(TYPE) h;\
h.id = UINT32_MAX;\
return h;\
}\
\
gs_inline\
gs_handle(TYPE) gs_handle_create_##TYPE(uint32_t id)\
{\
gs_handle(TYPE) h;\
h.id = id;\
return h;\
}
#define gs_handle_invalid(__TYPE)\
gs_handle_invalid_##__TYPE()
#define gs_handle_create(__TYPE, __ID)\
gs_handle_create_##__TYPE(__ID)
#define gs_handle_is_valid(HNDL)\
((HNDL.id) != UINT32_MAX)
/*===================================
// Color
===================================*/
#define gs_hsv(...) gs_hsv_ctor(__VA_ARGS__)
#define gs_color(...) gs_color_ctor(__VA_ARGS__)
typedef struct gs_hsv_t
{
union
{
float hsv[3];
struct
{
float h, s, v;
};
};
} gs_hsv_t;
gs_force_inline
gs_hsv_t gs_hsv_ctor(float h, float s, float v)
{
gs_hsv_t hsv;
hsv.h = h;
hsv.s = s;
hsv.v = v;
return hsv;
}
typedef struct gs_color_t
{
union
{
uint8_t rgba[4];
struct
{
uint8_t r, g, b, a;
};
};
} gs_color_t;
gs_force_inline
gs_color_t gs_color_ctor(uint8_t r, uint8_t g, uint8_t b, uint8_t a)
{
gs_color_t color;
color.r = r;
color.g = g;
color.b = b;
color.a = a;
return color;
}
#define GS_COLOR_BLACK gs_color(0, 0, 0, 255)
#define GS_COLOR_WHITE gs_color(255, 255, 255, 255)
#define GS_COLOR_RED gs_color(255, 0, 0, 255)
#define GS_COLOR_GREEN gs_color(0, 255, 0, 255)
#define GS_COLOR_BLUE gs_color(0, 0, 255, 255)
#define GS_COLOR_ORANGE gs_color(255, 100, 0, 255)
#define GS_COLOR_YELLOW gs_color(255, 255, 0, 255)
#define GS_COLOR_PURPLE gs_color(128, 0, 128, 255)
#define GS_COLOR_MAROON gs_color(128, 0, 0, 255)
#define GS_COLOR_BROWN gs_color(165, 42, 42, 255)
#define GS_COLOR_MAGENTA gs_color(255, 0, 255, 255)
gs_force_inline
gs_color_t gs_color_alpha(gs_color_t c, uint8_t a)
{
return gs_color(c.r, c.g, c.b, a);
}
gs_force_inline gs_hsv_t
gs_rgb2hsv(gs_color_t in)
{
float ir = (float)in.r / 255.f;
float ig = (float)in.g / 255.f;
float ib = (float)in.b / 255.f;
float ia = (float)in.a / 255.f;
gs_hsv_t out = gs_default_val();
double min, max, delta;
min = ir < ig ? ir : ig;
min = min < ib ? min : ib;
max = ir > ig ? ir : ig;
max = max > ib ? max : ib;
out.v = max; // v
delta = max - min;
if (delta < 0.00001)
{
out.s = 0;
out.h = 0; // undefined, maybe nan?
return out;
}
if(max > 0.0)
{ // NOTE: if Max is == 0, this divide would cause a crash
out.s = (delta / max); // s
}
else
{
// if max is 0, then r = g = b = 0
// s = 0, h is undefined
out.s = 0.0;
out.h = NAN; // its now undefined
return out;
}
if(ir >= max) // > is bogus, just keeps compilor happy
out.h = (ig - ib) / delta; // between yellow & magenta
else
if( ig >= max )
out.h = 2.0 + ( ib - ir ) / delta; // between cyan & yellow
else
out.h = 4.0 + ( ir - ig ) / delta; // between magenta & cyan
out.h *= 60.0; // degrees
if( out.h < 0.0 )
out.h += 360.0;
return out;
}
gs_force_inline gs_color_t
gs_hsv2rgb(gs_hsv_t in)
{
double hh, p, q, t, ff;
long i;
gs_color_t out;
if(in.s <= 0.0) { // < is bogus, just shuts up warnings
out.r = in.v * 255;
out.g = in.v * 255;
out.b = in.v * 255;
out.a = 255;
return out;
}
hh = in.h;
if(hh >= 360.0) hh = 0.0;
hh /= 60.0;
i = (long)hh;
ff = hh - i;