Untitled
Loading...
Searching...
No Matches
gltf.c
Go to the documentation of this file.
1
2#include <assert.h>
3#include <stdio.h>
4#include <stdlib.h>
5#include <string.h>
6
7#include <SDL2/SDL.h>
8#include "core/engine_types.h"
9#include "utilities/mathf.h"
11#include "utilities/types.h"
12#include "load/load.h"
13#include "load/init.h"
14#include "nuklear/nuklear.h"
15#include "nuklear/nuklear_sdl_gl3.h"
16#include "cJSON/cJSON.h"
17#include "utilities/utilities.h"
18
19static int comp_count(const char *type) {
20 if (!type) return 1;
21 if (strcmp(type, "SCALAR") == 0) return 1;
22 if (strcmp(type, "VEC2") == 0) return 2;
23 if (strcmp(type, "VEC3") == 0) return 3;
24 if (strcmp(type, "VEC4") == 0) return 4;
25 if (strcmp(type, "MAT4") == 0) return 16;
26 return 1;
27}
28
29static int comp_size(int componentType) {
30 switch (componentType) {
31 case 5120:
32 case 5121:
33 return 1;
34 case 5122:
35 case 5123:
36 return 2;
37 case 5125:
38 case 5126:
39 return 4;
40 default: return 0;
41 }
42}
43
44static char* load_text_file(const char *path) {
45 FILE *f = fopen(path, "rb");
46 if (!f) return NULL;
47 fseek(f, 0, SEEK_END);
48 long len = ftell(f); rewind(f);
49 char *buf = (char*)malloc(len+1);
50 fread(buf,1,len,f);
51 buf[len]=0;
52 fclose(f);
53 return buf;
54}
55
56static unsigned char* load_bin_file(const char *path, int expectedLen) {
57 FILE *f = fopen(path, "rb");
58 if (!f) return NULL;
59 fseek(f,0,SEEK_END);
60 long len = ftell(f); rewind(f);
61 if (expectedLen > 0 && len < expectedLen) {
62 fclose(f); return NULL;
63 }
64 unsigned char *data = (unsigned char*)malloc(len);
65 fread(data,1,len,f);
66 fclose(f);
67 return data;
68}
69
70static int str_eq(const char* a, const char* b){ return a && b && strcmp(a,b)==0; }
71
72static int json_get_int(cJSON* obj, const char* key, int defv){
73 cJSON* it = cJSON_GetObjectItemCaseSensitive(obj, key);
74 return cJSON_IsNumber(it) ? it->valueint : defv;
75}
76
77static const char* json_get_str(cJSON* obj, const char* key){
78 cJSON* it = cJSON_GetObjectItemCaseSensitive(obj, key);
79 return cJSON_IsString(it) ? it->valuestring : NULL;
80}
81static void json_get_vec3(cJSON *obj, const char *key, vec3 * out, const float def[3]) {
82 cJSON *arr = cJSON_GetObjectItemCaseSensitive(obj, key);
83 if (cJSON_IsArray(arr) && cJSON_GetArraySize(arr) == 3) {
84 cJSON *val = cJSON_GetArrayItem(arr,0);
85 out->x = cJSON_IsNumber(val) ? (float)val->valuedouble : def[0];
86 val = cJSON_GetArrayItem(arr,1);
87 out->y = cJSON_IsNumber(val) ? (float)val->valuedouble : def[1];
88 val = cJSON_GetArrayItem(arr,2);
89 out->z = cJSON_IsNumber(val) ? (float)val->valuedouble : def[2];
90 } else {
91 memcpy(out, def, sizeof(float)*3);
92 }
93}
94static void json_get_vec4(cJSON *obj, const char *key, vec4 * out, const float def[3]) {
95 cJSON *arr = cJSON_GetObjectItemCaseSensitive(obj, key);
96 if (cJSON_IsArray(arr) && cJSON_GetArraySize(arr) == 4) {
97 cJSON *val = cJSON_GetArrayItem(arr,0);
98 out->x = cJSON_IsNumber(val) ? (float)val->valuedouble : def[0];
99 val = cJSON_GetArrayItem(arr,1);
100 out->y = cJSON_IsNumber(val) ? (float)val->valuedouble : def[1];
101 val = cJSON_GetArrayItem(arr,2);
102 out->z = cJSON_IsNumber(val) ? (float)val->valuedouble : def[2];
103 val = cJSON_GetArrayItem(arr,3);
104 out->w = cJSON_IsNumber(val) ? (float)val->valuedouble : def[3];
105 } else {
106 memcpy(out, def, sizeof(float)*4);
107 }
108}
109
110
111static void json_get_float_array(cJSON *parent, const char *name, float *out, int count, const float *defaults) {
112 cJSON *arr = cJSON_GetObjectItemCaseSensitive(parent, name);
113 if (cJSON_IsArray(arr)) {
114 for (int i = 0; i < count; i++) {
115 cJSON *item = cJSON_GetArrayItem(arr, i);
116 out[i] = cJSON_IsNumber(item) ? (float)item->valuedouble : defaults[i];
117 }
118 } else {
119 for (int i = 0; i < count; i++) out[i] = defaults[i];
120 }
121}
122
123static int json_get_tex_index(cJSON *parent, const char *name) {
124 cJSON *obj = cJSON_GetObjectItemCaseSensitive(parent, name);
125 if (obj) {
126 cJSON *idx = cJSON_GetObjectItemCaseSensitive(obj, "index");
127 if (cJSON_IsNumber(idx)) return idx->valueint;
128 }
129 return -1;
130}
131
132void parse_gltf_materials(cJSON *root, GLTFDoc *doc) {
133 cJSON *materials = cJSON_GetObjectItemCaseSensitive(root, "materials");
134 if (!materials) return;
135
136 doc->material_count = cJSON_GetArraySize(materials);
137 doc->materials = calloc(doc->material_count, sizeof(GLTFMaterial));
138
139 printf("MAT COUNT: %d\n", doc->material_count);
140 for (int i = 0; i < doc->material_count; i++) {
141 cJSON *mat = cJSON_GetArrayItem(materials, i);
142 GLTFMaterial *dst = &doc->materials[i];
143
144 dst->base_color_factor[0] = 1.0f; dst->base_color_factor[1] = 1.0f;
145 dst->base_color_factor[2] = 1.0f; dst->base_color_factor[3] = 1.0f;
146 dst->metallic_factor = 1.0f;
147 dst->roughness_factor = 1.0f;
148 dst->emissive_factor[0] = 0.0f; dst->emissive_factor[1] = 0.0f; dst->emissive_factor[2] = 0.0f;
149
150 dst->base_color_tex = -1;
151 dst->metallic_roughness_tex = -1;
152 dst->normal_tex = -1;
153 dst->occlusion_tex = -1;
154 dst->emissive_tex = -1;
155
156 dst->normal_scale = 1.0f;
157 dst->occlusion_strength = 1.0f;
158 dst->alpha_cutoff = 0.5f;
160 dst->double_sided = false;
161
162 cJSON *name = cJSON_GetObjectItemCaseSensitive(mat, "name");
163 if (cJSON_IsString(name)) strncpy(dst->name, name->valuestring, sizeof(dst->name) - 1);
164
165 cJSON *pbr = cJSON_GetObjectItemCaseSensitive(mat, "pbrMetallicRoughness");
166 if (pbr) {
167 float defColor[4] = {1.0f, 1.0f, 1.0f, 1.0f};
168 json_get_float_array(pbr, "baseColorFactor", dst->base_color_factor, 4, defColor);
169
170 cJSON *mf = cJSON_GetObjectItemCaseSensitive(pbr, "metallicFactor");
171 if (cJSON_IsNumber(mf)) dst->metallic_factor = (float)mf->valuedouble;
172
173 cJSON *rf = cJSON_GetObjectItemCaseSensitive(pbr, "roughnessFactor");
174 if (cJSON_IsNumber(rf)) dst->roughness_factor = (float)rf->valuedouble;
175
176 dst->base_color_tex = json_get_tex_index(pbr, "baseColorTexture");
177 dst->metallic_roughness_tex = json_get_tex_index(pbr, "metallicRoughnessTexture");
178 }
179
180 dst->normal_tex = json_get_tex_index(mat, "normalTexture");
181 dst->occlusion_tex = json_get_tex_index(mat, "occlusionTexture");
182 dst->emissive_tex = json_get_tex_index(mat, "emissiveTexture");
183
184 cJSON *normObj = cJSON_GetObjectItemCaseSensitive(mat, "normalTexture");
185 if (normObj) {
186 cJSON *scale = cJSON_GetObjectItemCaseSensitive(normObj, "scale");
187 if (cJSON_IsNumber(scale)) dst->normal_scale = (float)scale->valuedouble;
188 }
189
190 cJSON *occObj = cJSON_GetObjectItemCaseSensitive(mat, "occlusionTexture");
191 if (occObj) {
192 cJSON *strength = cJSON_GetObjectItemCaseSensitive(occObj, "strength");
193 if (cJSON_IsNumber(strength)) dst->occlusion_strength = (float)strength->valuedouble;
194 }
195
196 float defEmissive[3] = {0.0f, 0.0f, 0.0f};
197 json_get_float_array(mat, "emissiveFactor", dst->emissive_factor, 3, defEmissive);
198
199 cJSON *alphaMode = cJSON_GetObjectItemCaseSensitive(mat, "alphaMode");
200 if (cJSON_IsString(alphaMode)) {
201 if (strcmp(alphaMode->valuestring, "MASK") == 0) dst->alpha_mode = ALPHA_MASK;
202 if (strcmp(alphaMode->valuestring, "BLEND") == 0) dst->alpha_mode = ALPHA_BLEND;
203 }
204
205 cJSON *cutoff = cJSON_GetObjectItemCaseSensitive(mat, "alphaCutoff");
206 if (cJSON_IsNumber(cutoff)) dst->alpha_cutoff = (float)cutoff->valuedouble;
207
208 cJSON *doubleSided = cJSON_GetObjectItemCaseSensitive(mat, "doubleSided");
209 if (cJSON_IsBool(doubleSided)) dst->double_sided = cJSON_IsTrue(doubleSided);
210
211 cJSON *extensions= cJSON_GetObjectItemCaseSensitive(mat, "extensions");
212
213
214 dst->emissive_strength = 1;
215 if (extensions)
216 {
217 cJSON * emissive_strength_ext = cJSON_GetObjectItemCaseSensitive(extensions, "KHR_materials_emissive_strength");
218 if (emissive_strength_ext)
219 {
220
221 cJSON * emissive_strength = cJSON_GetObjectItemCaseSensitive(emissive_strength_ext, "emissiveStrength");
222 if (cJSON_IsNumber(emissive_strength))
223 {
224
225 dst->emissive_strength = (float)emissive_strength->valuedouble;
226 }
227 }
228 }
229 cJSON *extras= cJSON_GetObjectItemCaseSensitive(mat, "extras");
230 dst->fwd_shader = 0;
231 dst->gbuffer_shader = 0;
232
233 for (int i = 0; i < AUDIO_NUM_BANDS; i++)
234 {
235
236 dst->absorption_coefficients[i] = 0.5f;
237 dst->scattering_coefficients[i] = 0.5f;
238 }
239 dst->override_transparent = false;
240
241 if (extras)
242 {
243
244 cJSON * fwd_shader = cJSON_GetObjectItemCaseSensitive(extras, "fwd_shader");
245 if (cJSON_IsString(fwd_shader))
246 {
247 for (int i = 0; i < UBERSHADER_VERSIONS; i++)
248 {
249
250 if (strcmp(fwd_shader->valuestring, DYNAMIC_SHADER[i].name) == 0)
251 {
252 dst->fwd_shader = i;
253 break;
254 }
255 }
256 }
257
258 cJSON * gbuffer_shader = cJSON_GetObjectItemCaseSensitive(extras, "gbuffer_shader");
259 if (cJSON_IsString(gbuffer_shader))
260 {
261 for (int i = 0; i < GBUFFER_VERSIONS; i++)
262 {
263
264 if (strcmp(gbuffer_shader->valuestring, DEPTH_PRE_PASS_SHADER[i].name) == 0)
265 {
266 dst->gbuffer_shader = i;
267 break;
268 }
269 }
270 }
271
272 cJSON * absorption_coefficients = cJSON_GetObjectItemCaseSensitive(extras, "absorption_coefficients");
273 if (cJSON_IsArray(absorption_coefficients))
274 {
275
276 for (int j = 0; j < AUDIO_NUM_BANDS; j++)
277 {
278 cJSON * c0 = cJSON_GetArrayItem(absorption_coefficients, j);
279
280 if (cJSON_IsNumber(c0))
281 {
282 dst->absorption_coefficients[j] = c0->valuedouble;
283 }
284
285 }
286
287 }
288 cJSON * scattering_coefficients = cJSON_GetObjectItemCaseSensitive(extras, "scattering_coefficients");
289 if (cJSON_IsArray(scattering_coefficients))
290 {
291 for (int j = 0; j < AUDIO_NUM_BANDS; j++)
292 {
293 cJSON * c0 = cJSON_GetArrayItem(scattering_coefficients, j);
294
295 if (cJSON_IsNumber(c0))
296 {
297 dst->scattering_coefficients[j] = c0->valuedouble;
298 }
299
300 }
301
302 }
303 cJSON * override = cJSON_GetObjectItemCaseSensitive(extras, "override_transparent");
304 if (cJSON_IsBool(override))
305 {
306 dst->override_transparent = override->valueint;
307
308 }
309
310 }
311 }
312}
313static int parse_gltf_json(const char *gltfPath, const char * prefix, GLTFDoc *doc) {
314 memset(doc,0,sizeof(*doc));
315
316 char *json = load_text_file(gltfPath);
317 if (!json) {
318 printf("EARLY RETURN LOAD\n");
319 return 0;
320 }
321
322 cJSON *root = cJSON_Parse(json);
323 if (!root) { free(json); printf("NO ROOT\n"); return 0; }
324
325 cJSON *buffers = cJSON_GetObjectItemCaseSensitive(root, "buffers");
326 doc->bufferCount = cJSON_GetArraySize(buffers);
327 doc->buffers = (GLTFBuffer*)calloc(doc->bufferCount, sizeof(GLTFBuffer));
328 for (int i=0;i<doc->bufferCount;i++){
329 cJSON *b = cJSON_GetArrayItem(buffers,i);
330 const char *uri = json_get_str(b,"uri");
331 int bytelen = json_get_int(b,"byteLength",0);
332 doc->buffers[i].byteLength = bytelen;
333 if (uri) {
334 doc->buffers[i].uri = strdup(uri);
335 } else {
336 doc->buffers[i].uri = NULL;
337 doc->buffers[i].data = NULL;
338 }
339 }
340
341 cJSON *views = cJSON_GetObjectItemCaseSensitive(root, "bufferViews");
342 doc->viewCount = cJSON_GetArraySize(views);
343 doc->views = (GLTFBufferView*)calloc(doc->viewCount,sizeof(GLTFBufferView));
344 for (int i=0;i<doc->viewCount;i++){
345 cJSON *v = cJSON_GetArrayItem(views,i);
346 doc->views[i].buffer = json_get_int(v,"buffer",0);
347 doc->views[i].byteOffset = json_get_int(v,"byteOffset",0);
348 doc->views[i].byteLength = json_get_int(v,"byteLength",0);
349 doc->views[i].byteStride = json_get_int(v,"byteStride",0);
350 }
351
352 cJSON *accs = cJSON_GetObjectItemCaseSensitive(root, "accessors");
353 doc->accessorCount = cJSON_GetArraySize(accs);
354 doc->accessors = (GLTFAccessor*)calloc(doc->accessorCount,sizeof(GLTFAccessor));
355 for (int i=0;i<doc->accessorCount;i++){
356 cJSON *a = cJSON_GetArrayItem(accs,i);
357 doc->accessors[i].bufferView = json_get_int(a,"bufferView",-1);
358 doc->accessors[i].byteOffset = json_get_int(a,"byteOffset",0);
359 doc->accessors[i].componentType = json_get_int(a,"componentType",0);
360 doc->accessors[i].count = json_get_int(a,"count",0);
361
362 const char *ty = json_get_str(a,"type");
363 if (ty) strncpy(doc->accessors[i].type, ty, sizeof(doc->accessors[i].type)-1);
364 else strcpy(doc->accessors[i].type, "SCALAR");
365 }
366
367 cJSON *meshes = cJSON_GetObjectItemCaseSensitive(root, "meshes");
368 doc->meshCount = cJSON_GetArraySize(meshes);
369 doc->meshes = (GLTFMesh*)calloc(doc->meshCount,sizeof(GLTFMesh));
370 for (int mi=0; mi<doc->meshCount; mi++){
371 cJSON *m = cJSON_GetArrayItem(meshes, mi);
372 cJSON *prims = cJSON_GetObjectItemCaseSensitive(m, "primitives");
373 int pc = cJSON_GetArraySize(prims);
374 doc->meshes[mi].primCount = pc;
375 doc->meshes[mi].prims = (GLTFPrimitive*)calloc(pc,sizeof(GLTFPrimitive));
376
377 for (int pi=0; pi<pc; pi++){
378 cJSON *p = cJSON_GetArrayItem(prims, pi);
379 GLTFPrimitive *dst = &doc->meshes[mi].prims[pi];
380 dst->position = dst->normal = dst->texcoord0 = dst->joints0 = dst->weights0 = -1;
381 dst->indices = -1;
382 dst->material = json_get_int(p,"material",-1);
383
384 cJSON *attrs = cJSON_GetObjectItemCaseSensitive(p,"attributes");
385 if (attrs) {
386 cJSON *POS = cJSON_GetObjectItemCaseSensitive(attrs,"POSITION");
387 cJSON *NOR = cJSON_GetObjectItemCaseSensitive(attrs,"NORMAL");
388 cJSON *TAN = cJSON_GetObjectItemCaseSensitive(attrs,"TANGENT");
389 cJSON *UV0 = cJSON_GetObjectItemCaseSensitive(attrs,"TEXCOORD_0");
390 cJSON *J0 = cJSON_GetObjectItemCaseSensitive(attrs,"JOINTS_0");
391 cJSON *W0 = cJSON_GetObjectItemCaseSensitive(attrs,"WEIGHTS_0");
392 if (cJSON_IsNumber(POS)) dst->position = POS->valueint;
393 if (cJSON_IsNumber(NOR)) dst->normal = NOR->valueint;
394 if (cJSON_IsNumber(TAN)) dst->tangent = TAN->valueint;
395 if (cJSON_IsNumber(UV0)) dst->texcoord0= UV0->valueint;
396 if (cJSON_IsNumber(J0)) dst->joints0 = J0->valueint;
397 if (cJSON_IsNumber(W0)) dst->weights0 = W0->valueint;
398 }
399 cJSON *IND = cJSON_GetObjectItemCaseSensitive(p,"indices");
400 if (cJSON_IsNumber(IND)) dst->indices = IND->valueint;
401 }
402 }
403
404 parse_gltf_materials(root, doc);
405
406 cJSON *textures = cJSON_GetObjectItemCaseSensitive(root,"textures");
407 doc->texture_count = cJSON_GetArraySize(textures);
408 doc->textures = calloc(doc->texture_count, sizeof(GLTFTexture));
409 for (int i = 0; i < doc->texture_count; i++)
410 {
411 cJSON * n = cJSON_GetArrayItem(textures, i);
412
413 GLTFTexture * tex = &doc->textures[i];
414
415 cJSON *sampler = cJSON_GetObjectItemCaseSensitive(n,"sampler");
416 if (cJSON_IsNumber(sampler)) {
417 tex->sampler = sampler->valueint;
418 }
419
420 cJSON *src = cJSON_GetObjectItemCaseSensitive(n,"source");
421 if (cJSON_IsNumber(src)) {
422 tex->source = src->valueint;
423 }
424 }
425
426
427 cJSON *images = cJSON_GetObjectItemCaseSensitive(root,"images");
428 doc->image_count = cJSON_GetArraySize(images);
429 doc->images = calloc(doc->image_count, sizeof(GLTFImage));
430 for (int i = 0; i < doc->image_count; i++)
431 {
432
433 cJSON * n = cJSON_GetArrayItem(images, i);
434 GLTFImage * img = &doc->images[i];
435
436 cJSON *mime_type = cJSON_GetObjectItemCaseSensitive(n,"mimeType");
437 if (cJSON_IsString(mime_type))
438 {
439 strncpy(img->mime_type, mime_type->valuestring, 254);
440 img->mime_type[255] = '\0';
441 }
442 cJSON *name = cJSON_GetObjectItemCaseSensitive(n,"name");
443 if (cJSON_IsString(name))
444 {
445 strncpy(img->name, name->valuestring, 254);
446 img->name[255] = '\0';
447 }
448 cJSON *uri = cJSON_GetObjectItemCaseSensitive(n,"uri");
449 if (cJSON_IsString(uri))
450 {
451 strncpy(img->uri, prefix, 254);
452 strncat(img->uri, uri->valuestring, 254);
453 // strncpy(img->uri, uri->valuestring, 254);
454 // img->uri[255] = '\0';
455 }
456 cJSON *buffer_view= cJSON_GetObjectItemCaseSensitive(n,"bufferView");
457 if (cJSON_IsNumber(buffer_view)) {
458 img->buffer_view = buffer_view->valueint;
459 }
460 }
461
462
463 cJSON *samplers = cJSON_GetObjectItemCaseSensitive(root,"samplers");
464 doc->sampler_count = cJSON_GetArraySize(samplers);
465 doc->samplers = calloc(doc->sampler_count, sizeof(GLTFSampler));
466 for (int i = 0; i < doc->sampler_count; i++)
467 {
468 cJSON * n = cJSON_GetArrayItem(samplers, i);
469
470 GLTFSampler * sampler = &doc->samplers[i];
471
472
473 cJSON *magFilter = cJSON_GetObjectItemCaseSensitive(n,"magFilter");
474 if (cJSON_IsNumber(magFilter)) {
475 sampler->mag_filter = magFilter->valueint;
476 }
477 cJSON *minFilter = cJSON_GetObjectItemCaseSensitive(n,"minFilter");
478 if (cJSON_IsNumber(minFilter)) {
479 sampler->min_filter = minFilter->valueint;
480 }
481 cJSON *wrapS = cJSON_GetObjectItemCaseSensitive(n,"wrapS");
482 if (cJSON_IsNumber(wrapS)) {
483 sampler->wrap_s = wrapS->valueint;
484 }
485
486 cJSON *wrapT = cJSON_GetObjectItemCaseSensitive(n,"wrapT");
487 if (cJSON_IsNumber(wrapT)) {
488 sampler->wrap_t = wrapT->valueint;
489 }
490 cJSON *name = cJSON_GetObjectItemCaseSensitive(n,"name");
491 if (cJSON_IsString(name))
492 {
493 strncpy(sampler->name, name->valuestring, 254);
494 sampler->name[255] = '\0';
495 }
496
497 }
498
499
500 cJSON *nodes = cJSON_GetObjectItemCaseSensitive(root,"nodes");
501 // check to see if extras exists for static / dynamic
502 doc->node_count = cJSON_GetArraySize(nodes);
503 doc->nodes = calloc(doc->node_count, sizeof(MeshNode));
504
505 for (int i=0; i<doc->node_count; i++) {
506 cJSON *n = cJSON_GetArrayItem(nodes,i);
507 MeshNode *dst = &doc->nodes[i];
508
509 dst->parent = -1;
510 dst->mesh = -1;
511 dst->skin = -1;
512
513 cJSON *name = cJSON_GetObjectItemCaseSensitive(n,"name");
514 if (cJSON_IsString(name)) strncpy(dst->name, name->valuestring, sizeof(dst->name)-1);
515
516 cJSON *mesh = cJSON_GetObjectItemCaseSensitive(n,"mesh");
517 if (cJSON_IsNumber(mesh)) dst->mesh = mesh->valueint;
518
519 cJSON *skin = cJSON_GetObjectItemCaseSensitive(n,"skin");
520 if (cJSON_IsNumber(skin)) dst->skin = skin->valueint;
521
522 json_get_vec3(n,"translation", &dst->translation, (float[3]){0,0,0});
523 json_get_vec4(n,"rotation", &dst->rotation, (float[4]){0,0,0,1});
524 json_get_vec3(n,"scale", &dst->scale, (float[3]){1,1,1});
525
526 cJSON *children = cJSON_GetObjectItemCaseSensitive(n,"children");
527 if (children) {
528 int cc = cJSON_GetArraySize(children);
529 dst->child_count = cc;
530 for (int ci=0; ci<cc; ci++) {
531 dst->children[ci] = cJSON_GetArrayItem(children,ci)->valueint;
532 doc->nodes[dst->children[ci]].parent = i;
533 }
534 }
535
536 cJSON *extras = cJSON_GetObjectItemCaseSensitive(n,"extras");
537 if (extras){
538 // check for static or dynamic
539
540 cJSON * mesh_mode = cJSON_GetObjectItemCaseSensitive(extras, "mesh_mode");
541 if (mesh_mode)
542 {
543 if (strcmp(mesh_mode->valuestring, "dynamic") == 0)
544 {
545 dst->static_mesh = false;
546
547 }
548 else
549 {
550 dst->static_mesh = true;
551
552 }
553
554 }
555 else
556 {
557 dst->static_mesh = true;
558 }
559 cJSON * physics_mode= cJSON_GetObjectItemCaseSensitive(extras, "physics_type");
560 if (physics_mode)
561 {
562 dst->physics_mode = physics_mode->valueint;
563 if (physics_mode->valueint >= 1)
564 {
565 dst->static_mesh = false;
566 }
567 else
568 {
569 dst->physics_mode = 0;
570 dst->static_mesh = true;
571 }
572 }
573 else
574 {
575 dst->physics_mode = false;
576 dst->static_mesh = true;
577 }
578 cJSON * collision_type = cJSON_GetObjectItemCaseSensitive(extras, "collision_type");
579 if (collision_type)
580 {
581 dst->collision_type = collision_type->valueint;
582 }
583 else
584 {
586 }
587
588
589 } else {
590 dst->static_mesh = true;
591 dst->physics_mode = false;
593 }
594 }
595
596 cJSON *skins = cJSON_GetObjectItemCaseSensitive(root,"skins");
597 doc->skin_count = cJSON_GetArraySize(skins);
598 doc->skins = calloc(doc->skin_count, sizeof(GLTFSkin));
599
600 for (int i=0; i<doc->skin_count; i++) {
601 cJSON *s = cJSON_GetArrayItem(skins,i);
602 GLTFSkin *dst = &doc->skins[i];
603
604 cJSON *joints = cJSON_GetObjectItemCaseSensitive(s,"joints");
605 int jc = cJSON_GetArraySize(joints);
606 dst->joint_count = jc;
607 dst->joints = calloc(jc,sizeof(int));
608 for (int ji=0; ji<jc; ji++)
609 dst->joints[ji] = cJSON_GetArrayItem(joints,ji)->valueint;
610
611 cJSON *ibm = cJSON_GetObjectItemCaseSensitive(s,"inverseBindMatrices");
612 if (cJSON_IsNumber(ibm)) {
613 dst->ibm_accessor = ibm->valueint;
614 }
615 cJSON * name = cJSON_GetObjectItemCaseSensitive(s, "name");
616 if (cJSON_IsString(name)){
617 strncpy(dst->name, name->valuestring, 62);
618 dst->name[63] = '\0';
619 } else {
620 sprintf(dst->name, "default");
621 }
622
623 }
624
625 cJSON *animations = cJSON_GetObjectItemCaseSensitive(root, "animations");
626 doc->animation_count = cJSON_GetArraySize(animations);
627 doc->animations = calloc(doc->animation_count, sizeof(GLTFAnimation));
628
629 for (int ai = 0; ai < doc->animation_count; ai++) {
630 cJSON *a = cJSON_GetArrayItem(animations, ai);
631 GLTFAnimation *dst = &doc->animations[ai];
632
633 cJSON *name = cJSON_GetObjectItemCaseSensitive(a, "name");
634 if (cJSON_IsString(name)) strncpy(dst->name, name->valuestring, sizeof(dst->name)-1);
635
636 cJSON *samplers = cJSON_GetObjectItemCaseSensitive(a, "samplers");
637 dst->sampler_count = cJSON_GetArraySize(samplers);
638 dst->samplers = calloc(dst->sampler_count, sizeof(GLTFAnimationSampler));
639 for (int si=0; si < dst->sampler_count; si++) {
640 cJSON *s = cJSON_GetArrayItem(samplers, si);
641 dst->samplers[si].input = json_get_int(s, "input", -1);
642 dst->samplers[si].output = json_get_int(s, "output", -1);
643
644 const char *interp = json_get_str(s, "interpolation");
645 if (!interp || strcmp(interp,"LINEAR")==0) dst->samplers[si].interpolation = 0;
646 else if (strcmp(interp,"STEP")==0) dst->samplers[si].interpolation = 1;
647 else if (strcmp(interp,"CUBICSPLINE")==0) dst->samplers[si].interpolation = 2;
648 }
649
650 cJSON *channels = cJSON_GetObjectItemCaseSensitive(a, "channels");
651 dst->channel_count = cJSON_GetArraySize(channels);
652 dst->channels = calloc(dst->channel_count, sizeof(GLTFAnimationChannel));
653 for (int ci=0; ci < dst->channel_count; ci++) {
654 cJSON *c = cJSON_GetArrayItem(channels, ci);
655 dst->channels[ci].sampler = json_get_int(c, "sampler", -1);
656
657 cJSON *target = cJSON_GetObjectItemCaseSensitive(c, "target");
658 if (target) {
659 dst->channels[ci].target_node = json_get_int(target,"node",-1);
660
661 const char *path = json_get_str(target,"path");
662 if (strcmp(path,"translation")==0) dst->channels[ci].path = TARGET_TRANSLATION;
663 else if (strcmp(path,"rotation")==0) dst->channels[ci].path = TARGET_ROTATION;
664 else if (strcmp(path,"scale")==0) dst->channels[ci].path = TARGET_SCALE;
665 else if (strcmp(path,"weights")==0) dst->channels[ci].path = TARGET_WEIGHTS;
666 }
667 }
668 }
669
670
671
672
673
674
675
676
677 char dir[512]; strcpy(dir, gltfPath);
678 for (int i=(int)strlen(dir)-1; i>=0; --i){ if (dir[i]=='/'||dir[i]=='\\'){ dir[i+1]='\0'; break; } }
679
680 for (int bi=0; bi<doc->bufferCount; bi++){
681 if (!doc->buffers[bi].uri) { /* TODO: handle embedded base64 */ continue; }
682 char full[1024]; snprintf(full, sizeof(full), "%s%s", dir, doc->buffers[bi].uri);
683 // doc->buffers[bi].data = load_bin_file(full, doc->buffers[bi].byteLength);
684 // doc->buffers[bi].data = load_bin_file(doc->buffers[bi].uri, doc->buffers[bi].byteLength);
685 doc->buffers[bi].data = load_bin_file(full, doc->buffers[bi].byteLength);
686 if (!doc->buffers[bi].data) { printf("NO DATA AT %s\n", full); cJSON_Delete(root); free(json); return 0; }
687 }
688
689 cJSON_Delete(root);
690 free(json);
691 return 1;
692}
693static unsigned char* accessor_base_ptr(GLTFDoc *doc, const GLTFAccessor *acc) {
694 if (acc->bufferView < 0) return NULL;
695 const GLTFBufferView *v = &doc->views[acc->bufferView];
696 const GLTFBuffer *b = &doc->buffers[v->buffer];
697 size_t offset = (size_t)v->byteOffset + (size_t)acc->byteOffset;
698 return b->data + offset;
699}
700
701static const unsigned char *accessor_elem_ptr(const GLTFDoc *doc, const GLTFAccessor *acc, int index) {
702 if (acc->bufferView < 0) return NULL;
703 const GLTFBufferView *view = &doc->views[acc->bufferView];
704 const GLTFBuffer *buf = &doc->buffers[view->buffer];
705 size_t base_off = (size_t)(view->byteOffset) + (size_t)(acc->byteOffset);
706 int comps = comp_count(acc->type);
707 int csize = comp_size(acc->componentType);
708 int tight = comps * csize;
709 int stride = view->byteStride ? view->byteStride : tight;
710 return buf->data + base_off + (size_t)index * stride;
711}
712
713static void fetch_vec3f(const GLTFDoc *doc, const GLTFAccessor *acc, int idx, float out[3]) {
714 const unsigned char *p = accessor_elem_ptr(doc, acc, idx);
715 if (!p) { out[0]=out[1]=out[2]=0.0f; return; }
716
717 int comp = acc->componentType;
718 int comps = comp_count(acc->type);
719
720 if (comp == 5126 && comps >= 3) {
721 const float *f = (const float*)p;
722 out[0] = f[0];
723 out[1] = f[1];
724 out[2] = f[2];
725 return;
726 }
727
728 if (comp == 5123 && comps >= 3) {
729 const unsigned short *s = (const unsigned short*)p;
730 bool normalized = false;
731 if (normalized) {
732 out[0] = s[0] / 65535.0f;
733 out[1] = s[1] / 65535.0f;
734 out[2] = s[2] / 65535.0f;
735 } else {
736 out[0] = (float)s[0];
737 out[1] = (float)s[1];
738 out[2] = (float)s[2];
739 }
740 return;
741 }
742
743 if (comp == 5121 && comps >= 3) {
744 const unsigned char *c = (const unsigned char*)p;
745 bool normalized = false;
746 if (normalized) {
747 out[0] = c[0] / 255.0f;
748 out[1] = c[1] / 255.0f;
749 out[2] = c[2] / 255.0f;
750 } else {
751 out[0] = (float)c[0];
752 out[1] = (float)c[1];
753 out[2] = (float)c[2];
754 }
755 return;
756 }
757
758 if (comp == 5122 && comps >= 3) {
759 const short *s = (const short*)p;
760 out[0] = (float)s[0];
761 out[1] = (float)s[1];
762 out[2] = (float)s[2];
763 return;
764 }
765 if (comp == 5125 && comps >= 3) {
766 const unsigned int *u = (const unsigned int*)p;
767 out[0] = (float)u[0];
768 out[1] = (float)u[1];
769 out[2] = (float)u[2];
770 return;
771 }
772
773 out[0]=out[1]=out[2]=0.0f;
774}
775static void fetch_vec4(const GLTFDoc *doc, const GLTFAccessor *acc, int idx, vec4 * out) {
776 const unsigned char *p = accessor_elem_ptr(doc, acc, idx);
777 if (!p) { out->x=out->y=out->z=out->w=0.0f; return; }
778
779 int comp = acc->componentType;
780 int comps = comp_count(acc->type);
781
782 if (comp == 5126 && comps >= 3) {
783 const float *f = (const float*)p;
784 out->x = f[0];
785 out->y = f[1];
786 out->z = f[2];
787 out->w = f[3];
788 return;
789 }
790
791 if (comp == 5123 && comps >= 3) {
792 const unsigned short *s = (const unsigned short*)p;
793 bool normalized = false;
794 if (normalized) {
795 out->x = s[0] / 65535.0f;
796 out->y = s[1] / 65535.0f;
797 out->z = s[2] / 65535.0f;
798 out->w = s[3] / 65535.0f;
799 } else {
800 out->x = (float)s[0];
801 out->y = (float)s[1];
802 out->z = (float)s[2];
803 out->w = (float)s[3];
804 }
805 return;
806 }
807
808 if (comp == 5121 && comps >= 3) {
809 const unsigned char *c = (const unsigned char*)p;
810 bool normalized = false;
811 if (normalized) {
812 out->x = c[0] / 255.0f;
813 out->y = c[1] / 255.0f;
814 out->z = c[2] / 255.0f;
815 out->w = c[3] / 255.0f;
816 } else {
817 out->x = (float)c[0];
818 out->y = (float)c[1];
819 out->z = (float)c[2];
820 out->w = (float)c[3];
821 }
822 return;
823 }
824
825 if (comp == 5122 && comps >= 3) {
826 const short *s = (const short*)p;
827 out->x = (float)s[0];
828 out->y = (float)s[1];
829 out->z = (float)s[2];
830 out->w = (float)s[3];
831 return;
832 }
833 if (comp == 5125 && comps >= 3) {
834 const unsigned int *u = (const unsigned int*)p;
835 out->x = (float)u[0];
836 out->y = (float)u[1];
837 out->z = (float)u[2];
838 out->w = (float)u[3];
839 return;
840 }
841
842 out->x=out->y=out->z=out->w=0.0f;
843}
844static void fetch_vec2f(GLTFDoc *doc, const GLTFAccessor *acc, int idx, float out[2]) {
845 const unsigned char* p = (const unsigned char*)accessor_elem_ptr(doc, acc, idx);
846 if (acc->componentType == 5126) {
847 const float *f = (const float*)p;
848 out[0]=f[0]; out[1]=f[1];
849 } else {
850 out[0]=out[1]=0.0f;
851 }
852}
853void fetch_joints4_from_accessor(const GLTFDoc *doc, const GLTFAccessor *acc, int vertexIndex, int out_joints[4]) {
854 out_joints[0]=out_joints[1]=out_joints[2]=out_joints[3] = 0;
855
856 if (!acc) return;
857 int elems = comp_count(acc->type);
858 if (elems < 1) return;
859
860 GLTFBufferView *view = &doc->views[acc->bufferView];
861 uint8_t *base = accessor_base_ptr(doc, acc);
862
863 size_t comp_sz = comp_size(acc->componentType);
864 size_t elem_sz = comp_sz * elems;
865 size_t stride = (view->byteStride && view->byteStride > 0) ? view->byteStride : elem_sz;
866
867 uint8_t *src = base + (size_t)vertexIndex * stride;
868 for (int k = 0; k < elems && k < 4; ++k) {
869 if (acc->componentType == 5121) {
870 out_joints[k] = *(uint8_t *)(src + k * comp_sz);
871 } else if (acc->componentType == 5123) {
872 out_joints[k] = *(uint16_t *)(src + k * comp_sz);
873 } else if (acc->componentType == 5125) {
874 out_joints[k] = *(uint32_t *)(src + k * comp_sz);
875 }
876 }
877}
878
879void fetch_weights4_from_accessor(const GLTFDoc *doc, const GLTFAccessor *acc, int vertexIndex, float out_weights[4]) {
880 out_weights[0]=out_weights[1]=out_weights[2]=out_weights[3]=0.0f;
881 if (!acc) return;
882 int elems = comp_count(acc->type);
883 if (elems < 1) return;
884
885 GLTFBufferView *view = &doc->views[acc->bufferView];
886 uint8_t *base = accessor_base_ptr(doc, acc);
887
888 size_t comp_sz = comp_size(acc->componentType);
889 size_t elem_sz = comp_sz * elems;
890 size_t stride = (view->byteStride && view->byteStride > 0) ? view->byteStride : elem_sz;
891
892 uint8_t *src = base + (size_t)vertexIndex * stride;
893
894 for (int k = 0; k < elems && k < 4; ++k) {
895 if (acc->componentType == 5126) {
896 float v;
897 memcpy(&v, src + k*4, 4);
898 out_weights[k] = v;
899 } else if (acc->componentType == 5121) {
900 uint8_t v = src[k];
901 out_weights[k] = (float)v / 255.0f;
902 } else if (acc->componentType == 5123) {
903 uint16_t v; memcpy(&v, src + k*2, 2);
904 out_weights[k] = (float)v / 65535.0f;
905 } else {
906 out_weights[k] = 0.0f;
907 }
908 }
909 float s = out_weights[0] + out_weights[1] + out_weights[2] + out_weights[3];
910 if (s > 0.0f && fabsf(s - 1.0f) > 1e-6f) {
911 out_weights[0] /= s; out_weights[1] /= s; out_weights[2] /= s; out_weights[3] /= s;
912 }
913}
914
915static unsigned int fetch_index(GLTFDoc *doc, const GLTFAccessor *acc, int idx) {
916 const unsigned char* p = (const unsigned char*)accessor_elem_ptr(doc, acc, idx);
917 switch (acc->componentType) {
918 case 5125: return *(const unsigned int*)p;
919 case 5123: return *(const unsigned short*)p;
920 case 5121: return *(const unsigned char*)p;
921 default: return 0;
922 }
923}
924
925
927 return (mat4){
928 1, 0, 0, 0,
929 0, 0, -1, 0,
930 0, 1, 0, 0,
931 0, 0, 0, 1
932 };
933}
934static void compute_node_globals_recursive(GLTFDoc *doc, int idx, const mat4 *parent_global) {
935 MeshNode *node = &doc->nodes[idx];
936 mat4 local = compose_trs_from_mesh_node(node);
937
938 if (parent_global == NULL) {
939 mat4 basis = gltf_to_engine_basis();
940 node->local_matrix = local;
941 node->global_matrix = local;
942 } else {
943 node->local_matrix = local;
944 node->global_matrix = m4_mul(*parent_global, local);
945 }
946
947 for (int i = 0; i < node->child_count; ++i) {
949 }
950}
951
953 for (int i = 0; i < doc->node_count; ++i) {
954 if (doc->nodes[i].parent == -1) {
955 compute_node_globals_recursive(doc, i, NULL);
956 }
957 }
958}
959static void bbox_of_points(vec3 *pts, int n, vec3 *minp, vec3 *maxp) {
960 vec3 mn = { INFINITY, INFINITY, INFINITY}, mx = { -INFINITY, -INFINITY, -INFINITY};
961 for (int i=0;i<n;i++){
962 mn.x = fminf(mn.x, pts[i].x); mx.x = fmaxf(mx.x, pts[i].x);
963 mn.y = fminf(mn.y, pts[i].y); mx.y = fmaxf(mx.y, pts[i].y);
964 mn.z = fminf(mn.z, pts[i].z); mx.z = fmaxf(mx.z, pts[i].z);
965 }
966 *minp = mn; *maxp = mx;
967}
968static float extent(vec3 a, vec3 b){ return fmaxf(0.0f, b.x-a.x) + 0.0f; }
969
970static vec3 apply_mapping_to_point(const vec3 p, const int perm[3], const int sign[3]) {
971 float src[3] = { p.x, p.y, p.z };
972 vec3 out;
973 out.x = sign[0] * src[perm[0]];
974 out.y = sign[1] * src[perm[1]];
975 out.z = sign[2] * src[perm[2]];
976 return out;
977}
978
979static const int perms[6][3] = {
980 {0,1,2}, {0,2,1}, {1,0,2}, {1,2,0}, {2,0,1}, {2,1,0}
981};
982
983int detect_best_axis_mapping(GLTFDoc *doc, GLTFAccessor *posAcc, MeshNode *node, int out_perm[3], int out_sign[3]) {
984 int count = posAcc->count;
985 int maxSample = 1500;
986 int step = 1 + (count / maxSample);
987 int n = 0;
988 vec3 *pts = malloc(sizeof(vec3) * ((count+step-1)/step));
989 for (int i=0; i<count; i+=step) {
990 float tmp[3]; fetch_vec3f(doc, posAcc, i, tmp);
991 vec3 w = mat4_mul_point(node->global_matrix, (vec3){tmp[0],tmp[1],tmp[2]});
992 pts[n++] = w;
993 }
994
995 float bestScore = 1e30f;
996 int best_p = 0, best_s = 0;
997 for (int pi=0; pi<6; ++pi) {
998 for (int s=0; s<8; ++s) {
999 int sign[3] = { (s&1)?-1:1, (s&2)?-1:1, (s&4)?-1:1 };
1000
1001 vec3 mn = { INFINITY, INFINITY, INFINITY}, mx = { -INFINITY, -INFINITY, -INFINITY};
1002 for (int k=0; k<n; ++k) {
1003 vec3 q = apply_mapping_to_point(pts[k], perms[pi], sign);
1004 if (q.x < mn.x) mn.x = q.x; if (q.x > mx.x) mx.x = q.x;
1005 if (q.y < mn.y) mn.y = q.y; if (q.y > mx.y) mx.y = q.y;
1006 if (q.z < mn.z) mn.z = q.z; if (q.z > mx.z) mx.z = q.z;
1007 }
1008 float extX = mx.x - mn.x;
1009
1010 float extY = mx.y - mn.y;
1011 float extZ = mx.z - mn.z;
1012 if (extX < 0.001f || extY < 0.001f) continue;
1013 float ratio = fabsf(extX - extY) / fmaxf(extX, extY);
1014 float zpen = extZ / fmaxf(1.0f, fmaxf(extX, extY));
1015 float score = ratio + 0.4f * zpen;
1016 if (score < bestScore) { bestScore = score; best_p = pi; best_s = s; }
1017 }
1018 }
1019
1020 free(pts);
1021 out_perm[0] = perms[best_p][0]; out_perm[1] = perms[best_p][1]; out_perm[2] = perms[best_p][2];
1022 out_sign[0] = (best_s & 1) ? -1 : 1;
1023 out_sign[1] = (best_s & 2) ? -1 : 1;
1024 out_sign[2] = (best_s & 4) ? -1 : 1;
1025 return 1;
1026}
1027
1028static float *expand_accessor(const GLTFAccessor *acc, int *out_elem_count, GLTFDoc * doc) {
1029
1030 int elem_count = 1;
1031 if (strcmp(acc->type, "SCALAR") == 0) {
1032 elem_count = 1;
1033 } else if (strcmp(acc->type, "VEC2") == 0){
1034
1035 elem_count = 2;
1036 } else if (strcmp(acc->type, "VEC3") == 0){
1037
1038 elem_count = 3;
1039 } else if (strcmp(acc->type, "VEC4") == 0){
1040
1041 elem_count = 4;
1042 } else if (strcmp(acc->type, "MAT3") == 0){
1043
1044 elem_count = 9;
1045 } else if (strcmp(acc->type, "MAT4") == 0){
1046
1047 elem_count = 16;
1048 }
1049 if (out_elem_count) *out_elem_count = elem_count;
1050
1051 GLTFBufferView *view = &doc->views[acc->bufferView];
1052 GLTFBuffer *buf = &doc->buffers[view->buffer];
1053
1054 unsigned char *src = buf->data + view->byteOffset + acc->byteOffset;
1055
1056 float *out = malloc(sizeof(float) * acc->count * elem_count);
1057
1058 for (int i = 0; i < acc->count; i++) {
1059 memcpy(&out[i * elem_count],
1060 src + i * (view->byteStride ? view->byteStride : elem_count * sizeof(float)),
1061 elem_count * sizeof(float));
1062 }
1063 return out;
1064}
1065
1066static AnimationSampler expand_sampler(const GLTFAccessor *input_acc, const GLTFAccessor *output_acc, int interpolation, GLTFDoc * doc) {
1068 s.count = input_acc->count;
1069 s.times = expand_accessor(input_acc, NULL, doc);
1070 s.values = expand_accessor(output_acc, &s.elem_count, doc);
1071 s.interpolation = interpolation;
1072 return s;
1073}
1074
1075static Animation build_animation(const char *name, GLTFAnimation * animation, GLTFDoc * doc) {
1076 Animation anim;
1077
1078 char * dot = strchr(name, '.');
1079 if (dot != NULL){
1080 *dot = '\0';
1081 }
1082 strncpy(anim.name, name, 63);
1083 anim.name[63] = '\0';
1084
1085 anim.sampler_count = animation->sampler_count;
1086 anim.samplers = malloc(sizeof(AnimationSampler) * animation->sampler_count);
1087 for (int i = 0; i < animation->sampler_count; i++) {
1088 anim.samplers[i] = expand_sampler(&doc->accessors[animation->samplers[i].input], &doc->accessors[animation->samplers[i].output], animation->samplers[i].interpolation, doc);
1089 }
1090
1091 anim.channel_count = animation->channel_count;
1092 anim.channels = malloc(sizeof(GLTFAnimationChannel) * animation->channel_count);
1093 memcpy(anim.channels, animation->channels, sizeof(GLTFAnimationChannel) * animation->channel_count);
1094
1095 return anim;
1096}
1097void remap_joints_to_skin(const GLTFSkin *skin, const int raw[4], int out[4]) {
1098 for (int k = 0; k < 4; ++k) {
1099 int nodeIdx = raw[k];
1100 int found = -1;
1101 for (int j = 0; j < skin->joint_count; ++j) {
1102 if (skin->joints[j] == nodeIdx) { found = j; break; }
1103 }
1104 out[k] = (found >= 0) ? found : 0;
1105 }
1106}
1107vec3 map_x_z_neg_y(vec3 p){ return (vec3){ p.x, p.z, p.y }; }
1108vec3 map_x_negz_y(vec3 p){ return (vec3){ p.x, -p.z, p.y }; }
1109
1110
1111
1112
1113int load_gltf_texture(GLTFTexture * texture, GLTFSampler * samplers, GLTFImage * gltf_images, bool normal)
1114{
1115
1116 int idx = -1;
1117
1118 if (texture->source != -1)
1119 {
1120
1121 GLTFImage * dimage = &gltf_images[texture->source];
1122 GLint min_filter;
1123 GLint mag_filter;
1124 GLint wrap_s;
1125 GLint wrap_t;
1126
1127 if (texture->sampler != -1)
1128 {
1129 GLTFSampler * dsampler = &samplers[texture->sampler];
1130 min_filter = dsampler->min_filter;
1131 mag_filter = dsampler->mag_filter;
1132 wrap_s = dsampler->wrap_s;
1133 wrap_t = dsampler->wrap_t;
1134 }
1135 else
1136 {
1137
1138 min_filter = GL_LINEAR_MIPMAP_LINEAR;
1139 mag_filter = GL_LINEAR;
1140 wrap_s = GL_REPEAT;
1141 wrap_t = GL_REPEAT;
1142
1143 }
1144
1145 idx = add_image_to_registry(dimage->uri, min_filter, mag_filter, wrap_s, wrap_t, (normal) ? 0 : 1);
1146 if (idx == -1) printf("AAAA\n");
1147 Image * images = CAST_VEC(GLOBALS.images, Image);
1148 Image * img = &images[idx];
1149 strncpy(img->name, dimage->name, 254);
1150 printf("LOADING: %s\n", img->name);
1151 img->name[255] = '\0';
1152 strncpy(img->mime_type, dimage->mime_type, 254);
1153 img->mime_type[255] = '\0';
1154 strncpy(img->path, dimage->uri, 254);
1155 img->path[255] = '\0';
1156 img->min_filter = min_filter;
1157 img->mag_filter = mag_filter;
1158 img->wrap_s = wrap_s;
1159 img->wrap_t = wrap_t;
1160 img->buf = NULL;
1161
1162
1163 }
1164
1165 return idx;
1166
1167
1168
1169}
1170
1171
1172void apply_static_mesh_to_children(MeshNode * mns, Mesh * meshes, MeshNode * mn, bool static_mesh)
1173{
1174 mn->static_mesh = static_mesh;
1175 if (mn->mesh != -1)
1176 {
1177 meshes[mn->mesh].static_mesh = static_mesh;
1178 }
1179 for (int i = 0; i < mn->child_count; i++)
1180 {
1181 apply_static_mesh_to_children(mns, meshes, &mns[mn->children[i]], static_mesh);
1182 }
1183
1184}
1185
1187{
1188
1189 AABB aabb;
1190 aabb.min_x = INFINITY;
1191 aabb.min_y = INFINITY;
1192 aabb.min_z = INFINITY;
1193 aabb.max_x = -INFINITY;
1194 aabb.max_y = -INFINITY;
1195 aabb.max_z = -INFINITY;
1196
1197 if (mn->mesh != -1)
1198 {
1199 Mesh * m = &meshes[mn->mesh];
1200 mat4 inv;
1201 m4_inverse((float*)&inv, (float*)&mn->global_matrix);
1202 AABB current = m->aabb;
1203
1204 if (current.min_x < aabb.min_x) aabb.min_x = current.min_x;
1205 if (current.min_y < aabb.min_y) aabb.min_y = current.min_y;
1206 if (current.min_z < aabb.min_z) aabb.min_z = current.min_z;
1207 if (current.max_x > aabb.max_x) aabb.max_x = current.max_x;
1208 if (current.max_y > aabb.max_y) aabb.max_y = current.max_y;
1209 if (current.max_z > aabb.max_z) aabb.max_z = current.max_z;
1210 }
1211
1212 for (int i = 0; i < mn->child_count; i++)
1213 {
1214 AABB ch = determine_aabb_of_children(mns, meshes, &mns[mn->children[i]]);
1215 if (ch.min_x < aabb.min_x) aabb.min_x = ch.min_x;
1216 if (ch.min_y < aabb.min_y) aabb.min_y = ch.min_y;
1217 if (ch.min_z < aabb.min_z) aabb.min_z = ch.min_z;
1218 if (ch.max_x > aabb.max_x) aabb.max_x = ch.max_x;
1219 if (ch.max_y > aabb.max_y) aabb.max_y = ch.max_y;
1220 if (ch.max_z > aabb.max_z) aabb.max_z = ch.max_z;
1221 }
1222
1223 return aabb;
1224
1225}
1226
1227
1229{
1230
1231 if (strcmp(mn->name, "Root") == 0)
1232 {
1233
1234 return mn;
1235
1236 }
1237
1238 if (mn->parent != -1)
1239 {
1240
1241 return find_root_node_armature(mns, &mns[mn->parent]);
1242 }
1243
1244 return NULL;
1245
1246}
1247
1248
1249
1250void load_gltf(const char *gltf_path)
1251{
1252 GLTFDoc doc = {0};
1253 char prefix[256];
1254 strcpy(prefix, gltf_path);
1255 char * last = strrchr(prefix, '/');
1256 if (last != NULL)
1257 {
1258 last[1] = '\0';
1259 }
1260 if (!parse_gltf_json(gltf_path, prefix, &doc)) {
1261 return;
1262 }
1263
1265 int * mesh_indices = NULL; size_t mesh_indices_count = 0; size_t mesh_indices_capacity = 0;
1266 int * node_indices = NULL; size_t node_indices_count = 0; size_t node_indices_capacity = 0;
1267 Asset * asset = vector_expand(&GLOBALS.assets, 1);
1268 init_vector(&asset->mesh_indices, 0, sizeof(int));
1269
1270
1271
1272
1273 asset->aabb.min_x = INFINITY;
1274 asset->aabb.min_y = INFINITY;
1275 asset->aabb.min_z = INFINITY;
1276 asset->aabb.max_x = -INFINITY;
1277 asset->aabb.max_y = -INFINITY;
1278 asset->aabb.max_z = -INFINITY;
1279 size_t start_material_count = GLOBALS.materials.count;
1280 GLTFMaterial * mats = doc.materials;
1281 GLTFTexture * textures = doc.textures;
1282 GLTFSampler * samplers = doc.samplers;
1283 GLTFImage * images = doc.images;
1284
1285 for (int i = 0; i < doc.material_count; i++)
1286 {
1287 GLTFMaterial * material = &mats[i];
1289 mat->diffuse_tex = -1;
1290 mat->arm_tex = -1;
1291 mat->mr_tex = -1;
1292 mat->ao_tex = -1;
1293 mat->normal_tex = -1;
1294 mat->fwd_shader = mats[i].fwd_shader;
1295 mat->gbuffer_shader = mats[i].gbuffer_shader;
1296 mat->override_arm = false;
1297
1298 if (material->base_color_tex != -1)
1299 {
1300
1301 GLTFTexture * diffuse = &textures[material->base_color_tex];
1302 int d = load_gltf_texture(diffuse, samplers, images, false);
1303 mat->diffuse_tex = d;
1304
1305 }
1306 else
1307 {
1308 mat->diffuse_tex = -1;
1309 }
1310 mat->kd = (vec4){
1311 material->base_color_factor[0],
1312 material->base_color_factor[1],
1313 material->base_color_factor[2],
1314 material->base_color_factor[3]
1315 };
1316 if (material->normal_tex != -1)
1317 {
1318
1319 GLTFTexture * normal = &textures[material->normal_tex];
1320 int d = load_gltf_texture(normal, samplers, images, true);
1321 mat->normal_tex = d;
1322
1323 }
1324 else
1325 {
1326 mat->normal_tex = -1;
1327 }
1328 mat->normal_scale = material->normal_scale;
1329
1330 mat->arm_tex = -1;
1331 // arm
1332 if (material->metallic_roughness_tex == material->occlusion_tex)
1333 {
1334 if (material->metallic_roughness_tex != -1)
1335 {
1336 GLTFTexture * arm = &textures[material->metallic_roughness_tex];
1337 int a = load_gltf_texture(arm, samplers, images, true);
1338 mat->arm_tex = a;
1339 }
1340 }
1341 else
1342 {
1343
1344 if (material->occlusion_tex != -1)
1345 {
1346
1347 GLTFTexture * occ = &textures[material->occlusion_tex];
1348 int o = load_gltf_texture(occ, samplers, images, true);
1349 mat->arm_tex = o;
1350 }
1351
1352 if (material->metallic_roughness_tex != -1)
1353 {
1354 GLTFTexture * mr = &textures[material->metallic_roughness_tex];
1355 int mr_tex = load_gltf_texture(mr, samplers, images, true);
1356 mat->arm_tex = mr_tex;
1357 }
1358
1359 }
1360 if (mat->arm_tex == -1)
1361 {
1362 mat->arm_tex = DEFAULT_ARM;
1363 }
1364
1365 mat->ao_strength = material->occlusion_strength;
1366 mat->metallic = material->metallic_factor;
1367 mat->roughness = material->roughness_factor;
1368 if (material->emissive_tex != -1)
1369 {
1370
1371 GLTFTexture * emissive = &textures[material->emissive_tex];
1372 int d = load_gltf_texture(emissive, samplers, images, false);
1373 mat->emissive_tex = d;
1374
1375 }
1376 else
1377 {
1378 mat->emissive_tex = -1;
1379 }
1380
1381 mat->ke = (vec4){
1382 material->emissive_factor[0],
1383 material->emissive_factor[1],
1384 material->emissive_factor[2],
1385 0.0
1386 };
1387 mat->ka = (vec4){0,0,0,0};
1388 mat->ks = (vec4){0,0,0,0};
1389
1390
1391 strncpy(mat->name, material->name, 62);
1392 mat->name[63] = '\0';
1393 mat->alpha_mode = material->alpha_mode;
1394 mat->alpha_cutoff = material->alpha_cutoff;
1395 mat->double_sided = material->double_sided;
1396 memcpy(mat->absorption_coefficients, material->absorption_coefficients, sizeof(float) * AUDIO_NUM_BANDS);
1397 memcpy(mat->scattering_coefficients, material->scattering_coefficients, sizeof(float) * AUDIO_NUM_BANDS);
1398
1399 mat->emissive_strength = material->emissive_strength;
1400 mat->override_transparent = material->override_transparent;
1401
1402 }
1403
1404 Mesh * meshes = CAST_VEC(GLOBALS.meshes, Mesh);
1406 size_t starting_mesh = GLOBALS.meshes.count;
1407 int root = 0;
1408 Vector roots;
1409 init_vector(&roots, 0, sizeof(size_t));
1410 for (int ni = 0; ni < doc.node_count; ++ni) {
1411 MeshNode *node = &doc.nodes[ni];
1412 if (node->parent == -1) {
1413 // root node, set root for the asset
1414 root = ni;
1415 size_t * r = vector_expand(&roots, 1);
1416 *r = ni;
1417 }
1418 if (node->mesh < 0 || node->mesh >= doc.meshCount) continue;
1419
1420
1421 bool valid = true;
1422 for (int i = 0; i < mesh_indices_count; i++) {
1423 if (node->mesh == mesh_indices[i]) valid = false;
1424 }
1425 if (!valid) continue;
1426
1427 GLTFMesh *mesh = &doc.meshes[node->mesh];
1428
1429 if (mesh_indices_count >= mesh_indices_capacity){
1430 mesh_indices_capacity = (mesh_indices_capacity + 2) * 2;
1431 mesh_indices = realloc(mesh_indices, sizeof(int) * mesh_indices_capacity);
1432 }
1433 mesh_indices[mesh_indices_count++] = node->mesh;
1434
1435
1436 Mesh * m = vector_expand(&GLOBALS.meshes, 1);
1437 m->static_mesh = node->static_mesh;
1438 int * new_mesh = vector_expand(&asset->mesh_indices, 1);
1439 *new_mesh = GLOBALS.meshes.count-1;
1440 m->id = GLOBALS.meshes.count-1;
1442 init_vector(&m->tris, 0, sizeof(MeshFace));
1443 init_vector(&m->vertices, 0, sizeof(Point));
1444 init_vector(&m->submeshes, 0, sizeof(SubMesh));
1445 strcpy(m->name, node->name);
1446 node->mesh = GLOBALS.meshes.count-1;
1447 m->aabb.min_x = INFINITY;
1448 m->aabb.min_y = INFINITY;
1449 m->aabb.min_z = INFINITY;
1450 m->aabb.max_x = -INFINITY;
1451 m->aabb.max_y = -INFINITY;
1452 m->aabb.max_z = -INFINITY;
1453 size_t current_mesh = GLOBALS.meshes.count-1;
1454 node->mesh = current_mesh;
1455
1456
1457
1458
1459 for (int p = 0; p < mesh->primCount; ++p) {
1460 GLTFPrimitive *prim = &mesh->prims[p];
1461 if (prim->position < 0 || prim->indices < 0) continue;
1462
1463 GLTFAccessor *aPos = &doc.accessors[prim->position];
1464 GLTFAccessor *aIdx = &doc.accessors[prim->indices];
1465 GLTFAccessor *aNrm = (prim->normal >= 0) ? &doc.accessors[prim->normal] : NULL;
1466 GLTFAccessor *aTan = (prim->tangent >= 0) ? &doc.accessors[prim->tangent] : NULL;
1467 GLTFAccessor *aUV = (prim->texcoord0 >= 0) ? &doc.accessors[prim->texcoord0] : NULL;
1468 GLTFAccessor *accJ = (prim->joints0 >= 0) ? &doc.accessors[prim->joints0] : NULL;
1469 GLTFAccessor *accW = (prim->weights0 >= 0) ? &doc.accessors[prim->weights0] : NULL;
1470 GLTFSkin *skin = (node->skin >= 0) ? &doc.skins[node->skin] : NULL;
1471 SubMesh * sm = vector_expand(&m->submeshes, 1);
1472
1473 if (prim->material == -1)
1474 {
1475 sm->material = 0;
1476 }
1477 else
1478 {
1479 sm->material = prim->material + start_material_count;
1480 }
1481 sm->lm_offset = 0;
1482 sm->draw_offset = 0;
1483 sm->first_vertex = m->vertices.count;
1484
1485 int vertex_count = aPos->count;
1486 // loop through and emit vertices
1487 for (int i = 0; i < vertex_count; i++)
1488 {
1489
1490 float p0[3];
1491 fetch_vec3f(&doc, aPos, i, p0);
1492 vec3 V0 = (vec3){p0[0],p0[1],p0[2]};
1493
1494 vec3 N0 = {0,0,1};
1495 vec4 T0 = {1,0,0,1};
1496
1497 float uv0f[2]={0,0};
1498 if (aUV)
1499 {
1500 fetch_vec2f(&doc, aUV, i, uv0f);
1501 }
1502
1503 vec2 UV = {uv0f[0],uv0f[1]};
1504 int rawJ0[4] = {0}, rawJ1[4] = {0}, rawJ2[4] = {0};
1505 float W0[4] = {1}, W1[4] ={1}, W2[4] = {1};
1506 int J0[4] = {0}, J1[4] = {0}, J2[4] = {0};
1507
1508 if (prim->joints0 >= 0 && prim->weights0 >= 0 && node->skin >= 0)
1509 {
1510
1511 V0 = (vec3){p0[0],p0[1],p0[2]};
1512 fetch_joints4_from_accessor(&doc, accJ, i, rawJ0);
1513 fetch_weights4_from_accessor(&doc, accW, i, W0);
1514 remap_joints_to_skin(skin, rawJ0, J0);
1515 rawJ0[0] += 1;
1516 rawJ0[1] += 1;
1517 rawJ0[2] += 1;
1518 rawJ0[3] += 1;
1519
1520 if (aNrm) {
1521
1522 float nn0[3]; fetch_vec3f(&doc, aNrm, i, nn0);
1523 N0 = (vec3){nn0[0], nn0[1], nn0[2]};
1524 N0 = vec3_normalize(N0);
1525
1526 }
1527 if (aTan)
1528 {
1529
1530 vec4 tt0; fetch_vec4(&doc, aTan, i, &tt0);
1532 T0.w = tt0.w;
1533
1534 }
1535
1536 }
1537 else
1538 {
1539
1540 rawJ0[0] = 0;
1541 rawJ0[1] = 0;
1542 rawJ0[2] = 0;
1543 rawJ0[3] = 0;
1544 W0[0] = 1;
1545 W0[1] = 0;
1546 W0[2] = 0;
1547 W0[3] = 0;
1548
1549 if (aNrm)
1550 {
1551
1552 float nn0[3]; fetch_vec3f(&doc, aNrm, i, nn0);
1553 vec3 n0 = {nn0[0], nn0[1], nn0[2]};
1554
1555 N0 = vec3_normalize(n0);
1556
1557 }
1558 if (aTan)
1559 {
1560
1561 vec4 tt0; fetch_vec4(&doc, aTan, i, &tt0);
1562
1564 T0.w = tt0.w;
1565
1566 }
1567 }
1568
1569
1570 Point * pt = vector_expand(&m->vertices, 1);
1571 mat4 inv;
1572 m4_inverse((float*)&inv, (float*)&node->global_matrix);
1573 pt->pos = V0;
1574 if (V0.x < m->aabb.min_x) m->aabb.min_x = V0.x;
1575 if (V0.y < m->aabb.min_y) m->aabb.min_y = V0.y;
1576 if (V0.z < m->aabb.min_z) m->aabb.min_z = V0.z;
1577 if (V0.x > m->aabb.max_x) m->aabb.max_x = V0.x;
1578 if (V0.y > m->aabb.max_y) m->aabb.max_y = V0.y;
1579 if (V0.z > m->aabb.max_z) m->aabb.max_z = V0.z;
1580 pt->normal = N0;
1581 pt->tangent = T0;
1582 pt->uv = UV;
1583 pt->joints = (ivec4){rawJ0[0], rawJ0[1], rawJ0[2], rawJ0[3]};
1584 pt->weights = (vec4){W0[0], W0[1], W0[2], W0[3]};
1585
1586 }
1587 sm->vertex_count = vertex_count;
1588
1589
1590
1591 Point * pts = CAST_VEC(m->vertices, Point);
1592
1593
1594 int sm_cnt = 0;
1595 sm->first_index = m->tris.count * 3;
1596 // loop through and emit indices
1597 int indexCount = aIdx->count;
1598 for (int i = 0; i < indexCount; i += 3) {
1599
1600 unsigned int i0 = fetch_index(&doc, aIdx, i+0);
1601 unsigned int i1 = fetch_index(&doc, aIdx, i+1);
1602 unsigned int i2 = fetch_index(&doc, aIdx, i+2);
1603
1604 MeshFace * tri = vector_expand(&m->tris, 1);
1605 tri->indices[0] = i0 + sm->first_vertex;
1606 tri->indices[1] = i1 + sm->first_vertex;
1607 tri->indices[2] = i2 + sm->first_vertex;
1608 tri->material_id = sm->material;
1609 tri->normal = compute_tri_normal(pts[tri->indices[0]].pos, pts[tri->indices[1]].pos, pts[tri->indices[2]].pos);
1610 sm_cnt += 3;
1611
1612
1613 }
1614 sm->index_count = sm_cnt;
1615 }
1617 }
1618
1619
1620 strcpy(asset->path, gltf_path);
1621 asset->asset_id = GLOBALS.assets.count-1;
1622 MeshNode * root_node = &doc.nodes[root];
1623
1624
1625 meshes = CAST_VEC(GLOBALS.meshes, Mesh);
1626 size_t * root_nodes = CAST_VEC(roots, size_t);
1627 for (int i = 0; i < roots.count; i++)
1628 {
1629 MeshNode * root = &doc.nodes[root_nodes[i]];
1630 if (root->mesh != -1)
1631 {
1632 meshes[root->mesh].static_mesh = root->static_mesh;
1633 }
1634
1635 for (int j = 0; j < root->child_count; j++)
1636 {
1637
1638 apply_static_mesh_to_children(doc.nodes, meshes, &doc.nodes[root->children[j]], root->static_mesh);
1639
1640 }
1641 }
1642
1643 for (int i = starting_mesh; i < GLOBALS.meshes.count; i++)
1644 {
1645
1646 Mesh * m = &meshes[i];
1647 init_mesh(m);
1648 if (asset->aabb.min_x > m->aabb.min_x) asset->aabb.min_x = m->aabb.min_x;
1649 if (asset->aabb.min_y > m->aabb.min_y) asset->aabb.min_y = m->aabb.min_y;
1650 if (asset->aabb.min_z > m->aabb.min_z) asset->aabb.min_z = m->aabb.min_z;
1651 if (asset->aabb.max_x < m->aabb.max_x) asset->aabb.max_x = m->aabb.max_x;
1652 if (asset->aabb.max_y < m->aabb.max_y) asset->aabb.max_y = m->aabb.max_y;
1653 if (asset->aabb.max_z < m->aabb.max_z) asset->aabb.max_z = m->aabb.max_z;
1654 }
1656
1657 asset->animation_count = doc.animation_count;
1658 if (doc.animation_count > 0) {
1659
1660 asset->animations = calloc(asset->animation_count, sizeof(Animation));
1661 for (int i = 0; i < doc.animation_count; i++) {
1662
1663 asset->animations[i].samplers = NULL;
1664 asset->animations[i].channels = NULL;
1665 asset->animations[i] = build_animation(doc.animations[i].name, &doc.animations[i], &doc);
1666 asset->animations[i].asset_id = GLOBALS.assets.count-1;
1667 }
1668 }
1669 else
1670 {
1671 asset->animations = NULL;
1672 }
1673
1674 asset->skin_count = doc.skin_count;
1675 if (doc.skin_count > 0)
1676 {
1677 for (int i = 0; i < doc.skin_count; i++) {
1678
1679 GLTFSkin * skin = &doc.skins[i];
1680
1681
1682 GLTFAccessor *acc = &doc.accessors[skin->ibm_accessor];
1683 GLTFBufferView *view = &doc.views[acc->bufferView];
1684
1685 uint8_t *base = doc.buffers[view->buffer].data;
1686
1687 uint8_t *data = base + view->byteOffset + acc->byteOffset;
1688
1689 size_t stride = view->byteStride ? view->byteStride : sizeof(float) * 16;
1690
1691 skin->inverse_bind = malloc(sizeof(mat4) * skin->joint_count);
1692
1693 for (int j = 0; j < skin->joint_count; j++) {
1694 memcpy(&skin->inverse_bind[j], data + j * stride, sizeof(mat4));
1695 }
1696 }
1697 asset->skins = calloc(asset->skin_count, sizeof(GLTFSkin));
1698 for (int i = 0; i < doc.skin_count; i++) {
1699 asset->skins[i].joint_count = doc.skins[i].joint_count;
1700 if (doc.skins[i].joint_count > 0)
1701 {
1702
1703 asset->skins[i].joints = malloc(sizeof(int) * asset->skins[i].joint_count);
1704 memcpy(asset->skins[i].joints, doc.skins[i].joints, sizeof(int) * asset->skins[i].joint_count);
1705 asset->skins[i].inverse_bind = malloc(sizeof(mat4) * asset->skins[i].joint_count);
1706 memcpy(asset->skins[i].inverse_bind, doc.skins[i].inverse_bind, sizeof(mat4) * asset->skins[i].joint_count);
1707 asset->skins[i].final_mat = calloc(doc.skins[i].joint_count, sizeof(mat4));
1708 }
1709 else
1710 {
1711 asset->skins[i].joints = NULL;
1712 asset->skins[i].inverse_bind = NULL;
1713 asset->skins[i].final_mat = NULL;
1714 }
1715 strcpy(asset->skins[i].name, doc.skins[i].name);
1716 GLTFSkin * skin = &asset->skins[i];
1717 printf("SKIN: %s\n", skin->name);
1718
1719 for (int a = 0; a < asset->animation_count; a++) {
1720
1721 Animation * anim = &asset->animations[a];
1722 for (int ch = 0; ch < anim->channel_count; ch++){
1723
1724 GLTFAnimationChannel * channel = &anim->channels[ch];
1725 bool match_found = false;
1726 for (int j = 0; j < skin->joint_count; j++){
1727
1728 if (channel->target_node == skin->joints[j]){
1729
1731 skin->animation_indices[skin->animation_indices_count++] = a;
1732 match_found = true;
1733 break;
1734 } else {
1735 printf("MAX ANIMATIONS REACHED\n");
1736 break;
1737 }
1738
1739 }
1740 if (match_found) break;
1741 }
1742 if (match_found) break;
1743 }
1744 }
1745 char idle_anim_name[128];
1746 sprintf(idle_anim_name, "%s_Idle", asset->skins[i].name);
1747
1748 }
1749
1750
1751 }
1752 else
1753 {
1754 asset->skins = NULL;
1755 }
1756 asset->node_count = doc.node_count;
1757 if (asset->node_count > 0)
1758 {
1759
1760 asset->nodes = calloc(asset->node_count, sizeof(MeshNode));
1761 for (int i = 0; i < doc.node_count; i++) {
1762 asset->nodes[i] = doc.nodes[i];
1763 asset->nodes[i].id = i;
1764 asset->nodes[i].mesh= doc.nodes[i].mesh;
1765 asset->nodes[i].uv_map = NULL;
1766 asset->nodes[i].ent = NULL;
1767
1768 asset->nodes[i].pc = NULL;
1769
1770 asset->nodes[i].aabb = determine_aabb_of_children(doc.nodes, meshes, &doc.nodes[i]);
1771 calculate_aabb_extents(&asset->nodes[i].aabb);
1772
1773 strcpy(asset->nodes[i].name, doc.nodes[i].name);
1774 asset->nodes[i].child_count = doc.nodes[i].child_count;
1775 if (doc.nodes[i].child_count > 0){
1776
1777 memcpy(asset->nodes[i].children, doc.nodes[i].children, sizeof(int) * doc.nodes[i].child_count);
1778
1779 } else {
1780 asset->nodes[i].child_count = 0;
1781 }
1782 strcpy(asset->nodes[i].name, doc.nodes[i].name);
1783
1784 }
1785
1786 }
1787 else
1788 {
1789 asset->nodes = NULL;
1790 }
1791
1792
1793 for (int i = 0; i < doc.bufferCount; i++)
1794 {
1795 if (doc.buffers[i].data) free(doc.buffers[i].data);
1796 if (doc.buffers[i].uri) free(doc.buffers[i].uri);
1797 }
1798 if (doc.buffers) free(doc.buffers);
1799 for (int i = 0; i < doc.meshCount; i++)
1800 {
1801 if (doc.meshes[i].prims) free(doc.meshes[i].prims);
1802 }
1803 if (doc.meshes) free(doc.meshes);
1804 if (doc.accessors) free(doc.accessors);
1805 if (doc.materials) free(doc.materials);
1806 if (doc.nodes) free(doc.nodes);
1807 if (doc.views) free(doc.views);
1808 for (int i = 0; i < doc.skin_count; i++)
1809 {
1810 if (doc.skins[i].final_mat) free(doc.skins[i].final_mat);
1811 if (doc.skins[i].inverse_bind) free(doc.skins[i].inverse_bind);
1812 if (doc.skins[i].joints) free(doc.skins[i].joints);
1813 }
1814 if (doc.skins) free(doc.skins);
1815 if (doc.animations) {
1816 for (int i = 0; i < doc.animation_count; i++){
1817
1818 if (doc.animations[i].channels) free(doc.animations[i].channels);
1819 if (doc.animations[i].samplers) free(doc.animations[i].samplers);
1820
1821 }
1822 free(doc.animations);
1823 }
1824 if (mesh_indices) free(mesh_indices);
1825 if (node_indices) free(node_indices);
1826 if (roots.buffer) free(roots.buffer);
1827}
in vec2 UV
uniform int material
Definition dynamic.frag:215
uniform uint n
Engine specific types and defines.
size_t first_vertex
The first Point in Mesh.vertices that this SubMesh refers to.
int joint_count
The amount of joints.
GLTFSkin * skins
#define GBUFFER_VERSIONS
Maxmimum gbuffer shader branches.
bool override_transparent
AlphaMode alpha_mode
int image_count
Vector mesh_nodes
MeshNodes.
size_t lm_offset
The starting index in LIGHTMAP_DATA that this SubMesh points to.
AnimationInterpolation interpolation
char name[256]
GLint min_filter
Refer to OpenGL texture loading.
int accessorCount
size_t animation_count
float scattering_coefficients[6]
GLTFMesh * meshes
float metallic_factor
int asset_id
The ID into Globals.assets.
size_t skin_count
float base_color_factor[4]
int sampler_count
size_t index_count
The amount of indices that this SubMesh refers to: Mesh.tris -> MeshFace.indices.
MeshNode * nodes
Vector meshes
Meshes.
int animation_indices_count
The amount of Animation indices.
@ ALPHA_MASK
@ ALPHA_OPAQUE
@ ALPHA_BLEND
int animation_indices[256]
Animation indices into Asset.
AnimationSampler * samplers
int material_count
GLint wrap_t
Refer to OpenGL texture loading.
float emissive_factor[3]
char uri[256]
GLTFAnimation * animations
float occlusion_strength
GLTFMaterial * materials
char name[256]
mat4 * inverse_bind
The inverse_bind that is computed on load_gltf().
GLTFTexture * textures
int texture_count
AABB aabb
AABB over each MeshNode for this Asset.
Globals GLOBALS
Engine Globals.
Definition main.c:310
size_t first_index
The first index that this SubMesh refers to (Mesh.tris count * 3).
int * joints
The joints for skeletal animating.
@ TARGET_ROTATION
@ TARGET_SCALE
@ TARGET_TRANSLATION
@ TARGET_WEIGHTS
int metallic_roughness_tex
GLint wrap_s
Refer to OpenGL texture loading.
char name[256]
The name of the skin from load.
GLTFSampler * samplers
GLTFSkin * skins
#define UBERSHADER_VERSIONS
Maxmimum main shader brances.
Vector mesh_indices
int - Indices into Globals.meshes which indicate what Meshes are within this Asset.
GLTFAnimationSampler * samplers
GLint mag_filter
Refer to OpenGL texture loading.
size_t material
The Material.
GLTFPrimitive * prims
int bufferCount
Vector images
Images.
MeshNode * nodes
unsigned char * buf
If available, the raw bytes of the Image.
char name[256]
The name of the Image file.
Vector materials
Materials.
#define MAX_ANIMATION_INDICES
The maximum amount of animation indices per GLTFSkin.
GLTFBufferView * views
mat4 * final_mat
The transformation after update_skin_matrices().
Vector assets
Assets.
float absorption_coefficients[6]
GLTFAnimationChannel * channels
char name[256]
Name of the shader.
size_t node_count
Animation * animations
char mime_type[256]
float emissive_strength
int ibm_accessor
Which GLTFAccessor this refers to.
char path[256]
The path to the Asset.
GLTFAccessor * accessors
unsigned char * data
size_t vertex_count
The amount of Points that this SubMesh refers to.
GLTFBuffer * buffers
GLTFAnimationChannel * channels
char name[256]
char path[256]
The path to the Image.
size_t draw_offset
Currently the same index as SubMesh.lm_offset.
float roughness_factor
char mime_type[256]
Unused, refer to GLTF spec.
int animation_count
GLTFImage * images
The structure of an Skeletatal Animation loaded in from GLTFAnimation.
Engine-side sampler version of GLTFAnimationSampler with the field allocated.
An Asset after it is loaded in from file into Globals.assets.
The accessors of a GLTF file.
The GLTF structure of an Animation.
The channels of an Animation.
The individual interpolation of an Animation.
The raw bytes of a GLTF file.
The views of a GLTF file.
The entire GLTF after it is parsed via load_gltf().
The Image before it is processed.
The structure for Materials when loaded in from file.
The Meshes of a GLTF file.
The primitives of a GLTF file.
The sampler for the Image before it is processed.
The structure of an Skeletatal Animation loaded in from GLTFAnimation.
The GLTFTexture before it is processed.
Where Material textures are saved upon loading from file.
Sections of Meshes that are divided based on Material for batching and DrawCommand ordering purposes.
mat4 compose_trs_from_mesh_node(MeshNode *mn)
char * load_text_file(const char *path)
Definition gltf.c:44
vec3 apply_mapping_to_point(const vec3 p, const int perm[3], const int sign[3])
Definition gltf.c:970
unsigned char * accessor_base_ptr(GLTFDoc *doc, const GLTFAccessor *acc)
Definition gltf.c:693
int str_eq(const char *a, const char *b)
Definition gltf.c:70
int comp_count(const char *type)
Definition gltf.c:19
void fetch_vec3f(const GLTFDoc *doc, const GLTFAccessor *acc, int idx, float out[3])
Definition gltf.c:713
int parse_gltf_json(const char *gltfPath, const char *prefix, GLTFDoc *doc)
Definition gltf.c:313
AnimationSampler expand_sampler(const GLTFAccessor *input_acc, const GLTFAccessor *output_acc, int interpolation, GLTFDoc *doc)
Definition gltf.c:1066
int detect_best_axis_mapping(GLTFDoc *doc, GLTFAccessor *posAcc, MeshNode *node, int out_perm[3], int out_sign[3])
Definition gltf.c:983
vec3 map_x_z_neg_y(vec3 p)
Definition gltf.c:1107
void parse_gltf_materials(cJSON *root, GLTFDoc *doc)
Definition gltf.c:132
void fetch_vec2f(GLTFDoc *doc, const GLTFAccessor *acc, int idx, float out[2])
Definition gltf.c:844
void bbox_of_points(vec3 *pts, int n, vec3 *minp, vec3 *maxp)
Definition gltf.c:959
void compute_all_node_globals(GLTFDoc *doc)
Definition gltf.c:952
int comp_size(int componentType)
Definition gltf.c:29
void apply_static_mesh_to_children(MeshNode *mns, Mesh *meshes, MeshNode *mn, bool static_mesh)
Definition gltf.c:1172
const unsigned char * accessor_elem_ptr(const GLTFDoc *doc, const GLTFAccessor *acc, int index)
Definition gltf.c:701
int json_get_tex_index(cJSON *parent, const char *name)
Definition gltf.c:123
MeshNode * find_root_node_armature(MeshNode *mns, MeshNode *mn)
Definition gltf.c:1228
void remap_joints_to_skin(const GLTFSkin *skin, const int raw[4], int out[4])
Definition gltf.c:1097
void fetch_weights4_from_accessor(const GLTFDoc *doc, const GLTFAccessor *acc, int vertexIndex, float out_weights[4])
Definition gltf.c:879
int load_gltf_texture(GLTFTexture *texture, GLTFSampler *samplers, GLTFImage *gltf_images, bool normal)
Definition gltf.c:1113
void fetch_joints4_from_accessor(const GLTFDoc *doc, const GLTFAccessor *acc, int vertexIndex, int out_joints[4])
Definition gltf.c:853
void fetch_vec4(const GLTFDoc *doc, const GLTFAccessor *acc, int idx, vec4 *out)
Definition gltf.c:775
void load_gltf(const char *gltf_path)
Loads a GLTF.
Definition gltf.c:1250
float * expand_accessor(const GLTFAccessor *acc, int *out_elem_count, GLTFDoc *doc)
Definition gltf.c:1028
Animation build_animation(const char *name, GLTFAnimation *animation, GLTFDoc *doc)
Definition gltf.c:1075
vec3 map_x_negz_y(vec3 p)
Definition gltf.c:1108
float extent(vec3 a, vec3 b)
Definition gltf.c:968
const int perms[6][3]
Definition gltf.c:979
void json_get_float_array(cJSON *parent, const char *name, float *out, int count, const float *defaults)
Definition gltf.c:111
unsigned int fetch_index(GLTFDoc *doc, const GLTFAccessor *acc, int idx)
Definition gltf.c:915
int json_get_int(cJSON *obj, const char *key, int defv)
Definition gltf.c:72
mat4 gltf_to_engine_basis()
Definition gltf.c:926
const char * json_get_str(cJSON *obj, const char *key)
Definition gltf.c:77
void json_get_vec4(cJSON *obj, const char *key, vec4 *out, const float def[3])
Definition gltf.c:94
void compute_node_globals_recursive(GLTFDoc *doc, int idx, const mat4 *parent_global)
Definition gltf.c:934
AABB determine_aabb_of_children(MeshNode *mns, Mesh *meshes, MeshNode *mn)
Definition gltf.c:1186
void json_get_vec3(cJSON *obj, const char *key, vec3 *out, const float def[3])
Definition gltf.c:81
unsigned char * load_bin_file(const char *path, int expectedLen)
Definition gltf.c:56
#define AUDIO_NUM_BANDS
The amount of bands to use for audio probe baking.
@ COL_HULL
Incremental hull generates a ConvexHull which is used for collision tests.
@ COL_TRIANGLE
The triangle BVH is generated for this mesh and triangle tests are performed on it.
int fwd_shader
The corresponding forward rendering shader branch in DYNAMIC_SHADER.
size_t id
The ID inside of Globals.mesh_nodes.
vec3 translation
int skin
The GLTFSkin it controls.
float normal_scale
Unused - Used to determine how much of the texture normal to use.
sampler2D emissive_tex
char name[256]
The Material path.
Entity * ent
The Entity this MeshNode refers to (all children point to the same Entity as parent).
PhysicsComponent * pc
The physics controller initialized based on data from this MeshNode.
bool override_transparent
If we are overriding transparency of this Material.
CollisionType collision_type
The type of collision to apply for the PhysicsComponent that may not have been created yet.
char name[256]
The name generated on loading from file.
vec4 ka
Ambient.
int children[128]
The children to this node, a global index into Globals.mesh_nodes.
mat4 local_matrix
float emissive_strength
vec4 ke
Emissive.
int mesh
The Mesh it references.
int parent
The parent to this node, a global index into Globals.mesh_nodes.
PhysicsType physics_mode
The type of physics to apply for the PhysicsComponent that may not have been created yet.
bool override_arm
If we override the ARM texture and bind a dummy instead.
int child_count
The amount of children.
sampler2D arm_tex
AABB aabb
The AABB of the MeshNode and its children.
sampler2D normal_tex
UVMapping * uv_map
The mapping between MeshNodes and UVIslands for uv lightmapping.
vec4 ks
Specular (unused).
bool static_mesh
If this mesh is static (DrawArrays) or dynamic (DrawElements), used to indicate Lightmap status.
int gbuffer_shader
The corresponding gbuffer rendering shader branch in DEPTH_PRE_PASS_SHADER or DEPTH_PRE_PASS_SHADER_M...
float alpha_cutoff
Used to discard transparent Materials.
float absorption_coefficients[6]
How much audio is absorbed when hitting this Material.
vec4 kd
Diffuse.
float scattering_coefficients[6]
How much audio specularly reflects when hitting this Material.
The Materials parsed in from scene files that determine rendering pipeline setup, uploads,...
MeshNodes that describe the position of Meshes, GLTF nodes for GLTFAnimations, or hold references to ...
void init_mesh(Mesh *mesh)
Initializes a static or dynamic Mesh.
Definition init.c:68
Important globals for the entire engine and initialization functions that are mainly called on engine...
size_t id
The ID into Globals.meshes.
size_t asset_id
The Asset ID into Globals.assets.
bool static_mesh
This Mesh is static and must create a BVH or if not it must perform incremental_hull.
AABB aabb
The AABB of the mesh.
Vector submeshes
The SubMeshes split via Materials.
char name[256]
The Mesh name assigned on load.
Vector tris
The MeshFaces.
Vector vertices
The Points.
A Mesh with geometry data that is either initialized as static or dynamic and split into SubMeshes.
int add_image_to_registry(char *filename, GLint min_filter, GLint mag_filter, GLint wrap_s, GLint wrap_t, bool sRGB)
Loads an adds an image to Globals.images.
Definition load.c:292
Saves and loads various files that store engine data.
ShaderProgram DEPTH_PRE_PASS_SHADER[1]
render/depth_pre_pass.vert render/depth_pre_pass.frag
Definition main.c:116
int DEFAULT_ARM
Definition main.c:198
ShaderProgram DYNAMIC_SHADER[32]
render/dynamic.vert render/dynamic.frag
Definition main.c:114
vec3 vec3_normalize(vec3 v)
Definition mathf.h:46
mat4 m4_mul(mat4 a, mat4 b)
Definition mathf.h:401
bool m4_inverse(float out[16], const float m[16])
Definition mathf.h:164
uniform mat4 view
Definition shadow.vert:16
float w
Definition types.h:13
vec3 normal
Definition types.h:284
float z
Definition types.h:13
vec4 weights
Definition types.h:227
int material_id
Definition types.h:285
float x
Definition types.h:13
float x
Definition types.h:12
float max_z
Definition types.h:39
float min_x
Definition types.h:37
ivec4 joints
Definition types.h:226
float max_y
Definition types.h:38
float y
Definition types.h:13
size_t indices[3]
Definition types.h:283
float y
Definition types.h:12
vec3 pos
Definition types.h:220
float z
Definition types.h:12
size_t count
Definition types.h:209
float min_z
Definition types.h:39
float min_y
Definition types.h:38
vec4 tangent
Definition types.h:222
void * buffer
Definition types.h:210
vec2 uv
Definition types.h:224
vec3 normal
Definition types.h:221
float max_x
Definition types.h:37
Definition types.h:218
Definition types.h:16
Definition types.h:21
Definition types.h:11
Definition types.h:12
Definition types.h:13
void init_vector(Vector *v, size_t i, size_t type_size)
Definition utilities.c:74
void calculate_aabb_extents(AABB *aabb)
Definition utilities.c:298
vec4 perm(vec4 x)
Definition utilities.c:139
void * vector_expand(Vector *v, size_t i)
Definition utilities.c:49
vec4 vec3_to_vec4(vec3 v)
Definition utilities.h:166
#define CAST_VEC(vec, type)
Definition utilities.h:134
vec3 mat4_mul_point(mat4 m, vec3 v)
Definition utilities.h:313
vec3 compute_tri_normal(vec3 a, vec3 b, vec3 c)
Definition utilities.h:254
vec3 vec4_to_vec3(vec4 v)
Definition utilities.h:165