-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathsofren.c
More file actions
10492 lines (8770 loc) · 382 KB
/
Copy pathsofren.c
File metadata and controls
10492 lines (8770 loc) · 382 KB
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 SFR_H
#define SFR_H
#ifdef __cplusplus
extern "C" {
#endif
//================================================
//: PUBLIC API
//================================================
#ifndef NULL
#define NULL (void*)0
#endif
//: threading config
#ifdef SFR_THREAD_COUNT
#if SFR_THREAD_COUNT < 1 || SFR_THREAD_COUNT > 32
#error "SFR ERROR: SFR_THREAD_COUNT must be between 1 and 32 (32 arbitrary)"
#endif
#else
#define SFR_THREAD_COUNT 8
#endif
#if SFR_THREAD_COUNT > 1
#define SFR_MULTITHREADED
#ifndef SFR_TILE_WIDTH
#define SFR_TILE_WIDTH 64
#endif
#ifndef SFR_TILE_HEIGHT
#define SFR_TILE_HEIGHT 64
#endif
#define SFR_TILE_DIM (SFR_TILE_WIDTH * SFR_TILE_HEIGHT)
#ifndef SFR_GEOMETRY_JOB_SIZE
// number of triangles per geometry job
#define SFR_GEOMETRY_JOB_SIZE 64
#endif
#endif
#ifdef SFR_MULTITHREADED
#ifdef _WIN32
#ifndef _WIN32_WINNT
// for CreateSemaphoreEx
#define _WIN32_WINNT 0x0600
#endif
#define NOGDI
#define NOUSER
#define NOMINMAX
#define WIN32_LEAN_AND_MEAN
#include <windows.h>
#ifdef near
#undef near
#endif
#ifdef far
#undef far
#endif
#include <process.h> // for _beginthreadex
typedef HANDLE SfrThread;
typedef HANDLE SfrSemaphore;
typedef CRITICAL_SECTION SfrMutex;
typedef volatile LONG SfrAtomic32;
typedef volatile LONG64 SfrAtomic64;
#else
#include <pthread.h>
#include <semaphore.h>
#include <sched.h> // for sched_yield
#include <errno.h>
typedef pthread_t SfrThread;
typedef sem_t SfrSemaphore;
typedef pthread_mutex_t SfrMutex;
typedef volatile int SfrAtomic32;
typedef volatile long long SfrAtomic64;
#endif
#ifndef SFR_THREAD_LOCAL
#if defined(_MSC_VER)
#define SFR_THREAD_LOCAL __declspec(thread)
#elif defined(__GNUC__) || defined(__clang__)
#define SFR_THREAD_LOCAL __thread
#else
#define SFR_THREAD_LOCAL _Thread_local
#endif
#endif
#else
#define SfrAtomic32 i32
#define SfrAtomic64 i64
#define SFR_THREAD_LOCAL
#endif
//: types
#ifdef SFR_PREFIXED_TYPES
#define i8 sfri8_t
#define u8 sfru8_t
#define i16 sfri16_t
#define u16 sfru16_t
#define i32 sfri32_t
#define u32 sfru32_t
#define i64 sfri64_t
#define u64 sfru64_t
#define f32 sfrf32_t
#define f64 sfrf64_t
#define vf32 sfrvf32_t
#define vf32s sfrvf32s_t
#define vi32 sfrvi32_t
#endif
#ifndef SFR_NO_STDINT
#include <stdint.h>
typedef int8_t i8;
typedef uint8_t u8;
typedef int16_t i16;
typedef uint16_t u16;
typedef int32_t i32;
typedef uint32_t u32;
typedef int64_t i64;
typedef uint64_t u64;
#else
typedef signed char i8;
typedef unsigned char u8;
typedef signed short i16;
typedef unsigned short u16;
typedef signed int i32;
typedef unsigned int u32;
typedef signed long long i64;
typedef unsigned long long u64;
#endif
typedef float f32;
typedef double f64;
typedef union sfrvec sfrvec;
typedef union sfrmat sfrmat;
typedef struct sfrmesh SfrMesh;
typedef struct sfrdmesh SfrDynamicMesh;
typedef struct sfrtex SfrTexture;
typedef struct sfrMaterial SfrMaterial;
typedef struct sfrfont SfrFont;
typedef struct sfrRenderTarget SfrRenderTarget;
typedef struct sfrShadowBind SfrShadowBind;
typedef struct sfrScene SfrScene;
typedef struct sfrSceneObject SfrSceneObject;
typedef struct sfrRayHit SfrRayHit;
typedef struct sfrBillboard SfrBillboard;
typedef struct sfrlight SfrLight;
#ifdef SFR_USE_CGLTF
typedef struct sfrModel SfrModel;
typedef struct sfrEntity SfrEntity;
#endif
//: extern variables
extern SfrAtomic32 sfrRasterCount; // how many triangles have been rasterized since the last call to clear
extern sfrmat sfrMatModel, sfrMatView, sfrMatProj;
extern sfrvec sfrCamPos, sfrCamUp, sfrCamTarget;
extern f32 sfrCamFov;
extern f32 sfrNearDist, sfrFarDist;
#if defined(SFR_FUNC) && defined(SFR_USE_INLINE) && !defined(SFR_NO_WARNINGS)
#warning "SFR WARNING: SFR_FUNC and SFR_USE_INLINE both being defined is contradictory, using SFR_FUNC"
#endif
#ifndef SFR_FUNC
#ifdef SFR_USE_INLINE
#define SFR_FUNC static inline
#else
#define SFR_FUNC static
#endif
#endif
#if defined(_MSC_VER)
#define SFR_FORCE_INLINE static __forceinline
#elif defined(__GNUC__) || defined(__clang__)
#define SFR_FORCE_INLINE static inline __attribute__((always_inline))
#else
#define SFR_FORCE_INLINE static inline
#endif
#ifndef SFR_SQRT_ACCURACY
#define SFR_SQRT_ACCURACY 20
#endif
#ifndef SFR_TRIG_ACCURACY
#define SFR_TRIG_ACCURACY 10
#endif
#ifndef SFR_FONT_GLYPH_MAX
#define SFR_FONT_GLYPH_MAX 512
#endif
#ifndef SFR_FONT_VERT_MAX
// 72 verts max == 12 tris max
#define SFR_FONT_VERT_MAX 72
#endif
#define SFR_FONT_VERT_EMPTY 1234321
#ifndef SFR_MAX_SHADOWMAPS
#define SFR_MAX_SHADOWMAPS 4
#endif
//: math functions
SFR_FUNC sfrvec sfr_vec_add(sfrvec a, sfrvec b);
SFR_FUNC sfrvec sfr_vec_sub(sfrvec a, sfrvec b);
SFR_FUNC sfrvec sfr_vec_mul(sfrvec a, f32 b);
SFR_FUNC sfrvec sfr_vec_div(sfrvec a, f32 b);
SFR_FUNC f32 sfr_vec_dot(sfrvec a, sfrvec b);
SFR_FUNC f32 sfr_vec_length(sfrvec v);
SFR_FUNC f32 sfr_vec_length2(sfrvec v);
SFR_FUNC sfrvec sfr_vec_cross(sfrvec a, sfrvec b);
SFR_FUNC sfrvec sfr_vec_norm(sfrvec v);
SFR_FUNC sfrvec sfr_vec_normf(f32 x, f32 y, f32 z);
SFR_FUNC sfrvec sfr_vec_face_normal(sfrvec a, sfrvec b, sfrvec c);
SFR_FUNC sfrvec sfr_vec_lerp(sfrvec a, sfrvec b, f32 t);
SFR_FUNC sfrvec sfr_vec_perpendicular(sfrvec v);
SFR_FUNC sfrvec sfr_vec_rotate_by_quat(sfrvec v, sfrvec q);
SFR_FUNC sfrmat sfr_mat_identity();
SFR_FUNC sfrmat sfr_mat_rot_x(f32 a);
SFR_FUNC sfrmat sfr_mat_rot_y(f32 a);
SFR_FUNC sfrmat sfr_mat_rot_z(f32 a);
SFR_FUNC sfrmat sfr_mat_translate(f32 x, f32 y, f32 z);
SFR_FUNC sfrmat sfr_mat_scale(f32 x, f32 y, f32 z);
SFR_FUNC sfrmat sfr_mat_proj(f32 fovDeg, f32 aspect, f32 near, f32 far);
SFR_FUNC sfrmat sfr_mat_ortho(f32 left, f32 right, f32 bottom, f32 top, f32 near, f32 far);
SFR_FUNC sfrmat sfr_mat_mul(sfrmat a, sfrmat b);
SFR_FUNC sfrvec sfr_mat_mul_vec(sfrmat m, sfrvec v);
SFR_FUNC sfrmat sfr_mat_qinv(sfrmat m);
SFR_FUNC sfrmat sfr_mat_model_look_at(sfrvec pos, sfrvec target, sfrvec up); // used for when a 3D object (e.g. a missile or spotlight) should rotate to face a target
SFR_FUNC sfrmat sfr_mat_view_look_at(sfrvec pos, sfrvec target, sfrvec up); // used only for cameras, computes the inverse translation required for view spaces
SFR_FUNC void sfr_mat_decompose(sfrmat m, sfrvec* pos, sfrvec* rot, sfrvec* scale);
SFR_FUNC sfrmat sfr_mat_from_quat(sfrvec q);
SFR_FUNC sfrvec sfr_quat_mul(sfrvec a, sfrvec b);
SFR_FUNC sfrvec sfr_quat_slerp(sfrvec a, sfrvec b, f32 t);
SFR_FUNC sfrvec sfr_quat_invert(sfrvec q);
SFR_FUNC sfrvec sfr_quat_norm(sfrvec q);
//: core functions
SFR_FUNC void sfr_init(i32 w, i32 h, f32 fovDeg,
void* (*mallocFunc)(u64), void (*freeFunc)(void*), void* (*reallocFunc)(void*, u64));
SFR_FUNC void sfr_release(void);
// finish rendering triangles, must be called for any thread count
SFR_FUNC void sfr_present(void);
// shadow mapping
SFR_FUNC void sfr_shadow_pass_begin(SfrRenderTarget* target, sfrvec lightDir, sfrvec center, f32 orthoSize, f32 distance, f32 zFar);
SFR_FUNC void sfr_shadow_pass_point_begin(SfrRenderTarget* target, sfrvec center, f32 radius, i32 faceInd);
SFR_FUNC void sfr_shadow_pass_end(void);
SFR_FUNC void sfr_shadow_push_state(void); // temporarily disable shadowmap and save its state
SFR_FUNC void sfr_shadow_pop_state(void); // restores the previously stored shadowmap
// render targets
SFR_FUNC SfrRenderTarget* sfr_create_target(i32 width, i32 height, u8 hasPixels);
SFR_FUNC void sfr_release_target(SfrRenderTarget** target);
SFR_FUNC void sfr_set_render_target(SfrRenderTarget* target); // NULL resets to default
SFR_FUNC void sfr_set_viewport(i32 x, i32 y, i32 w, i32 h); // restrict drawing to a sub region
SFR_FUNC void sfr_resize(i32 width, i32 height); // resize internals to new dimensions
SFR_FUNC void sfr_reset(void); // reset model matrix to identity
SFR_FUNC void sfr_rotate_x(f32 theta); // rotate model matrix about x by theta radians
SFR_FUNC void sfr_rotate_y(f32 theta); // rotate model matrix about y by theta radians
SFR_FUNC void sfr_rotate_z(f32 theta); // rotate model matrix about z by theta radians
SFR_FUNC void sfr_translate(f32 x, f32 y, f32 z); // translate model matrix by x y z
SFR_FUNC void sfr_scale(f32 x, f32 y, f32 z); // scale model matrix by x y z
SFR_FUNC void sfr_look_at(f32 x, f32 y, f32 z); // set view matrix to look at x y z
// clear all buffers to default states
SFR_FUNC void sfr_clear(u32 clearCol);
SFR_FUNC void sfr_clear_depth(void);
// texture order: front, right, back, left, top, bottom
SFR_FUNC void sfr_skybox(const SfrMaterial* faces[6]);
// triangle drawing functions
SFR_FUNC void sfr_triangle(
f32 ax, f32 ay, f32 az,
f32 bx, f32 by, f32 bz,
f32 cx, f32 cy, f32 cz,
u32 col);
SFR_FUNC void sfr_triangle_mat(
f32 ax, f32 ay, f32 az, f32 au, f32 av,
f32 bx, f32 by, f32 bz, f32 bu, f32 bv,
f32 cx, f32 cy, f32 cz, f32 cu, f32 cv,
const SfrMaterial* mat);
// other drawing functions, if mat is NULL sfrState.baseMat (white 1x1 texture) will be used
SFR_FUNC void sfr_point(f32 worldX, f32 worldY, f32 worldZ, i32 radius, u32 col);
SFR_FUNC void sfr_billboard(const SfrMaterial* mat);
SFR_FUNC void sfr_cube(const SfrMaterial* mat);
SFR_FUNC void sfr_cube_inv(const SfrMaterial* mat);
SFR_FUNC void sfr_sphere(i32 rings, i32 slices, u32 col);
SFR_FUNC void sfr_capsule(sfrvec start, sfrvec end, f32 radius, i32 slices, i32 rings, u32 col);
SFR_FUNC void sfr_cylinder(sfrvec startPos, sfrvec endPos, f32 startRadius, f32 endRadius, i32 sides, u32 col);
SFR_FUNC void sfr_mesh(const SfrMesh* mesh, const SfrMaterial* mat);
SFR_FUNC void sfr_string(const SfrFont* font, const char* s, i32 sLength, u32 col); // not yet implemented
SFR_FUNC void sfr_glyph(const SfrFont* font, u16 id, u32 col); // draw a single character
// drawing functions that use SfrDynamicMesh
// generates batched camera facing hexagonal billboards
SFR_FUNC void sfr_draw_billboards_hex(const SfrBillboard* billboards, i32 count, const SfrMaterial* mat);
// dynamic mesh functions
SFR_FUNC SfrDynamicMesh* sfr_dmesh_request(i32 vertCount);
SFR_FUNC void sfr_dmesh_submit(const SfrDynamicMesh* dmesh, const SfrMaterial* mat);
// static scene functions
SFR_FUNC SfrScene* sfr_scene_create(SfrSceneObject* objects, i32 count);
SFR_FUNC void sfr_scene_apply_lights(const SfrScene* scene);
SFR_FUNC void sfr_scene_draw(const SfrScene* scene);
SFR_FUNC SfrRayHit sfr_scene_raycast(const SfrScene* scene, f32 ox, f32 oy, f32 oz, f32 dx, f32 dy, f32 dz);
SFR_FUNC void sfr_scene_set_transform(SfrScene* scene, sfrvec pos, sfrvec rot, sfrvec scale);
// project the world position specified to screen coordinates
SFR_FUNC u8 sfr_world_to_screen(f32 x, f32 y, f32 z, i32* screenX, i32* screenY);
// update the camera with the new position and view
SFR_FUNC void sfr_set_camera(f32 x, f32 y, f32 z, f32 yaw, f32 pitch, f32 roll);
SFR_FUNC void sfr_set_fov(f32 fovDeg); // update projection matrix with new fov
SFR_FUNC void sfr_set_rendermode(i32 mode); // takes SFR_RENDERMODE_[mode] enum
SFR_FUNC void sfr_set_lightmap(SfrTexture* lightmap, f32 strength); // NULL => disable lightmap, strength = multiplier
SFR_FUNC void sfr_set_shadowmaps(const SfrShadowBind* binds, i32 count); // NULL / 0 => disable shadowmaps
// helpers for adding and removing lights, only enabled when lighting is enabled
SFR_FUNC SfrLight* sfr_light_add_point(f32 posX, f32 posY, f32 posZ, f32 ambient, f32 intensity, f32 attenuation, f32 r, f32 g, f32 b);
SFR_FUNC SfrLight* sfr_light_add_directional(f32 dirX, f32 dirY, f32 dirZ, f32 ambient, f32 intensity, f32 r, f32 g, f32 b);
SFR_FUNC void sfr_light_remove(SfrLight* light);
SFR_FUNC void sfr_light_clear_all(void);
#ifdef SFR_USE_CGLTF
SFR_FUNC void sfr_model_animate(SfrModel* model, i32 animInd, f32 time);
SFR_FUNC void sfr_model_animate_blend(SfrModel* model, i32 animAInd, f32 timeA, i32 animBInd, f32 timeB, f32 blendFactor);
SFR_FUNC SfrModel* sfr_load_gltf(const char* filename, i32 uvChannel, i32 texMaxWidth, i32 texMaxHeight);
SFR_FUNC void sfr_model_draw(const SfrModel* model, sfrmat transform, const SfrMaterial* overrideMat);
SFR_FUNC SfrScene* sfr_scene_from_model(const SfrModel* model);
SFR_FUNC void sfr_release_model(SfrModel** model);
#endif
// material / texture helpers
SFR_FUNC SfrMaterial* sfr_material_request_color(u32 col); // allocates a temporary arena pointer, doesn't need to be freed
SFR_FUNC SfrMaterial* sfr_material_request_clone(const SfrMaterial* baseMat); // ^^^^^
SFR_FUNC void sfr_material_resize_textures(SfrMaterial* mat, i32 newW, i32 newH);
SFR_FUNC SfrTexture* sfr_load_texture_raw(i32 w, i32 h, const u32* pixels);
// lightmap helpers
SFR_FUNC SfrTexture* sfr_lightmap_create(i32 w, i32 h, const u8* fullAtlasRGB);
SFR_FUNC void sfr_lightmap_update_rect(SfrTexture* tex, i32 rectX, i32 rectY, i32 rectW, i32 rectH, const u8* fullAtlasRGB);
// things requiring stdio
SFR_FUNC SfrMesh* sfr_load_mesh(const char* filename); // load an obj file into a struct that sofren can use
SFR_FUNC void sfr_release_mesh(SfrMesh** mesh); // release loaded mesh's memory
// wrappers of sfr_load_texture and sfr_release_texture
SFR_FUNC SfrMaterial* sfr_load_material(const char* albedoPath, const char* metRoughPath);
SFR_FUNC void sfr_release_material(SfrMaterial** mat);
SFR_FUNC SfrTexture* sfr_load_texture(const char* filename); // load a BMP texture
SFR_FUNC void sfr_release_texture(SfrTexture** texture); // release loaded texture's memory
SFR_FUNC SfrFont* sfr_load_font(const char* filename); // load a .srft (sofren font type) font, see 'sfr-fontmaker'
SFR_FUNC void sfr_release_font(SfrFont** font); // release loaded font's memory
// NOTE: the editor to create .qsf files is not public yet
// if the editor is public on GitHub and this comment is still here then I just forgot to remove it
SFR_FUNC SfrScene* sfr_load_scene(const char* filename); // load a .qsf (TrenchBroom to sofren) file
SFR_FUNC void sfr_release_scene(SfrScene** scene, u8 freeObjects); // release a loaded scene's memory
SFR_FUNC void sfr_rand_seed(u32 seed); // seed random number generator
SFR_FUNC u32 sfr_rand_next(void); // Lehmer random number generator
SFR_FUNC i32 sfr_rand_int(i32 min, i32 max); // random int in range [min, max)
SFR_FUNC f32 sfr_rand_flt(f32 min, f32 max); // random f32 in range [min, max)
// threading related functions
#ifdef SFR_MULTITHREADED
static void sfr__process_geometry_jobs(void);
static void sfr__process_raster_jobs(void* tData); // actually struct sfrThreadData* tData
#ifdef _WIN32
static unsigned __stdcall sfr__worker_thread_func(void* arg);
#else
static void* sfr__worker_thread_func(void* arg);
#endif
SFR_FUNC i32 sfr_atomic_add(SfrAtomic32* a, i32 val);
SFR_FUNC i32 sfr_atomic_get(SfrAtomic32* a);
SFR_FUNC void sfr_atomic_set(SfrAtomic32* a, i32 val);
SFR_FUNC i32 sfr_atomic_cas(SfrAtomic32* ptr, i32 oldVal, i32 newVal);
SFR_FUNC i64 sfr_atomic_add64(SfrAtomic64* a, i64 val);
SFR_FUNC i64 sfr_atomic_get64(SfrAtomic64* a);
SFR_FUNC void sfr_atomic_set64(SfrAtomic64* a, i64 val);
SFR_FUNC i64 sfr_atomic_cas64(SfrAtomic64* ptr, i64 oldVal, i64 newVal);
SFR_FUNC void sfr_mutex_init(SfrMutex* m);
SFR_FUNC void sfr_mutex_destroy(SfrMutex* m);
SFR_FUNC void sfr_mutex_lock(SfrMutex* m);
SFR_FUNC void sfr_mutex_unlock(SfrMutex* m);
SFR_FUNC i32 sfr_semaphore_init(SfrSemaphore* s, i32 initialCount);
SFR_FUNC void sfr_semaphore_destroy(SfrSemaphore* s);
SFR_FUNC void sfr_semaphore_wait(SfrSemaphore* s);
SFR_FUNC void sfr_semaphore_post(SfrSemaphore* s, i32 n);
#endif
// SIMD wrappers
#ifndef SFR_NO_SIMD
#if defined(__AVX2__)
#include <immintrin.h>
#define SFR_SIMD_LANES 8
#define SFR_SIMD_LANE_MAX_OFFSET 7.f
#define SFR_SIMD_FULL_LANE_MASK 0xFF
#define SFR_SIMD_FULL_BYTE_MASK -1
#define SFR_SIMD_SET_STEPS() sfrvf_setr(0.f, 1.f, 2.f, 3.f, 4.f, 5.f, 6.f, 7.f)
#define SFR_SIMD_SET_HALF_STEPS() sfrvf_setr(0.5f, 1.5f, 2.5f, 3.5f, 4.5f, 5.5f, 6.5f, 7.5f)
#define SFR_SIMD_SET_INDICES() sfrvi_setr(0, 1, 2, 3, 4, 5, 6, 7)
typedef __m256 vf32; // 8 floats
typedef __m128 vf32s; // 4 floats (for vector math)
typedef __m256i vi32; // 8 ints
#elif defined(__ARM_NEON)
#include <arm_neon.h>
#define SFR_SIMD_LANES 4
#define SFR_SIMD_LANE_MAX_OFFSET 3.f
#define SFR_SIMD_FULL_LANE_MASK 0x0F
#define SFR_SIMD_FULL_BYTE_MASK 0xFFFF
#define SFR_SIMD_SET_STEPS() sfrvf_setr(0.f, 1.f, 2.f, 3.f)
#define SFR_SIMD_SET_HALF_STEPS() sfrvf_setr(0.5f, 1.5f, 2.5f, 3.5f)
#define SFR_SIMD_SET_INDICES() sfrvi_setr(0, 1, 2, 3)
typedef float32x4_t vf32; // 4 floats
typedef float32x4_t vf32s; // 4 floats (same for NEON)
typedef int32x4_t vi32; // 4 ints
#else
#define SFR_NO_SIMD
#ifndef SFR_NO_WARNINGS
#warning "SFR WARNING: SIMD explicitly supported architecture not found, SFR_NO_SIMD auto defined"
#endif
#define SFR_SIMD_LANE_MAX_OFFSET 7.f
#endif
#else
#define SFR_SIMD_LANE_MAX_OFFSET 7.f
#endif
#ifndef SFR_NO_SIMD
enum sfrCmpMode {
SFR_CMP_EQ_OQ = 0x00, // a == b (ordered)
SFR_CMP_UNORD_Q = 0x03, // isnan(a) || isnan(b)
SFR_CMP_LT_OQ = 0x11, // a < b
SFR_CMP_LE_OQ = 0x12, // a <= b
SFR_CMP_GE_OQ = 0x1D, // a >= b
SFR_CMP_GT_OQ = 0x1E, // a > b
};
#define SFR_SHUFFLE(z, y, x, w) (((z) << 6) | ((y) << 4) | ((x) << 2) | (w))
#if defined(__AVX2__)
#define sfrvf_setr(e0, e1, e2, e3, e4, e5, e6, e7) _mm256_setr_ps(e0, e1, e2, e3, e4, e5, e6, e7)
#define sfrvi_setr(e0, e1, e2, e3, e4, e5, e6, e7) _mm256_setr_epi32(e0, e1, e2, e3, e4, e5, e6, e7)
#define sfrvi_gather(src, base, vindex, mask, scale) _mm256_mask_i32gather_epi32((src), (base), (vindex), (mask), (scale))
#define sfrvf_gather(src, base, vindex, mask, scale) _mm256_mask_i32gather_ps((src), (base), (vindex), (mask), (scale))
#define sfrvi_slli(a, imm) _mm256_slli_epi32((a), (imm))
#define sfrvi_srli(a, imm) _mm256_srli_epi32((a), (imm))
#define sfrvf_cmp(a, b, imm) _mm256_cmp_ps((a), (b), (imm))
#define sfrvfs_shuffle(a, b, imm) _mm_shuffle_ps((a), (b), (imm))
#define sfrvfs_dp(a, b, imm) _mm_dp_ps((a), (b), (imm))
#elif defined(__ARM_NEON)
#define sfrvf_setr(e0, e1, e2, e3) (float32x4_t){e0, e1, e2, e3}
#define sfrvi_setr(e0, e1, e2, e3) (int32x4_t){e0, e1, e2, e3}
#define sfrvi_gather(src, base, vindex, mask, scale) ({ \
SFR_ALIGNED(16) int32_t ind[4]; \
SFR_ALIGNED(16) uint32_t m[4]; \
SFR_ALIGNED(16) int32_t out[4]; \
\
vst1q_s32(ind, (vindex)); \
vst1q_u32(m, vreinterpretq_u32_s32(mask)); \
vst1q_s32(out, (src)); \
\
const char* b = (const char*)(base); \
\
if (m[0] & 0x80000000) out[0] = *(const int32_t*)(b + ind[0] * (scale)); \
if (m[1] & 0x80000000) out[1] = *(const int32_t*)(b + ind[1] * (scale)); \
if (m[2] & 0x80000000) out[2] = *(const int32_t*)(b + ind[2] * (scale)); \
if (m[3] & 0x80000000) out[3] = *(const int32_t*)(b + ind[3] * (scale)); \
\
vld1q_s32(out); \
})
#define sfrvf_gather(src, base, vindex, mask, scale) ({ \
SFR_ALIGNED(16) int32_t ind[4]; \
SFR_ALIGNED(16) uint32_t m[4]; \
SFR_ALIGNED(16) float out[4]; \
\
vst1q_s32(ind, (vindex)); \
vst1q_u32(m, vreinterpretq_u32_f32(mask)); \
vst1q_f32(out, (src)); \
\
const char* b = (const char*)(base); \
\
if (m[0] & 0x80000000) out[0] = *(const float*)(b + ind[0] * (scale)); \
if (m[1] & 0x80000000) out[1] = *(const float*)(b + ind[1] * (scale)); \
if (m[2] & 0x80000000) out[2] = *(const float*)(b + ind[2] * (scale)); \
if (m[3] & 0x80000000) out[3] = *(const float*)(b + ind[3] * (scale)); \
\
vld1q_f32(out); \
})
#define sfrvi_slli(a, imm) vshlq_s32((a), vdupq_n_s32((imm)))
#define sfrvi_srli(a, imm) vreinterpretq_s32_u32(vshlq_u32(vreinterpretq_u32_s32(a), vdupq_n_s32(-(imm))))
#define sfrvf_cmp(a, b, imm) \
( (imm) == SFR_CMP_EQ_OQ ? \
vreinterpretq_f32_u32(vceqq_f32((a), (b))) : \
(imm) == SFR_CMP_UNORD_Q ? \
vreinterpretq_f32_u32( \
vorrq_u32( \
vmvnq_u32(vceqq_f32((a), (a))), \
vmvnq_u32(vceqq_f32((b), (b))) \
) \
) : \
(imm) == SFR_CMP_LT_OQ ? \
vreinterpretq_f32_u32(vcltq_f32((a), (b))) : \
(imm) == SFR_CMP_LE_OQ ? \
vreinterpretq_f32_u32(vcleq_f32((a), (b))) : \
(imm) == SFR_CMP_GE_OQ ? \
vreinterpretq_f32_u32(vcgeq_f32((a), (b))) : \
(imm) == SFR_CMP_GT_OQ ? \
vreinterpretq_f32_u32(vcgtq_f32((a), (b))) : \
vdupq_n_f32(0.f) )
#define sfrvfs_shuffle(a, b, imm) \
(float32x4_t){ \
vgetq_lane_f32((a), ((imm) >> 0) & 0x3), \
vgetq_lane_f32((a), ((imm) >> 2) & 0x3), \
vgetq_lane_f32((b), ((imm) >> 4) & 0x3), \
vgetq_lane_f32((b), ((imm) >> 6) & 0x3) \
}
// upper 4 bits of imm control which lanes are multiplied and accumulated,
// lower 4 bits of imm control which lanes the result is broadcasted to
#define sfrvfs_dp(a, b, imm) ({ \
const float32x4_t m = vmulq_f32((a), (b)); \
float sum = 0.f; \
if ((imm) & 0x10) sum += vgetq_lane_f32(m, 0); \
if ((imm) & 0x20) sum += vgetq_lane_f32(m, 1); \
if ((imm) & 0x40) sum += vgetq_lane_f32(m, 2); \
if ((imm) & 0x80) sum += vgetq_lane_f32(m, 3); \
float32x4_t res = vdupq_n_f32(0.f); \
if ((imm) & 0x01) res = vsetq_lane_f32(sum, res, 0); \
if ((imm) & 0x02) res = vsetq_lane_f32(sum, res, 1); \
if ((imm) & 0x04) res = vsetq_lane_f32(sum, res, 2); \
if ((imm) & 0x08) res = vsetq_lane_f32(sum, res, 3); \
res; \
})
#endif
SFR_FUNC vf32 sfrvf_set1(f32 v);
SFR_FUNC vi32 sfrvi_set1(i32 v);
SFR_FUNC vf32 sfrvf_zero(void);
SFR_FUNC vi32 sfrvi_zero(void);
SFR_FUNC vf32 sfrvf_loadu(const f32* mem);
SFR_FUNC void sfrvf_storeu(f32* mem, vf32 a);
SFR_FUNC vi32 sfrvi_loadu(const vi32* mem);
SFR_FUNC void sfrvi_storeu(vi32* mem, vi32 a);
SFR_FUNC vf32s sfrvfs_set1(f32 v);
SFR_FUNC f32 sfrvfs_cvtss_f32(vf32s a);
SFR_FUNC vf32s sfrvfs_add(vf32s a, vf32s b);
SFR_FUNC vf32s sfrvfs_sub(vf32s a, vf32s b);
SFR_FUNC vf32s sfrvfs_mul(vf32s a, vf32s b);
SFR_FUNC vf32s sfrvfs_div(vf32s a, vf32s b);
SFR_FUNC vf32s sfrvfs_rsqrt(vf32s a);
SFR_FUNC vf32s sfrvfs_sqrt_ss(vf32s a);
SFR_FUNC vf32 sfrvf_add(vf32 a, vf32 b);
SFR_FUNC vf32 sfrvf_sub(vf32 a, vf32 b);
SFR_FUNC vf32 sfrvf_mul(vf32 a, vf32 b);
SFR_FUNC f32 sfrvf_cvtss_f32(vf32 a);
SFR_FUNC vf32 sfrvf_fmadd(vf32 a, vf32 b, vf32 c);
SFR_FUNC vf32 sfrvf_fnmadd(vf32 a, vf32 b, vf32 c);
SFR_FUNC vf32 sfrvf_div(vf32 a, vf32 b);
SFR_FUNC vf32 sfrvf_sqrt(vf32 a);
SFR_FUNC vf32 sfrvf_rsqrt(vf32 a);
SFR_FUNC vf32 sfrvf_rcp(vf32 a);
SFR_FUNC vf32 sfrvf_floor(vf32 a);
SFR_FUNC vf32 sfrvf_min(vf32 a, vf32 b);
SFR_FUNC vf32 sfrvf_max(vf32 a, vf32 b);
SFR_FUNC vf32 sfrvf_log2(vf32 x);
SFR_FUNC vf32 sfrvf_exp2(vf32 x);
SFR_FUNC vf32 sfrvf_pow(vf32 x, vf32 y);
SFR_FUNC vi32 sfrvi_add(vi32 a, vi32 b);
SFR_FUNC vi32 sfrvi_sub(vi32 a, vi32 b);
SFR_FUNC vi32 sfrvi_mullo(vi32 a, vi32 b);
SFR_FUNC vi32 sfrvi_min(vi32 a, vi32 b);
SFR_FUNC vi32 sfrvi_max(vi32 a, vi32 b);
SFR_FUNC vi32 sfrvi_and(vi32 a, vi32 b);
SFR_FUNC vi32 sfrvi_or(vi32 a, vi32 b);
SFR_FUNC vi32 sfrvi_cmpeq(vi32 a, vi32 b);
SFR_FUNC vi32 sfrvi_cvtps(vf32 a);
SFR_FUNC i32 sfrvi_movemask_epi8(vi32 a);
SFR_FUNC vf32 sfrvf_cast_from_vi32(vi32 a);
SFR_FUNC vi32 sfrvi_cast_from_vf32(vf32 a);
SFR_FUNC vf32 sfrvf_cvtepi32(vi32 a);
SFR_FUNC vi32 sfrvi_cvttps(vf32 a);
SFR_FUNC vf32 sfrvf_and(vf32 a, vf32 b);
SFR_FUNC vf32 sfrvf_or(vf32 a, vf32 b);
SFR_FUNC vf32 sfrvf_andnot(vf32 a, vf32 b);
SFR_FUNC i32 sfrvf_movemask(vf32 a);
SFR_FUNC void sfrvi_maskstore(int* mem, vi32 mask, vi32 a);
SFR_FUNC vf32 sfrvf_blendv(vf32 a, vf32 b, vf32 mask);
#endif
//================================================
//: PUBLIC MACROS
//================================================
#define SFR_PI (3.14159265358979323846)
#define SFR_EPSILON (1e-8)
#define SFR_ARRLEN(_arr) (sizeof(_arr) / sizeof((_arr)[0]))
#define SFR_MIN(_a, _b) ((_a) < (_b) ? (_a) : (_b))
#define SFR_MAX(_a, _b) ((_a) > (_b) ? (_a) : (_b))
#define SFR_CLAMP(_x, _min, _max) ((_x) < (_min) ? (_min) : ((_x) > (_max) ? (_max) : (_x)))
//================================================
//: IMPLEMENTATION / TYPES
//================================================
#ifdef SFR_IMPL
#ifdef _MSC_VER
#define SFR_ALIGNED(n) __declspec(align(n))
#else
#define SFR_ALIGNED(n) __attribute__((aligned(n)))
#endif
#ifndef SFR_NO_SIMD
typedef union SFR_ALIGNED(16) sfrvec {
vf32s v;
struct { f32 x, y, z, w; };
} sfrvec;
#else
typedef union sfrvec { struct { f32 x, y, z, w; }; } sfrvec;
#endif
typedef union sfrmat {
struct { f32 m[4][4]; };
sfrvec rows[4];
} sfrmat;
typedef struct sfrmesh {
f32* tris; // vertex positions (3 floats per vert)
f32* uvs; // uv coordinates (2 floats per vert)
f32* lmUvs; // lightmap uvs (2 floats per vert)
f32* normals; // vertex normals (3 floats per vert)
f32* tangents; // vertex tangents (4 floats per vert (x, y, z, sign)) currently unused but will be used when normals are implemented
u16* joints; // joint indices (4 inds per vert)
f32* weights; // joint weights (4 floats per vert)
i32 vertCount; // total number of floats in tris array
} SfrMesh;
typedef struct sfrdmesh {
// pointing into sfrDynamicArena
f32* positions;
f32* uvs;
f32* lmUvs;
f32* normals;
f32* tangents;
i32 vertCount;
SfrMesh _mesh; // underlying mesh passed to the rasterizer
} SfrDynamicMesh;
typedef struct sfrtex {
u32* pixels;
i32 w, h;
// only allocated and used for lightmaps to avoid expensive filtering
struct sfrRGB32 { u32 r, g, b; }* quads;
// index 0 is base texture, index 1-n are mipmaps
u32* allPixels[14];
i32 allW[14];
i32 allH[14];
i32 blocksW[14]; // how many 4x4 blocks across
i32 strideShift[14]; // if POT, log2(blocksW) to avoid integer multiplication
i32 mipLevels; // total levels including base
u8 isPot; // power of 2 flag
} SfrTexture;
typedef struct sfrMaterial {
// texture maps
SfrTexture* albedoTex;
SfrTexture* metallicRoughnessTex; // g = roughness, b = metallic
// fallbacks
u32 baseColor;
f32 metallicFactor;
f32 roughnessFactor;
} SfrMaterial;
typedef struct sfrfont {
// xy pairs [x0, y0, x1, y1, x2, ...]
f32 verts[SFR_FONT_GLYPH_MAX][SFR_FONT_VERT_MAX];
} SfrFont;
typedef struct sfrRenderTarget {
i32 width, height;
u32* pixels; // NULL if depth only
f32* depth;
f32 shadowStrength;
u8 ownsMem;
} SfrRenderTarget;
typedef struct sfrShadowBind {
SfrRenderTarget* map;
sfrmat matLightVP; // for directional shadows
sfrvec lightVec; // pos (point) or direction (directional)
f32 radiusSq; // for point lights
u8 isPoint;
} SfrShadowBind;
struct sfrBounds {
f32 minX, minY, minZ;
f32 maxX, maxY, maxZ;
};
// the navigation and entity related things really shouldn't be in sofren
struct sfrNavPolygonNode {
i32 neighbors[6];
i32 edgeCount;
};
struct sfrNavEdge {
i32 v0, v1;
i32 polyIndex, edgeIndex;
};
typedef struct sfrScene {
SfrSceneObject* objects;
i32 count;
SfrTexture** textures;
SfrMaterial** materials;
i32 textureCount;
SfrTexture* globalLightmap;
SfrTexture* globalDirectionmap;
SfrLight* lights;
i32 lightCount;
u32 skyColor;
f32 ambientLight;
sfrvec spawnPos;
u8 hasSpawn;
#ifdef SFR_USE_CGLTF
SfrEntity* entities;
i32 entityCount;
#endif
i32 navVertCount;
i32 navPolyCount;
i32 navMaxVertsPerPoly;
f32* navVerts;
i32* navPolys; // size = navPolyCount * navMaxVertsPerPoly
struct sfrNavPolygonNode* navGraph;
} SfrScene;
struct sfrBvhNode {
f32 minX, minY, minZ;
f32 maxX, maxY, maxZ;
// if count == 0 this is an internal node and 'leftFirst' is the index of the left child
// the right child is always at 'leftFirst + 1'
// if count > 0 this is a leaf node and 'leftFirst' is the index of the first triangle
i32 leftFirst;
i32 count;
};
typedef struct sfrSceneObject {
// all provided when creating the list of objects
SfrMesh* mesh;
sfrvec pos, rot, scale;
SfrMaterial* mat;
// calculated and set in sfr_scene_create
sfrmat _model, _invModel, _normal;
struct sfrBvhNode* _bvhNodes;
i32 _bvhRoot;
i32 _bvhNodeCount;
} SfrSceneObject;
typedef struct sfrRayHit {
u8 hit; // 1 if hit, 0 if not
f32 distance; // distance along the ray to the hit
sfrvec pos; // world space hit position
sfrvec normal; // geometric normal of the triangle hit
f32 u, v; // barycentric coords of the hit
i32 objectInd; // index of the object in the scene->objects array
i32 triangleInd; // index of the triangle within that object's mesh
SfrSceneObject* obj; // pointer to the object hit
} SfrRayHit;
// stateless billboard for batched particle rendering
typedef struct sfrBillboard {
f32 x, y, z;
f32 size;
f32 u, v; // coordinates for the center of the billboard (for palettes or atlases)
} SfrBillboard;
#ifdef SFR_USE_CGLTF
enum sfrAnimPathType {
SFR_ANIM_PATH_TRANSLATION,
SFR_ANIM_PATH_ROTATION,
SFR_ANIM_PATH_SCALE
};
struct sfrAnimSampler {
f32* inputs; // times
f32* outputs; // values
i32 count;
u8 isCubic; // if the sampler requires Hermite interp
u8 isStep;
};
struct sfrAnimChannel {
i32 transformNodeInd; // into model->transforms
i32 samplerInd;
enum sfrAnimPathType path;
};
struct sfrAnimation {
char* name;
f32 duration;
struct sfrAnimSampler* samplers;
i32 samplerCount;
struct sfrAnimChannel* channels;
i32 channelCount;
};
struct sfrTransformNode {
// local transform components
sfrvec localPos;
sfrvec localRot; // quaternion
sfrvec localScale;
// base pose for blending fallbacks
sfrvec basePos;
sfrvec baseRot;
sfrvec baseScale;
i32 parentInd;
u8 isAnimated; // protects static matrices from destruction
// cached matrices
sfrmat localMatrix;
sfrmat worldMatrix;
};
// for evaluating tracks safely
struct sfrBlendState {
sfrvec posA, rotA, scaleA;
sfrvec posB, rotB, scaleB;
u8 maskA, maskB;
};
struct sfrSkin {
i32* jointNodes; // inds mapping into model->transforms
sfrmat* inverseBindMatrices; // inverse bind matrix for each joint
sfrmat* jointMatrices; // per frame computed joint matrices
i32 jointCount;
};
struct sfrModelNode {
SfrMesh* mesh;
SfrMaterial* mat;
i32 transformInd; // link to the scene graph hierarchy
i32 skinInd; // link to the skin array (-1 if not skinned)
};
typedef struct sfrModel {
struct sfrModelNode* nodes; // renderable parts
i32 nodeCount;
struct sfrTransformNode* transforms; // hierarchy logic (1:1 with gltf nodes)
i32 transformCount;
struct sfrAnimation* animations;
i32 animCount;
// pre calculated topological sort of transforms
i32* sortedNodes;
struct sfrSkin* skins;
i32 skinCount;
// resource tracking for cleanup
SfrMesh** _allMeshes;
i32 _meshCount;
SfrMaterial** _allMaterials;
i32 _matCount;
SfrTexture** _allTextures;
i32 _texCount;
} SfrModel;
typedef struct sfrEntity {
char classname[64];
char targetname[64];
char target[64];
char modelPath[256];
sfrvec pos;
sfrvec rot;
sfrvec scale;
i32 userInt; // generic int data
f32 userFloat; // generic float data
SfrModel* model; // left NULL by the parser
} SfrEntity;
#endif // SFR_USE_CGLTF
typedef struct sfrlight {
enum sfrLightType {
SFR_LIGHT_DIRECTIONAL,
SFR_LIGHT_POINT,
} type;
f32 x, y, z; // position in point lights, direction in directional lights
f32 r, g, b; // color [0.0, 1.0]
f32 ambient; // ambient contribution
f32 intensity; // diffuse/specular multiplier
f32 attenuation; // radius/falloff for point lights
} SfrLight;
struct sfrVertexData {
f32 invZ;
u32 n; // packed normal, 10-10-10-2
u32 t; // packed tangent + sign, 10-10-10-2
f32 u, v;
u16 lu, lv; // packed UNORM
};
// helper to track vertex attributes during clipping
struct sfrTexVert {
sfrvec pos; // position in view space
f32 u, v; // texture coords
f32 lu, lv; // lightmap coords
sfrvec normal; // world space normal for lighting
sfrvec tangent; // transformed tangent and handedness sign in w
f32 viewZ; // z in view space for perspective correction
};
struct sfrGeomTri {
const f32* posA;
const f32* uvA;
const f32* lmUvA;
const f32* normA;
const f32* tanA;
const f32* posB;
const f32* uvB;
const f32* lmUvB;
const f32* normB;
const f32* tanB;
const f32* posC;
const f32* uvC;
const f32* lmUvC;
const f32* normC;
const f32* tanC;