forked from rgriege/Violet
-
Notifications
You must be signed in to change notification settings - Fork 0
/
sdl_gl.h
2219 lines (1915 loc) · 66.6 KB
/
sdl_gl.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
#ifndef VIOLET_SDL_GL_H
#define VIOLET_SDL_GL_H
/* GL */
const char *gl_get_err_str(GLenum err);
/* Error checking can be expensive on some machines & configurations.
* I've seen it work fine on both OpenGL and WebGL, but I've also seen
* it be very slow in WebGL on a computer that had no problems in OpenGL. */
#if defined(DEBUG) || defined(CHECK_GL)
#define GL_ERR_CHECK(label) \
do { \
GLenum gl_err; \
while ((gl_err = glGetError()) != GL_NO_ERROR) { \
const char *gl_err_str = gl_get_err_str(gl_err); \
log_error("%s: %s(%x) @ %s:%d", label, gl_err_str, gl_err, \
__FILE__, __LINE__); \
} \
} while (0)
#define GL_CHECK(func, ...) \
do { \
func(__VA_ARGS__); \
GL_ERR_CHECK(#func); \
} while (0)
#define GL_ERR_IGNORE() \
while (glGetError() != GL_NO_ERROR);
#else
#define GL_ERR_CHECK(label) NOOP
#define GL_CHECK(func, ...) func(__VA_ARGS__)
#define GL_ERR_IGNORE() NOOP
#endif
/* Mesh */
typedef struct mesh_t
{
u32 vbo;
u32 sz;
} mesh_t;
void mesh_init(mesh_t *m, const v2f *poly, u32 n);
void mesh_destroy(mesh_t *m);
void mesh_poly(const mesh_t *m, v2f *poly);
void mesh_bind(const mesh_t *m);
void mesh_unbind(void);
void mesh_set_vertices(mesh_t *m, const v2f *v, u32 n);
/* Texture */
b32 texture_load(gui_texture_t *tex, const char *filename);
void texture_init(gui_texture_t *tex, u32 w, u32 h, u32 fmt, const void *data);
void texture_destroy(gui_texture_t *tex);
void texture_coords_from_poly(mesh_t *tex_coords, const v2f *v, u32 n);
void texture_bind(const gui_texture_t *tex);
void texture_unbind(void);
/* Shader */
typedef enum shader_type
{
VERTEX_SHADER,
FRAGMENT_SHADER
} shader_type_e;
typedef struct shader_t
{
u32 handle;
} shader_t;
b32 shader_init_from_string(shader_t *shader, const char *str,
shader_type_e type, const char *name);
b32 shader_init_from_file(shader_t *shader, const char *fname,
shader_type_e type, const char *name);
void shader_destroy(shader_t *shader);
typedef struct shader_prog_t
{
u32 handle;
shader_t vertex_shader;
shader_t frag_shader;
} shader_prog_t;
b32 shader_program_load_from_files(shader_prog_t *prog,
const char *vert_fname,
const char *frag_fname,
const char *name);
b32 shader_program_load_from_strings(shader_prog_t *prog,
const char *vert_str,
const char *frag_str,
const char *name);
b32 shader_program_create(shader_prog_t *prog, shader_t vertex_shader,
shader_t frag_shader, const char *name);
void shader_program_destroy(shader_prog_t *p);
void shader_program_bind(const shader_prog_t *p);
void shader_program_unbind(void);
s32 shader_program_attrib(const shader_prog_t *p, const char *name);
s32 shader_program_uniform(const shader_prog_t *p, const char *name);
/* Image */
b32 img_load(gui_img_t *img, const char *filename);
void img_init(gui_img_t *img, u32 w, u32 h, u32 fmt, void *data);
void img_destroy(gui_img_t *img);
void save_screenshot(box2i bounds, const char *filename);
/* Font */
#ifndef WINDOW_FONT_FILE_PATH
#define WINDOW_FONT_FILE_PATH "Roboto.ttf"
#endif
typedef struct font_t
{
const char *filename;
u32 path_hash;
s32 size;
s32 num_glyphs;
gui_font_metrics_t metrics;
void *char_info;
void *index_map;
gui_texture_t texture;
} font_t;
b32 font_load(font_t *f, const char *filename, s32 size);
void font_destroy(font_t *f);
typedef enum window_flags
{
WINDOW_BORDERLESS = 1 << 0,
WINDOW_RESIZABLE = 1 << 1,
WINDOW_MAXIMIZED = 1 << 2,
WINDOW_FULLSCREEN = 1 << 3,
WINDOW_CENTERED = 1 << 4,
/* vsync protip:
* enable this and call window_end_frame_ex with 0 target_frame_milli to
* avoid sleeping between draws, this seems to block on glClear in
* window_begin_frame to rate limit according to the system. */
WINDOW_NOVSYNC = 1 << 5,
} window_flags_e;
typedef struct window window_t;
typedef void (*window_endsession_callback_t)(void);
window_t *window_create(s32 x, s32 y, s32 w, s32 h, const char *title,
window_flags_e flags);
window_t *window_create_ex(s32 x, s32 y, s32 w, s32 h, const char *title,
window_flags_e flags, const char *font_file_path);
void window_destroy(window_t *window);
b32 window_begin_frame(window_t *window);
void window_end_frame(window_t *window);
void window_end_frame_ex(window_t *window, u32 target_frame_milli,
u32 idle_frame_milli, u32 idle_start_milli);
void window_move(const window_t *window, s32 dx, s32 dy);
b32 window_is_maximized(const window_t *window);
void window_minimize(window_t *window);
void window_maximize(window_t *window);
void window_restore(window_t *window);
void window_fullscreen(window_t *window);
void window_set_title(window_t *window, const char *title);
void window_run(window_t *window, u32 fps, b32(*ufunc)(window_t*, void*), void *udata);
void window_set_endsession_callback(window_t* window,
window_endsession_callback_t endsession_callback);
gui_t *window_get_gui(window_t *window);
const gui_img_t *window_get_img(window_t *window, const char *fname);
void window_drag(window_t *window, s32 x, s32 y, s32 w, s32 h);
s32 window_get_scale_for_dpi(const window_t *window);
void mouse_pos_global(const window_t *window, s32 *x, s32 *y);
#endif // VIOLET_SDL_GL_H
#ifdef SDL_GL_IMPLEMENTATION
#define SDL_MAIN_HANDLED
#include <SDL2/SDL.h>
#include <SDL2/SDL_surface.h>
#ifdef _WIN32
#include <SDL2/SDL_syswm.h>
#endif
#define STB_IMAGE_IMPLEMENTATION
// #define STB_IMAGE_STATIC
#include "stbi.h"
#define STB_RECT_PACK_IMPLEMENTATION
// #define STBRP_STATIC
#include "stb_rect_pack.h"
#define STB_TRUETYPE_IMPLEMENTATION
// #define STBTT_STATIC
#define stbtt_uint8 u8
#define stbtt_int8 s8
#define stbtt_uint16 u16
#define stbtt_int16 s16
#define stbtt_uint32 u32
#define stbtt_int32 s32
#define STBTT_malloc(x, u) ((allocator_t*)(u))->malloc_(x, u MEMCALL_LOCATION)
#define STBTT_free(x, u) ((allocator_t*)(u))->free_(x, u MEMCALL_LOCATION)
#include "stb_truetype.h"
static const char *g_vertex_shader;
static const char *g_fragment_shader;
/* GL */
const char *gl_get_err_str(GLenum err)
{
switch (err) {
case GL_INVALID_ENUM:
return "INVALID_ENUM";
case GL_INVALID_VALUE:
return "INVALID_VALUE";
case GL_INVALID_OPERATION:
return "INVALID_OPERATION";
case GL_INVALID_FRAMEBUFFER_OPERATION:
return "INVALID_FRAMEBUFFER_OPERATION";
case GL_OUT_OF_MEMORY:
return "OUT_OF_MEMORY";
case GL_STACK_UNDERFLOW:
return "STACK_UNDERFLOW";
case GL_STACK_OVERFLOW:
return "STACK_OVERFLOW";
default:
return "UNKNOWN ERROR";
}
}
/* Mesh */
void mesh_init(mesh_t *m, const v2f *poly, u32 n)
{
GL_CHECK(glGenBuffers, 1, &m->vbo);
mesh_set_vertices(m, poly, n);
}
void mesh_destroy(mesh_t *m)
{
if (m->vbo != 0)
GL_CHECK(glDeleteBuffers, 1, &m->vbo);
}
void mesh_poly(const mesh_t *m, v2f *poly)
{
array_clear(poly);
array_reserve(poly, m->sz);
array_sz(poly) = m->sz;
mesh_bind(m);
GL_CHECK(glGetBufferSubData, GL_ARRAY_BUFFER, 0, m->sz * 2 * sizeof(GL_FLOAT), poly);
}
void mesh_bind(const mesh_t *m)
{
GL_CHECK(glBindBuffer, GL_ARRAY_BUFFER, m->vbo);
}
void mesh_unbind(void)
{
GL_CHECK(glBindBuffer, GL_ARRAY_BUFFER, 0);
}
void mesh_set_vertices(mesh_t *m, const v2f *v, u32 n)
{
mesh_bind(m);
m->sz = n;
GL_CHECK(glBufferData, GL_ARRAY_BUFFER, m->sz * 2 * sizeof(GL_FLOAT), v, GL_STATIC_DRAW);
}
/* Texture */
b32 texture_load(gui_texture_t *tex, const char *filename)
{
b32 ret = false;
int w, h;
stbi_set_flip_vertically_on_load(true);
u8 *image = stbi_load(filename, &w, &h, NULL, 4);
if (image) {
texture_init(tex, w, h, GL_RGBA, image);
stbi_image_free(image);
ret = true;
}
return ret;
}
void texture_init(gui_texture_t *tex, u32 w, u32 h, u32 fmt, const void *data)
{
tex->width = w;
tex->height = h;
tex->blend = GUI_BLEND_NRM;
GL_CHECK(glGenTextures, 1, &tex->handle);
texture_bind(tex);
GL_CHECK(glTexImage2D, GL_TEXTURE_2D, 0, fmt, w, h, 0, fmt,
GL_UNSIGNED_BYTE, data);
GL_CHECK(glTexParameteri, GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE);
GL_CHECK(glTexParameteri, GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_EDGE);
GL_CHECK(glTexParameteri, GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR);
GL_CHECK(glTexParameteri, GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR);
}
void texture_destroy(gui_texture_t *tex)
{
if (tex->handle != 0) {
GL_CHECK(glDeleteTextures, 1, &tex->handle);
tex->handle = 0;
}
}
void texture_coords_from_poly(mesh_t *tex_coords, const v2f *v, u32 n)
{
box2f extent;
v2f dimension;
v2f *coords;
polyf_bounding_box(v, n, &extent);
dimension = v2f_sub(extent.max, extent.min);
array_init_ex(coords, n, g_temp_allocator);
for (const v2f *vi = v, *vn = v + n; vi != vn; ++vi)
array_append(coords, v2f_div(v2f_sub(*vi, extent.min), dimension));
mesh_init(tex_coords, coords, n);
array_destroy(coords);
}
void texture_bind(const gui_texture_t *tex)
{
GL_CHECK(glBindTexture, GL_TEXTURE_2D, tex->handle);
}
void texture_unbind(void)
{
GL_CHECK(glBindTexture, GL_TEXTURE_2D, 0);
}
/* Shader */
static const char *g_shader_type_names[2] = {
[VERTEX_SHADER] = "vertex",
[FRAGMENT_SHADER] = "fragment",
};
b32 shader_init_from_string(shader_t *shader, const char *str,
shader_type_e type, const char *name)
{
const char *type_name = g_shader_type_names[type];
b32 retval = false;
GLint compiled = GL_FALSE;
GLenum err = GL_NO_ERROR;
/* NOTE(rgriege): Do OpenGL error checking here even in release builds
* since a lot of graphics errors have shown up here, and the cause
* is typically very opaque to the user. Additionally, we can
* add more customized log messages, including more than just the OpenGL
* function name. I didn't profile this code with error checking,
* but shader compilation is supposedly expensive, so a little
* error checking shouldn't impact performance too badly. */
glGetError(); /* clear error flag */
shader->handle = glCreateShader( type == VERTEX_SHADER
? GL_VERTEX_SHADER : GL_FRAGMENT_SHADER);
if ((err = glGetError()) != GL_NO_ERROR) {
log_error("glCreateShader(%s, %s) = %s", name,
type_name, gl_get_err_str(err));
goto err;
}
glShaderSource(shader->handle, 1, (const GLchar **)&str, 0);
if ((err = glGetError()) != GL_NO_ERROR) {
log_error("glShaderSource(%s, %s) = %s", name,
type_name, gl_get_err_str(err));
goto err;
}
glCompileShader(shader->handle);
if ((err = glGetError()) != GL_NO_ERROR) {
log_error("glCompileShader(%s, %s) = %s", name,
type_name, gl_get_err_str(err));
goto err;
}
glGetShaderiv(shader->handle, GL_COMPILE_STATUS, &compiled);
if ((err = glGetError()) != GL_NO_ERROR) {
log_error("glGetShaderiv(%s, %s, GL_COMPILE_STATUS) = %s", name,
type_name, gl_get_err_str(err));
goto err;
}
if (compiled == GL_FALSE) {
GLint log_len;
char *log_buf;
glGetShaderiv(shader->handle, GL_INFO_LOG_LENGTH, &log_len);
if ((err = glGetError()) != GL_NO_ERROR) {
log_error("glGetShaderiv(%s, %s, GL_INFO_LOG_LENGTH) = %s", name,
type_name, gl_get_err_str(err));
goto err;
}
log_buf = amalloc(log_len, g_temp_allocator);
glGetShaderInfoLog(shader->handle, log_len, NULL, log_buf);
if ((err = glGetError()) != GL_NO_ERROR) {
log_error("glGetShaderInfoLog(%s, %s) = %s", name,
type_name, gl_get_err_str(err));
goto err;
}
log_error("Compilation error in %s shader '%s': %s",
g_shader_type_names[type], name, log_buf);
afree(log_buf, g_temp_allocator);
shader->handle = 0;
goto err;
}
retval = true;
err:
return retval;
}
b32 shader_init_from_file(shader_t *shader, const char *fname,
shader_type_e type, const char *name)
{
b32 retval = false;
FILE *file;
char *file_buf;
size_t fsize;
file = file_open(fname, "rb");
if (!file) {
log_error("Failed to open file '%s' for %s shader '%s'",
fname, g_shader_type_names[type], name);
return retval;
}
fseek(file, 0, SEEK_END);
fsize = ftell(file);
rewind(file);
file_buf = amalloc(fsize + 1, g_allocator);
if (fread(file_buf, 1, fsize, file) != fsize) {
log_error("Failed to read file '%s' for %s shader '%s'",
fname, g_shader_type_names[type], name);
goto err;
}
file_buf[fsize] = 0;
retval = shader_init_from_string(shader, file_buf, type, fname);
err:
afree(file_buf, g_allocator);
fclose(file);
return retval;
}
void shader_destroy(shader_t *shader)
{
GL_CHECK(glDeleteShader, shader->handle);
shader->handle = 0;
}
b32 shader_program_load_from_strings(shader_prog_t *prog,
const char *vert_str,
const char *frag_str,
const char *name)
{
b32 retval = false;
if (!shader_init_from_string(&prog->vertex_shader, vert_str,
VERTEX_SHADER, name))
goto out;
if (!shader_init_from_string(&prog->frag_shader, frag_str,
FRAGMENT_SHADER, name))
goto err_frag;
if (shader_program_create(prog, prog->vertex_shader, prog->frag_shader, name)) {
retval = true;
goto out;
}
shader_destroy(&prog->frag_shader);
err_frag:
shader_destroy(&prog->vertex_shader);
out:
return retval;
}
b32 shader_program_load_from_files(shader_prog_t *prog,
const char *vert_fname,
const char *frag_fname,
const char *name)
{
b32 retval = false;
if (!shader_init_from_file(&prog->vertex_shader, vert_fname, VERTEX_SHADER, name))
goto out;
if (!shader_init_from_file(&prog->frag_shader, frag_fname, FRAGMENT_SHADER, name))
goto err_frag;
if (shader_program_create(prog, prog->vertex_shader, prog->frag_shader, name)) {
retval = true;
goto out;
}
shader_destroy(&prog->frag_shader);
err_frag:
shader_destroy(&prog->vertex_shader);
out:
return retval;
}
b32 shader_program_create(shader_prog_t *p, shader_t vertex_shader,
shader_t frag_shader, const char *name)
{
b32 retval = false;
GLint status = GL_FALSE;
GLenum err = GL_NO_ERROR;
/* NOTE(rgriege): Do OpenGL error checking here even in release builds
* since a lot of graphics errors have shown up here, and the cause
* is typically very opaque to the user. Additionally, we can
* add more customized log messages, including more than just the OpenGL
* function name. I didn't profile this code with error checking,
* but shader compilation is supposedly expensive, so a little
* error checking shouldn't impact performance too badly. */
glGetError(); /* clear error flag */
p->handle = glCreateProgram();
if ((err = glGetError()) != GL_NO_ERROR) {
log_error("glCreateProgram(%s) = %s", name, gl_get_err_str(err));
goto err;
}
glAttachShader(p->handle, vertex_shader.handle);
if ((err = glGetError()) != GL_NO_ERROR) {
log_error("glAttachShader(%s, vertex) = %s", name, gl_get_err_str(err));
goto err;
}
p->vertex_shader = vertex_shader;
glAttachShader(p->handle, frag_shader.handle);
if ((err = glGetError()) != GL_NO_ERROR) {
log_error("glAttachShader(%s, fragment) = %s", name, gl_get_err_str(err));
goto err;
}
p->frag_shader = frag_shader;
glLinkProgram(p->handle);
if ((err = glGetError()) != GL_NO_ERROR) {
log_error("glLinkProgram(%s) = %s", name, gl_get_err_str(err));
goto err;
}
glGetProgramiv(p->handle, GL_LINK_STATUS, &status);
if ((err = glGetError()) != GL_NO_ERROR) {
log_error("glGetProgramiv(%s, GL_LINK_STATUS) = %s", name, gl_get_err_str(err));
goto err;
}
if (status == GL_FALSE) {
GLint length;
char *log_buf;
glGetProgramiv(p->handle, GL_INFO_LOG_LENGTH, &length);
if ((err = glGetError()) != GL_NO_ERROR) {
log_error("glGetProgramiv(%s, GL_INFO_LOG_LENGTH) = %s", name, gl_get_err_str(err));
goto err;
}
log_buf = amalloc(length, g_temp_allocator);
glGetProgramInfoLog(p->handle, length, NULL, log_buf);
if ((err = glGetError()) != GL_NO_ERROR) {
log_error("glGetProgramInfoLog(%s) = %s", name, gl_get_err_str(err));
goto err;
}
log_error("Link error in shader '%s': %s", name, log_buf);
afree(log_buf, g_temp_allocator);
goto err;
}
#ifdef GUI_VALIDATE_SHADER
glValidateProgram(p->handle);
if ((err = glGetError()) != GL_NO_ERROR) {
log_error("glValidateProgram(%s) = %s", name, gl_get_err_str(err));
goto err;
}
glGetProgramiv(p->handle, GL_VALIDATE_STATUS, &status);
if ((err = glGetError()) != GL_NO_ERROR) {
log_error("glGetProgramiv(%s, GL_VALIDATE_STATUS) = %s", name, gl_get_err_str(err));
goto err;
}
if (status == GL_FALSE) {
GLint length;
char *log_buf;
glGetProgramiv(p->handle, GL_INFO_LOG_LENGTH, &length);
if ((err = glGetError()) != GL_NO_ERROR) {
log_error("glGetProgramiv(%s, GL_INFO_LOG_LENGTH) = %s", name, gl_get_err_str(err));
goto err;
}
log_buf = amalloc(length, g_temp_allocator);
glGetProgramInfoLog(p->handle, length, NULL, log_buf);
if ((err = glGetError()) != GL_NO_ERROR) {
log_error("glGetProgramInfoLog(%s) = %s", name, gl_get_err_str(err));
goto err;
}
log_error("Validation error in shader '%s': %s", name, log_buf);
afree(log_buf, g_temp_allocator);
goto err;
}
#endif
retval = true;
err:
return retval;
}
void shader_program_bind(const shader_prog_t *p)
{
GL_CHECK(glUseProgram, p->handle);
}
void shader_program_unbind(void)
{
GL_CHECK(glUseProgram, 0);
}
void shader_program_destroy(shader_prog_t *p)
{
GL_CHECK(glDetachShader, p->handle, p->vertex_shader.handle);
shader_destroy(&p->vertex_shader);
GL_CHECK(glDetachShader, p->handle, p->frag_shader.handle);
shader_destroy(&p->frag_shader);
GL_CHECK(glDeleteProgram, p->handle);
p->handle = 0;
}
s32 shader_program_attrib(const shader_prog_t *p, const char *name)
{
s32 attrib = glGetAttribLocation(p->handle, name);
GL_ERR_CHECK("glGetAttribLocation");
return attrib;
}
s32 shader_program_uniform(const shader_prog_t *p, const char *name)
{
s32 uniform = glGetUniformLocation(p->handle, name);
GL_ERR_CHECK("glGetUniformLocation");
return uniform;
}
/* Image */
b32 img_load(gui_img_t *img, const char *filename)
{
if (!texture_load(img, filename)) {
log_error("img_load(%s) error", filename);
return false;
}
return true;
}
void img_init(gui_img_t *img, u32 w, u32 h, u32 fmt, void *data)
{
texture_init(img, w, h, fmt, data);
}
void img_destroy(gui_img_t *img)
{
texture_destroy(img);
}
void save_screenshot(box2i bounds, const char *filename)
{
s32 x, y, w, h;
box2i_to_xywh(bounds, &x, &y, &w, &h);
SDL_Surface *surface;
char *bytes = amalloc(w * h * 4, g_allocator);
char *bytes_flip = amalloc(w * h * 4, g_allocator);
glReadPixels(x, y, w, h, GL_RGBA, GL_UNSIGNED_BYTE, bytes);
for (s32 i = 0; i < h; i++)
memcpy(&bytes_flip[i * w * 4], &bytes[(h - i - 1) * w * 4], w * 4);
surface = SDL_CreateRGBSurfaceFrom(bytes_flip, w, h, 32, 4 * w,
0x000000ff, 0x0000ff00,
0x00ff0000, 0x00000000);
SDL_SaveBMP(surface, filename);
SDL_FreeSurface(surface);
afree(bytes, g_allocator);
afree(bytes_flip, g_allocator);
}
/* copied + modified from stbtt_PackFontRangesGatherRects */
static
void vltt_PackFontAllGatherRects(stbtt_pack_context *spc, const stbtt_fontinfo *info,
int font_size, stbrp_rect *rects)
{
int missing_glyph_added = 0;
float fh = font_size;
float scale = fh > 0 ? stbtt_ScaleForPixelHeight(info, fh)
: stbtt_ScaleForMappingEmToPixels(info, -fh);
for (int glyph = 0; glyph < info->numGlyphs; ++glyph) {
int x0,y0,x1,y1;
if (glyph == 0 && (spc->skip_missing || missing_glyph_added)) {
rects[glyph].w = rects[glyph].h = 0;
} else {
stbtt_GetGlyphBitmapBoxSubpixel(info,glyph,
scale * spc->h_oversample,
scale * spc->v_oversample,
0,0,
&x0,&y0,&x1,&y1);
rects[glyph].w = (stbrp_coord) (x1-x0 + spc->padding + spc->h_oversample-1);
rects[glyph].h = (stbrp_coord) (y1-y0 + spc->padding + spc->v_oversample-1);
if (glyph == 0)
missing_glyph_added = 1;
}
}
}
/* copied + modified from stbtt_PackFontRangesRenderIntoRects */
static
int vltt_PackFontAllRenderIntoRects(stbtt_pack_context *spc, const stbtt_fontinfo *info,
int font_size, stbrp_rect *rects,
stbtt_packedchar *chardata, int *num_unpacked)
{
int missing_glyph = -1, return_value = 1;
float fh = font_size;
float scale = fh > 0 ? stbtt_ScaleForPixelHeight(info, fh)
: stbtt_ScaleForMappingEmToPixels(info, -fh);
*num_unpacked = 0;
for (int glyph = 0; glyph < info->numGlyphs; ++glyph) {
float recip_h,recip_v,sub_x,sub_y;
recip_h = 1.0f / spc->h_oversample;
recip_v = 1.0f / spc->v_oversample;
sub_x = stbtt__oversample_shift(spc->h_oversample);
sub_y = stbtt__oversample_shift(spc->v_oversample);
stbrp_rect *r = &rects[glyph];
if (r->was_packed && r->w != 0 && r->h != 0) {
stbtt_packedchar *bc = &chardata[glyph];
int advance, lsb, x0,y0,x1,y1;
stbrp_coord pad = (stbrp_coord) spc->padding;
// pad on left and top
r->x += pad;
r->y += pad;
r->w -= pad;
r->h -= pad;
stbtt_GetGlyphHMetrics(info, glyph, &advance, &lsb);
stbtt_GetGlyphBitmapBox(info, glyph,
scale * spc->h_oversample,
scale * spc->v_oversample,
&x0,&y0,&x1,&y1);
stbtt_MakeGlyphBitmapSubpixel(info,
spc->pixels + r->x + r->y*spc->stride_in_bytes,
r->w - spc->h_oversample+1,
r->h - spc->v_oversample+1,
spc->stride_in_bytes,
scale * spc->h_oversample,
scale * spc->v_oversample,
0,0,
glyph);
if (spc->h_oversample > 1)
stbtt__h_prefilter(spc->pixels + r->x + r->y*spc->stride_in_bytes,
r->w, r->h, spc->stride_in_bytes,
spc->h_oversample);
if (spc->v_oversample > 1)
stbtt__v_prefilter(spc->pixels + r->x + r->y*spc->stride_in_bytes,
r->w, r->h, spc->stride_in_bytes,
spc->v_oversample);
bc->x0 = (stbtt_int16) r->x;
bc->y0 = (stbtt_int16) r->y;
bc->x1 = (stbtt_int16) (r->x + r->w);
bc->y1 = (stbtt_int16) (r->y + r->h);
bc->xadvance = scale * advance;
bc->xoff = (float) x0 * recip_h + sub_x;
bc->yoff = (float) y0 * recip_v + sub_y;
bc->xoff2 = (x0 + r->w) * recip_h + sub_x;
bc->yoff2 = (y0 + r->h) * recip_v + sub_y;
if (glyph == 0)
missing_glyph = glyph;
} else if (spc->skip_missing) {
return_value = 0;
++*num_unpacked;
} else if (r->was_packed && r->w == 0 && r->h == 0 && missing_glyph >= 0) {
chardata[glyph] = chardata[missing_glyph];
} else {
return_value = 0; // if any fail, report failure
++*num_unpacked;
}
}
return return_value;
}
/* Instead of packing individual ranges, pack all the codepoints that are in the file.
* Since the stbtt interface wasn't designed for this use, I had to copy+paste+refactor
* a few functions from the library. A cleaner approach would be to build a list
* of ranges from the font's character mapping, but I don't understand the TTF file
* format well enough to do that.
*
* This function is copied + modified from stbtt_PackFontRanges */
static
int vltt_PackFontAll(stbtt_pack_context *spc, stbtt_fontinfo *info,
int font_size, stbtt_packedchar *chardata, int *num_unpacked)
{
const int n = info->numGlyphs;
int return_value = 1;
stbrp_rect *rects;
// flag all characters as NOT packed
for (int i = 0; i < n; ++i)
chardata[i].x0 = chardata[i].y0 = chardata[i].x1 = chardata[i].y1 = 0;
rects = STBTT_malloc(sizeof(*rects) * n, spc->user_allocator_context);
if (!rects)
return 0;
vltt_PackFontAllGatherRects(spc, info, font_size, rects);
stbtt_PackFontRangesPackRects(spc, rects, n);
return_value = vltt_PackFontAllRenderIntoRects(spc, info, font_size, rects, chardata, num_unpacked);
STBTT_free(rects, spc->user_allocator_context);
return return_value;
}
static
int vltt_PackFont(stbtt_fontinfo *info, int font_size, stbtt_packedchar *chardata, gui_texture_t *tex)
{
#ifdef __EMSCRIPTEN__
const s32 bpp = 2;
#else
const s32 bpp = 1;
#endif
temp_memory_mark_t mark = temp_memory_save(g_temp_allocator);
unsigned char *bitmap = NULL;
s32 w = 512, h = 512;
s32 h_oversample = 3;
stbtt_pack_context context;
b32 packed = false, failed = false;
s32 num_unpacked = 0;
while (!packed && !failed) {
temp_memory_restore(mark);
bitmap = amalloc(w * h * bpp, g_temp_allocator);
/* NOTE(rgriege): otherwise bitmap has noise at the bottom */
memset(bitmap, 0, w * h * bpp);
if ((failed = !stbtt_PackBegin(&context, bitmap, w, h, w * bpp, 1, g_temp_allocator)))
break;
stbtt_PackSetOversampling(&context, h_oversample, 1);
if (vltt_PackFontAll(&context, info, font_size, chardata, &num_unpacked)) {
stbtt_PackEnd(&context); // not really necessary, handled by memory mark
packed = true;
} else {
const s32 num_glyphs_packed = info->numGlyphs - num_unpacked;
s32 est_glyphs_packed = num_glyphs_packed;
s32 est_glyphs_packed_prev;
do {
est_glyphs_packed_prev = est_glyphs_packed;
if (w < 2048) {
w *= 2;
est_glyphs_packed *= 2;
} else if (h_oversample > 1) {
const s32 old_h_oversample = h_oversample;
h_oversample = 1;
est_glyphs_packed *= old_h_oversample;
} else if (h < 2048) {
h *= 2;
est_glyphs_packed *= 2;
}
} while ( est_glyphs_packed < info->numGlyphs / 2
&& est_glyphs_packed > est_glyphs_packed_prev);
// fail on fonts needing too large a texture,
// but try one last time if we've changed a parameter
failed = (est_glyphs_packed == num_glyphs_packed);
}
}
if (packed) {
#ifdef __EMSCRIPTEN__
unsigned char *row = amalloc(w * bpp, g_temp_allocator);
for (s32 r = 0; r < h; ++r) {
memset(row, ~0, w * bpp);
for (s32 c = 0; c < w; ++c)
row[c * bpp + bpp - 1] = bitmap[r * w * bpp + c];
memcpy(&bitmap[r * w * bpp], row, w * bpp);
}
texture_init(tex, w, h, GL_LUMINANCE_ALPHA, bitmap);
#else
texture_init(tex, w, h, GL_RED, bitmap);
GL_CHECK(glTexParameteri, GL_TEXTURE_2D, GL_TEXTURE_SWIZZLE_R, GL_ONE);
GL_CHECK(glTexParameteri, GL_TEXTURE_2D, GL_TEXTURE_SWIZZLE_G, GL_ONE);
GL_CHECK(glTexParameteri, GL_TEXTURE_2D, GL_TEXTURE_SWIZZLE_B, GL_ONE);
GL_CHECK(glTexParameteri, GL_TEXTURE_2D, GL_TEXTURE_SWIZZLE_A, GL_RED);
#endif
}
temp_memory_restore(mark);
return packed;
}
/* See https://docs.microsoft.com/en-us/typography/opentype/spec/cmap */
static
size_t font__index_map_size(const stbtt_fontinfo *info)
{
stbtt_uint8 *data = info->data;
stbtt_uint32 index_map = info->index_map;
stbtt_uint16 format = ttUSHORT(data + index_map + 0);
if (format == 0) { // byte encoding table
return ttUSHORT(data + index_map + 2);
} else if (format == 2) { // high-byte mapping through table
return ttUSHORT(data + index_map + 2);
} else if (format == 4) { // segment mapping to delta values
return ttUSHORT(data + index_map + 2);
} else if (format == 6) { // trimmed table mapping
return ttUSHORT(data + index_map + 2);
} else if (format == 8) { // mixed 16-bit and 32-bit coverage
return ttULONG(data + index_map + 4);
} else if (format == 10) { // trimmed array
return ttULONG(data + index_map + 4);
} else if (format == 12) { // segmented coverage
return ttULONG(data + index_map + 4);
} else if (format == 13) { // many-to-one range mappings
return ttULONG(data + index_map + 4);
} else if (format == 14) { // unicode variation sequences
return ttULONG(data + index_map + 2);
} else {
assert(0);
return 0;
}
}
static
void font__index_map_copy(font_t *f, const stbtt_fontinfo *info, allocator_t *alloc)
{
stbtt_uint8 *data = info->data;
stbtt_uint32 index_map = info->index_map;
size_t size = font__index_map_size(info);
f->index_map = amalloc(size, alloc);
memcpy(f->index_map, data + index_map, size);
}
static
int font__get_index_for_codepoint(const font_t *f, s32 codepoint)
{
/* NOTE(rgriege): kinda hacky - only works as long as stbtt_FindGlyphIndex
* doesn't use any other fields from info. Storing our own hash map instead
* of the TTF's index map may be faster & more robust. */
stbtt_fontinfo info = {
.data = f->index_map,
.index_map = 0,
};
return stbtt_FindGlyphIndex(&info, codepoint);
}
b32 font_load(font_t *f, const char *filename, s32 size)
{
b32 retval = false;
stbtt_fontinfo info = { .userdata = g_temp_allocator };
int ascent, descent, line_gap;
r32 scale;
void *ttf;
f->char_info = NULL;
if (!(ttf = file_read_all(filename, "rb", NULL, g_temp_allocator))) {
log_error("failed to read font file '%s'", filename);
goto out;
}
if (!stbtt_InitFont(&info, ttf, stbtt_GetFontOffsetForIndex(ttf, 0))) {