-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathcore.c
More file actions
1967 lines (1655 loc) · 74 KB
/
core.c
File metadata and controls
1967 lines (1655 loc) · 74 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
#include "core.h"
#include "deps/ne.h"
#include "deps/sokol_app.h"
#include "deps/sokol_gl.h"
#include "deps/sokol_debugtext.h"
#include "deps/sokol_audio.h"
#include "deps/sokol_log.h"
#include "deps/dds-ktx.h"
#include "deps/tiny_webp.h"
#include "deps/iqm.h"
#include "deps/tinyendian.c"
#include "deps/tmixer.h"
#include <stdio.h>
#include <assert.h>
#include <string.h>
//--ALLOCATORS-------------------------------------------------------
void* core_alloc(Allocator* alloc, size_t size, size_t align) {
if (alloc && alloc->alloc) {
return alloc->alloc(size, align, alloc->udata);
}
return NULL;
}
void core_free(Allocator* alloc, void* ptr) {
if (alloc && alloc->free) {
alloc->free(ptr, alloc->udata);
}
}
//DEFAULTS
static void* _default_alloc(size_t size, size_t align, void* udata) {
(void)udata;
(void)align;
return malloc(size);
}
static void _default_free(void* ptr, void* udata) {
(void)udata;
free(ptr);
}
Allocator default_allocator(void) {
Allocator alloc = {0};
alloc.alloc = _default_alloc;
alloc.free = _default_free;
return alloc;
}
//--IO------------------------------------------------------------------------------------------------------------------
Result load_file(ArenaAlloc *alloc, IoMemory* out, const char *path, bool null_terminate) {
if (!alloc || !out || !path) return RESULT_INVALID_PARAMS;
FILE *file = fopen(path, "rb");
if (!file) {
LOG_ERROR("Failed to open file: %s", path);
return RESULT_FILE_NOT_FOUND;
}
fseek(file, 0, SEEK_END);
long filesize = ftell(file);
fseek(file, 0, SEEK_SET);
out->ptr = arena_alloc(alloc, filesize + 1, alignof(uint8_t));
if (!out->ptr) {
fclose(file);
LOG_ERROR("Failed to allocate IoMemory for file: %s", path);
return RESULT_NOMEM;
}
fread(out->ptr, 1, filesize, file);
fclose(file);
if (null_terminate) {
out->ptr[filesize] = '\0';
}
out->size = filesize;
LOG_INFO("Loaded file: %s (%ld bytes)\n", path, filesize);
return RESULT_SUCCESS;
}
//--CAMERA-------------------------------------------------------------------------------
HMM_Mat4 camera_view_mtx(Camera *cam) {
return HMM_LookAt_RH(cam->position, cam->target, HMM_V3(0.0f, 1.0f, 0.0f));
}
HMM_Mat4 camera_proj_mtx(Camera *cam, int width, int height) {
return HMM_Perspective_RH_ZO(cam->fov * HMM_DegToRad, (float)width / (float)height, cam->nearz, cam->farz);
}
//--IMAGES-------------------------------------------------------------------------------
static sg_pixel_format dds_to_sg_pixelformt(ddsktx_format fmt) {
switch(fmt) {
case DDSKTX_FORMAT_BC1: return SG_PIXELFORMAT_BC1_RGBA; break;
case DDSKTX_FORMAT_BC2: return SG_PIXELFORMAT_BC2_RGBA; break;
case DDSKTX_FORMAT_BC3: return SG_PIXELFORMAT_BC3_RGBA; break;
case DDSKTX_FORMAT_BC4: return SG_PIXELFORMAT_BC4_R; break;
case DDSKTX_FORMAT_BC5: return SG_PIXELFORMAT_BC5_RG; break;
case DDSKTX_FORMAT_BC6H: return SG_PIXELFORMAT_BC6H_RGBF; break;
case DDSKTX_FORMAT_BC7: return SG_PIXELFORMAT_BC7_RGBA; break;
case DDSKTX_FORMAT_A8:
case DDSKTX_FORMAT_R8: return SG_PIXELFORMAT_R8; break;
case DDSKTX_FORMAT_RGBA8:
case DDSKTX_FORMAT_RGBA8S: return SG_PIXELFORMAT_RGBA8; break;
case DDSKTX_FORMAT_RG16: return SG_PIXELFORMAT_RG16; break;
case DDSKTX_FORMAT_RGB8: return SG_PIXELFORMAT_RGBA8; break;
case DDSKTX_FORMAT_R16: return SG_PIXELFORMAT_R16; break;
case DDSKTX_FORMAT_R32F: return SG_PIXELFORMAT_R32F; break;
case DDSKTX_FORMAT_R16F: return SG_PIXELFORMAT_R16F; break;
case DDSKTX_FORMAT_RG16F: return SG_PIXELFORMAT_RG16F; break;
case DDSKTX_FORMAT_RG16S: return SG_PIXELFORMAT_RG16; break;
case DDSKTX_FORMAT_RGBA16F: return SG_PIXELFORMAT_RGBA16F; break;
case DDSKTX_FORMAT_RGBA16: return SG_PIXELFORMAT_RGBA16; break;
case DDSKTX_FORMAT_BGRA8: return SG_PIXELFORMAT_BGRA8; break;
case DDSKTX_FORMAT_RGB10A2: return SG_PIXELFORMAT_RGB10A2; break;
case DDSKTX_FORMAT_RG11B10F:return SG_PIXELFORMAT_RG11B10F; break;
case DDSKTX_FORMAT_RG8: return SG_PIXELFORMAT_RG8; break;
case DDSKTX_FORMAT_RG8S: return SG_PIXELFORMAT_RG8; break;
default: return SG_PIXELFORMAT_NONE;
}
}
sg_image_type dds_to_sg_image_type(unsigned int flags) {
if (flags & DDSKTX_TEXTURE_FLAG_CUBEMAP) {
return SG_IMAGETYPE_CUBE;
}
if(flags & DDSKTX_TEXTURE_FLAG_VOLUME) {
return SG_IMAGETYPE_3D;
}
return SG_IMAGETYPE_2D;
}
Result load_texture(ArenaAlloc* alloc, Texture* out, const IoMemory* mem) {
//webp magic is "RIFF" at [0] and "WEBP" at [8]
if (mem->size >= 12 &&
memcmp(mem->ptr, "RIFF", 4) == 0 &&
memcmp(mem->ptr + 8, "WEBP", 4) == 0) {
int width, height;
unsigned char* rgba = twp_read_from_memory(
(void*)mem->ptr, (int)mem->size, &width, &height, twp_FORMAT_RGBA, 0);
if (!rgba) {
LOG_ERROR("Failed to decode WebP texture\n");
return RESULT_UNKNOWN_ERROR;
}
sg_image_desc desc = {
.width = width,
.height = height,
.pixel_format = SG_PIXELFORMAT_RGBA8,
.data.mip_levels[0] = (sg_range){ rgba, (size_t)(width * height * 4) },
};
out->image = sg_make_image(&desc);
free(rgba);
out->view = sg_make_view(&(sg_view_desc){
.texture = out->image,
});
return RESULT_SUCCESS;
}
ddsktx_texture_info tc = {0};
if (ddsktx_parse(&tc, (const void*)mem->ptr, (int)mem->size, NULL)) {
sg_image_desc desc = {0};
desc.num_mipmaps = tc.num_mips;
desc.num_slices = tc.num_layers;
desc.pixel_format = dds_to_sg_pixelformt(tc.format);
desc.width = tc.width;
desc.height = tc.height;
desc.type = dds_to_sg_image_type(tc.flags);
for (int mip = 0; mip < tc.num_mips; mip++) {
ddsktx_sub_data sub_data;
ddsktx_get_sub(&tc, &sub_data, (const void*)mem->ptr, (int)mem->size, 0, 0, mip);
void* ptr = arena_alloc(alloc, sub_data.size_bytes, 0);
assert(ptr);
memcpy(ptr, sub_data.buff, sub_data.size_bytes);
desc.data.mip_levels[mip] = (sg_range){ptr, sub_data.size_bytes};
}
if (desc.pixel_format != SG_PIXELFORMAT_NONE && !sg_query_pixelformat(desc.pixel_format).sample) {
LOG_ERROR("Pixel format %d not supported by GPU (compressed texture not available?)\n", desc.pixel_format);
return RESULT_UNKNOWN_ERROR;
}
out->image = sg_make_image(&desc);
out->view = sg_make_view(&(sg_view_desc) {
.texture = out->image,
});
return RESULT_SUCCESS;
}
return RESULT_UNKNOWN_ERROR;
}
//--MODEL--------------------------------------------------------------------------------
sg_vertex_layout_state pnt_vtx_layout() {
return (sg_vertex_layout_state) {
.buffers[0].stride = sizeof(VertexPNT),
.attrs = {
[0].format = SG_VERTEXFORMAT_FLOAT3,
[1].format = SG_VERTEXFORMAT_FLOAT3,
[2].format = SG_VERTEXFORMAT_FLOAT2,
},
};
}
sg_vertex_layout_state skinned_vtx_layout() {
return (sg_vertex_layout_state) {
.buffers = {
[0].stride = sizeof(VertexPNT),
[1].stride = sizeof(VertexSkin),
},
.attrs = {
[0] = {.buffer_index = 0, .format = SG_VERTEXFORMAT_FLOAT3},
[1] = {.buffer_index = 0, .format = SG_VERTEXFORMAT_FLOAT3},
[2] = {.buffer_index = 0, .format = SG_VERTEXFORMAT_FLOAT2},
[3] = {.buffer_index = 1, .format = SG_VERTEXFORMAT_UBYTE4},
[4] = {.buffer_index = 1, .format = SG_VERTEXFORMAT_UBYTE4N},
}
};
}
Result load_model(ArenaAlloc *alloc, Model* out, const IoMemory* mem) {
assert(mem && mem->size > sizeof(iqmheader));
iqmheader* header = (iqmheader*)mem->ptr;
{
uint32_t* fields = &header->version;
int n = (sizeof(iqmheader) - sizeof(header->magic)) / sizeof(uint32_t);
for (int i = 0; i < n; i++) fields[i] = tole32(fields[i]);
}
if (header->num_vertexarrays) {
uint32_t* p = (uint32_t*)(mem->ptr + header->ofs_vertexarrays);
for (unsigned int i = 0; i < header->num_vertexarrays * sizeof(iqmvertexarray) / sizeof(uint32_t); i++) p[i] = tole32(p[i]);
}
if (header->num_triangles) {
uint32_t* p = (uint32_t*)(mem->ptr + header->ofs_triangles);
for (unsigned int i = 0; i < header->num_triangles * sizeof(iqmtriangle) / sizeof(uint32_t); i++) p[i] = tole32(p[i]);
}
if (header->num_meshes) {
uint32_t* p = (uint32_t*)(mem->ptr + header->ofs_meshes);
for (unsigned int i = 0; i < header->num_meshes * sizeof(iqmmesh) / sizeof(uint32_t); i++) p[i] = tole32(p[i]);
}
if (header->num_joints) {
uint32_t* p = (uint32_t*)(mem->ptr + header->ofs_joints);
for (unsigned int i = 0; i < header->num_joints * sizeof(iqmjoint) / sizeof(uint32_t); i++) p[i] = tole32(p[i]);
}
if (header->ofs_bounds) {
uint32_t* p = (uint32_t*)(mem->ptr + header->ofs_bounds);
for (unsigned int i = 0; i < header->num_frames * sizeof(iqmbounds) / sizeof(uint32_t); i++) p[i] = tole32(p[i]);
}
iqmmesh* imesh = (iqmmesh*)(mem->ptr + header->ofs_meshes);
iqmtriangle* tri = (iqmtriangle*)(mem->ptr + header->ofs_triangles);
iqmvertexarray* va = (iqmvertexarray*)(mem->ptr + header->ofs_vertexarrays);
memset(out, 0, sizeof(Model));
out->meshes_count = header->num_meshes > 4 ? 4 : (int)header->num_meshes;
uint32_t total_verts = header->num_vertexes;
VertexPNT* vertices = arena_alloc(alloc, sizeof(VertexPNT) * total_verts, alignof(VertexPNT));
VertexSkin* skin = arena_alloc(alloc, sizeof(VertexSkin) * total_verts, alignof(VertexSkin));
if (!vertices || !skin) return RESULT_NOMEM;
memset(vertices, 0, sizeof(VertexPNT) * total_verts);
memset(skin, 0, sizeof(VertexSkin) * total_verts);
bool has_skin = false;
for (unsigned int i = 0; i < header->num_vertexarrays; i++) {
switch (va[i].type) {
case IQM_POSITION: {
assert(va[i].format == IQM_FLOAT && va[i].size == 3);
float* positions = (float*)(mem->ptr + va[i].offset);
{ uint32_t* p = (uint32_t*)positions; for (unsigned int k = 0; k < 3 * total_verts; k++) p[k] = tole32(p[k]); }
for (unsigned int v = 0; v < total_verts; v++) {
vertices[v].pos = HMM_V3(positions[v*3+0], positions[v*3+1], positions[v*3+2]);
}
} break;
case IQM_NORMAL: {
assert(va[i].format == IQM_FLOAT && va[i].size == 3);
float* normals = (float*)(mem->ptr + va[i].offset);
{ uint32_t* p = (uint32_t*)normals; for (unsigned int k = 0; k < 3 * total_verts; k++) p[k] = tole32(p[k]); }
for (unsigned int v = 0; v < total_verts; v++) {
vertices[v].nrm = HMM_V3(normals[v*3+0], normals[v*3+1], normals[v*3+2]);
}
} break;
case IQM_TEXCOORD: {
assert(va[i].format == IQM_FLOAT && va[i].size == 2);
float* uvs = (float*)(mem->ptr + va[i].offset);
{ uint32_t* p = (uint32_t*)uvs; for (unsigned int k = 0; k < 2 * total_verts; k++) p[k] = tole32(p[k]); }
for (unsigned int v = 0; v < total_verts; v++) {
vertices[v].uv = HMM_V2(uvs[v*2+0], uvs[v*2+1]);
}
} break;
case IQM_BLENDINDEXES: {
assert(va[i].format == IQM_UBYTE && va[i].size == 4);
has_skin = true;
uint8_t* bi = (uint8_t*)(mem->ptr + va[i].offset);
for (unsigned int v = 0; v < total_verts; v++) {
skin[v].indices[0] = bi[v*4+0]; skin[v].indices[1] = bi[v*4+1];
skin[v].indices[2] = bi[v*4+2]; skin[v].indices[3] = bi[v*4+3];
}
} break;
case IQM_BLENDWEIGHTS: {
assert(va[i].format == IQM_UBYTE && va[i].size == 4);
uint8_t* bw = (uint8_t*)(mem->ptr + va[i].offset);
for (unsigned int v = 0; v < total_verts; v++) {
skin[v].weights[0] = bw[v*4+0]; skin[v].weights[1] = bw[v*4+1];
skin[v].weights[2] = bw[v*4+2]; skin[v].weights[3] = bw[v*4+3];
}
} break;
}
}
if (header->ofs_bounds) {
iqmbounds* bounds = (iqmbounds*)(mem->ptr + header->ofs_bounds);
memcpy(out->bounds.min, bounds->bbmin, sizeof(float) * 3);
memcpy(out->bounds.max, bounds->bbmax, sizeof(float) * 3);
out->bounds.radius_xy = bounds->xyradius;
out->bounds.radius = bounds->radius;
}
for (int m = 0; m < out->meshes_count; m++) {
uint32_t num_indices = imesh[m].num_triangles * 3;
uint32_t* mesh_indices = arena_alloc(alloc, sizeof(uint32_t) * num_indices, alignof(uint32_t));
if (!mesh_indices) return RESULT_NOMEM;
int tcounter = 0;
for (unsigned int i = imesh[m].first_triangle;
i < imesh[m].first_triangle + imesh[m].num_triangles; i++) {
mesh_indices[tcounter++] = tri[i].vertex[0] - imesh[m].first_vertex;
mesh_indices[tcounter++] = tri[i].vertex[1] - imesh[m].first_vertex;
mesh_indices[tcounter++] = tri[i].vertex[2] - imesh[m].first_vertex;
}
VertexPNT* mesh_verts = &vertices[imesh[m].first_vertex];
VertexSkin* mesh_skin = &skin[imesh[m].first_vertex];
out->meshes[m].vbufs[0] = sg_make_buffer(&(sg_buffer_desc){
.data = (sg_range){ mesh_verts, sizeof(VertexPNT) * imesh[m].num_vertexes },
.label = "iqm vertex buffer"
});
if (has_skin) {
out->meshes[m].vbufs[1] = sg_make_buffer(&(sg_buffer_desc){
.data = (sg_range){ mesh_skin, sizeof(VertexSkin) * imesh[m].num_vertexes },
.label = "iqm skin buffer"
});
}
out->meshes[m].ibuf = sg_make_buffer(&(sg_buffer_desc){
.usage.index_buffer = true,
.data = (sg_range){ mesh_indices, sizeof(uint32_t) * num_indices },
.label = "iqm index buffer"
});
out->meshes[m].first_element = 0;
out->meshes[m].element_count = num_indices;
}
LOG_INFO("Loaded IQM model (%d meshes, %u verts)\n", out->meshes_count, total_verts);
return RESULT_SUCCESS;
}
void release_model(Model* model) {
for (int m = 0; m < model->meshes_count; m++) {
for (int i = 0; i < MESH_MAX_VBUFS; ++i) {
sg_destroy_buffer(model->meshes[m].vbufs[i]);
}
sg_destroy_buffer(model->meshes[m].ibuf);
}
memset(model, 0, sizeof(Model));
}
//--ANIMATION----------------------------------------------------------------------------
static HMM_Mat4 HMM_TRS(HMM_Vec3 pos, HMM_Quat rotation, HMM_Vec3 scale) {
HMM_Mat4 T = HMM_Translate(pos);
HMM_Mat4 R = HMM_QToM4(rotation);
HMM_Mat4 S = HMM_Scale(scale);
return HMM_MulM4(HMM_MulM4(T, R), S);
}
Result load_anims(ArenaAlloc* allocator, AnimSet* out, const IoMemory* mem) {
assert(mem && mem->size > sizeof(iqmheader));
iqmheader* hdr = (iqmheader*)mem->ptr;
if (!hdr->num_joints || !hdr->num_poses) {
LOG_ERROR("IQM data does not contain skeleton!\n");
return RESULT_INVALID_PARAMS;
}
iqmjoint* joints = (iqmjoint*)&mem->ptr[hdr->ofs_joints];
out->num_joints = hdr->num_joints;
out->joint_parents = arena_alloc(allocator, sizeof(int) * hdr->num_joints, alignof(int));
if (!out->joint_parents) return RESULT_NOMEM;
for (int i = 0; i < (int)hdr->num_joints; i++) {
out->joint_parents[i] = joints[i].parent;
}
//validate poses and joints
if ((int)hdr->num_poses != out->num_joints) {
LOG_ERROR("IQM poses (%u) don't match joints (%d)!\n", hdr->num_poses, out->num_joints);
return RESULT_INVALID_PARAMS;
}
const char* str = hdr->ofs_text ? (char*)&mem->ptr[hdr->ofs_text] : "";
iqmanim* iqm_anims = (iqmanim*)&mem->ptr[hdr->ofs_anims];
iqmpose* poses = (iqmpose*)&mem->ptr[hdr->ofs_poses];
{
uint32_t* p = (uint32_t*)poses;
for (unsigned int i = 0; i < hdr->num_poses * sizeof(iqmpose) / sizeof(uint32_t); i++) p[i] = tole32(p[i]);
}
{
uint32_t* p = (uint32_t*)iqm_anims;
for (unsigned int i = 0; i < hdr->num_anims * sizeof(iqmanim) / sizeof(uint32_t); i++) p[i] = tole32(p[i]);
}
//allocate persistent data first
out->num_anims = hdr->num_anims;
out->num_frames = hdr->num_frames;
out->anims = arena_alloc(allocator, sizeof(AnimInfo) * hdr->num_anims, alignof(AnimInfo));
out->frames = arena_alloc(allocator, sizeof(HMM_Mat4) * hdr->num_frames * hdr->num_poses, alignof(HMM_Mat4));
if (!out->anims || !out->frames) return RESULT_NOMEM;
//temp baseframe/inverse_baseframe allocated last so we can pop it after pre-baking
HMM_Mat4* temp = arena_alloc(allocator, sizeof(HMM_Mat4) * hdr->num_joints * 2, alignof(HMM_Mat4));
if (!temp) return RESULT_NOMEM;
HMM_Mat4* baseframe = temp;
HMM_Mat4* inverse_baseframe = temp + hdr->num_joints;
for (int i = 0; i < (int)hdr->num_joints; i++) {
iqmjoint* j = &joints[i];
HMM_Quat rot = HMM_NormQ(HMM_Q(j->rotate[0], j->rotate[1], j->rotate[2], j->rotate[3]));
HMM_Vec3 pos = HMM_V3(j->translate[0], j->translate[1], j->translate[2]);
HMM_Vec3 scl = HMM_V3(j->scale[0], j->scale[1], j->scale[2]);
baseframe[i] = HMM_TRS(pos, rot, scl);
inverse_baseframe[i] = HMM_InvGeneralM4(baseframe[i]);
if (j->parent >= 0) {
baseframe[i] = HMM_MulM4(baseframe[j->parent], baseframe[i]);
inverse_baseframe[i] = HMM_MulM4(inverse_baseframe[i], inverse_baseframe[j->parent]);
}
}
uint16_t* framedata = (uint16_t*)&mem->ptr[hdr->ofs_frames];
{
unsigned int n = hdr->num_frames * hdr->num_framechannels;
for (unsigned int i = 0; i < n; i++) framedata[i] = tole16(framedata[i]);
}
//just pre-bake the whole shabang
for (int i = 0; i < (int)hdr->num_frames; i++) {
for (int j = 0; j < (int)hdr->num_poses; j++) {
iqmpose* p = &poses[j];
HMM_Quat rotate;
HMM_Vec3 translate, scale;
translate.X = p->channeloffset[0]; if (p->mask & 0x01) translate.X += *framedata++ * p->channelscale[0];
translate.Y = p->channeloffset[1]; if (p->mask & 0x02) translate.Y += *framedata++ * p->channelscale[1];
translate.Z = p->channeloffset[2]; if (p->mask & 0x04) translate.Z += *framedata++ * p->channelscale[2];
rotate.X = p->channeloffset[3]; if (p->mask & 0x08) rotate.X += *framedata++ * p->channelscale[3];
rotate.Y = p->channeloffset[4]; if (p->mask & 0x10) rotate.Y += *framedata++ * p->channelscale[4];
rotate.Z = p->channeloffset[5]; if (p->mask & 0x20) rotate.Z += *framedata++ * p->channelscale[5];
rotate.W = p->channeloffset[6]; if (p->mask & 0x40) rotate.W += *framedata++ * p->channelscale[6];
scale.X = p->channeloffset[7]; if (p->mask & 0x80) scale.X += *framedata++ * p->channelscale[7];
scale.Y = p->channeloffset[8]; if (p->mask & 0x100) scale.Y += *framedata++ * p->channelscale[8];
scale.Z = p->channeloffset[9]; if (p->mask & 0x200) scale.Z += *framedata++ * p->channelscale[9];
rotate = HMM_NormQ(rotate);
HMM_Mat4 m = HMM_TRS(translate, rotate, scale);
if (p->parent >= 0)
out->frames[i * hdr->num_poses + j] = HMM_MulM4(HMM_MulM4(baseframe[p->parent], m), inverse_baseframe[j]);
else
out->frames[i * hdr->num_poses + j] = HMM_MulM4(m, inverse_baseframe[j]);
}
}
//temporary baseframe/inverse_baseframe
arena_pop(allocator);
//copy metadata
for (int i = 0; i < (int)hdr->num_anims; i++) {
iqmanim* a = &iqm_anims[i];
out->anims[i].first_frame = a->first_frame;
out->anims[i].num_frames = a->num_frames;
out->anims[i].framerate = a->framerate;
strncpy(out->anims[i].name, &str[a->name], MAX_NAME_LEN - 1);
out->anims[i].name[MAX_NAME_LEN - 1] = '\0';
LOG_INFO("Loaded anim: %s (frames %u-%u, fps: %.1f)\n",
out->anims[i].name,
out->anims[i].first_frame,
out->anims[i].first_frame + out->anims[i].num_frames - 1,
out->anims[i].framerate
);
}
return RESULT_SUCCESS;
}
void update_anim_state(AnimState* state, AnimSet* set, float dt) {
if (!(state->flags & ANIM_FLAG_PLAY) || state->anim < 0 || state->anim >= set->num_anims) return;
AnimInfo* anim = &set->anims[state->anim];
state->current_frame += anim->framerate * dt;
if (state->flags & ANIM_FLAG_LOOP) {
float loop_point = (float)(anim->num_frames - 1);
if (state->current_frame >= loop_point) {
state->current_frame = fmodf(state->current_frame, loop_point);
}
} else {
if (state->current_frame >= (float)(anim->num_frames - 1)) {
state->current_frame = (float)(anim->num_frames - 1);
state->flags &= ~ANIM_FLAG_PLAY;
}
}
}
void play_anim(u_skeleton_t* out, AnimSet* set, AnimState* state) {
if (!out || !set || !state || state->anim < 0 || state->anim >= set->num_anims) return;
if (set->num_frames <= 0) return;
AnimInfo* anim = &set->anims[state->anim];
float curframe = state->current_frame;
int frame1 = (int)floor(curframe);
int frame2 = frame1 + 1;
float frameoffset = curframe - frame1;
if (state->flags & ANIM_FLAG_LOOP) {
frame1 = frame1 % (int)anim->num_frames;
frame2 = frame2 % (int)anim->num_frames;
} else {
if (frame1 >= (int)anim->num_frames) frame1 = anim->num_frames - 1;
if (frame2 >= (int)anim->num_frames) frame2 = anim->num_frames - 1;
}
int global_frame1 = anim->first_frame + frame1;
int global_frame2 = anim->first_frame + frame2;
HMM_Mat4* mat1 = &set->frames[global_frame1 * set->num_joints];
HMM_Mat4* mat2 = &set->frames[global_frame2 * set->num_joints];
for (int i = 0; i < set->num_joints; i++) {
HMM_Mat4 first = HMM_MulM4F(mat1[i], 1.0f - frameoffset);
HMM_Mat4 second = HMM_MulM4F(mat2[i], frameoffset);
HMM_Mat4 mat = HMM_AddM4(first, second);
if (set->joint_parents[i] >= 0) {
out->bones[i] = HMM_MulM4(out->bones[set->joint_parents[i]], mat);
} else {
out->bones[i] = mat;
}
}
}
void blend_anims(u_skeleton_t* out_a, const u_skeleton_t* out_b, float weight, int num_joints) {
if (!out_a || !out_b) return;
for (int i = 0; i < num_joints; i++) {
HMM_Mat4 a = HMM_MulM4F(out_a->bones[i], 1.0f - weight);
HMM_Mat4 b = HMM_MulM4F(out_b->bones[i], weight);
out_a->bones[i] = HMM_AddM4(a, b);
}
}
//--GFX----------------------------------------------------------------------------------
RenderContext* gfx_new_context(Allocator* alloc, const RenderContextDesc* desc) {
RenderContext* ctx = core_alloc(alloc, sizeof(RenderContext), alignof(RenderContext));
if (!ctx) {
LOG_ERROR("Failed to allocate RenderContext\n");
return NULL;
}
memset(ctx, 0, sizeof(RenderContext));
//init anims
hp_Handle* anim_dense = core_alloc(alloc, desc->max_anim_sets * sizeof(hp_Handle), alignof(hp_Handle));
int* anim_sparse = core_alloc(alloc, desc->max_anim_sets * sizeof(int), alignof(int));
if (!anim_dense || !anim_sparse || !hp_init(&ctx->anims.pool, anim_dense, anim_sparse, desc->max_anim_sets)) {
LOG_ERROR("Failed to initialize animation pool\n");
core_free(alloc, ctx);
return NULL;
}
ctx->anims.data = core_alloc(alloc, desc->max_anim_sets * sizeof(AnimSet), alignof(AnimSet));
if (!ctx->anims.data) {
LOG_ERROR("Failed to allocate animation data\n");
return NULL;
}
void* anim_arena_buffer = core_alloc(alloc, desc->max_anim_data, 1);
if (!anim_arena_buffer || !arena_init(&ctx->anims.alloc, anim_arena_buffer, desc->max_anim_data)) {
LOG_ERROR("Failed to initialize animation arena\n");
return NULL;
}
//init meshes
hp_Handle* mesh_dense = core_alloc(alloc, desc->max_meshes * sizeof(hp_Handle), alignof(hp_Handle));
int* mesh_sparse = core_alloc(alloc, desc->max_meshes * sizeof(int), alignof(int));
if (!mesh_dense || !mesh_sparse || !hp_init(&ctx->meshes.pool, mesh_dense, mesh_sparse, desc->max_meshes)) {
LOG_ERROR("Failed to initialize mesh pool\n");
return NULL;
}
ctx->meshes.data = core_alloc(alloc, desc->max_meshes * sizeof(Model), alignof(Model));
if (!ctx->meshes.data) {
LOG_ERROR("Failed to allocate mesh data\n");
return NULL;
}
//init textures
hp_Handle* texture_dense = core_alloc(alloc, desc->max_textures * sizeof(hp_Handle), alignof(hp_Handle));
int* texture_sparse = core_alloc(alloc, desc->max_textures * sizeof(int), alignof(int));
if (!texture_dense || !texture_sparse || !hp_init(&ctx->textures.pool, texture_dense, texture_sparse, desc->max_textures)) {
LOG_ERROR("Failed to initialize texture pool\n");
return NULL;
}
ctx->textures.data = core_alloc(alloc, desc->max_textures * sizeof(Texture), alignof(Texture));
if (!ctx->textures.data) {
LOG_ERROR("Failed to allocate texture data\n");
return NULL;
}
ctx->offscreen.width = desc->width;
ctx->offscreen.height = desc->height;
sg_setup(&(sg_desc){
.environment = desc->environment,
.logger.func = slog_func,
});
if (sg_isvalid() == false) {
LOG_ERROR("Failed to initialize sokol_gfx!\n");
return NULL;
}
sgl_setup(&(sgl_desc_t){
.sample_count = 1,
.logger.func = slog_func,
.color_format = SG_PIXELFORMAT_RGBA8,
.depth_format = SG_PIXELFORMAT_DEPTH,
});
ctx->offscreen.physics_pip = sgl_make_pipeline(&(sg_pipeline_desc) {
.depth = {
.write_enabled = true,
.compare = SG_COMPAREFUNC_LESS_EQUAL,
},
});
sdtx_setup(&(sdtx_desc_t) {
.context = {
.canvas_width = (float)ctx->offscreen.width,
.canvas_height = (float)ctx->offscreen.height,
.depth_format = SG_PIXELFORMAT_DEPTH,
.color_format = SG_PIXELFORMAT_RGBA8
},
.logger.func = slog_func,
.fonts[0] = sdtx_font_c64(),
});
ctx->display.action = (sg_pass_action){
.colors[0] = {
.load_action = SG_LOADACTION_CLEAR,
.clear_value = { 0.0f, 0.0f, 0.0f, 1.0f },
}
};
const float dsp_vertices[] = {
1.0f, 1.0f, 1.0f, 1.0f,
1.0f, -1.0f, 1.0f, 0.0f,
-1.0f, -1.0f, 0.0f, 0.0f,
-1.0f, 1.0f, 0.0f, 1.0f
};
const uint16_t dsp_indices[] = {
0, 1, 3,
1, 2, 3
};
ctx->offscreen.color_img = sg_make_image(&(sg_image_desc){
.usage.color_attachment = true,
.width = ctx->offscreen.width,
.height = ctx->offscreen.height,
.pixel_format = SG_PIXELFORMAT_RGBA8,
.sample_count = 1,
});
ctx->offscreen.depth_img = sg_make_image(&(sg_image_desc){
.usage.depth_stencil_attachment = true,
.width = ctx->offscreen.width,
.height = ctx->offscreen.height,
.pixel_format = SG_PIXELFORMAT_DEPTH,
.sample_count = 1,
});
ctx->offscreen.pass = (sg_pass){
.attachments = {
.colors[0] = sg_make_view(&(sg_view_desc){
.color_attachment = ctx->offscreen.color_img,
}),
.depth_stencil = sg_make_view(&(sg_view_desc){
.depth_stencil_attachment = ctx->offscreen.depth_img,
}),
},
.action.colors[0] = {
.load_action = SG_LOADACTION_CLEAR,
.clear_value = { 0.1f, 0.1f, 0.1f, 1.0f },
}
};
ctx->display.rect = (sg_bindings) {
.vertex_buffers[0] = sg_make_buffer(&(sg_buffer_desc){
.data = SG_RANGE(dsp_vertices),
.usage.immutable = true,
}),
.index_buffer = sg_make_buffer(&(sg_buffer_desc){
.data = SG_RANGE(dsp_indices),
.usage.immutable = true,
.usage.index_buffer = true,
}),
.views[0] = sg_make_view(&(sg_view_desc){
.texture.image = ctx->offscreen.color_img,
}),
.views[1] = sg_make_view(&(sg_view_desc){
.texture.image = ctx->offscreen.depth_img,
}),
.samplers[0] = sg_make_sampler(&(sg_sampler_desc){
.mag_filter = SG_FILTER_NEAREST,
.min_filter = SG_FILTER_NEAREST,
.wrap_u = SG_WRAP_CLAMP_TO_EDGE,
.wrap_v = SG_WRAP_CLAMP_TO_EDGE,
}),
.samplers[1] = sg_make_sampler(&(sg_sampler_desc){
.wrap_u = SG_WRAP_CLAMP_TO_EDGE,
.wrap_v = SG_WRAP_CLAMP_TO_EDGE,
}),
};
ctx->display.pip = sg_make_pipeline(&(sg_pipeline_desc){
.layout = {
.attrs = {
[ATTR_display_shd_position].format = SG_VERTEXFORMAT_FLOAT2,
[ATTR_display_shd_uv].format = SG_VERTEXFORMAT_FLOAT2,
}
},
.shader = sg_make_shader(display_shd_shader_desc(sg_query_backend())),
.index_type = SG_INDEXTYPE_UINT16,
.primitive_type = SG_PRIMITIVETYPE_TRIANGLES,
.label = "display_pip",
});
ctx->offscreen.pip[GFX_PIP_DEFAULT] = sg_make_pipeline(&(sg_pipeline_desc) {
.layout = pnt_vtx_layout(),
.shader = sg_make_shader(tex_lit_shader_desc(sg_query_backend())),
.index_type = SG_INDEXTYPE_UINT32,
.depth = {
.pixel_format = SG_PIXELFORMAT_DEPTH,
.compare = SG_COMPAREFUNC_LESS_EQUAL,
.write_enabled = true,
},
.colors[0].pixel_format = SG_PIXELFORMAT_RGBA8,
});
ctx->offscreen.pip[GFX_PIP_SKINNED] = sg_make_pipeline(&(sg_pipeline_desc) {
.layout = skinned_vtx_layout(),
.shader = sg_make_shader(tex_lit_skinned_shader_desc(sg_query_backend())),
.index_type = SG_INDEXTYPE_UINT32,
.depth = {
.pixel_format = SG_PIXELFORMAT_DEPTH,
.compare = SG_COMPAREFUNC_LESS_EQUAL,
.write_enabled = true,
},
.colors[0].pixel_format = SG_PIXELFORMAT_RGBA8,
});
//CUBEMAP
ctx->offscreen.pip[GFX_PIP_CUBEMAP] = sg_make_pipeline(&(sg_pipeline_desc) {
.layout.attrs = {
[ATTR_cubemap_pos] = {.format = SG_VERTEXFORMAT_FLOAT3, .buffer_index = 0},
},
.shader = sg_make_shader(cubemap_shader_desc((sg_query_backend()))),
.index_type = SG_INDEXTYPE_UINT16,
.depth = {
.pixel_format = SG_PIXELFORMAT_DEPTH,
.compare = SG_COMPAREFUNC_LESS_EQUAL,
.write_enabled = true,
},
.colors[0].pixel_format = SG_PIXELFORMAT_RGBA8,
});
ctx->offscreen.light = (u_dir_light_t) {
.ambient = {0.2f, 0.2f, 0.2f, 1.0f},
.diffuse = {1.0f, 1.0f, 1.0f, 1.0f},
.direction = {0.25f, -0.75f, -0.25f},
};
ctx->offscreen.default_sampler = sg_make_sampler(&(sg_sampler_desc){
.wrap_u = SG_WRAP_CLAMP_TO_BORDER,
.wrap_v = SG_WRAP_CLAMP_TO_BORDER,
});
LOG_INFO("Graphics initialized.\n");
return ctx;
}
void gfx_render(RenderContext* ctx, Scene* scene, Camera* cam, sg_swapchain swapchain, float dt) {
u_skeleton_t u_skel = {0};
u_skeleton_t u_skel_prev = {0};
AnimState* anim_states = scene->anim_states;
AnimState* prev_anim_states = scene->prev_anim_states;
float* blend_weights = scene->anim_blend_weights;
u_vs_params_t u_vs = {
.view = camera_view_mtx(cam),
.proj = camera_proj_mtx(cam, ctx->offscreen.width, ctx->offscreen.height),
};
//offscreen pass
sg_begin_pass(&ctx->offscreen.pass);
if(ctx->offscreen.cubemap.vbuf.id != SG_INVALID_ID) {
sg_apply_pipeline(ctx->offscreen.pip[GFX_PIP_CUBEMAP]);
sg_bindings binds = {0};
binds.vertex_buffers[0] = ctx->offscreen.cubemap.vbuf;
binds.index_buffer = ctx->offscreen.cubemap.ibuf;
binds.views[0] = ctx->offscreen.cubemap.tex.view;
binds.samplers[0] = ctx->offscreen.cubemap.smp;
sg_apply_bindings(&binds);
u_vs.model = HMM_Scale(HMM_V3(500, 500, 500));
sg_apply_uniforms(UB_u_vs_params, &SG_RANGE(u_vs));
sg_draw(0, 36, 1);
}
sg_apply_pipeline(ctx->offscreen.pip[GFX_PIP_SKINNED]);
sg_apply_uniforms(UB_u_dir_light, &SG_RANGE(ctx->offscreen.light));
for (int i = 0; i < scene->pool.count; i++) {
Entity handle = { .id = hp_handle_at(&scene->pool, i) };
int idx = hp_index(handle.id);
uint16_t model_flags = scene->model_flags[idx];
uint16_t anim_flags = scene->anim_flags[idx];
if ((model_flags & ENTITY_HAS_MODEL) && (anim_flags & ENTITY_HAS_ANIM)) {
if (scene->models[idx].id == 0) continue;
int mdl_idx = hp_index(scene->models[idx].id);
Model* model = &ctx->meshes.data[mdl_idx];
u_vs.model = entity_mtx(scene, handle);
int anim_idx = hp_index(scene->anims[idx].id);
AnimSet* set = &ctx->anims.data[anim_idx];
//advance and sample current animation
update_anim_state(&anim_states[idx], set, dt);
memset(&u_skel, 0, sizeof(u_skel));
play_anim(&u_skel, set, &anim_states[idx]);
//blend with previous animation if transitioning
if (blend_weights[idx] < 1.0f) {
update_anim_state(&prev_anim_states[idx], set, dt);
memset(&u_skel_prev, 0, sizeof(u_skel_prev));
play_anim(&u_skel_prev, set, &prev_anim_states[idx]);
blend_anims(&u_skel, &u_skel_prev, 1.0f - blend_weights[idx], set->num_joints);
blend_weights[idx] += dt / ANIM_BLEND_DURATION;
if (blend_weights[idx] > 1.0f) blend_weights[idx] = 1.0f;
}
sg_apply_uniforms(UB_u_skeleton, &SG_RANGE(u_skel));
sg_apply_uniforms(UB_u_vs_params, &SG_RANGE(u_vs));
for (int j = 0; j < model->meshes_count; j++) {
Mesh* mesh = &model->meshes[j];
if (mesh->vbufs[0].id == SG_INVALID_ID || mesh->vbufs[1].id == SG_INVALID_ID) continue;
sg_bindings binds = {0};
memcpy(&binds.vertex_buffers, mesh->vbufs, MESH_MAX_VBUFS * sizeof(sg_buffer));
binds.index_buffer = mesh->ibuf;
binds.samplers[0] = ctx->offscreen.default_sampler;
binds.views[0] = ctx->textures.data[hp_index(scene->textures[idx].tex[j].id)].view;
sg_apply_bindings(&binds);
sg_draw(0, mesh->element_count, 1);
}
}
}
sg_apply_pipeline(ctx->offscreen.pip[GFX_PIP_DEFAULT]);
sg_apply_uniforms(UB_u_dir_light, &SG_RANGE(ctx->offscreen.light));
for (int i = 0; i < scene->pool.count; i++) {
Entity handle = { .id = hp_handle_at(&scene->pool, i) };
int idx = hp_index(handle.id);
uint16_t model_flags = scene->model_flags[idx];
uint16_t anim_flags = scene->anim_flags[idx];
if ((model_flags & ENTITY_HAS_MODEL) && !(anim_flags & ENTITY_HAS_ANIM)) {
if (scene->models[idx].id == 0) continue;
int mdl_idx = hp_index(scene->models[idx].id);
Model* model = &ctx->meshes.data[mdl_idx];
u_vs.model = entity_mtx(scene, handle);
sg_apply_uniforms(UB_u_vs_params, &SG_RANGE(u_vs));
for (int j = 0; j < model->meshes_count; j++) {
Mesh* mesh = &model->meshes[j];
if (mesh->vbufs[0].id == SG_INVALID_ID) continue;
sg_bindings binds = {0};
memcpy(&binds.vertex_buffers, mesh->vbufs, MESH_MAX_VBUFS * sizeof(sg_buffer));
binds.index_buffer = mesh->ibuf;
binds.samplers[0] = ctx->offscreen.default_sampler;
binds.views[0] = ctx->textures.data[hp_index(scene->textures[idx].tex[0].id)].view;
sg_apply_bindings(&binds);
sg_draw(0, mesh->element_count, 1);
}
}
}
//(debug visualization)
sgl_defaults();
sgl_viewport(0, 0, ctx->offscreen.width, ctx->offscreen.height, true);
sgl_matrix_mode_projection();
sgl_load_matrix((const float*)&u_vs.proj);
sgl_matrix_mode_modelview();
sgl_load_matrix((const float*)&u_vs.view);
sgl_load_pipeline(ctx->offscreen.physics_pip);
//draw mouse cursor point when unlocked
/*
sgl_load_default_pipeline();
sgl_matrix_mode_projection();
sgl_load_identity();
sgl_matrix_mode_modelview();
sgl_load_identity();
sgl_point_size(4.0f);
sgl_c3b(200, 125, 0);
sgl_begin_points();
//if (!sapp_mouse_locked()) {
float ndc_x = (2.0f * ctx->display.mouse_pos.X / swapchain.width) - 1.0f;
float ndc_y = 1.0f - (2.0f * ctx->display.mouse_pos.Y / swapchain.height);
sgl_v2f(ndc_x, ndc_y);
//}
sgl_end();
*/
sgl_draw();
sdtx_draw();
sg_end_pass();
//display pass
sg_begin_pass(&(sg_pass) {
.swapchain = swapchain,
.action.colors[0] = {
.clear_value = { 0.0f, 0.0f, 0.0f, 1.0f },
.load_action = SG_LOADACTION_CLEAR,
}
});
sg_apply_pipeline(ctx->display.pip);
display_vs_params_t vs_params = {
.resolution = HMM_V2((float)swapchain.width, (float)swapchain.height),
.offscreen_size = HMM_V2((float)ctx->offscreen.width, (float)ctx->offscreen.height),
};
sg_apply_uniforms(UB_display_vs_params, &SG_RANGE(vs_params));
sg_apply_bindings(&ctx->display.rect);
sg_draw(0, 6, 1);
sg_end_pass();
sg_commit();
}
void gfx_reset(RenderContext* ctx) {
for (int i = 0; i < ctx->meshes.pool.count; i++) {
hp_Handle hnd = hp_handle_at(&ctx->meshes.pool, i);
release_model(&ctx->meshes.data[hp_index(hnd)]);
}
hp_reset(&ctx->meshes.pool);
for (int i = 0; i < ctx->textures.pool.count; i++) {
hp_Handle hnd = hp_handle_at(&ctx->textures.pool, i);
int idx = hp_index(hnd);