forked from excessive/exmview
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathtinyfx.c
3960 lines (3498 loc) · 118 KB
/
tinyfx.c
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
#define TFX_IMPLEMENTATION
#if !defined(TFX_DEBUG) && defined(_DEBUG)
// enable tfx debug in msvc debug configurations.
#define TFX_DEBUG
#endif
#include "tinyfx.h"
#ifdef TFX_LEAK_CHECK
#define STB_LEAKCHECK_IMPLEMENTATION
#include "stb_leakcheck.h"
#endif
/**********************\
| implementation stuff |
\**********************/
#ifdef TFX_IMPLEMENTATION
#ifdef __cplusplus
extern "C" {
#endif
// TODO: look into just keeping the stuff from GL header in here, this thing
// isn't included on many systems and is kind of annoying to always need.
#include <GL/glcorearb.h>
//#ifdef __ANDROID__
//#include <GLES3/gl32.h>
//#endif
#include <math.h>
#include <stdarg.h>
#include <string.h>
#include <stdio.h>
#ifdef TFX_DEBUG
#include <assert.h>
#else
#define assert(op) (void)(op);
#endif
// needed on msvc
#if defined(_MSC_VER) && !defined(snprintf)
#define snprintf _snprintf
#endif
#ifdef _MSC_VER
#pragma warning( push )
#pragma warning( disable : 4996 )
#endif
#ifndef TFX_TRANSIENT_BUFFER_COUNT
#define TFX_TRANSIENT_BUFFER_COUNT 3
#endif
#ifndef TFX_UNIFORM_BUFFER_SIZE
// by default, allow up to 4MB of uniform updates per frame.
#define TFX_UNIFORM_BUFFER_SIZE 1024*1024*4
#endif
#ifndef TFX_TRANSIENT_BUFFER_SIZE
// by default, allow up to 4MB of transient buffer data per frame.
#define TFX_TRANSIENT_BUFFER_SIZE 1024*1024*4
#endif
// The following code is public domain, from https://github.com/nothings/stb
//////////////////////////////////////////////////////////////////////////////
#ifdef __cplusplus
#define STB_STRETCHY_BUFFER_CPP
#endif
#ifndef STB_STRETCHY_BUFFER_H_INCLUDED
#define STB_STRETCHY_BUFFER_H_INCLUDED
#ifndef NO_STRETCHY_BUFFER_SHORT_NAMES
#define sb_free stb_sb_free
#define sb_push stb_sb_push
#define sb_count stb_sb_count
#define sb_add stb_sb_add
#define sb_last stb_sb_last
#endif
#ifdef STB_STRETCHY_BUFFER_CPP
#define stb_sb_push(t,a,v) (stb__sbmaybegrow(t,a,1), (a)[stb__sbn(a)++] = (v))
#define stb_sb_add(t,a,n) (stb__sbmaybegrow(t,a,n), stb__sbn(a)+=(n), &(a)[stb__sbn(a)-(n)])
#define stb__sbmaybegrow(t,a,n) (stb__sbneedgrow(a,(n)) ? stb__sbgrow(t,a,n) : 0)
#define stb__sbgrow(t,a,n) ((a) = (t*)stb__sbgrowf((void*)(a), (n), sizeof(t)))
#else
#define stb_sb_push(a,v) (stb__sbmaybegrow(a,1), (a)[stb__sbn(a)++] = (v))
#define stb_sb_add(a,n) (stb__sbmaybegrow(a,n), stb__sbn(a)+=(n), &(a)[stb__sbn(a)-(n)])
#define stb__sbmaybegrow(a,n) (stb__sbneedgrow(a,(n)) ? stb__sbgrow(a,n) : 0)
#define stb__sbgrow(a,n) ((a) = stb__sbgrowf((a), (n), sizeof(*(a))))
#endif
#define stb_sb_free(a) ((a) ? free(stb__sbraw(a)),0 : 0)
#define stb_sb_count(a) ((a) ? stb__sbn(a) : 0)
#define stb_sb_last(a) ((a)[stb__sbn(a)-1])
#define stb__sbraw(a) ((int *) (a) - 2)
#define stb__sbm(a) stb__sbraw(a)[0]
#define stb__sbn(a) stb__sbraw(a)[1]
#define stb__sbneedgrow(a,n) ((a)==0 || stb__sbn(a)+(n) >= stb__sbm(a))
#include <stdlib.h>
static void * stb__sbgrowf(void *arr, int increment, int itemsize)
{
int dbl_cur = arr ? 2 * stb__sbm(arr) : 0;
int min_needed = stb_sb_count(arr) + increment;
int m = dbl_cur > min_needed ? dbl_cur : min_needed;
int *p = (int *)realloc(arr ? stb__sbraw(arr) : 0, itemsize * m + sizeof(int) * 2);
if (p) {
if (!arr)
p[1] = 0;
p[0] = m;
return p + 2;
}
else {
#ifdef STRETCHY_BUFFER_OUT_OF_MEMORY
STRETCHY_BUFFER_OUT_OF_MEMORY;
#endif
return (void *)(2 * sizeof(int)); // try to force a NULL pointer exception later
}
}
#endif // STB_STRETCHY_BUFFER_H_INCLUDED
//////////////////////////////////////////////////////////////////////////////
static char *tfx_strdup(const char *src) {
size_t len = strlen(src) + 1;
char *s = malloc(len);
if (s == NULL)
return NULL;
// copy len includes the \0 terminator
return (char *)memcpy(s, src, len);
}
#ifdef TFX_DEBUG
//#define TFX_FATAL_ERRORS
# ifdef TFX_FATAL_ERRORS
# define CHECK(fn) fn; { GLenum _status; while ((_status = tfx_glGetError())) { if (_status == GL_NO_ERROR) break; TFX_ERROR("%s:%d GL ERROR: %d", __FILE__, __LINE__, _status); assert(0); } }
# else
# define CHECK(fn) fn; { GLenum _status; while ((_status = tfx_glGetError())) { if (_status == GL_NO_ERROR) break; TFX_ERROR("%s:%d GL ERROR: %d", __FILE__, __LINE__, _status); } }
# endif
#else
# define CHECK(fn) fn;
#endif
#define TFX_INFO(msg, ...) tfx_printf(TFX_SEVERITY_INFO, msg, __VA_ARGS__)
#define TFX_WARN(msg, ...) tfx_printf(TFX_SEVERITY_WARNING, msg, __VA_ARGS__)
#define TFX_ERROR(msg, ...) tfx_printf(TFX_SEVERITY_ERROR, msg, __VA_ARGS__)
#define TFX_FATAL(msg, ...) tfx_printf(TFX_SEVERITY_FATAL, msg, __VA_ARGS__)
#define VIEW_MAX 256
#define TIMER_LATENCY 3
#define TIMER_COUNT ((VIEW_MAX+1)*TIMER_LATENCY)
// view flags
enum {
// clear modes
TFXI_VIEW_CLEAR_COLOR = 1 << 0,
TFXI_VIEW_CLEAR_DEPTH = 1 << 1,
// depth modes
TFXI_VIEW_DEPTH_TEST_LT = 1 << 2,
TFXI_VIEW_DEPTH_TEST_GT = 1 << 3,
TFXI_VIEW_DEPTH_TEST_EQ = 1 << 4,
// scissor test
TFXI_VIEW_SCISSOR = 1 << 5,
TFXI_VIEW_INVALIDATE = 1 << 6,
TFXI_VIEW_FLUSH = 1 << 7,
TFXI_VIEW_SORT_SEQUENTIAL = 1 << 8
};
typedef struct tfx_rect {
uint16_t x;
uint16_t y;
uint16_t w;
uint16_t h;
} tfx_rect;
typedef struct tfx_blit_op {
tfx_canvas *source;
int source_mip;
tfx_rect rect;
GLenum mask;
} tfx_blit_op;
typedef struct tfx_draw {
tfx_draw_callback callback;
uint64_t flags;
tfx_program program;
tfx_uniform *uniforms;
tfx_texture textures[8];
uint8_t textures_mip[8];
bool textures_write[8];
tfx_buffer ssbos[8];
bool ssbo_write[8];
tfx_buffer vbo;
bool use_vbo;
tfx_buffer ibo;
bool use_ibo;
tfx_vertex_format tvb_fmt;
bool use_tvb;
tfx_rect scissor_rect;
bool use_scissor;
size_t offset;
uint32_t indices;
uint32_t depth;
// for compute jobs
uint32_t threads_x;
uint32_t threads_y;
uint32_t threads_z;
} tfx_draw;
typedef struct tfx_view {
uint32_t flags;
const char *name;
bool has_canvas;
tfx_canvas canvas;
int canvas_layer;
tfx_draw *draws;
tfx_draw *jobs;
tfx_blit_op *blits;
unsigned clear_color;
float clear_depth;
tfx_rect scissor_rect;
// https://opengl.gpuinfo.org/displaycapability.php?name=GL_MAX_VIEWPORTS
tfx_rect viewports[16];
int viewport_count;
// for single pass rendering to eyes, cubes, shadowmaps etc.
int instance_mul;
float view[16];
float proj_left[16];
float proj_right[16];
} tfx_view;
#define TFXI_VIEW_CLEAR_MASK (TFXI_VIEW_CLEAR_COLOR | TFXI_VIEW_CLEAR_DEPTH)
#define TFXI_VIEW_DEPTH_TEST_MASK (TFXI_VIEW_DEPTH_TEST_LT | TFXI_VIEW_DEPTH_TEST_GT | TFXI_VIEW_DEPTH_TEST_EQ)
#define TFXI_STATE_CULL_MASK (TFX_STATE_CULL_CW | TFX_STATE_CULL_CCW)
#define TFXI_STATE_BLEND_MASK (TFX_STATE_BLEND_ALPHA)
#define TFXI_STATE_DRAW_MASK (TFX_STATE_DRAW_POINTS \
| TFX_STATE_DRAW_LINES | TFX_STATE_DRAW_LINE_STRIP | TFX_STATE_DRAW_LINE_LOOP \
| TFX_STATE_DRAW_TRI_STRIP | TFX_STATE_DRAW_TRI_FAN \
)
static tfx_canvas g_backbuffer;
static tfx_timing_info last_timings[VIEW_MAX];
static tfx_platform_data g_platform_data;
typedef struct tfx_glext {
const char *ext;
bool supported;
} tfx_glext;
static tfx_glext available_exts[] = {
{ "GL_ARB_multisample", false },
{ "GL_ARB_compute_shader", false },
{ "GL_ARB_texture_float", false },
{ "GL_EXT_debug_marker", false },
{ "GL_ARB_debug_output", false },
{ "GL_KHR_debug", false },
{ "GL_NVX_gpu_memory_info", false },
// guaranteed by desktop GL 3.3+ or GLES 3.0+
{ "GL_ARB_instanced_arrays", false },
{ "GL_ARB_seamless_cube_map", false },
{ "GL_EXT_texture_filter_anisotropic", false },
{ "GL_ARB_multi_bind", false },
// TODO
// GL_AMD_vertex_shader_layer
// GL_AMD_vertex_shader_viewport_index
// GL_ARB_multi_bind
// GL_ARB_multi_draw_indirect
// GL_QCOM_texture_foveated
// GL_OVR_multiview2
// GL_OVR_multiview_multisampled_render_to_texture
// GL_OES_element_index_uint
// GL_OES_depth24
// GL_OES_depth_texture
// GL_OES_depth_texture_cube_map
// GL_EXT_sRGB
// GL_EXT_multisampled_render_to_texture
// GL_EXT_disjoint_timer_query
// GL_EXT_clip_control
// GL_EXT_clip_cull_distance
// GL_EXT_color_buffer_float
// GL_EXT_color_buffer_half_float
{ NULL, false }
};
PFNGLFLUSHPROC tfx_glFlush;
PFNGLGETSTRINGPROC tfx_glGetString;
PFNGLGETSTRINGIPROC tfx_glGetStringi;
PFNGLGETERRORPROC tfx_glGetError;
PFNGLBLENDFUNCPROC tfx_glBlendFunc;
PFNGLCOLORMASKPROC tfx_glColorMask;
PFNGLGETINTEGERVPROC tfx_glGetIntegerv;
PFNGLGETFLOATVPROC tfx_glGetFloatv;
PFNGLGENQUERIESPROC tfx_glGenQueries;
PFNGLDELETEQUERIESPROC tfx_glDeleteQueries;
PFNGLBEGINQUERYPROC tfx_glBeginQuery;
PFNGLENDQUERYPROC tfx_glEndQuery;
PFNGLQUERYCOUNTERPROC tfx_glQueryCounter;
PFNGLGETQUERYOBJECTUIVPROC tfx_glGetQueryObjectuiv;
PFNGLGETQUERYOBJECTUI64VPROC tfx_glGetQueryObjectui64v;
PFNGLGENBUFFERSPROC tfx_glGenBuffers;
PFNGLBINDBUFFERPROC tfx_glBindBuffer;
PFNGLBUFFERDATAPROC tfx_glBufferData;
PFNGLBUFFERSTORAGEPROC tfx_glBufferStorage;
PFNGLDELETEBUFFERSPROC tfx_glDeleteBuffers;
PFNGLDELETETEXTURESPROC tfx_glDeleteTextures;
PFNGLCREATESHADERPROC tfx_glCreateShader;
PFNGLSHADERSOURCEPROC tfx_glShaderSource;
PFNGLCOMPILESHADERPROC tfx_glCompileShader;
PFNGLGETSHADERIVPROC tfx_glGetShaderiv;
PFNGLGETSHADERINFOLOGPROC tfx_glGetShaderInfoLog;
PFNGLDELETESHADERPROC tfx_glDeleteShader;
PFNGLCREATEPROGRAMPROC tfx_glCreateProgram;
PFNGLATTACHSHADERPROC tfx_glAttachShader;
PFNGLBINDATTRIBLOCATIONPROC tfx_glBindAttribLocation;
PFNGLLINKPROGRAMPROC tfx_glLinkProgram;
PFNGLGETPROGRAMIVPROC tfx_glGetProgramiv;
PFNGLGETPROGRAMINFOLOGPROC tfx_glGetProgramInfoLog;
PFNGLDELETEPROGRAMPROC tfx_glDeleteProgram;
PFNGLGENTEXTURESPROC tfx_glGenTextures;
PFNGLBINDTEXTUREPROC tfx_glBindTexture;
PFNGLBINDTEXTURESPROC tfx_glBindTextures;
PFNGLTEXPARAMETERIPROC tfx_glTexParameteri;
PFNGLTEXPARAMETERIVPROC tfx_glTexParameteriv;
PFNGLTEXPARAMETERFPROC tfx_glTexParameterf;
PFNGLPIXELSTOREIPROC tfx_glPixelStorei;
PFNGLTEXIMAGE2DPROC tfx_glTexImage2D;
PFNGLTEXIMAGE3DPROC tfx_glTexImage3D;
PFNGLTEXIMAGE2DMULTISAMPLEPROC tfx_glTexImage2DMultisample;
PFNGLTEXSTORAGE2DPROC tfx_glTexStorage2D;
PFNGLTEXSTORAGE3DPROC tfx_glTexStorage3D;
PFNGLTEXSTORAGE2DMULTISAMPLEPROC tfx_glTexStorage2DMultisample;
PFNGLTEXSUBIMAGE2DPROC tfx_glTexSubImage2D;
PFNGLTEXSUBIMAGE3DPROC tfx_glTexSubImage3D;
PFNGLINVALIDATETEXSUBIMAGEPROC tfx_glInvalidateTexSubImage;
PFNGLGENERATEMIPMAPPROC tfx_glGenerateMipmap;
PFNGLGENFRAMEBUFFERSPROC tfx_glGenFramebuffers;
PFNGLDELETEFRAMEBUFFERSPROC tfx_glDeleteFramebuffers;
PFNGLBINDFRAMEBUFFERPROC tfx_glBindFramebuffer;
PFNGLBLITFRAMEBUFFERPROC tfx_glBlitFramebuffer;
PFNGLCOPYIMAGESUBDATAPROC tfx_glCopyImageSubData;
PFNGLFRAMEBUFFERTEXTURE2DPROC tfx_glFramebufferTexture2D;
PFNGLINVALIDATEFRAMEBUFFERPROC tfx_glInvalidateFramebuffer;
PFNGLGENRENDERBUFFERSPROC tfx_glGenRenderbuffers;
PFNGLBINDRENDERBUFFERPROC tfx_glBindRenderbuffer;
PFNGLRENDERBUFFERSTORAGEPROC tfx_glRenderbufferStorage;
PFNGLRENDERBUFFERSTORAGEMULTISAMPLEPROC tfx_glRenderbufferStorageMultisample;
PFNGLFRAMEBUFFERRENDERBUFFERPROC tfx_glFramebufferRenderbuffer;
PFNGLFRAMEBUFFERTEXTUREPROC tfx_glFramebufferTexture;
PFNGLDRAWBUFFERSPROC tfx_glDrawBuffers;
PFNGLREADBUFFERPROC tfx_glReadBuffer;
PFNGLCHECKFRAMEBUFFERSTATUSPROC tfx_glCheckFramebufferStatus;
PFNGLGETUNIFORMLOCATIONPROC tfx_glGetUniformLocation;
PFNGLRELEASESHADERCOMPILERPROC tfx_glReleaseShaderCompiler;
PFNGLGENVERTEXARRAYSPROC tfx_glGenVertexArrays;
PFNGLBINDVERTEXARRAYPROC tfx_glBindVertexArray;
PFNGLMAPBUFFERRANGEPROC tfx_glMapBufferRange;
PFNGLBUFFERSUBDATAPROC tfx_glBufferSubData;
PFNGLUNMAPBUFFERPROC tfx_glUnmapBuffer;
PFNGLUSEPROGRAMPROC tfx_glUseProgram;
PFNGLMEMORYBARRIERPROC tfx_glMemoryBarrier;
PFNGLBINDBUFFERBASEPROC tfx_glBindBufferBase;
PFNGLDISPATCHCOMPUTEPROC tfx_glDispatchCompute;
PFNGLVIEWPORTPROC tfx_glViewport;
PFNGLVIEWPORTINDEXEDFPROC tfx_glViewportIndexedf;
PFNGLSCISSORPROC tfx_glScissor;
PFNGLCLEARCOLORPROC tfx_glClearColor;
PFNGLCLEARDEPTHFPROC tfx_glClearDepthf;
PFNGLCLEARPROC tfx_glClear;
PFNGLENABLEPROC tfx_glEnable;
PFNGLDEPTHFUNCPROC tfx_glDepthFunc;
PFNGLDISABLEPROC tfx_glDisable;
PFNGLDEPTHMASKPROC tfx_glDepthMask;
PFNGLFRONTFACEPROC tfx_glFrontFace;
PFNGLPOLYGONMODEPROC tfx_glPolygonMode;
PFNGLUNIFORM1IVPROC tfx_glUniform1iv;
PFNGLUNIFORM1FVPROC tfx_glUniform1fv;
PFNGLUNIFORM2FVPROC tfx_glUniform2fv;
PFNGLUNIFORM3FVPROC tfx_glUniform3fv;
PFNGLUNIFORM4FVPROC tfx_glUniform4fv;
PFNGLUNIFORMMATRIX2FVPROC tfx_glUniformMatrix2fv;
PFNGLUNIFORMMATRIX3FVPROC tfx_glUniformMatrix3fv;
PFNGLUNIFORMMATRIX4FVPROC tfx_glUniformMatrix4fv;
PFNGLENABLEVERTEXATTRIBARRAYPROC tfx_glEnableVertexAttribArray;
PFNGLVERTEXATTRIBPOINTERPROC tfx_glVertexAttribPointer;
PFNGLDISABLEVERTEXATTRIBARRAYPROC tfx_glDisableVertexAttribArray;
PFNGLACTIVETEXTUREPROC tfx_glActiveTexture;
PFNGLDRAWELEMENTSINSTANCEDPROC tfx_glDrawElementsInstanced;
PFNGLDRAWARRAYSINSTANCEDPROC tfx_glDrawArraysInstanced;
PFNGLDRAWELEMENTSPROC tfx_glDrawElements;
PFNGLDRAWARRAYSPROC tfx_glDrawArrays;
PFNGLDELETEVERTEXARRAYSPROC tfx_glDeleteVertexArrays;
PFNGLBINDFRAGDATALOCATIONPROC tfx_glBindFragDataLocation;
// debug output/markers
PFNGLPUSHDEBUGGROUPPROC tfx_glPushDebugGroup;
PFNGLPOPDEBUGGROUPPROC tfx_glPopDebugGroup;
PFNGLINSERTEVENTMARKEREXTPROC tfx_glInsertEventMarkerEXT;
void load_em_up(void* (*get_proc_address)(const char*)) {
tfx_glFlush = get_proc_address("glFlush");
tfx_glGetString = get_proc_address("glGetString");
tfx_glGetStringi = get_proc_address("glGetStringi");
tfx_glGetError = get_proc_address("glGetError");
tfx_glBlendFunc = get_proc_address("glBlendFunc");
tfx_glColorMask = get_proc_address("glColorMask");
tfx_glGetIntegerv = get_proc_address("glGetIntegerv");
tfx_glGetFloatv = get_proc_address("glGetFloatv");
tfx_glGenQueries = get_proc_address("glGenQueries");
tfx_glDeleteQueries = get_proc_address("glDeleteQueries");
tfx_glBeginQuery = get_proc_address("glBeginQuery");
tfx_glEndQuery = get_proc_address("glEndQuery");
tfx_glQueryCounter = get_proc_address("glQueryCounter");
tfx_glGetQueryObjectuiv = get_proc_address("glGetQueryObjectuiv");
tfx_glGetQueryObjectui64v = get_proc_address("glGetQueryObjectui64v");
tfx_glGenBuffers = get_proc_address("glGenBuffers");
tfx_glBindBuffer = get_proc_address("glBindBuffer");
tfx_glBufferData = get_proc_address("glBufferData");
tfx_glBufferStorage = get_proc_address("glBufferStorage");
tfx_glDeleteBuffers = get_proc_address("glDeleteBuffers");
tfx_glDeleteTextures= get_proc_address("glDeleteTextures");
tfx_glCreateShader = get_proc_address("glCreateShader");
tfx_glShaderSource = get_proc_address("glShaderSource");
tfx_glCompileShader = get_proc_address("glCompileShader");
tfx_glGetShaderiv = get_proc_address("glGetShaderiv");
tfx_glGetShaderInfoLog = get_proc_address("glGetShaderInfoLog");
tfx_glDeleteShader = get_proc_address("glDeleteShader");
tfx_glCreateProgram = get_proc_address("glCreateProgram");
tfx_glAttachShader = get_proc_address("glAttachShader");
tfx_glBindAttribLocation = get_proc_address("glBindAttribLocation");
tfx_glLinkProgram = get_proc_address("glLinkProgram");
tfx_glGetProgramiv = get_proc_address("glGetProgramiv");
tfx_glGetProgramInfoLog = get_proc_address("glGetProgramInfoLog");
tfx_glDeleteProgram = get_proc_address("glDeleteProgram");
tfx_glGenTextures = get_proc_address("glGenTextures");
tfx_glBindTexture = get_proc_address("glBindTexture");
tfx_glBindTextures = get_proc_address("glBindTextures"); // GL_ARB_multi_bind (GL 4.4)
tfx_glTexParameteri = get_proc_address("glTexParameteri");
tfx_glTexParameteriv = get_proc_address("glTexParameteriv");
tfx_glTexParameterf = get_proc_address("glTexParameterf");
tfx_glPixelStorei = get_proc_address("glPixelStorei");
tfx_glTexImage2D = get_proc_address("glTexImage2D");
tfx_glTexImage3D = get_proc_address("glTexImage3D");
tfx_glTexImage2DMultisample = get_proc_address("glTexImage2DMultisample");
tfx_glTexStorage2D = get_proc_address("glTexStorage2D");
tfx_glTexStorage3D = get_proc_address("glTexStorage3D");
tfx_glTexStorage2DMultisample = get_proc_address("glTexStorage2DMultisample");
tfx_glTexSubImage2D = get_proc_address("glTexSubImage2D");
tfx_glTexSubImage3D = get_proc_address("glTexSubImage3D");
tfx_glInvalidateTexSubImage = get_proc_address("glInvalidateTexSubImage");
tfx_glGenerateMipmap = get_proc_address("glGenerateMipmap");
tfx_glGenFramebuffers = get_proc_address("glGenFramebuffers");
tfx_glDeleteFramebuffers = get_proc_address("glDeleteFramebuffers");
tfx_glBindFramebuffer = get_proc_address("glBindFramebuffer");
tfx_glBlitFramebuffer = get_proc_address("glBlitFramebuffer");
tfx_glCopyImageSubData = get_proc_address("glCopyImageSubData");
tfx_glFramebufferTexture2D = get_proc_address("glFramebufferTexture2D");
tfx_glInvalidateFramebuffer = get_proc_address("glInvalidateFramebuffer");
tfx_glGenRenderbuffers = get_proc_address("glGenRenderbuffers");
tfx_glBindRenderbuffer = get_proc_address("glBindRenderbuffer");
tfx_glRenderbufferStorage = get_proc_address("glRenderbufferStorage");
tfx_glRenderbufferStorageMultisample = get_proc_address("glRenderbufferStorageMultisample");
tfx_glFramebufferRenderbuffer = get_proc_address("glFramebufferRenderbuffer");
tfx_glFramebufferTexture = get_proc_address("glFramebufferTexture");
tfx_glDrawBuffers = get_proc_address("glDrawBuffers");
tfx_glReadBuffer = get_proc_address("glReadBuffer");
tfx_glCheckFramebufferStatus = get_proc_address("glCheckFramebufferStatus");
tfx_glGetUniformLocation = get_proc_address("glGetUniformLocation");
tfx_glReleaseShaderCompiler = get_proc_address("glReleaseShaderCompiler");
tfx_glGenVertexArrays = get_proc_address("glGenVertexArrays");
tfx_glBindVertexArray = get_proc_address("glBindVertexArray");
tfx_glMapBufferRange = get_proc_address("glMapBufferRange");
tfx_glBufferSubData = get_proc_address("glBufferSubData");
tfx_glUnmapBuffer = get_proc_address("glUnmapBuffer");
tfx_glUseProgram = get_proc_address("glUseProgram");
tfx_glMemoryBarrier = get_proc_address("glMemoryBarrier");
tfx_glBindBufferBase = get_proc_address("glBindBufferBase");
tfx_glDispatchCompute = get_proc_address("glDispatchCompute");
tfx_glViewport = get_proc_address("glViewport");
tfx_glViewportIndexedf = get_proc_address("glViewportIndexedf");
tfx_glScissor = get_proc_address("glScissor");
tfx_glClearColor = get_proc_address("glClearColor");
tfx_glClearDepthf = get_proc_address("glClearDepthf");
tfx_glClear = get_proc_address("glClear");
tfx_glEnable = get_proc_address("glEnable");
tfx_glDepthFunc = get_proc_address("glDepthFunc");
tfx_glDisable = get_proc_address("glDisable");
tfx_glDepthMask = get_proc_address("glDepthMask");
tfx_glFrontFace = get_proc_address("glFrontFace");
tfx_glPolygonMode = get_proc_address("glPolygonMode");
tfx_glUniform1iv = get_proc_address("glUniform1iv");
tfx_glUniform1fv = get_proc_address("glUniform1fv");
tfx_glUniform2fv = get_proc_address("glUniform2fv");
tfx_glUniform3fv = get_proc_address("glUniform3fv");
tfx_glUniform4fv = get_proc_address("glUniform4fv");
tfx_glUniformMatrix2fv = get_proc_address("glUniformMatrix2fv");
tfx_glUniformMatrix3fv = get_proc_address("glUniformMatrix3fv");
tfx_glUniformMatrix4fv = get_proc_address("glUniformMatrix4fv");
tfx_glEnableVertexAttribArray = get_proc_address("glEnableVertexAttribArray");
tfx_glVertexAttribPointer = get_proc_address("glVertexAttribPointer");
tfx_glDisableVertexAttribArray = get_proc_address("glDisableVertexAttribArray");
tfx_glActiveTexture = get_proc_address("glActiveTexture");
tfx_glDrawElementsInstanced = get_proc_address("glDrawElementsInstanced");
tfx_glDrawArraysInstanced = get_proc_address("glDrawArraysInstanced");
tfx_glDrawElements = get_proc_address("glDrawElements");
tfx_glDrawArrays = get_proc_address("glDrawArrays");
tfx_glDeleteVertexArrays = get_proc_address("glDeleteVertexArrays");
tfx_glBindFragDataLocation = get_proc_address("glBindFragDataLocation");
tfx_glPushDebugGroup = get_proc_address("glPushDebugGroup");
tfx_glPopDebugGroup = get_proc_address("glPopDebugGroup");
tfx_glInsertEventMarkerEXT = get_proc_address("glInsertEventMarkerEXT");
}
static const char *tfx_sprintf(const char *fmt, ...) {
va_list args;
va_start(args, fmt);
char *buf = NULL;
int need = vsnprintf(buf, 0, fmt, args) + 1;
va_end(args);
va_start(args, fmt);
buf = malloc(need + 1);
buf[need] = '\0';
vsnprintf(buf, need, fmt, args);
va_end(args);
return buf;
}
static void tfx_printf(tfx_severity severity, const char *fmt, ...) {
va_list args;
va_start(args, fmt);
char *buf = NULL;
int need = vsnprintf(buf, 0, fmt, args) + 1;
va_end(args);
va_start(args, fmt);
buf = malloc(need + 1);
buf[need] = '\0';
vsnprintf(buf, need, fmt, args);
g_platform_data.info_log(buf, severity);
free(buf);
va_end(args);
}
static void tfx_printb(tfx_severity severity, const char *k, bool v) {
tfx_printf(severity, "TinyFX %s: %s", k, v ? "true" : "false");
}
static float g_max_aniso = 0.0f;
tfx_caps tfx_get_caps() {
tfx_caps caps;
memset(&caps, 0, sizeof(tfx_caps));
if (tfx_glGetStringi) {
GLint ext_count = 0;
CHECK(tfx_glGetIntegerv(GL_NUM_EXTENSIONS, &ext_count));
for (int i = 0; i < ext_count; i++) {
const char *search = (const char*)CHECK(tfx_glGetStringi(GL_EXTENSIONS, i));
#if defined(_MSC_VER) && 0
OutputDebugString(search);
OutputDebugString("\n");
#endif
for (int j = 0;; j++) {
tfx_glext *tmp = &available_exts[j];
if (!tmp->ext) {
break;
}
if (strcmp(tmp->ext, search) == 0) {
tmp->supported = true;
break;
}
}
}
}
else if (tfx_glGetString) {
const char *real = (const char*)CHECK(tfx_glGetString(GL_EXTENSIONS));
char *exts = tfx_strdup(real);
char *pch = strtok(exts, " ");
int len = 0;
char **supported = NULL;
while (pch != NULL) {
sb_push(supported, pch);
pch = strtok(NULL, " ");
len++;
}
free(exts);
int n = sb_count(supported);
for (int i = 0; i < n; i++) {
const char *search = supported[i];
for (int j = 0; ; j++) {
tfx_glext *tmp = &available_exts[j];
if (!tmp->ext) {
break;
}
if (strcmp(tmp->ext, search) == 0) {
tmp->supported = true;
break;
}
}
}
sb_free(supported);
}
bool gl30 = g_platform_data.context_version >= 30 && !g_platform_data.use_gles;
bool gl32 = g_platform_data.context_version >= 32 && !g_platform_data.use_gles;
bool gl33 = g_platform_data.context_version >= 33 && !g_platform_data.use_gles;
bool gl43 = g_platform_data.context_version >= 43 && !g_platform_data.use_gles;
bool gl44 = g_platform_data.context_version >= 44 && !g_platform_data.use_gles;
bool gl46 = g_platform_data.context_version >= 46 && !g_platform_data.use_gles;
bool gles30 = g_platform_data.context_version >= 30 && g_platform_data.use_gles;
bool gles31 = g_platform_data.context_version >= 31 && g_platform_data.use_gles;
caps.multisample = available_exts[0].supported || gl30;
caps.compute = available_exts[1].supported || gles31 || gl43;
caps.float_canvas = available_exts[2].supported || gles30 || gl30;
caps.debug_marker = available_exts[3].supported || available_exts[5].supported;
caps.debug_output = available_exts[4].supported || gl43;
caps.memory_info = available_exts[6].supported;
caps.instancing = available_exts[7].supported || gl33 || gles30;
caps.seamless_cubemap = available_exts[8].supported || gl32;
caps.anisotropic_filtering = available_exts[9].supported || gl46;
caps.multibind = available_exts[10].supported || gl44;
g_max_aniso = 0.0f;
GLenum GL_TEXTURE_MAX_ANISOTROPY_EXT = 0x84FE;
if (caps.anisotropic_filtering) {
GLenum GL_MAX_TEXTURE_MAX_ANISOTROPY_EXT = 0x84FF;
CHECK(tfx_glGetFloatv(GL_MAX_TEXTURE_MAX_ANISOTROPY_EXT, &g_max_aniso));
if (g_max_aniso <= 0.0f) {
caps.anisotropic_filtering = false;
}
}
return caps;
}
void tfx_dump_caps() {
tfx_caps caps = tfx_get_caps();
// I am told by the docs that this can be 0.
// It's not on the RPi, but since it's only a few lines of code...
int release_shader_c = 0;
tfx_glGetIntegerv(GL_SHADER_COMPILER, &release_shader_c);
TFX_INFO("GL shader compiler control: %d", release_shader_c);
TFX_INFO("GL vendor: %s", tfx_glGetString(GL_VENDOR));
TFX_INFO("GL version: %s", tfx_glGetString(GL_VERSION));
TFX_INFO("%s", "GL extensions:");
if (tfx_glGetStringi) {
GLint ext_count = 0;
CHECK(tfx_glGetIntegerv(GL_NUM_EXTENSIONS, &ext_count));
for (int i = 0; i < ext_count; i++) {
const char *real = (const char*)CHECK(tfx_glGetStringi(GL_EXTENSIONS, i));
TFX_INFO("\t%s", real);
}
}
else if (tfx_glGetString) {
const char *real = (const char*)CHECK(tfx_glGetString(GL_EXTENSIONS));
char *exts = tfx_strdup(real);
int len = 0;
char *pch = strtok(exts, " ");
while (pch != NULL) {
TFX_INFO("\t%s", pch);
pch = strtok(NULL, " ");
len++;
}
free(exts);
}
#define FUG(V) "GLES" #V
const char *glver =
#ifdef TFX_USE_GLES // NYI
FUG(TFX_USE_GLES/10)
#else
"GL4"
#endif
;
#undef FUG
TFX_INFO("TinyFX renderer: %s", glver);
tfx_printb(TFX_SEVERITY_INFO, "instancing", caps.instancing);
tfx_printb(TFX_SEVERITY_INFO, "compute", caps.compute);
tfx_printb(TFX_SEVERITY_INFO, "fp canvas", caps.float_canvas);
tfx_printb(TFX_SEVERITY_INFO, "multisample", caps.multisample);
}
// this is all definitely not the simplest way to deal with maps for uniform
// caches, but it's the simplest way I know which handles collisions.
#define TFX_HASHSIZE 101
typedef struct tfx_set {
struct tfx_set *next;
const char *key;
} tfx_set;
static unsigned tfx_hash(const char *s) {
unsigned hashval;
for (hashval = 0; *s != '\0'; s++)
hashval = *s + 31 * hashval;
return hashval % TFX_HASHSIZE;
}
static unsigned tfx_nohash(unsigned id) {
return id % TFX_HASHSIZE;
}
static bool tfx_slookup(tfx_set **hashtab, const char *s) {
#ifdef TFX_DEBUG
assert(s);
#endif
struct tfx_set *np;
for (np = hashtab[tfx_hash(s)]; np != NULL; np = np->next) {
if (strcmp(s, np->key) == 0) {
return true;
}
//TFX_WARN("collision\n");
}
return false;
}
static void tfx_sset(tfx_set **hashtab, const char *name) {
if (tfx_slookup(hashtab, name)) {
return;
}
unsigned hashval = tfx_hash(name);
tfx_set *np = malloc(sizeof(tfx_set));
np->key = name;
np->next = hashtab[hashval];
hashtab[hashval] = np;
}
static tfx_set **tfx_set_new() {
return calloc(sizeof(tfx_set*), TFX_HASHSIZE);
}
static void tfx_set_delete(tfx_set **hashtab) {
for (int i = 0; i < TFX_HASHSIZE; i++) {
if (hashtab[i] != NULL) {
free(hashtab[i]);
}
}
free(hashtab);
}
typedef struct tfx_locmap {
struct tfx_locmap *next;
const char *key;
GLuint value; // uniform location
} tfx_locmap;
static tfx_locmap *tfx_loclookup(tfx_locmap **hashtab, const char *s) {
#ifdef TFX_DEBUG
assert(s);
#endif
struct tfx_locmap *np;
for (np = hashtab[tfx_hash(s)]; np != NULL; np = np->next) {
if (strcmp(s, np->key) == 0) {
return np;
}
//TFX_WARN("collision\n");
}
return NULL;
}
static tfx_locmap* tfx_locset(tfx_locmap **hashtab, const char *name, GLuint value) {
tfx_locmap *found = tfx_loclookup(hashtab, name);
if (found) {
return NULL;
}
unsigned hashval = tfx_hash(name);
tfx_locmap *np = malloc(sizeof(tfx_locmap));
np->key = name;
np->next = hashtab[hashval];
np->value = value;
hashtab[hashval] = np;
return np;
}
static tfx_locmap **tfx_locmap_new() {
return calloc(sizeof(tfx_locmap*), TFX_HASHSIZE);
}
static void tfx_locmap_delete(tfx_locmap **hashtab) {
for (int i = 0; i < TFX_HASHSIZE; i++) {
if (hashtab[i] != NULL) {
free(hashtab[i]);
}
}
free(hashtab);
}
typedef struct tfx_shadermap {
struct tfx_shadermap *next;
GLint key; // shader program
tfx_locmap **value;
} tfx_shadermap;
static tfx_shadermap *tfx_proglookup(tfx_shadermap **hashtab, GLint program) {
#ifdef TFX_DEBUG
assert(program);
#endif
struct tfx_shadermap *np;
for (np = hashtab[tfx_nohash(program)]; np != NULL; np = np->next) {
if (program == np->key) {
return np;
}
//TFX_WARN("collision\n");
}
return NULL;
}
static tfx_shadermap* tfx_progset(tfx_shadermap **hashtab, GLint program) {
tfx_shadermap *found = tfx_proglookup(hashtab, program);
if (found) {
return found;
}
unsigned hashval = tfx_nohash(program);
tfx_shadermap *np = malloc(sizeof(tfx_shadermap));
np->key = program;
np->next = hashtab[hashval];
np->value = tfx_locmap_new();
hashtab[hashval] = np;
return np;
}
static tfx_shadermap **tfx_progmap_new() {
return calloc(sizeof(tfx_shadermap*), TFX_HASHSIZE);
}
static void tfx_progmap_delete(tfx_shadermap **hashtab) {
for (int i = 0; i < TFX_HASHSIZE; i++) {
if (hashtab[i] != NULL) {
tfx_locmap_delete(hashtab[i]->value);
free(hashtab[i]);
}
}
free(hashtab);
}
static tfx_buffer *g_buffers;
typedef struct tfx_frame_state {
// uniforms updated this frame
tfx_uniform *uniforms;
uint8_t *uniform_buffer;
uint8_t *ub_cursor;
tfx_shadermap **uniform_map;
tfx_view views[VIEW_MAX];
} tfx_frame_state;
static tfx_frame_state g_back; // staging update
/*
// TODO
static tfx_frame_state g_front; // processing update
void swap_state_buffer() {
tfx_frame_state tmp;
memcpy(&tmp, &g_back, sizeof(tfx_frame_state));
g_back = g_front;
g_front = tmp;
}
*/
static struct {
uint8_t *data;
uint32_t offset;
tfx_buffer buffers[TFX_TRANSIENT_BUFFER_COUNT];
} g_transient_buffer;
static tfx_caps g_caps;
// fallback printf
static void basic_log(const char *msg, tfx_severity level) {
#ifdef _MSC_VER
OutputDebugString(msg);
OutputDebugString("\n");
printf("%s\n", msg);
#else
printf("%s\n", msg);
#endif
}
static void tvb_reset() {
g_transient_buffer.offset = 0;
for (int i = 0; i < TFX_TRANSIENT_BUFFER_COUNT; i++) {
if (!g_transient_buffer.buffers[i].gl_id) {
GLuint id;
CHECK(tfx_glGenBuffers(1, &id));
CHECK(tfx_glBindBuffer(GL_ARRAY_BUFFER, id));
if (tfx_glBufferStorage) {
CHECK(tfx_glBufferStorage(GL_ARRAY_BUFFER, TFX_TRANSIENT_BUFFER_SIZE, NULL, GL_DYNAMIC_STORAGE_BIT | GL_MAP_WRITE_BIT));
}
else {
CHECK(tfx_glBufferData(GL_ARRAY_BUFFER, TFX_TRANSIENT_BUFFER_SIZE, NULL, GL_DYNAMIC_DRAW));
}
g_transient_buffer.buffers[i].gl_id = id;
}
}
}
void tfx_set_platform_data(tfx_platform_data pd) {
// supported: GL > 3, 2.1, ES 2.0, ES 3.0+
assert(0
|| (pd.context_version >= 30)
|| (pd.use_gles && pd.context_version == 20)
|| (!pd.use_gles && pd.context_version == 21)
);
if (pd.info_log == NULL) {
pd.info_log = &basic_log;
}
memcpy(&g_platform_data, &pd, sizeof(tfx_platform_data));
}
// null format = index buffer
tfx_transient_buffer tfx_transient_buffer_new(tfx_vertex_format *fmt, uint16_t num_verts) {
// transient index buffers aren't supported yet
assert(fmt != NULL);
assert(fmt->stride > 0);
tfx_transient_buffer buf;
memset(&buf, 0, sizeof(tfx_transient_buffer));
buf.data = g_transient_buffer.data + g_transient_buffer.offset;
buf.num = num_verts;
buf.offset = g_transient_buffer.offset;
uint32_t stride = sizeof(uint16_t);
if (fmt) {
buf.has_format = true;
buf.format = *fmt;
stride = (uint32_t)fmt->stride;
}
g_transient_buffer.offset += (uint32_t)(num_verts * stride);
g_transient_buffer.offset += g_transient_buffer.offset % 4; // align, in case the stride is weird
return buf;
}
// null format = available indices (uint16)
uint32_t tfx_transient_buffer_get_available(tfx_vertex_format *fmt) {
assert(fmt->stride > 0);
uint32_t avail = TFX_TRANSIENT_BUFFER_SIZE;
avail -= g_transient_buffer.offset;
uint32_t stride = sizeof(uint16_t);
if (fmt) {
stride = fmt->stride;
}
avail /= (uint32_t)stride;
return avail;
}
static tfx_program *g_programs = NULL;
static tfx_texture *g_textures = NULL;
static tfx_reset_flags g_flags = TFX_RESET_NONE;
static GLuint g_timers[TIMER_COUNT];
static int g_timer_offset = 0;
static bool use_timers = false;
static uint32_t *g_debug_data = NULL;
static tfx_program g_debug_program = 0;
static tfx_texture g_debug_overlay;
static tfx_uniform g_debug_texture;
static const char *g_debug_fss_legacy =
"in vec2 f_coord;\n"
"uniform sampler2D _tfx_texture;\n"
"void main() {\n"
" vec4 color = texture2D(_tfx_texture, vec2(f_coord.x, 1.0 - f_coord.y));\n"
" if (color.a < 0.01) discard;\n"
" gl_FragColor = vec4(color.rgb, 1.0) * color.a;\n"
"}\n"
;
static const char *g_debug_vss =
"in vec3 v_position;\n"
"out vec2 f_coord;\n"
"void main() {\n"