-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathgltf_loader_impl.cpp
More file actions
2322 lines (2095 loc) · 83.3 KB
/
Copy pathgltf_loader_impl.cpp
File metadata and controls
2322 lines (2095 loc) · 83.3 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
/*
* VRM Overlay - glTF/GLB Loader C++ Implementation
*
* Uses tinygltf for actual parsing. This file bridges C++ tinygltf
* to our C interface.
*/
#define TINYGLTF_NO_STB_IMAGE_WRITE
#include "tiny_gltf.h"
#include <array>
#include <cglm/cglm.h>
#include <cmath>
#include <cstdint>
#include <cstdio>
#include <cstring>
#include <set>
#include <unordered_map>
#include <vector>
extern "C" {
#include "gltf_loader.h"
}
static void mat4_to_quat(const float *m, float *q);
/* Helper to copy string safely */
static void copy_name(char *dst, const std::string &src, size_t max_len) {
size_t len = src.length();
if (len >= max_len)
len = max_len - 1;
memcpy(dst, src.c_str(), len);
dst[len] = '\0';
}
static void normalize_quat(float *q) {
float len = sqrtf(q[0] * q[0] + q[1] * q[1] + q[2] * q[2] + q[3] * q[3]);
if (len > 0.0001f) {
q[0] /= len;
q[1] /= len;
q[2] /= len;
q[3] /= len;
}
}
static float vec3_len(const float *v) {
return sqrtf(v[0] * v[0] + v[1] * v[1] + v[2] * v[2]);
}
static void vec3_norm(float *v) {
float len = vec3_len(v);
if (len > 1e-6f) {
v[0] /= len;
v[1] /= len;
v[2] /= len;
}
}
static float vec3_dot(const float *a, const float *b) {
return a[0] * b[0] + a[1] * b[1] + a[2] * b[2];
}
static void vec3_cross(const float *a, const float *b, float *out) {
float x = a[1] * b[2] - a[2] * b[1];
float y = a[2] * b[0] - a[0] * b[2];
float z = a[0] * b[1] - a[1] * b[0];
out[0] = x;
out[1] = y;
out[2] = z;
}
static bool read_vec3_value(const tinygltf::Value &v, float *out) {
if (v.IsArray() && v.ArrayLen() >= 3) {
out[0] = (float)v.Get(0).Get<double>();
out[1] = (float)v.Get(1).Get<double>();
out[2] = (float)v.Get(2).Get<double>();
return true;
}
if (v.IsObject()) {
out[0] = v.Has("x") ? (float)v.Get("x").Get<double>() : 0.0f;
out[1] = v.Has("y") ? (float)v.Get("y").Get<double>() : 0.0f;
out[2] = v.Has("z") ? (float)v.Get("z").Get<double>() : 0.0f;
return true;
}
return false;
}
static void quat_mul(const float *a, const float *b, float *out) {
out[0] = a[3] * b[0] + a[0] * b[3] + a[1] * b[2] - a[2] * b[1];
out[1] = a[3] * b[1] - a[0] * b[2] + a[1] * b[3] + a[2] * b[0];
out[2] = a[3] * b[2] + a[0] * b[1] - a[1] * b[0] + a[2] * b[3];
out[3] = a[3] * b[3] - a[0] * b[0] - a[1] * b[1] - a[2] * b[2];
}
static void quat_inv(const float *q, float *out) {
out[0] = -q[0];
out[1] = -q[1];
out[2] = -q[2];
out[3] = q[3];
}
static void mat4_mul(const float *a, const float *b, float *out) {
for (int col = 0; col < 4; col++) {
for (int row = 0; row < 4; row++) {
float sum = 0.0f;
for (int k = 0; k < 4; k++) {
sum += a[k * 4 + row] * b[col * 4 + k];
}
out[col * 4 + row] = sum;
}
}
}
static void mat4_to_quat(const float *m, float *q) {
float m00 = m[0], m01 = m[4], m02 = m[8];
float m10 = m[1], m11 = m[5], m12 = m[9];
float m20 = m[2], m21 = m[6], m22 = m[10];
float trace = m00 + m11 + m22;
if (trace > 0.0f) {
float s = sqrtf(trace + 1.0f) * 2.0f;
q[3] = 0.25f * s;
q[0] = (m21 - m12) / s;
q[1] = (m02 - m20) / s;
q[2] = (m10 - m01) / s;
} else if (m00 > m11 && m00 > m22) {
float s = sqrtf(1.0f + m00 - m11 - m22) * 2.0f;
q[3] = (m21 - m12) / s;
q[0] = 0.25f * s;
q[1] = (m01 + m10) / s;
q[2] = (m02 + m20) / s;
} else if (m11 > m22) {
float s = sqrtf(1.0f + m11 - m00 - m22) * 2.0f;
q[3] = (m02 - m20) / s;
q[0] = (m01 + m10) / s;
q[1] = 0.25f * s;
q[2] = (m12 + m21) / s;
} else {
float s = sqrtf(1.0f + m22 - m00 - m11) * 2.0f;
q[3] = (m10 - m01) / s;
q[0] = (m02 + m20) / s;
q[1] = (m12 + m21) / s;
q[2] = 0.25f * s;
}
normalize_quat(q);
}
static GLenum component_gl_type(int componentType) {
switch (componentType) {
case TINYGLTF_COMPONENT_TYPE_BYTE:
return GL_BYTE;
case TINYGLTF_COMPONENT_TYPE_UNSIGNED_BYTE:
return GL_UNSIGNED_BYTE;
case TINYGLTF_COMPONENT_TYPE_SHORT:
return GL_SHORT;
case TINYGLTF_COMPONENT_TYPE_UNSIGNED_SHORT:
return GL_UNSIGNED_SHORT;
case TINYGLTF_COMPONENT_TYPE_UNSIGNED_INT:
return GL_UNSIGNED_INT;
case TINYGLTF_COMPONENT_TYPE_FLOAT:
return GL_FLOAT;
default:
return GL_FLOAT;
}
}
static size_t component_type_size(int componentType) {
switch (componentType) {
case TINYGLTF_COMPONENT_TYPE_BYTE:
case TINYGLTF_COMPONENT_TYPE_UNSIGNED_BYTE:
return 1;
case TINYGLTF_COMPONENT_TYPE_SHORT:
case TINYGLTF_COMPONENT_TYPE_UNSIGNED_SHORT:
return 2;
case TINYGLTF_COMPONENT_TYPE_UNSIGNED_INT:
case TINYGLTF_COMPONENT_TYPE_FLOAT:
return 4;
default:
return 0;
}
}
static GLuint create_texture(const tinygltf::Image &image,
size_t *texture_bytes, size_t *texture_bytes_mip) {
GLuint tex;
glGenTextures(1, &tex);
glBindTexture(GL_TEXTURE_2D, tex);
GLenum format = GL_RGBA;
if (image.component == 3)
format = GL_RGB;
glTexImage2D(GL_TEXTURE_2D, 0, GL_RGBA, image.width, image.height, 0, format,
GL_UNSIGNED_BYTE, image.image.data());
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_REPEAT);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_REPEAT);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER,
GL_LINEAR_MIPMAP_LINEAR);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR);
glGenerateMipmap(GL_TEXTURE_2D);
if (texture_bytes) {
size_t base = (size_t)image.width * (size_t)image.height * 4;
*texture_bytes += base;
if (texture_bytes_mip) {
*texture_bytes_mip += (base * 4) / 3;
}
}
return tex;
}
/* Create OpenGL buffers for a primitive */
static void create_primitive_buffers(GltfPrimitive *prim,
const tinygltf::Model &gltf,
const tinygltf::Primitive &tprim,
size_t *gpu_buffer_bytes) {
glGenVertexArrays(1, &prim->vao);
glBindVertexArray(prim->vao);
auto bind_attribute = [&](int accessor_idx, GLuint *vbo, GLint location,
int components, bool integer_attr,
bool normalize) -> bool {
if (accessor_idx < 0)
return false;
const auto &accessor = gltf.accessors[accessor_idx];
if (accessor.bufferView < 0)
return false;
const auto &view = gltf.bufferViews[accessor.bufferView];
const auto &buffer = gltf.buffers[view.buffer];
const uint8_t *view_data = buffer.data.data() + view.byteOffset;
glGenBuffers(1, vbo);
glBindBuffer(GL_ARRAY_BUFFER, *vbo);
glBufferData(GL_ARRAY_BUFFER, view.byteLength, view_data, GL_STATIC_DRAW);
if (gpu_buffer_bytes) {
*gpu_buffer_bytes += (size_t)view.byteLength;
}
size_t stride = accessor.ByteStride(view);
if (stride == 0) {
stride = components * component_type_size(accessor.componentType);
}
const void *offset = (const void *)(uintptr_t)accessor.byteOffset;
GLenum gl_type = component_gl_type(accessor.componentType);
if (integer_attr) {
glVertexAttribIPointer(location, components, gl_type, (GLsizei)stride,
offset);
} else {
glVertexAttribPointer(location, components, gl_type,
normalize ? GL_TRUE : GL_FALSE, (GLsizei)stride,
offset);
}
glEnableVertexAttribArray(location);
return true;
};
prim->mode = GL_TRIANGLES;
prim->vertex_count = 0;
if (tprim.mode >= 0) {
switch (tprim.mode) {
case TINYGLTF_MODE_POINTS:
prim->mode = GL_POINTS;
break;
case TINYGLTF_MODE_LINE:
prim->mode = GL_LINES;
break;
case TINYGLTF_MODE_LINE_LOOP:
prim->mode = GL_LINE_LOOP;
break;
case TINYGLTF_MODE_LINE_STRIP:
prim->mode = GL_LINE_STRIP;
break;
case TINYGLTF_MODE_TRIANGLE_STRIP:
prim->mode = GL_TRIANGLE_STRIP;
break;
case TINYGLTF_MODE_TRIANGLE_FAN:
prim->mode = GL_TRIANGLE_FAN;
break;
case TINYGLTF_MODE_TRIANGLES:
default:
prim->mode = GL_TRIANGLES;
break;
}
}
/* Positions (required) */
auto it = tprim.attributes.find("POSITION");
if (it != tprim.attributes.end()) {
bind_attribute(it->second, &prim->vbo_positions, 0, 3, false, false);
prim->vertex_count = (uint32_t)gltf.accessors[it->second].count;
}
/* Normals */
it = tprim.attributes.find("NORMAL");
if (it != tprim.attributes.end()) {
if (bind_attribute(it->second, &prim->vbo_normals, 1, 3, false, false)) {
prim->has_normals = true;
}
}
/* Texcoords */
it = tprim.attributes.find("TEXCOORD_0");
if (it != tprim.attributes.end()) {
const auto &accessor = gltf.accessors[it->second];
if (bind_attribute(it->second, &prim->vbo_texcoords, 2, 2, false,
accessor.normalized)) {
prim->has_texcoords = true;
}
}
/* Joints */
it = tprim.attributes.find("JOINTS_0");
if (it != tprim.attributes.end()) {
const auto &accessor = gltf.accessors[it->second];
if (accessor.bufferView >= 0) {
const auto &view = gltf.bufferViews[accessor.bufferView];
const auto &buffer = gltf.buffers[view.buffer];
const uint8_t *data =
buffer.data.data() + view.byteOffset + accessor.byteOffset;
size_t comp_size = component_type_size(accessor.componentType);
size_t stride = accessor.ByteStride(view);
if (stride == 0) {
stride = 4 * comp_size;
}
std::vector<int> palette;
palette.reserve(GLTF_MAX_PALETTE_BONES);
std::unordered_map<uint32_t, uint32_t> remap;
bool palette_overflow = false;
int count = (int)accessor.count;
std::vector<uint8_t> remapped;
remapped.resize((size_t)count * 4 * comp_size);
auto read_joint = [&](const uint8_t *ptr) -> uint32_t {
if (comp_size == 1)
return *ptr;
if (comp_size == 2) {
uint16_t v;
memcpy(&v, ptr, sizeof(v));
return v;
}
uint32_t v;
memcpy(&v, ptr, sizeof(v));
return v;
};
auto write_joint = [&](uint8_t *ptr, uint32_t v) {
if (comp_size == 1) {
*ptr = (uint8_t)v;
} else if (comp_size == 2) {
uint16_t out = (uint16_t)v;
memcpy(ptr, &out, sizeof(out));
} else {
memcpy(ptr, &v, sizeof(v));
}
};
for (int i = 0; i < count; i++) {
const uint8_t *src = data + (size_t)i * stride;
uint8_t *dst = remapped.data() + (size_t)i * 4 * comp_size;
for (int c = 0; c < 4; c++) {
uint32_t joint = read_joint(src + (size_t)c * comp_size);
auto itp = remap.find(joint);
uint32_t local_idx = 0;
if (itp == remap.end()) {
if ((int)palette.size() < GLTF_MAX_PALETTE_BONES) {
local_idx = (uint32_t)palette.size();
remap[joint] = local_idx;
palette.push_back((int)joint);
} else {
palette_overflow = true;
local_idx = 0;
}
} else {
local_idx = itp->second;
}
write_joint(dst + (size_t)c * comp_size, local_idx);
}
}
if (palette_overflow) {
fprintf(stderr,
"Warning: primitive uses >%d joints, using bone texture path\n",
GLTF_MAX_PALETTE_BONES);
if (bind_attribute(it->second, &prim->vbo_joints, 3, 4, true, false)) {
prim->has_skinning = true;
}
prim->joint_palette_count = 0;
prim->joint_palette = NULL;
} else {
glGenBuffers(1, &prim->vbo_joints);
glBindBuffer(GL_ARRAY_BUFFER, prim->vbo_joints);
glBufferData(GL_ARRAY_BUFFER, remapped.size(), remapped.data(),
GL_STATIC_DRAW);
if (gpu_buffer_bytes) {
*gpu_buffer_bytes += remapped.size();
}
prim->joint_palette_count = (int)palette.size();
prim->joint_palette =
(int *)malloc((size_t)prim->joint_palette_count * sizeof(int));
for (int i = 0; i < prim->joint_palette_count; i++) {
prim->joint_palette[i] = palette[i];
}
GLenum gl_type = component_gl_type(accessor.componentType);
glVertexAttribIPointer(3, 4, gl_type, (GLsizei)(4 * comp_size),
(const void *)0);
glEnableVertexAttribArray(3);
prim->has_skinning = prim->joint_palette_count > 0;
}
}
}
/* Weights */
it = tprim.attributes.find("WEIGHTS_0");
if (it != tprim.attributes.end()) {
const auto &accessor = gltf.accessors[it->second];
bind_attribute(it->second, &prim->vbo_weights, 4, 4, false,
accessor.normalized);
}
/* Indices */
if (tprim.indices >= 0) {
const auto &accessor = gltf.accessors[tprim.indices];
const auto &view = gltf.bufferViews[accessor.bufferView];
const auto &buffer = gltf.buffers[view.buffer];
const uint8_t *data =
buffer.data.data() + view.byteOffset + accessor.byteOffset;
glGenBuffers(1, &prim->ebo);
glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, prim->ebo);
size_t elem_size = 2;
if (accessor.componentType == TINYGLTF_COMPONENT_TYPE_UNSIGNED_INT) {
prim->index_type = GL_UNSIGNED_INT;
elem_size = 4;
} else if (accessor.componentType ==
TINYGLTF_COMPONENT_TYPE_UNSIGNED_BYTE) {
prim->index_type = GL_UNSIGNED_BYTE;
elem_size = 1;
} else {
prim->index_type = GL_UNSIGNED_SHORT;
}
glBufferData(GL_ELEMENT_ARRAY_BUFFER, accessor.count * elem_size, data,
GL_STATIC_DRAW);
prim->index_count = (uint32_t)accessor.count;
if (gpu_buffer_bytes) {
*gpu_buffer_bytes += (size_t)accessor.count * elem_size;
}
}
/* Load morph targets */
int target_count = (int)tprim.targets.size();
if (target_count > 0) {
if (target_count > MAX_MORPH_TARGETS) {
fprintf(stderr,
"Warning: primitive has %d morph targets, capping to %d\n",
target_count, MAX_MORPH_TARGETS);
prim->morph_gpu_count = MAX_MORPH_TARGETS;
} else {
prim->morph_gpu_count = target_count;
}
prim->morph_target_count = target_count;
prim->morph_targets =
(MorphTarget *)calloc(target_count, sizeof(MorphTarget));
for (int t = 0; t < target_count; t++) {
const auto &target = tprim.targets[t];
MorphTarget *mt = &prim->morph_targets[t];
/* POSITION deltas */
auto pos_it = target.find("POSITION");
if (pos_it != target.end() && pos_it->second >= 0) {
const auto &accessor = gltf.accessors[pos_it->second];
if (accessor.bufferView >= 0) {
const auto &view = gltf.bufferViews[accessor.bufferView];
const auto &buffer = gltf.buffers[view.buffer];
const float *data =
(const float *)(buffer.data.data() + view.byteOffset +
accessor.byteOffset);
size_t count = accessor.count;
mt->position_deltas = (float *)malloc(count * 3 * sizeof(float));
memcpy(mt->position_deltas, data, count * 3 * sizeof(float));
}
}
/* NORMAL deltas (optional) */
auto norm_it = target.find("NORMAL");
if (norm_it != target.end() && norm_it->second >= 0) {
const auto &accessor = gltf.accessors[norm_it->second];
if (accessor.bufferView >= 0) {
const auto &view = gltf.bufferViews[accessor.bufferView];
const auto &buffer = gltf.buffers[view.buffer];
const float *data =
(const float *)(buffer.data.data() + view.byteOffset +
accessor.byteOffset);
size_t count = accessor.count;
mt->normal_deltas = (float *)malloc(count * 3 * sizeof(float));
memcpy(mt->normal_deltas, data, count * 3 * sizeof(float));
mt->has_normals = true;
}
}
}
printf("Loaded %d morph targets for primitive (%d for GPU)\n", target_count,
prim->morph_gpu_count);
/* Debug: print sample deltas for morph 39 (mouth A) if available */
if (target_count > 39 && prim->morph_targets[39].position_deltas) {
float *pd = prim->morph_targets[39].position_deltas;
float max_delta = 0.0f;
for (uint32_t v = 0; v < prim->vertex_count; v++) {
float d =
fabsf(pd[v * 3]) + fabsf(pd[v * 3 + 1]) + fabsf(pd[v * 3 + 2]);
if (d > max_delta)
max_delta = d;
}
printf(" Morph 39 (A): max delta magnitude = %.4f\n", max_delta);
}
/* Create GPU morph texture if we have targets to put on GPU */
if (prim->morph_gpu_count > 0 && prim->vertex_count > 0) {
/*
* Pack morphs into a 2D RGBA32F texture small enough for GL_MAX_TEXTURE_SIZE.
* Each vertex uses two texels: [posDelta.xyz, 0] and [normDelta.xyz, 0].
*
* Texture layout:
* width = vertsPerRow * 2 texels
* height = morphCount * rowsPerMorph
* y = morphIndex * rowsPerMorph + rowWithin
* x = (vertexWithinRow * 2) [+0 for pos, +1 for norm]
*/
GLint max_tex = 0;
glGetIntegerv(GL_MAX_TEXTURE_SIZE, &max_tex);
if (max_tex <= 0) {
max_tex = 16384;
}
int verts_per_row = (int)prim->vertex_count;
int max_verts_per_row = max_tex / 2;
if (max_verts_per_row < 1) {
max_verts_per_row = 1;
}
if (verts_per_row > max_verts_per_row) {
verts_per_row = max_verts_per_row;
}
int rows_per_morph =
(int)((prim->vertex_count + (uint32_t)verts_per_row - 1) /
(uint32_t)verts_per_row);
int max_morphs_fit = max_tex / (rows_per_morph > 0 ? rows_per_morph : 1);
if (max_morphs_fit < prim->morph_gpu_count) {
fprintf(stderr,
"Warning: morph texture too tall for GL_MAX_TEXTURE_SIZE=%d; "
"capping morphs from %d to %d\n",
max_tex, prim->morph_gpu_count, max_morphs_fit);
prim->morph_gpu_count = max_morphs_fit;
}
if (prim->morph_gpu_count > 0 && rows_per_morph > 0) {
int tex_width = verts_per_row * 2;
int tex_height = prim->morph_gpu_count * rows_per_morph;
float *tex_data = (float *)calloc(
(size_t)tex_width * (size_t)tex_height * 4, sizeof(float));
for (int t = 0; t < prim->morph_gpu_count; t++) {
MorphTarget *mt = &prim->morph_targets[t];
for (uint32_t v = 0; v < prim->vertex_count; v++) {
int row_within = (int)(v / (uint32_t)verts_per_row);
int col = (int)(v - (uint32_t)row_within * (uint32_t)verts_per_row);
int y = t * rows_per_morph + row_within;
int x = col * 2;
float *pos_dest =
tex_data + (((size_t)y * (size_t)tex_width) + (size_t)x) * 4;
float *nrm_dest = pos_dest + 4;
if (mt->position_deltas) {
pos_dest[0] = mt->position_deltas[v * 3 + 0];
pos_dest[1] = mt->position_deltas[v * 3 + 1];
pos_dest[2] = mt->position_deltas[v * 3 + 2];
}
if (mt->normal_deltas) {
nrm_dest[0] = mt->normal_deltas[v * 3 + 0];
nrm_dest[1] = mt->normal_deltas[v * 3 + 1];
nrm_dest[2] = mt->normal_deltas[v * 3 + 2];
}
}
}
prim->morph_tex_verts_per_row = verts_per_row;
prim->morph_tex_rows_per_morph = rows_per_morph;
glGenTextures(1, &prim->morph_vbo);
glBindTexture(GL_TEXTURE_2D, prim->morph_vbo);
glTexImage2D(GL_TEXTURE_2D, 0, GL_RGBA32F, tex_width, tex_height, 0,
GL_RGBA, GL_FLOAT, tex_data);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_NEAREST);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_NEAREST);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_EDGE);
glBindTexture(GL_TEXTURE_2D, 0);
free(tex_data);
printf("Created morph texture %dx%d for primitive\n", tex_width,
tex_height);
}
}
}
prim->material_index = tprim.material;
glBindVertexArray(0);
}
extern "C" bool gltf_load_impl(GltfModel *model, const char *path) {
tinygltf::TinyGLTF loader;
tinygltf::Model gltf;
std::string err, warn;
size_t gpu_texture_bytes = 0;
size_t gpu_texture_bytes_mip = 0;
size_t gpu_buffer_bytes = 0;
bool ret;
std::string spath(path);
if (spath.ends_with(".glb") || spath.ends_with(".vrm") ||
spath.ends_with(".vrma")) {
ret = loader.LoadBinaryFromFile(&gltf, &err, &warn, path);
} else {
ret = loader.LoadASCIIFromFile(&gltf, &err, &warn, path);
}
if (!warn.empty()) {
fprintf(stderr, "glTF warning: %s\n", warn.c_str());
}
if (!ret) {
fprintf(stderr, "Failed to load glTF: %s\n", err.c_str());
return false;
}
printf("Loaded glTF: %zu meshes, %zu materials, %zu textures, %zu nodes, %zu "
"skins\n",
gltf.meshes.size(), gltf.materials.size(), gltf.textures.size(),
gltf.nodes.size(), gltf.skins.size());
/* Count nodes with meshes */
int mesh_nodes = 0;
for (size_t i = 0; i < gltf.nodes.size(); i++) {
if (gltf.nodes[i].mesh >= 0)
mesh_nodes++;
}
printf("Nodes with meshes: %d\n", mesh_nodes);
/* Load textures */
model->texture_count = (int)gltf.textures.size();
if (model->texture_count > 0) {
model->textures =
(GltfTexture *)calloc(model->texture_count, sizeof(GltfTexture));
for (size_t i = 0; i < gltf.textures.size(); i++) {
int img_idx = gltf.textures[i].source;
if (img_idx >= 0 && img_idx < (int)gltf.images.size()) {
model->textures[i].id = create_texture(
gltf.images[img_idx], &gpu_texture_bytes, &gpu_texture_bytes_mip);
model->textures[i].width = gltf.images[img_idx].width;
model->textures[i].height = gltf.images[img_idx].height;
gltf.images[img_idx].image.clear();
gltf.images[img_idx].image.shrink_to_fit();
}
}
}
/* Load materials */
model->material_count = (int)gltf.materials.size();
if (model->material_count > 0) {
model->materials =
(GltfMaterial *)calloc(model->material_count, sizeof(GltfMaterial));
for (size_t i = 0; i < gltf.materials.size(); i++) {
const auto &mat = gltf.materials[i];
GltfMaterial *m = &model->materials[i];
copy_name(m->name, mat.name, sizeof(m->name));
const auto &pbr = mat.pbrMetallicRoughness;
m->base_color[0] = (float)pbr.baseColorFactor[0];
m->base_color[1] = (float)pbr.baseColorFactor[1];
m->base_color[2] = (float)pbr.baseColorFactor[2];
m->base_color[3] = (float)pbr.baseColorFactor[3];
m->metallic = (float)pbr.metallicFactor;
m->roughness = (float)pbr.roughnessFactor;
m->base_color_texture = pbr.baseColorTexture.index;
m->metallic_roughness_texture = pbr.metallicRoughnessTexture.index;
m->normal_texture = mat.normalTexture.index;
if (mat.alphaMode == "MASK") {
m->alpha_mode = 1;
m->alpha_cutoff = (float)mat.alphaCutoff;
} else if (mat.alphaMode == "BLEND") {
m->alpha_mode = 2;
} else {
m->alpha_mode = 0;
}
m->double_sided = mat.doubleSided;
m->alpha_write_depth = false;
}
}
/* Apply VRM material overrides (MToon) */
if (gltf.extensions.count("VRM")) {
const auto &vrm = gltf.extensions.at("VRM");
if (vrm.Has("materialProperties")) {
const auto &props = vrm.Get("materialProperties");
size_t count = props.ArrayLen();
for (size_t i = 0; i < count; i++) {
const auto &mp = props.Get(i);
if (i >= (size_t)model->material_count)
break;
GltfMaterial *m = &model->materials[i];
if (mp.Has("floatProperties")) {
const auto &fp = mp.Get("floatProperties");
if (fp.Has("_BlendMode")) {
int blend_mode = (int)fp.Get("_BlendMode").GetNumberAsDouble();
if (blend_mode == 3) {
m->alpha_write_depth = true;
}
}
if (fp.Has("_CullMode")) {
int cull_mode = (int)fp.Get("_CullMode").GetNumberAsDouble();
if (cull_mode == 0) {
m->double_sided = true;
} else if (cull_mode == 2) {
m->double_sided = false;
}
}
}
}
}
}
/* Load meshes */
model->mesh_count = (int)gltf.meshes.size();
if (model->mesh_count > 0) {
model->meshes = (GltfMesh *)calloc(model->mesh_count, sizeof(GltfMesh));
for (size_t i = 0; i < gltf.meshes.size(); i++) {
const auto &mesh = gltf.meshes[i];
GltfMesh *m = &model->meshes[i];
copy_name(m->name, mesh.name, sizeof(m->name));
m->primitive_count = (int)mesh.primitives.size();
m->primitives =
(GltfPrimitive *)calloc(m->primitive_count, sizeof(GltfPrimitive));
for (size_t j = 0; j < mesh.primitives.size(); j++) {
create_primitive_buffers(&m->primitives[j], gltf, mesh.primitives[j],
&gpu_buffer_bytes);
}
/* Morph targets - use mesh.weights if available, otherwise use max from
* primitives */
m->morph_target_count = (int)mesh.weights.size();
if (m->morph_target_count == 0) {
/* Fall back to max morph count from primitives */
for (int j = 0; j < m->primitive_count; j++) {
if (m->primitives[j].morph_target_count > m->morph_target_count) {
m->morph_target_count = m->primitives[j].morph_target_count;
}
}
}
if (m->morph_target_count > 0) {
m->morph_weights =
(float *)calloc(m->morph_target_count, sizeof(float));
for (size_t j = 0; j < mesh.weights.size(); j++) {
m->morph_weights[j] = (float)mesh.weights[j];
}
printf("Mesh '%s': %d morph targets, weights array allocated\n",
m->name, m->morph_target_count);
}
}
}
/* Load nodes */
model->node_count = (int)gltf.nodes.size();
if (model->node_count > 0) {
model->nodes = (GltfNode *)calloc(model->node_count, sizeof(GltfNode));
for (size_t i = 0; i < gltf.nodes.size(); i++) {
const auto &node = gltf.nodes[i];
GltfNode *n = &model->nodes[i];
copy_name(n->name, node.name, sizeof(n->name));
n->mesh_index = node.mesh;
n->skin_index = node.skin;
n->parent_index = -1; /* Will be set below */
/* Default transform */
n->translation[0] = n->translation[1] = n->translation[2] = 0.0f;
n->rotation[0] = n->rotation[1] = n->rotation[2] = 0.0f;
n->rotation[3] = 1.0f;
n->scale[0] = n->scale[1] = n->scale[2] = 1.0f;
n->base_translation[0] = n->base_translation[1] = n->base_translation[2] =
0.0f;
n->base_rotation[0] = n->base_rotation[1] = n->base_rotation[2] = 0.0f;
n->base_rotation[3] = 1.0f;
n->base_scale[0] = n->base_scale[1] = n->base_scale[2] = 1.0f;
if (node.translation.size() == 3) {
n->translation[0] = (float)node.translation[0];
n->translation[1] = (float)node.translation[1];
n->translation[2] = (float)node.translation[2];
}
if (node.rotation.size() == 4) {
n->rotation[0] = (float)node.rotation[0];
n->rotation[1] = (float)node.rotation[1];
n->rotation[2] = (float)node.rotation[2];
n->rotation[3] = (float)node.rotation[3];
normalize_quat(n->rotation);
}
if (node.scale.size() == 3) {
n->scale[0] = (float)node.scale[0];
n->scale[1] = (float)node.scale[1];
n->scale[2] = (float)node.scale[2];
}
n->base_translation[0] = n->translation[0];
n->base_translation[1] = n->translation[1];
n->base_translation[2] = n->translation[2];
n->base_rotation[0] = n->rotation[0];
n->base_rotation[1] = n->rotation[1];
n->base_rotation[2] = n->rotation[2];
n->base_rotation[3] = n->rotation[3];
n->base_scale[0] = n->scale[0];
n->base_scale[1] = n->scale[1];
n->base_scale[2] = n->scale[2];
/* Children */
n->child_count = (int)node.children.size();
if (n->child_count > 0) {
n->children = (int *)malloc(n->child_count * sizeof(int));
for (size_t j = 0; j < node.children.size(); j++) {
n->children[j] = node.children[j];
}
}
}
/* Set parent indices */
for (int i = 0; i < model->node_count; i++) {
GltfNode *n = &model->nodes[i];
for (int j = 0; j < n->child_count; j++) {
if (n->children[j] >= 0 && n->children[j] < model->node_count) {
model->nodes[n->children[j]].parent_index = i;
}
}
}
}
/* Load skins */
model->skin_count = (int)gltf.skins.size();
if (model->skin_count > 0) {
model->skins = (GltfSkin *)calloc(model->skin_count, sizeof(GltfSkin));
for (size_t i = 0; i < gltf.skins.size(); i++) {
const auto &skin = gltf.skins[i];
GltfSkin *s = &model->skins[i];
s->joint_count = (int)skin.joints.size();
s->joints = (int *)malloc(s->joint_count * sizeof(int));
for (size_t j = 0; j < skin.joints.size(); j++) {
s->joints[j] = skin.joints[j];
}
s->skeleton_root = skin.skeleton;
/* Inverse bind matrices */
if (skin.inverseBindMatrices >= 0) {
const auto &accessor = gltf.accessors[skin.inverseBindMatrices];
const auto &view = gltf.bufferViews[accessor.bufferView];
const auto &buffer = gltf.buffers[view.buffer];
const float *data =
(const float *)(buffer.data.data() + view.byteOffset +
accessor.byteOffset);
s->inverse_bind_matrices =
(float *)malloc(s->joint_count * 16 * sizeof(float));
memcpy(s->inverse_bind_matrices, data,
s->joint_count * 16 * sizeof(float));
}
}
}
/* Scene roots */
if (!gltf.scenes.empty()) {
const auto &scene =
gltf.scenes[gltf.defaultScene >= 0 ? gltf.defaultScene : 0];
model->scene_root_count = (int)scene.nodes.size();
model->scene_roots = (int *)malloc(model->scene_root_count * sizeof(int));
for (size_t i = 0; i < scene.nodes.size(); i++) {
model->scene_roots[i] = scene.nodes[i];
}
}
/* Load animations */
model->animation_count = (int)gltf.animations.size();
if (model->animation_count > 0) {
model->animations =
(GltfAnimation *)calloc(model->animation_count, sizeof(GltfAnimation));
for (size_t i = 0; i < gltf.animations.size(); i++) {
const auto &anim = gltf.animations[i];
GltfAnimation *a = &model->animations[i];
copy_name(a->name, anim.name, sizeof(a->name));
/* Load samplers */
a->sampler_count = (int)anim.samplers.size();
a->samplers =
(GltfAnimSampler *)calloc(a->sampler_count, sizeof(GltfAnimSampler));
for (size_t j = 0; j < anim.samplers.size(); j++) {
const auto &sampler = anim.samplers[j];
GltfAnimSampler *s = &a->samplers[j];
/* Input (times) */
const auto &input_acc = gltf.accessors[sampler.input];
const auto &input_view = gltf.bufferViews[input_acc.bufferView];
const auto &input_buf = gltf.buffers[input_view.buffer];
const float *input_data =
(const float *)(input_buf.data.data() + input_view.byteOffset +
input_acc.byteOffset);
const auto &output_acc = gltf.accessors[sampler.output];
const auto &output_view = gltf.bufferViews[output_acc.bufferView];
const auto &output_buf = gltf.buffers[output_view.buffer];
const float *output_data =
(const float *)(output_buf.data.data() + output_view.byteOffset +
output_acc.byteOffset);
int input_count = (int)input_acc.count;
int output_count = (int)output_acc.count;
int keyframe_count =
input_count < output_count ? input_count : output_count;
if (input_count != output_count) {
fprintf(stderr,
"Warning: sampler %zu input/output count mismatch (%d/%d), "
"clamping to %d\n",
j, input_count, output_count, keyframe_count);
}
s->keyframe_count = keyframe_count;
s->input = (float *)malloc(s->keyframe_count * sizeof(float));
memcpy(s->input, input_data, s->keyframe_count * sizeof(float));
/* Track max time for duration */
if (s->keyframe_count > 0 &&
s->input[s->keyframe_count - 1] > a->duration) {
a->duration = s->input[s->keyframe_count - 1];
}
/* Output (values) */
int components = 1;
if (output_acc.type == TINYGLTF_TYPE_VEC3)
components = 3;
else if (output_acc.type == TINYGLTF_TYPE_VEC4)
components = 4;
s->output_stride = components;
s->output =
(float *)malloc(s->keyframe_count * components * sizeof(float));
memcpy(s->output, output_data,
s->keyframe_count * components * sizeof(float));
}
/* Load channels */
a->channel_count = (int)anim.channels.size();
a->channels =
(GltfAnimChannel *)calloc(a->channel_count, sizeof(GltfAnimChannel));
a->node_mask_count = model->node_count;
a->node_mask = (uint8_t *)calloc(a->node_mask_count, sizeof(uint8_t));
for (size_t j = 0; j < anim.channels.size(); j++) {
const auto &channel = anim.channels[j];
GltfAnimChannel *c = &a->channels[j];
c->sampler_index = channel.sampler;
c->target_node = channel.target_node;
if (channel.target_path == "translation")
c->path = GLTF_PATH_TRANSLATION;
else if (channel.target_path == "rotation")
c->path = GLTF_PATH_ROTATION;
else if (channel.target_path == "scale")
c->path = GLTF_PATH_SCALE;
else if (channel.target_path == "weights")
c->path = GLTF_PATH_WEIGHTS;
if (c->sampler_index >= 0 && c->sampler_index < a->sampler_count) {
int expected = 0;
if (c->path == GLTF_PATH_TRANSLATION || c->path == GLTF_PATH_SCALE)
expected = 3;