-
Notifications
You must be signed in to change notification settings - Fork 29
Expand file tree
/
Copy pathskinned_mesh.c
More file actions
2756 lines (2383 loc) · 90.5 KB
/
skinned_mesh.c
File metadata and controls
2756 lines (2383 loc) · 90.5 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 "meshes.h"
#include "webgpu/imgui_overlay.h"
#include "webgpu/wgpu_common.h"
#include <cglm/cglm.h>
#define SOKOL_FETCH_IMPL
#include <sokol_fetch.h>
#define SOKOL_LOG_IMPL
#include <sokol_log.h>
#define SOKOL_TIME_IMPL
#include <sokol_time.h>
#include <cgltf.h>
#include "core/image_loader.h"
#ifdef __GNUC__
#pragma GCC diagnostic push
#pragma GCC diagnostic ignored "-Wpedantic"
#define CIMGUI_DEFINE_ENUMS_AND_STRUCTS
#endif
#include <cimgui.h>
#ifdef __GNUC__
#pragma GCC diagnostic pop
#endif
/* -------------------------------------------------------------------------- *
* WebGPU Example - Skinned Mesh
*
* This example demonstrates basic GLTF loading and mesh skinning, ported from
* https://webgl2fundamentals.org/webgl/lessons/webgl-skinning.html. Mesh data,
* per vertex attributes, and skin inverseBindMatrices are taken from the JSON
* parsed from the binary output of the .glb file. Animations are generated
* programmatically, with animated joint matrices updated and passed to shaders
* per frame via uniform buffers.
*
* Ref:
* https://github.com/webgpu/webgpu-samples/tree/main/src/sample/skinnedMesh
* https://webgl2fundamentals.org/webgl/lessons/webgl-skinning.html
* -------------------------------------------------------------------------- */
/* -------------------------------------------------------------------------- *
* WGSL Shaders
* -------------------------------------------------------------------------- */
static const char* gltf_vertex_shader_wgsl;
static const char* gltf_fragment_shader_wgsl;
static const char* grid_vertex_shader_wgsl;
static const char* grid_fragment_shader_wgsl;
static const char* skybox_vertex_shader_wgsl;
static const char* skybox_fragment_shader_wgsl;
/* -------------------------------------------------------------------------- *
* Constants
* -------------------------------------------------------------------------- */
#define MAX_JOINTS (64)
#define MAT4X4_BYTES (64)
/* Skybox constants */
#define SKYBOX_FACES (6)
#define SKYBOX_FACE_WIDTH (2048)
#define SKYBOX_FACE_HEIGHT (2048)
#define SKYBOX_FACE_BYTES (SKYBOX_FACE_WIDTH * SKYBOX_FACE_HEIGHT * 4)
/* Render modes */
typedef enum render_mode_t {
RENDER_MODE_NORMAL = 0,
RENDER_MODE_JOINTS = 1,
RENDER_MODE_WEIGHTS = 2,
} render_mode_t;
/* Skin modes */
typedef enum skin_mode_t {
SKIN_MODE_ON = 0,
SKIN_MODE_OFF = 1,
} skin_mode_t;
/* Object types */
typedef enum object_type_t {
OBJECT_TYPE_WHALE = 0,
OBJECT_TYPE_SKINNED_GRID = 1,
} object_type_t;
/* -------------------------------------------------------------------------- *
* GLTF Structures
* -------------------------------------------------------------------------- */
/* GLTF Vertex */
typedef struct gltf_vertex_t {
vec3 position;
vec3 normal;
vec2 texcoord;
uint8_t joints[4];
vec4 weights;
} gltf_vertex_t;
/* GLTF Primitive */
typedef struct gltf_primitive_t {
wgpu_buffer_t vertex_buffer;
wgpu_buffer_t index_buffer;
uint32_t vertex_count;
uint32_t index_count;
WGPURenderPipeline pipeline;
} gltf_primitive_t;
/* GLTF Node */
typedef struct gltf_node_t {
char name[64];
int32_t parent_index;
vec3 translation;
versor rotation;
vec3 scale;
mat4 local_matrix;
mat4 world_matrix;
int32_t mesh_index;
int32_t skin_index;
WGPUBuffer uniform_buffer;
WGPUBindGroup bind_group;
} gltf_node_t;
/* GLTF Skin */
typedef struct gltf_skin_t {
char name[64];
uint32_t* joints;
uint32_t joint_count;
mat4* inverse_bind_matrices;
WGPUBuffer joint_matrices_buffer;
WGPUBuffer inverse_bind_matrices_buffer;
WGPUBindGroup bind_group;
} gltf_skin_t;
/* GLTF Mesh */
typedef struct gltf_mesh_t {
char name[64];
gltf_primitive_t* primitives;
uint32_t primitive_count;
} gltf_mesh_t;
/* GLTF Scene */
typedef struct gltf_scene_t {
gltf_node_t* nodes;
uint32_t node_count;
gltf_mesh_t* meshes;
uint32_t mesh_count;
gltf_skin_t* skins;
uint32_t skin_count;
uint8_t* glb_buffer;
size_t glb_buffer_size;
cgltf_data* gltf_data;
} gltf_scene_t;
/* -------------------------------------------------------------------------- *
* Grid Structures
* -------------------------------------------------------------------------- */
/* Grid buffers */
typedef struct grid_buffers_t {
wgpu_buffer_t positions;
wgpu_buffer_t joints;
wgpu_buffer_t weights;
wgpu_buffer_t indices;
uint32_t index_count;
} grid_buffers_t;
/* Bone collection */
typedef struct bone_collection_t {
mat4 transforms[5];
mat4 bind_poses[5];
mat4 bind_poses_inv[5];
uint32_t bone_count;
} bone_collection_t;
/* -------------------------------------------------------------------------- *
* State Structure
* -------------------------------------------------------------------------- */
static struct {
/* Scene and objects */
gltf_scene_t whale_scene;
grid_buffers_t grid_buffers;
bone_collection_t grid_bones;
/* Uniforms */
struct {
mat4 projection;
mat4 view;
mat4 model;
} camera_matrices;
struct {
WGPUBuffer buffer;
WGPUBindGroup bind_group;
} camera_uniform;
struct {
uint32_t render_mode;
uint32_t skin_mode;
WGPUBuffer buffer;
WGPUBindGroup bind_group;
} general_uniforms;
/* Pipeline resources */
WGPUBindGroupLayout camera_bind_group_layout;
WGPUBindGroupLayout general_bind_group_layout;
WGPUBindGroupLayout node_bind_group_layout;
WGPUBindGroupLayout skin_bind_group_layout;
WGPURenderPipeline grid_pipeline;
/* Skybox resources */
struct {
WGPUTexture texture;
WGPUTextureView view;
WGPUSampler sampler;
WGPUBuffer vertex_buffer;
WGPUBuffer uniform_buffer;
WGPUBindGroup bind_group;
WGPUBindGroupLayout bind_group_layout;
WGPURenderPipeline pipeline;
uint8_t face_pixels[SKYBOX_FACES][SKYBOX_FACE_BYTES];
int load_count;
bool is_dirty;
bool initialized;
} skybox;
/* Render pass */
struct {
WGPUTexture texture;
WGPUTextureView view;
} depth_texture;
WGPURenderPassColorAttachment color_attachment;
WGPURenderPassDepthStencilAttachment depth_stencil_attachment;
WGPURenderPassDescriptor render_pass_descriptor;
/* GUI settings */
struct {
float camera_x;
float camera_y;
float camera_z;
float object_scale;
float angle;
float speed;
object_type_t object_type;
render_mode_t render_mode;
skin_mode_t skin_mode;
bool skybox_enabled;
} settings;
/* Animation */
mat4 orig_matrices[MAX_JOINTS];
bool orig_matrices_initialized[MAX_JOINTS];
/* Original TRS values for animation */
vec3 orig_translations[MAX_JOINTS];
versor orig_rotations[MAX_JOINTS];
vec3 orig_scales[MAX_JOINTS];
/* File loading */
bool glb_loaded;
bool initialized;
/* Frame timing */
uint64_t last_frame_time;
} state = {
.color_attachment = {
.loadOp = WGPULoadOp_Clear,
.storeOp = WGPUStoreOp_Store,
.clearValue = {0.3, 0.3, 0.3, 1.0},
.depthSlice = WGPU_DEPTH_SLICE_UNDEFINED,
},
.depth_stencil_attachment = {
.depthLoadOp = WGPULoadOp_Clear,
.depthStoreOp = WGPUStoreOp_Store,
.depthClearValue = 1.0f,
},
.render_pass_descriptor = {
.colorAttachmentCount = 1,
.colorAttachments = &state.color_attachment,
.depthStencilAttachment = &state.depth_stencil_attachment,
},
.settings = {
.camera_x = 0.0f,
.camera_y = -5.1f,
.camera_z = -14.6f,
.object_scale = 1.0f,
.angle = 0.2f,
.speed = 50.0f,
.object_type = OBJECT_TYPE_WHALE,
.render_mode = RENDER_MODE_NORMAL,
.skin_mode = SKIN_MODE_ON,
.skybox_enabled = true,
},
.glb_loaded = false,
.initialized = false,
};
/* -------------------------------------------------------------------------- *
* Helper Functions
* -------------------------------------------------------------------------- */
static void anim_skinned_grid(mat4* bone_transforms, float angle)
{
/* Match TypeScript:
* mat4.rotateZ(m, angle, boneTransforms[0]); // boneTransforms[0] =
* rotateZ(m) mat4.translate(boneTransforms[0], vec3.create(4, 0, 0), m); //
* m = translate(boneTransforms[0]) mat4.rotateZ(m, angle, boneTransforms[1]);
* // boneTransforms[1] = rotateZ(m) mat4.translate(boneTransforms[1],
* vec3.create(4, 0, 0), m); // m = translate(boneTransforms[1])
* mat4.rotateZ(m, angle, boneTransforms[2]); // boneTransforms[2] =
* rotateZ(m)
*/
mat4 m;
glm_mat4_identity(m);
/* Bone 0: rotate m, store in bone_transforms[0] */
glm_rotate_z(m, angle, bone_transforms[0]);
/* Then translate bone_transforms[0], store in m for next bone */
glm_mat4_copy(bone_transforms[0], m);
glm_translate(m, (vec3){4.0f, 0.0f, 0.0f});
/* Bone 1: rotate m, store in bone_transforms[1] */
glm_rotate_z(m, angle, bone_transforms[1]);
/* Then translate bone_transforms[1], store in m for next bone */
glm_mat4_copy(bone_transforms[1], m);
glm_translate(m, (vec3){4.0f, 0.0f, 0.0f});
/* Bone 2: just rotate m, store in bone_transforms[2] */
glm_rotate_z(m, angle, bone_transforms[2]);
}
static void create_bone_collection(bone_collection_t* collection,
uint32_t num_bones)
{
collection->bone_count = num_bones;
/* Initialize transforms and bind poses */
for (uint32_t i = 0; i < num_bones; ++i) {
glm_mat4_identity(collection->transforms[i]);
glm_mat4_identity(collection->bind_poses[i]);
}
/* Get initial bind pose positions */
anim_skinned_grid(collection->bind_poses, 0.0f);
/* Calculate inverse bind poses */
for (uint32_t i = 0; i < num_bones; ++i) {
glm_mat4_inv(collection->bind_poses[i], collection->bind_poses_inv[i]);
}
}
static void update_node_matrix(gltf_node_t* node)
{
/* Compose local matrix from TRS
* TypeScript does: T * R * S order
* - Start with identity
* - Scale it
* - Rotate the result
* - Translate the result
*/
mat4 scale_mat, rotation_mat;
/* 1. Create scale matrix */
glm_mat4_identity(scale_mat);
glm_scale(scale_mat, node->scale);
/* 2. Create rotation matrix from quaternion */
glm_quat_mat4(node->rotation, rotation_mat);
/* 3. Multiply: rotation * scale */
glm_mat4_mul(rotation_mat, scale_mat, node->local_matrix);
/* 4. Translate the result */
glm_translate(node->local_matrix, node->translation);
}
static void update_world_matrix(gltf_scene_t* scene, gltf_node_t* node,
mat4 parent_matrix)
{
/* Update world matrix */
if (parent_matrix) {
glm_mat4_mul(parent_matrix, node->local_matrix, node->world_matrix);
}
else {
glm_mat4_copy(node->local_matrix, node->world_matrix);
}
/* Find child nodes and update their world matrices */
for (uint32_t i = 0; i < scene->node_count; ++i) {
if (scene->nodes[i].parent_index == (int32_t)i) {
continue; /* Skip self */
}
if (scene->nodes[i].parent_index >= 0) {
gltf_node_t* parent = &scene->nodes[scene->nodes[i].parent_index];
if (parent == node) {
update_world_matrix(scene, &scene->nodes[i], node->world_matrix);
}
}
}
}
static void anim_whale_skin(wgpu_context_t* wgpu_context, gltf_skin_t* skin,
float angle)
{
UNUSED_VAR(wgpu_context);
for (uint32_t i = 0; i < skin->joint_count; ++i) {
uint32_t joint_index = skin->joints[i];
/* Bounds check */
if (joint_index >= state.whale_scene.node_count) {
continue;
}
gltf_node_t* node = &state.whale_scene.nodes[joint_index];
mat4* orig_matrix = &state.orig_matrices[joint_index];
bool* orig_matrix_init = &state.orig_matrices_initialized[joint_index];
/* Store original TRS values on first run */
if (!*orig_matrix_init) {
glm_mat4_copy(node->local_matrix, *orig_matrix);
glm_vec3_copy(node->translation, state.orig_translations[joint_index]);
glm_quat_copy(node->rotation, state.orig_rotations[joint_index]);
glm_vec3_copy(node->scale, state.orig_scales[joint_index]);
*orig_matrix_init = true;
}
/* TypeScript approach: rotate the original matrix, then extract TRS
* MATCHING TypeScript exactly:
* - mat4.getTranslation(m) -> translation from column 3
* - mat4.getScaling(m) -> scale from column lengths
* - quat.fromMat(m) -> quaternion from matrix (NOT normalized!) */
mat4 m;
glm_mat4_copy(*orig_matrix, m);
/* Apply rotations based on joint index */
if (joint_index == 1 || joint_index == 0) {
glm_rotate_y(m, -angle, m);
}
else if (joint_index == 3 || joint_index == 4) {
glm_rotate_x(m, (joint_index == 3) ? angle : -angle, m);
}
else {
glm_rotate_z(m, angle, m);
}
/* Extract translation from column 3 (matches mat4.getTranslation) */
node->translation[0] = m[3][0];
node->translation[1] = m[3][1];
node->translation[2] = m[3][2];
/* Extract scale from column lengths (matches mat4.getScaling) */
node->scale[0] = glm_vec3_norm((vec3){m[0][0], m[0][1], m[0][2]});
node->scale[1] = glm_vec3_norm((vec3){m[1][0], m[1][1], m[1][2]});
node->scale[2] = glm_vec3_norm((vec3){m[2][0], m[2][1], m[2][2]});
/* Extract quaternion from matrix
* Note: TypeScript uses quat.fromMat(m) which works on the scaled matrix
* We need to normalize the matrix columns before extracting quaternion */
mat4 normalized;
glm_mat4_copy(m, normalized);
/* Normalize the rotation part (first 3 columns) by dividing by scale */
if (node->scale[0] > 0.0001f) {
normalized[0][0] /= node->scale[0];
normalized[0][1] /= node->scale[0];
normalized[0][2] /= node->scale[0];
}
if (node->scale[1] > 0.0001f) {
normalized[1][0] /= node->scale[1];
normalized[1][1] /= node->scale[1];
normalized[1][2] /= node->scale[1];
}
if (node->scale[2] > 0.0001f) {
normalized[2][0] /= node->scale[2];
normalized[2][1] /= node->scale[2];
normalized[2][2] /= node->scale[2];
}
/* Now extract quaternion from normalized rotation matrix */
glm_mat4_quat(normalized, node->rotation);
/* Rebuild local matrix from TRS */
update_node_matrix(node);
}
}
static void update_skin_buffers(wgpu_context_t* wgpu_context, gltf_skin_t* skin,
uint32_t skinned_mesh_node_index)
{
mat4 joint_matrices[MAX_JOINTS];
/* Get the inverse of the skinned mesh node's world matrix */
mat4 global_world_inverse;
glm_mat4_inv(state.whale_scene.nodes[skinned_mesh_node_index].world_matrix,
global_world_inverse);
/* Calculate joint matrices: globalWorldInverse * joint.worldMatrix */
for (uint32_t i = 0; i < skin->joint_count; ++i) {
uint32_t joint_index = skin->joints[i];
/* Bounds check */
if (joint_index >= state.whale_scene.node_count) {
glm_mat4_identity(joint_matrices[i]);
continue;
}
gltf_node_t* node = &state.whale_scene.nodes[joint_index];
/* joint_matrix = globalWorldInverse * joint.worldMatrix */
glm_mat4_mul(global_world_inverse, node->world_matrix, joint_matrices[i]);
}
/* Upload to GPU */
wgpuQueueWriteBuffer(wgpu_context->queue, skin->joint_matrices_buffer, 0,
joint_matrices, skin->joint_count * sizeof(mat4));
}
/* -------------------------------------------------------------------------- *
* GLTF Loading Functions
* -------------------------------------------------------------------------- */
static void parse_gltf_nodes(gltf_scene_t* scene, cgltf_data* data)
{
scene->node_count = (uint32_t)data->nodes_count;
scene->nodes = (gltf_node_t*)calloc(scene->node_count, sizeof(gltf_node_t));
for (uint32_t i = 0; i < scene->node_count; ++i) {
cgltf_node* src_node = &data->nodes[i];
gltf_node_t* node = &scene->nodes[i];
/* Copy name */
if (src_node->name) {
strncpy(node->name, src_node->name, sizeof(node->name) - 1);
}
/* Find parent index */
node->parent_index = -1;
if (src_node->parent) {
for (uint32_t j = 0; j < scene->node_count; ++j) {
if (&data->nodes[j] == src_node->parent) {
node->parent_index = (int32_t)j;
break;
}
}
}
/* Get transform */
if (src_node->has_matrix) {
/* Matrix provided directly */
memcpy(node->local_matrix, src_node->matrix, sizeof(mat4));
vec4 translation_v4;
mat4 rotation_mat;
glm_decompose(node->local_matrix, translation_v4, rotation_mat,
node->scale);
glm_vec3_copy(translation_v4, node->translation);
glm_mat4_quat(rotation_mat, node->rotation);
}
else {
/* Use TRS */
if (src_node->has_translation) {
memcpy(node->translation, src_node->translation, sizeof(vec3));
}
else {
glm_vec3_zero(node->translation);
}
if (src_node->has_rotation) {
memcpy(node->rotation, src_node->rotation, sizeof(versor));
}
else {
glm_quat_identity(node->rotation);
}
if (src_node->has_scale) {
memcpy(node->scale, src_node->scale, sizeof(vec3));
}
else {
glm_vec3_one(node->scale);
}
update_node_matrix(node);
}
/* Mesh index */
node->mesh_index = -1;
if (src_node->mesh) {
for (size_t j = 0; j < data->meshes_count; ++j) {
if (&data->meshes[j] == src_node->mesh) {
node->mesh_index = (int32_t)j;
break;
}
}
}
/* Skin index */
node->skin_index = -1;
if (src_node->skin) {
for (size_t j = 0; j < data->skins_count; ++j) {
if (&data->skins[j] == src_node->skin) {
node->skin_index = (int32_t)j;
break;
}
}
}
/* Initialize world matrix */
glm_mat4_identity(node->world_matrix);
}
}
static void parse_gltf_skins(wgpu_context_t* wgpu_context, gltf_scene_t* scene,
cgltf_data* data)
{
scene->skin_count = (uint32_t)data->skins_count;
if (scene->skin_count == 0) {
return;
}
scene->skins = (gltf_skin_t*)calloc(scene->skin_count, sizeof(gltf_skin_t));
for (uint32_t i = 0; i < scene->skin_count; ++i) {
cgltf_skin* src_skin = &data->skins[i];
gltf_skin_t* skin = &scene->skins[i];
/* Copy name */
if (src_skin->name) {
strncpy(skin->name, src_skin->name, sizeof(skin->name) - 1);
}
/* Parse joints */
skin->joint_count = (uint32_t)src_skin->joints_count;
skin->joints = (uint32_t*)calloc(skin->joint_count, sizeof(uint32_t));
for (uint32_t j = 0; j < skin->joint_count; ++j) {
cgltf_node* joint_node = src_skin->joints[j];
/* Find node index */
for (uint32_t k = 0; k < scene->node_count; ++k) {
if (&data->nodes[k] == joint_node) {
skin->joints[j] = k;
break;
}
}
}
/* Parse inverse bind matrices */
skin->inverse_bind_matrices
= (mat4*)calloc(skin->joint_count, sizeof(mat4));
if (src_skin->inverse_bind_matrices) {
cgltf_accessor* accessor = src_skin->inverse_bind_matrices;
const uint8_t* data_ptr
= (const uint8_t*)cgltf_buffer_view_data(accessor->buffer_view);
data_ptr += accessor->offset;
for (uint32_t j = 0; j < skin->joint_count; ++j) {
memcpy(skin->inverse_bind_matrices[j], data_ptr + j * sizeof(mat4),
sizeof(mat4));
}
}
/* Create GPU buffers */
skin->joint_matrices_buffer = wgpuDeviceCreateBuffer(
wgpu_context->device,
&(WGPUBufferDescriptor){
.label = STRVIEW("Joint matrices buffer"),
.usage = WGPUBufferUsage_Storage | WGPUBufferUsage_CopyDst,
.size = skin->joint_count * sizeof(mat4),
.mappedAtCreation = false,
});
skin->inverse_bind_matrices_buffer = wgpuDeviceCreateBuffer(
wgpu_context->device,
&(WGPUBufferDescriptor){
.label = STRVIEW("Inverse bind matrices buffer"),
.usage = WGPUBufferUsage_Storage | WGPUBufferUsage_CopyDst,
.size = skin->joint_count * sizeof(mat4),
.mappedAtCreation = false,
});
/* Upload inverse bind matrices */
wgpuQueueWriteBuffer(
wgpu_context->queue, skin->inverse_bind_matrices_buffer, 0,
skin->inverse_bind_matrices, skin->joint_count * sizeof(mat4));
}
}
static void parse_gltf_meshes(wgpu_context_t* wgpu_context, gltf_scene_t* scene,
cgltf_data* data)
{
scene->mesh_count = (uint32_t)data->meshes_count;
if (scene->mesh_count == 0) {
return;
}
scene->meshes = (gltf_mesh_t*)calloc(scene->mesh_count, sizeof(gltf_mesh_t));
for (uint32_t i = 0; i < scene->mesh_count; ++i) {
cgltf_mesh* src_mesh = &data->meshes[i];
gltf_mesh_t* mesh = &scene->meshes[i];
/* Copy name */
if (src_mesh->name) {
strncpy(mesh->name, src_mesh->name, sizeof(mesh->name) - 1);
}
/* Parse primitives */
mesh->primitive_count = (uint32_t)src_mesh->primitives_count;
mesh->primitives = (gltf_primitive_t*)calloc(mesh->primitive_count,
sizeof(gltf_primitive_t));
for (uint32_t j = 0; j < mesh->primitive_count; ++j) {
cgltf_primitive* src_prim = &src_mesh->primitives[j];
gltf_primitive_t* prim = &mesh->primitives[j];
/* Find accessors */
cgltf_accessor* position_accessor = NULL;
cgltf_accessor* normal_accessor = NULL;
cgltf_accessor* texcoord_accessor = NULL;
cgltf_accessor* joints_accessor = NULL;
cgltf_accessor* weights_accessor = NULL;
for (size_t k = 0; k < src_prim->attributes_count; ++k) {
cgltf_attribute* attr = &src_prim->attributes[k];
if (attr->type == cgltf_attribute_type_position) {
position_accessor = attr->data;
}
else if (attr->type == cgltf_attribute_type_normal) {
normal_accessor = attr->data;
}
else if (attr->type == cgltf_attribute_type_texcoord) {
texcoord_accessor = attr->data;
}
else if (attr->type == cgltf_attribute_type_joints) {
joints_accessor = attr->data;
}
else if (attr->type == cgltf_attribute_type_weights) {
weights_accessor = attr->data;
}
}
if (!position_accessor) {
continue; /* Skip if no positions */
}
prim->vertex_count = (uint32_t)position_accessor->count;
/* Build vertex buffer */
gltf_vertex_t* vertices
= (gltf_vertex_t*)calloc(prim->vertex_count, sizeof(gltf_vertex_t));
for (uint32_t v = 0; v < prim->vertex_count; ++v) {
/* Position */
cgltf_accessor_read_float(position_accessor, v, vertices[v].position,
3);
/* Normal */
if (normal_accessor) {
cgltf_accessor_read_float(normal_accessor, v, vertices[v].normal, 3);
}
/* Texcoord */
if (texcoord_accessor) {
cgltf_accessor_read_float(texcoord_accessor, v, vertices[v].texcoord,
2);
}
/* Joints */
if (joints_accessor) {
uint32_t joints[4] = {0};
cgltf_accessor_read_uint(joints_accessor, v, joints, 4);
vertices[v].joints[0] = (uint8_t)joints[0];
vertices[v].joints[1] = (uint8_t)joints[1];
vertices[v].joints[2] = (uint8_t)joints[2];
vertices[v].joints[3] = (uint8_t)joints[3];
}
/* Weights */
if (weights_accessor) {
cgltf_accessor_read_float(weights_accessor, v, vertices[v].weights,
4);
}
}
/* Create vertex buffer */
prim->vertex_buffer = wgpu_create_buffer(
wgpu_context,
&(wgpu_buffer_desc_t){
.label = "GLTF vertex buffer",
.usage = WGPUBufferUsage_CopyDst | WGPUBufferUsage_Vertex,
.size = prim->vertex_count * sizeof(gltf_vertex_t),
.initial.data = vertices,
});
free(vertices);
/* Parse indices */
if (src_prim->indices) {
cgltf_accessor* index_accessor = src_prim->indices;
prim->index_count = (uint32_t)index_accessor->count;
uint16_t* indices
= (uint16_t*)calloc(prim->index_count, sizeof(uint16_t));
for (uint32_t idx = 0; idx < prim->index_count; ++idx) {
uint32_t index_value = 0;
cgltf_accessor_read_uint(index_accessor, idx, &index_value, 1);
indices[idx] = (uint16_t)index_value;
}
/* Create index buffer */
prim->index_buffer = wgpu_create_buffer(
wgpu_context,
&(wgpu_buffer_desc_t){
.label = "GLTF index buffer",
.usage = WGPUBufferUsage_CopyDst | WGPUBufferUsage_Index,
.size = prim->index_count * sizeof(uint16_t),
.initial.data = indices,
});
free(indices);
}
}
}
}
static void load_gltf_scene(wgpu_context_t* wgpu_context, gltf_scene_t* scene,
const uint8_t* buffer, size_t size)
{
/* Parse GLTF */
cgltf_options options = {0};
cgltf_result result = cgltf_parse(&options, buffer, size, &scene->gltf_data);
if (result != cgltf_result_success) {
fprintf(stderr, "Failed to parse GLTF: %d\n", result);
return;
}
/* Load buffers - for GLB files, buffers are already embedded */
result = cgltf_load_buffers(&options, scene->gltf_data, NULL);
if (result != cgltf_result_success) {
fprintf(stderr, "Failed to load GLTF buffers: %d\n", result);
cgltf_free(scene->gltf_data);
scene->gltf_data = NULL;
return;
}
/* Parse data */
parse_gltf_nodes(scene, scene->gltf_data);
parse_gltf_skins(wgpu_context, scene, scene->gltf_data);
parse_gltf_meshes(wgpu_context, scene, scene->gltf_data);
}
/* Callback for asynchronously loading the GLB file */
static void glb_fetch_callback(const sfetch_response_t* response)
{
if (!response->fetched) {
fprintf(stderr, "Failed to load GLB file, error: %d\n",
response->error_code);
return;
}
/* Store buffer */
state.whale_scene.glb_buffer_size = response->data.size;
state.whale_scene.glb_buffer
= (uint8_t*)malloc(state.whale_scene.glb_buffer_size);
memcpy(state.whale_scene.glb_buffer, response->data.ptr,
state.whale_scene.glb_buffer_size);
state.glb_loaded = true;
}
/* -------------------------------------------------------------------------- *
* Grid Functions
* -------------------------------------------------------------------------- */
/* clang-format off */
/* Grid vertex data - 2D grid matching TypeScript gridData.ts */
static const float grid_vertices[] = {
/* B0 */ 0.0f, 1.0f, 0.0f, -1.0f,
/* CONNECTOR */ 2.0f, 1.0f, 2.0f, -1.0f,
/* B1 */ 4.0f, 1.0f, 4.0f, -1.0f,
/* CONNECTOR */ 6.0f, 1.0f, 6.0f, -1.0f,
/* B2 */ 8.0f, 1.0f, 8.0f, -1.0f,
/* CONNECTOR */ 10.0f, 1.0f, 10.0f, -1.0f,
/* B3 */ 12.0f, 1.0f, 12.0f, -1.0f,
};
/* Joint indices (4 per vertex) */
static const uint32_t grid_joints[] = {
0, 0, 0, 0, /* Vertex 0 */ 0, 0, 0, 0, /* Vertex 1 */
0, 1, 0, 0, /* Vertex 2 */ 0, 1, 0, 0, /* Vertex 3 */
1, 0, 0, 0, /* Vertex 4 */ 1, 0, 0, 0, /* Vertex 5 */
1, 2, 0, 0, /* Vertex 6 */ 1, 2, 0, 0, /* Vertex 7 */
2, 0, 0, 0, /* Vertex 8 */ 2, 0, 0, 0, /* Vertex 9 */
1, 2, 3, 0, /* Vertex 10 */ 1, 2, 3, 0, /* Vertex 11 */
2, 3, 0, 0, /* Vertex 12 */ 2, 3, 0, 0, /* Vertex 13 */
};
/* Weights (4 per vertex) */
static const float grid_weights[] = {
1.0f, 0.0f, 0.0f, 0.0f, /* Vertex 0 */ 1.0f, 0.0f, 0.0f, 0.0f, /* Vertex 1 */
0.5f, 0.5f, 0.0f, 0.0f, /* Vertex 2 */ 0.5f, 0.5f, 0.0f, 0.0f, /* Vertex 3 */
1.0f, 0.0f, 0.0f, 0.0f, /* Vertex 4 */ 1.0f, 0.0f, 0.0f, 0.0f, /* Vertex 5 */
0.5f, 0.5f, 0.0f, 0.0f, /* Vertex 6 */ 0.5f, 0.5f, 0.0f, 0.0f, /* Vertex 7 */
1.0f, 0.0f, 0.0f, 0.0f, /* Vertex 8 */ 1.0f, 0.0f, 0.0f, 0.0f, /* Vertex 9 */
0.5f, 0.5f, 0.0f, 0.0f, /* Vertex 10 */ 0.5f, 0.5f, 0.0f, 0.0f, /* Vertex 11 */
1.0f, 0.0f, 0.0f, 0.0f, /* Vertex 12 */ 1.0f, 0.0f, 0.0f, 0.0f, /* Vertex 13 */
};
/* Line indices for grid rendering */
static const uint16_t grid_indices[] = {
/* B0 */ 0, 1, 0, 2, 1, 3,
/* CONNECTOR */ 2, 3, 2, 4, 3, 5,
/* B1 */ 4, 5, 4, 6, 5, 7,
/* CONNECTOR */ 6, 7, 6, 8, 7, 9,
/* B2 */ 8, 9, 8, 10, 9, 11,
/* CONNECTOR */ 10, 11, 10, 12, 11, 13,
/* B3 */ 12, 13,
};
/* clang-format on */
static void init_grid_buffers(wgpu_context_t* wgpu_context)
{
state.grid_buffers.positions = wgpu_create_buffer(
wgpu_context, &(wgpu_buffer_desc_t){
.label = "Grid positions buffer",
.usage = WGPUBufferUsage_CopyDst | WGPUBufferUsage_Vertex,
.size = sizeof(grid_vertices),
.initial.data = grid_vertices,
});
state.grid_buffers.joints = wgpu_create_buffer(
wgpu_context, &(wgpu_buffer_desc_t){
.label = "Grid joints buffer",
.usage = WGPUBufferUsage_CopyDst | WGPUBufferUsage_Vertex,
.size = sizeof(grid_joints),
.initial.data = grid_joints,
});
state.grid_buffers.weights = wgpu_create_buffer(
wgpu_context, &(wgpu_buffer_desc_t){
.label = "Grid weights buffer",
.usage = WGPUBufferUsage_CopyDst | WGPUBufferUsage_Vertex,
.size = sizeof(grid_weights),
.initial.data = grid_weights,
});
state.grid_buffers.indices = wgpu_create_buffer(
wgpu_context, &(wgpu_buffer_desc_t){
.label = "Grid indices buffer",
.usage = WGPUBufferUsage_CopyDst | WGPUBufferUsage_Index,
.size = sizeof(grid_indices),
.initial.data = grid_indices,
});
state.grid_buffers.index_count
= sizeof(grid_indices) / sizeof(grid_indices[0]);
}
/* -------------------------------------------------------------------------- *
* Bind Group Layouts
* -------------------------------------------------------------------------- */
static void init_bind_group_layouts(wgpu_context_t* wgpu_context)
{
/* Camera bind group layout */
state.camera_bind_group_layout = wgpuDeviceCreateBindGroupLayout(
wgpu_context->device,
&(WGPUBindGroupLayoutDescriptor){
.label = STRVIEW("Camera bind group layout"),
.entryCount = 1,
.entries = &(WGPUBindGroupLayoutEntry){
.binding = 0,
.visibility = WGPUShaderStage_Vertex,
.buffer = (WGPUBufferBindingLayout){
.type = WGPUBufferBindingType_Uniform,
.minBindingSize = MAT4X4_BYTES * 3,
},
},
});
/* General uniforms bind group layout */
state.general_bind_group_layout = wgpuDeviceCreateBindGroupLayout(
wgpu_context->device,
&(WGPUBindGroupLayoutDescriptor){
.label = STRVIEW("General uniforms bind group layout"),
.entryCount = 1,
.entries = &(WGPUBindGroupLayoutEntry){
.binding = 0,
.visibility = WGPUShaderStage_Vertex | WGPUShaderStage_Fragment,
.buffer = (WGPUBufferBindingLayout){
.type = WGPUBufferBindingType_Uniform,
.minBindingSize = sizeof(uint32_t) * 2,
},
},
});
/* Node uniforms bind group layout */
state.node_bind_group_layout = wgpuDeviceCreateBindGroupLayout(