Coverage Report

Created: 2026-11-16 06:29

next uncovered line (L), next uncovered region (R), next uncovered branch (B)
/src/tinygltf/tiny_gltf_v3.h
Line
Count
Source
1
/*
2
 * tiny_gltf_v3.h - C-first glTF 2.0 loader and writer API (v3)
3
 *
4
 * The MIT License (MIT)
5
 * Copyright (c) 2026 - Present: Syoyo Fujita
6
 *
7
 * Permission is hereby granted, free of charge, to any person obtaining a copy
8
 * of this software and associated documentation files (the "Software"), to deal
9
 * in the Software without restriction, including without limitation the rights
10
 * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
11
 * copies of the Software, and to permit persons to whom the Software is
12
 * furnished to do so, subject to the following conditions:
13
 *
14
 * The above copyright notice and this permission notice shall be included in
15
 * all copies or substantial portions of the Software.
16
 *
17
 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
18
 * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
19
 * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
20
 * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
21
 * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
22
 * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
23
 * THE SOFTWARE.
24
 */
25
26
/*
27
 * Version: v3.0.0-alpha
28
 *
29
 * Ground-up C-centric API rewrite of tinygltf.
30
 * The default runtime implementation lives in tiny_gltf_v3.c.
31
 *
32
 * Key differences from v2:
33
 *   - Pure C POD structs (no STL containers in public API)
34
 *   - Arena-based memory management (single tg3_model_free() frees all)
35
 *   - Filesystem and image decoding OFF by default (opt-in)
36
 *   - Structured error reporting via tg3_error_stack
37
 *   - Streaming parse/write via callbacks
38
 *   - No RTTI, no exceptions required
39
 *   - C++20 coroutine facade (optional)
40
 *
41
 * Security considerations (read before processing untrusted glTF):
42
 *
43
 *   1. External URI loading. When TINYGLTF3_ENABLE_FS is defined and no custom
44
 *      tg3_fs_callbacks are supplied, the parser opens external buffer/image
45
 *      URIs through the libc default fopen(). The parser rejects URIs that
46
 *      contain '..' segments, leading '/' or '\\', Windows drive prefixes
47
 *      (e.g. "C:"), or NUL bytes — but it does NOT chroot or canonicalize the
48
 *      result. Production callers SHOULD provide a tg3_fs_callbacks with a
49
 *      read_file callback that confines reads to a known directory (e.g. via
50
 *      openat(AT_FDCWD, path, O_NOFOLLOW) plus a realpath() prefix check) when
51
 *      the input glTF is attacker-controlled.
52
 *
53
 *   2. Index validation. Many glTF fields are integer indices into model
54
 *      arrays (accessor.bufferView, primitive.material, scene.nodes[], etc.).
55
 *      With opts.validate_indices = 1 (the default) the parser rejects every
56
 *      out-of-range index after the structural parse and returns
57
 *      TG3_ERR_INVALID_INDEX. Set opts.validate_indices = 0 only when you
58
 *      need to round-trip raw or extension data and have your own validator.
59
 *
60
 *   3. Image decoding. The parser does not decode image bytes by default.
61
 *      Set opts.images_as_is = 1 (already the safe default for untrusted
62
 *      input) to skip any decoder and store raw bytes only.
63
 *
64
 *   4. Memory budget. The arena is capped at TINYGLTF3_MAX_MEMORY_BYTES
65
 *      (1 GB by default; configurable per-parse via tg3_memory_config).
66
 *      The parser returns TG3_ERR_OUT_OF_MEMORY rather than overcommitting.
67
 *
68
 *   5. Error message lifetime. Error strings on tg3_error_stack are
69
 *      arena-allocated and remain valid until tg3_model_free() is called.
70
 *      Read or copy them BEFORE freeing the model.
71
 */
72
73
#ifndef TINY_GLTF_V3_H_
74
#define TINY_GLTF_V3_H_
75
76
/* ======================================================================
77
 * Section 2: Configuration Macros
78
 * ====================================================================== */
79
80
/* Legacy single-translation-unit build mode: define in ONE C or C++ file */
81
/* #define TINYGLTF3_IMPLEMENTATION */
82
83
/* Opt-in features (OFF by default) */
84
/* #define TINYGLTF3_ENABLE_FS */
85
/* #define TINYGLTF3_ENABLE_STB_IMAGE */
86
/* #define TINYGLTF3_ENABLE_STB_IMAGE_WRITE */
87
88
/* Opt-out */
89
/* #define TINYGLTF3_NO_IMAGE_DECODE */
90
91
/* C++20 coroutines (auto-detected, or force) */
92
/* #define TINYGLTF3_ENABLE_COROUTINES */
93
94
/* SIMD for JSON parsing (forwarded to tinygltf_json.h) */
95
/* #define TINYGLTF3_JSON_SIMD_SSE2 */
96
/* #define TINYGLTF3_JSON_SIMD_AVX2 */
97
/* #define TINYGLTF3_JSON_SIMD_NEON */
98
99
/* Memory limits */
100
#ifndef TINYGLTF3_MAX_MEMORY_BYTES
101
28
#define TINYGLTF3_MAX_MEMORY_BYTES (1ULL << 30) /* 1 GB */
102
#endif
103
104
#ifndef TINYGLTF3_MAX_NESTING_DEPTH
105
14
#define TINYGLTF3_MAX_NESTING_DEPTH 512
106
#endif
107
108
#ifndef TINYGLTF3_MAX_STRING_LENGTH
109
14
#define TINYGLTF3_MAX_STRING_LENGTH (64 * 1024 * 1024) /* 64 MB */
110
#endif
111
112
/* Linkage control */
113
#ifndef TINYGLTF3_API
114
#define TINYGLTF3_API
115
#endif
116
117
/* Assert override */
118
#ifndef TINYGLTF3_ASSERT
119
#ifndef TINYGLTF3_NO_STDLIB
120
#include <assert.h>
121
#define TINYGLTF3_ASSERT(x) assert(x)
122
#else
123
#define TINYGLTF3_ASSERT(x) ((void)(x))
124
#endif
125
#endif
126
127
/* ======================================================================
128
 * Section 3: C Includes
129
 * ====================================================================== */
130
131
#include <stddef.h>
132
#include <stdint.h>
133
#include <stdarg.h>
134
#ifndef TINYGLTF3_NO_STDLIB
135
#include <string.h>
136
#include <stdlib.h>
137
#endif
138
139
#ifndef TINYGLTF3_MALLOC
140
#ifndef TINYGLTF3_NO_STDLIB
141
314
#define TINYGLTF3_MALLOC(sz) malloc(sz)
142
#else
143
#define TINYGLTF3_MALLOC(sz) NULL
144
#endif
145
#endif
146
147
#ifndef TINYGLTF3_REALLOC
148
#ifndef TINYGLTF3_NO_STDLIB
149
453
#define TINYGLTF3_REALLOC(ptr, sz) realloc((ptr), (sz))
150
#else
151
#define TINYGLTF3_REALLOC(ptr, sz) NULL
152
#endif
153
#endif
154
155
#ifndef TINYGLTF3_FREE
156
#ifndef TINYGLTF3_NO_STDLIB
157
758
#define TINYGLTF3_FREE(ptr) free(ptr)
158
#else
159
#define TINYGLTF3_FREE(ptr) ((void)(ptr))
160
#endif
161
#endif
162
163
/* ======================================================================
164
 * Section 4: Constants and Enums
165
 * ====================================================================== */
166
167
#ifdef __cplusplus
168
extern "C" {
169
#endif
170
171
/* Primitive modes */
172
#define TG3_MODE_POINTS         0
173
#define TG3_MODE_LINE           1
174
#define TG3_MODE_LINE_LOOP      2
175
#define TG3_MODE_LINE_STRIP     3
176
0
#define TG3_MODE_TRIANGLES      4
177
#define TG3_MODE_TRIANGLE_STRIP 5
178
#define TG3_MODE_TRIANGLE_FAN   6
179
180
/* Component types */
181
0
#define TG3_COMPONENT_TYPE_BYTE           5120
182
0
#define TG3_COMPONENT_TYPE_UNSIGNED_BYTE  5121
183
0
#define TG3_COMPONENT_TYPE_SHORT          5122
184
0
#define TG3_COMPONENT_TYPE_UNSIGNED_SHORT 5123
185
0
#define TG3_COMPONENT_TYPE_INT            5124
186
0
#define TG3_COMPONENT_TYPE_UNSIGNED_INT   5125
187
0
#define TG3_COMPONENT_TYPE_FLOAT          5126
188
0
#define TG3_COMPONENT_TYPE_DOUBLE         5130
189
190
/* Accessor types */
191
0
#define TG3_TYPE_VEC2   2
192
0
#define TG3_TYPE_VEC3   3
193
0
#define TG3_TYPE_VEC4   4
194
0
#define TG3_TYPE_MAT2   (32 + 2)
195
0
#define TG3_TYPE_MAT3   (32 + 3)
196
0
#define TG3_TYPE_MAT4   (32 + 4)
197
0
#define TG3_TYPE_SCALAR (64 + 1)
198
#define TG3_TYPE_VECTOR (64 + 4)
199
#define TG3_TYPE_MATRIX (64 + 16)
200
201
/* Texture filter */
202
0
#define TG3_TEXTURE_FILTER_NEAREST                9728
203
0
#define TG3_TEXTURE_FILTER_LINEAR                 9729
204
0
#define TG3_TEXTURE_FILTER_NEAREST_MIPMAP_NEAREST 9984
205
#define TG3_TEXTURE_FILTER_LINEAR_MIPMAP_NEAREST  9985
206
#define TG3_TEXTURE_FILTER_NEAREST_MIPMAP_LINEAR  9986
207
0
#define TG3_TEXTURE_FILTER_LINEAR_MIPMAP_LINEAR   9987
208
209
/* Texture wrap */
210
0
#define TG3_TEXTURE_WRAP_REPEAT          10497
211
0
#define TG3_TEXTURE_WRAP_CLAMP_TO_EDGE   33071
212
0
#define TG3_TEXTURE_WRAP_MIRRORED_REPEAT 33648
213
214
/* Image format */
215
#define TG3_IMAGE_FORMAT_JPEG 0
216
#define TG3_IMAGE_FORMAT_PNG  1
217
#define TG3_IMAGE_FORMAT_BMP  2
218
#define TG3_IMAGE_FORMAT_GIF  3
219
220
/* Texture format */
221
#define TG3_TEXTURE_FORMAT_ALPHA           6406
222
#define TG3_TEXTURE_FORMAT_RGB             6407
223
#define TG3_TEXTURE_FORMAT_RGBA            6408
224
#define TG3_TEXTURE_FORMAT_LUMINANCE       6409
225
#define TG3_TEXTURE_FORMAT_LUMINANCE_ALPHA 6410
226
227
/* Texture target / type */
228
#define TG3_TEXTURE_TARGET_TEXTURE2D    3553
229
#define TG3_TEXTURE_TYPE_UNSIGNED_BYTE  5121
230
231
/* Buffer targets */
232
0
#define TG3_TARGET_ARRAY_BUFFER         34962
233
0
#define TG3_TARGET_ELEMENT_ARRAY_BUFFER 34963
234
235
/* Sentinel for absent index */
236
#define TG3_INDEX_NONE (-1)
237
238
/* ----------------------------------------------------------------------
239
 * glTF 2.1 support  [TG3_GLTF21_UNSTABLE]
240
 *
241
 * glTF 2.1 is NOT a ratified Khronos specification. Everything marked
242
 * TG3_GLTF21_UNSTABLE (GLB container version 3 with 64-bit lengths,
243
 * `id`, `files`, `thumbnails`, the promoted-extension names below,
244
 * write_glb_64bit) follows a draft and may change incompatibly in any
245
 * release without a version bump. Reading a GLB v3 container pushes a
246
 * TG3_SEVERITY_WARNING.
247
 * ---------------------------------------------------------------------- */
248
#define TG3_GLTF21_UNSTABLE 1
249
250
/* glTF 2.1 promoted extension names [TG3_GLTF21_UNSTABLE] */
251
#define TG3_EXT_TEXTURE_WEBP "EXT_texture_webp"
252
#define TG3_EXT_MATERIALS_EMISSIVE_STRENGTH "KHR_materials_emissive_strength"
253
#define TG3_EXT_MESH_QUANTIZATION "KHR_mesh_quantization"
254
#define TG3_EXT_NODE_VISIBILITY "KHR_node_visibility"
255
256
/* Section check flags */
257
#define TG3_NO_REQUIRE       0x00
258
14
#define TG3_REQUIRE_VERSION  0x01
259
#define TG3_REQUIRE_SCENE    0x02
260
#define TG3_REQUIRE_SCENES   0x04
261
#define TG3_REQUIRE_NODES    0x08
262
#define TG3_REQUIRE_ACCESSORS    0x10
263
#define TG3_REQUIRE_BUFFERS      0x20
264
#define TG3_REQUIRE_BUFFER_VIEWS 0x40
265
#define TG3_REQUIRE_ALL          0x7f
266
267
/* Parse strictness.
268
 *
269
 * Spec-conformance rules (enum values, value ranges, required non-empty
270
 * arrays, ...; see formal/GlTF/Validate.lean for the normative list) are
271
 * reported as TG3_SEVERITY_WARNING under TG3_PERMISSIVE (the default) and as
272
 * TG3_SEVERITY_ERROR (parse fails) under TG3_STRICT.
273
 *
274
 * Memory-safety rules (out-of-range indices and byte ranges, unknown
275
 * component types) are always errors, independent of strictness; they can
276
 * only be disabled through validate_indices / validate_ranges. */
277
typedef enum tg3_strictness {
278
    TG3_PERMISSIVE = 0,
279
    TG3_STRICT     = 1
280
} tg3_strictness;
281
282
/* ======================================================================
283
 * Section 5: Foundation Types
284
 * ====================================================================== */
285
286
typedef struct tg3_str {
287
    const char *data;
288
    uint32_t    len;
289
} tg3_str;
290
291
typedef struct tg3_span_i32 {
292
    const int32_t *data;
293
    uint32_t       count;
294
} tg3_span_i32;
295
296
typedef struct tg3_span_f64 {
297
    const double *data;
298
    uint32_t      count;
299
} tg3_span_f64;
300
301
typedef struct tg3_span_u8 {
302
    const uint8_t *data;
303
    uint64_t       count;
304
} tg3_span_u8;
305
306
typedef struct tg3_str_int_pair {
307
    tg3_str  key;
308
    int32_t  value;
309
} tg3_str_int_pair;
310
311
/* ======================================================================
312
 * Section 6: Allocator Interface
313
 * ====================================================================== */
314
315
typedef struct tg3_allocator {
316
    void *(*alloc)(size_t size, void *user_data);
317
    void *(*realloc)(void *ptr, size_t old_size, size_t new_size, void *user_data);
318
    void  (*free)(void *ptr, size_t size, void *user_data);
319
    void  *user_data;
320
} tg3_allocator;
321
322
/* ======================================================================
323
 * Section 7: Error Reporting
324
 * ====================================================================== */
325
326
typedef enum tg3_severity {
327
    TG3_SEVERITY_INFO    = 0,
328
    TG3_SEVERITY_WARNING = 1,
329
    TG3_SEVERITY_ERROR   = 2
330
} tg3_severity;
331
332
typedef enum tg3_error_code {
333
    TG3_OK = 0,
334
335
    /* I/O errors: 1-9 */
336
    TG3_ERR_FILE_NOT_FOUND     = 1,
337
    TG3_ERR_FILE_READ          = 2,
338
    TG3_ERR_FILE_WRITE         = 3,
339
    TG3_ERR_FILE_TOO_LARGE     = 4,
340
341
    /* JSON errors: 10-19 */
342
    TG3_ERR_JSON_PARSE         = 10,
343
    TG3_ERR_JSON_TYPE_MISMATCH = 11,
344
    TG3_ERR_JSON_MISSING_FIELD = 12,
345
    TG3_ERR_JSON_INVALID_VALUE = 13,
346
347
    /* GLB errors: 20-29 */
348
    TG3_ERR_GLB_INVALID_MAGIC  = 20,
349
    TG3_ERR_GLB_INVALID_VERSION = 21,
350
    TG3_ERR_GLB_INVALID_HEADER = 22,
351
    TG3_ERR_GLB_CHUNK_ERROR    = 23,
352
    TG3_ERR_GLB_SIZE_MISMATCH  = 24,
353
354
    /* Schema / validation errors: 30-49 */
355
    TG3_ERR_MISSING_REQUIRED   = 30,
356
    TG3_ERR_INVALID_INDEX      = 31,
357
    TG3_ERR_INVALID_TYPE       = 32,
358
    TG3_ERR_INVALID_VALUE      = 33,
359
    TG3_ERR_INVALID_ACCESSOR   = 34,
360
    TG3_ERR_INVALID_BUFFER     = 35,
361
    TG3_ERR_INVALID_BUFFER_VIEW = 36,
362
    TG3_ERR_INVALID_IMAGE      = 37,
363
    TG3_ERR_INVALID_MATERIAL   = 38,
364
    TG3_ERR_INVALID_MESH       = 39,
365
    TG3_ERR_INVALID_NODE       = 40,
366
    TG3_ERR_INVALID_ANIMATION  = 41,
367
    TG3_ERR_INVALID_SKIN       = 42,
368
    TG3_ERR_INVALID_CAMERA     = 43,
369
    TG3_ERR_INVALID_SCENE      = 44,
370
    TG3_ERR_BUFFER_SIZE_MISMATCH = 45,
371
372
    /* Resource errors: 50-59 */
373
    TG3_ERR_OUT_OF_MEMORY      = 50,
374
    TG3_ERR_DATA_URI_DECODE    = 51,
375
    TG3_ERR_BASE64_DECODE      = 52,
376
    TG3_ERR_EXTERNAL_RESOURCE  = 53,
377
    TG3_ERR_IMAGE_DECODE       = 54,
378
379
    /* Callback errors: 60-69 */
380
    TG3_ERR_CALLBACK_FAILED    = 60,
381
    TG3_ERR_FS_NOT_AVAILABLE   = 61,
382
383
    /* Streaming errors: 70-79 */
384
    TG3_ERR_STREAM_ABORTED     = 70,
385
386
    /* Writer errors: 80-89 */
387
    TG3_ERR_WRITE_FAILED       = 80,
388
    TG3_ERR_SERIALIZE_FAILED   = 81
389
} tg3_error_code;
390
391
typedef struct tg3_error_entry {
392
    tg3_severity   severity;
393
    tg3_error_code code;
394
    const char    *message;     /* Arena-owned, null-terminated */
395
    const char    *json_path;   /* e.g. "/meshes/0/primitives/1" or NULL */
396
    int64_t        byte_offset; /* -1 if unknown */
397
} tg3_error_entry;
398
399
typedef struct tg3_error_stack {
400
    tg3_error_entry *entries;
401
    uint32_t         count;
402
    uint32_t         capacity;
403
    int32_t          has_error; /* 1 if any entry with severity == ERROR */
404
} tg3_error_stack;
405
406
/* Error stack query functions */
407
TINYGLTF3_API int32_t  tg3_errors_has_error(const tg3_error_stack *es);
408
TINYGLTF3_API uint32_t tg3_errors_count(const tg3_error_stack *es);
409
TINYGLTF3_API const tg3_error_entry *tg3_errors_get(const tg3_error_stack *es,
410
                                                     uint32_t index);
411
412
/* ======================================================================
413
 * Section 8: Generic Value Type (for extras/extensions)
414
 * ====================================================================== */
415
416
typedef enum tg3_value_type {
417
    TG3_VALUE_NULL   = 0,
418
    TG3_VALUE_BOOL   = 1,
419
    TG3_VALUE_INT    = 2,
420
    TG3_VALUE_REAL   = 3,
421
    TG3_VALUE_STRING = 4,
422
    TG3_VALUE_ARRAY  = 5,
423
    TG3_VALUE_BINARY = 6,
424
    TG3_VALUE_OBJECT = 7
425
} tg3_value_type;
426
427
typedef struct tg3_kv_pair tg3_kv_pair;
428
429
typedef struct tg3_value {
430
    tg3_value_type type;
431
    union {
432
        int32_t  bool_val;
433
        int64_t  int_val;
434
        double   real_val;
435
    };
436
    tg3_str                string_val;
437
    const struct tg3_value *array_data;
438
    uint32_t               array_count;
439
    const tg3_kv_pair      *object_data;
440
    uint32_t               object_count;
441
    tg3_span_u8            binary_val;
442
} tg3_value;
443
444
struct tg3_kv_pair {
445
    tg3_str   key;
446
    tg3_value value;
447
};
448
449
typedef struct tg3_extension {
450
    tg3_str   name;
451
    tg3_value value;
452
} tg3_extension;
453
454
typedef struct tg3_extras_ext {
455
    const tg3_value     *extras;           /* NULL if absent */
456
    const tg3_extension *extensions;       /* Array */
457
    uint32_t             extensions_count;
458
    tg3_str              extras_json;      /* Raw JSON if store_original_json */
459
    tg3_str              extensions_json;
460
    tg3_str              id;               /* glTF 2.1 unique id (optional) [TG3_GLTF21_UNSTABLE] */
461
} tg3_extras_ext;
462
463
/* ======================================================================
464
 * Section 9: Core POD Structs
465
 * ====================================================================== */
466
467
/* --- Asset --- */
468
typedef struct tg3_asset {
469
    tg3_str       version;    /* Required, e.g. "2.0" */
470
    tg3_str       generator;
471
    tg3_str       min_version;
472
    tg3_str       copyright;
473
    tg3_extras_ext ext;
474
} tg3_asset;
475
476
/* --- Buffer --- */
477
typedef struct tg3_buffer {
478
    tg3_str       name;
479
    uint64_t      byte_length;  /* Declared buffer.byteLength */
480
    tg3_span_u8   data;
481
    tg3_str       uri;
482
    tg3_extras_ext ext;
483
} tg3_buffer;
484
485
/* --- BufferView --- */
486
typedef struct tg3_buffer_view {
487
    tg3_str       name;
488
    int32_t       buffer;       /* Index, required */
489
    uint64_t      byte_offset;
490
    uint64_t      byte_length;  /* Required */
491
    uint32_t      byte_stride;  /* 0 = tightly packed */
492
    int32_t       target;       /* 0 = unspecified */
493
    int32_t       draco_decoded;
494
    tg3_extras_ext ext;
495
} tg3_buffer_view;
496
497
/* --- Accessor Sparse --- */
498
typedef struct tg3_accessor_sparse_indices {
499
    uint64_t  byte_offset;
500
    int32_t   buffer_view; /* Required */
501
    int32_t   component_type; /* Required */
502
    tg3_extras_ext ext;
503
} tg3_accessor_sparse_indices;
504
505
typedef struct tg3_accessor_sparse_values {
506
    int32_t   buffer_view; /* Required */
507
    uint64_t  byte_offset;
508
    tg3_extras_ext ext;
509
} tg3_accessor_sparse_values;
510
511
typedef struct tg3_accessor_sparse {
512
    int32_t  count;      /* Required if sparse */
513
    int32_t  is_sparse;  /* 0 or 1 */
514
    tg3_accessor_sparse_indices indices;
515
    tg3_accessor_sparse_values  values;
516
    tg3_extras_ext ext;
517
} tg3_accessor_sparse;
518
519
/* --- Accessor --- */
520
typedef struct tg3_accessor {
521
    tg3_str       name;
522
    int32_t       buffer_view;    /* -1 if absent */
523
    uint64_t      byte_offset;
524
    int32_t       normalized;     /* 0 or 1 */
525
    int32_t       component_type; /* Required */
526
    uint64_t      count;          /* Required */
527
    int32_t       type;           /* Required: TG3_TYPE_* */
528
    const double *min_values;
529
    uint32_t      min_values_count;
530
    const double *max_values;
531
    uint32_t      max_values_count;
532
    tg3_accessor_sparse sparse;
533
    tg3_extras_ext ext;
534
} tg3_accessor;
535
536
/* --- Image --- */
537
typedef struct tg3_image {
538
    tg3_str       name;
539
    int32_t       width;
540
    int32_t       height;
541
    int32_t       component;  /* Channels */
542
    int32_t       bits;       /* Bits per channel */
543
    int32_t       pixel_type; /* Component type */
544
    tg3_span_u8   image;      /* Decoded pixel data (or raw if as_is) */
545
    int32_t       buffer_view; /* -1 if absent */
546
    tg3_str       mime_type;
547
    tg3_str       uri;
548
    int32_t       as_is;
549
    tg3_extras_ext ext;
550
} tg3_image;
551
552
/* --- Sampler --- */
553
typedef struct tg3_sampler {
554
    tg3_str  name;
555
    int32_t  min_filter;  /* -1 = unspecified */
556
    int32_t  mag_filter;  /* -1 = unspecified */
557
    int32_t  wrap_s;      /* Default: TG3_TEXTURE_WRAP_REPEAT */
558
    int32_t  wrap_t;      /* Default: TG3_TEXTURE_WRAP_REPEAT */
559
    tg3_extras_ext ext;
560
} tg3_sampler;
561
562
/* --- Texture --- */
563
typedef struct tg3_texture {
564
    tg3_str  name;
565
    int32_t  sampler;  /* -1 if absent */
566
    int32_t  source;   /* -1 if absent */
567
    tg3_extras_ext ext;
568
} tg3_texture;
569
570
/* --- TextureInfo --- */
571
typedef struct tg3_texture_info {
572
    int32_t  index;     /* -1 if absent */
573
    int32_t  tex_coord; /* Default: 0 */
574
    tg3_extras_ext ext;
575
} tg3_texture_info;
576
577
/* --- NormalTextureInfo --- */
578
typedef struct tg3_normal_texture_info {
579
    int32_t  index;
580
    int32_t  tex_coord;
581
    double   scale;     /* Default: 1.0 */
582
    tg3_extras_ext ext;
583
} tg3_normal_texture_info;
584
585
/* --- OcclusionTextureInfo --- */
586
typedef struct tg3_occlusion_texture_info {
587
    int32_t  index;
588
    int32_t  tex_coord;
589
    double   strength;  /* Default: 1.0 */
590
    tg3_extras_ext ext;
591
} tg3_occlusion_texture_info;
592
593
/* --- PBR Metallic Roughness --- */
594
typedef struct tg3_pbr_metallic_roughness {
595
    double             base_color_factor[4]; /* Default: {1,1,1,1} */
596
    tg3_texture_info   base_color_texture;
597
    double             metallic_factor;      /* Default: 1.0 */
598
    double             roughness_factor;     /* Default: 1.0 */
599
    tg3_texture_info   metallic_roughness_texture;
600
    tg3_extras_ext     ext;
601
} tg3_pbr_metallic_roughness;
602
603
/* --- Material --- */
604
typedef struct tg3_material {
605
    tg3_str                     name;
606
    double                      emissive_factor[3]; /* Default: {0,0,0} */
607
    tg3_str                     alpha_mode;         /* "OPAQUE","MASK","BLEND" */
608
    double                      alpha_cutoff;       /* Default: 0.5 */
609
    int32_t                     double_sided;       /* 0 or 1 */
610
    const int32_t              *lods;
611
    uint32_t                    lods_count;
612
    tg3_pbr_metallic_roughness  pbr_metallic_roughness;
613
    tg3_normal_texture_info     normal_texture;
614
    tg3_occlusion_texture_info  occlusion_texture;
615
    tg3_texture_info            emissive_texture;
616
    tg3_extras_ext              ext;
617
} tg3_material;
618
619
/* --- Primitive --- */
620
typedef struct tg3_primitive {
621
    const tg3_str_int_pair *attributes;
622
    uint32_t                attributes_count;
623
    int32_t                 material;  /* -1 if absent */
624
    int32_t                 indices;   /* -1 if absent */
625
    int32_t                 mode;      /* -1 = default (TRIANGLES) */
626
627
    /* Morph targets: array of arrays of attribute pairs */
628
    const tg3_str_int_pair *const *targets;
629
    const uint32_t         *target_attribute_counts;
630
    uint32_t                targets_count;
631
632
    tg3_extras_ext ext;
633
} tg3_primitive;
634
635
/* --- Mesh --- */
636
typedef struct tg3_mesh {
637
    tg3_str              name;
638
    const tg3_primitive *primitives;
639
    uint32_t             primitives_count;
640
    const double        *weights;
641
    uint32_t             weights_count;
642
    tg3_extras_ext       ext;
643
} tg3_mesh;
644
645
/* --- Node --- */
646
typedef struct tg3_node {
647
    tg3_str       name;
648
    int32_t       camera;     /* -1 if absent */
649
    int32_t       skin;       /* -1 if absent */
650
    int32_t       mesh;       /* -1 if absent */
651
    int32_t       light;      /* -1 if absent (KHR_lights_punctual) */
652
    int32_t       emitter;    /* -1 if absent (KHR_audio) */
653
654
    const int32_t *lods;
655
    uint32_t       lods_count;
656
    const int32_t *children;
657
    uint32_t       children_count;
658
659
    double         rotation[4];     /* Default: {0,0,0,1} */
660
    double         scale[3];        /* Default: {1,1,1} */
661
    double         translation[3];  /* Default: {0,0,0} */
662
    double         matrix[16];      /* Identity if not set */
663
    int32_t        has_matrix;      /* 1 if matrix was specified */
664
665
    const double  *weights;
666
    uint32_t       weights_count;
667
668
    tg3_extras_ext ext;
669
} tg3_node;
670
671
/* --- Skin --- */
672
typedef struct tg3_skin {
673
    tg3_str        name;
674
    int32_t        inverse_bind_matrices; /* -1 if absent */
675
    int32_t        skeleton;              /* -1 if absent */
676
    const int32_t *joints;
677
    uint32_t       joints_count;
678
    tg3_extras_ext ext;
679
} tg3_skin;
680
681
/* --- Animation --- */
682
typedef struct tg3_animation_channel_target {
683
    int32_t  node;    /* -1 if absent */
684
    tg3_str  path;    /* "translation","rotation","scale","weights" */
685
    tg3_extras_ext ext;
686
} tg3_animation_channel_target;
687
688
typedef struct tg3_animation_channel {
689
    int32_t  sampler; /* Required */
690
    tg3_animation_channel_target target;
691
    tg3_extras_ext ext;
692
} tg3_animation_channel;
693
694
typedef struct tg3_animation_sampler {
695
    int32_t  input;          /* Required */
696
    int32_t  output;         /* Required */
697
    tg3_str  interpolation;  /* "LINEAR","STEP","CUBICSPLINE" */
698
    tg3_extras_ext ext;
699
} tg3_animation_sampler;
700
701
typedef struct tg3_animation {
702
    tg3_str                      name;
703
    const tg3_animation_channel *channels;
704
    uint32_t                     channels_count;
705
    const tg3_animation_sampler *samplers;
706
    uint32_t                     samplers_count;
707
    tg3_extras_ext               ext;
708
} tg3_animation;
709
710
/* --- Camera --- */
711
typedef struct tg3_perspective_camera {
712
    double aspect_ratio;
713
    double yfov;
714
    double zfar;  /* 0 = infinite */
715
    double znear;
716
    tg3_extras_ext ext;
717
} tg3_perspective_camera;
718
719
typedef struct tg3_orthographic_camera {
720
    double xmag;
721
    double ymag;
722
    double zfar;
723
    double znear;
724
    tg3_extras_ext ext;
725
} tg3_orthographic_camera;
726
727
typedef struct tg3_camera {
728
    tg3_str                  name;
729
    tg3_str                  type; /* "perspective" or "orthographic" */
730
    tg3_perspective_camera   perspective;
731
    tg3_orthographic_camera  orthographic;
732
    tg3_extras_ext           ext;
733
} tg3_camera;
734
735
/* --- Scene --- */
736
typedef struct tg3_scene {
737
    tg3_str        name;
738
    const int32_t *nodes;
739
    uint32_t       nodes_count;
740
    const int32_t *audio_emitters;
741
    uint32_t       audio_emitters_count;
742
    tg3_extras_ext ext;
743
} tg3_scene;
744
745
/* --- Light (KHR_lights_punctual) --- */
746
typedef struct tg3_spot_light {
747
    double inner_cone_angle; /* Default: 0 */
748
    double outer_cone_angle; /* Default: PI/4 */
749
    tg3_extras_ext ext;
750
} tg3_spot_light;
751
752
typedef struct tg3_light {
753
    tg3_str        name;
754
    double         color[3];    /* Default: {1,1,1} */
755
    double         intensity;   /* Default: 1.0 */
756
    tg3_str        type;        /* "directional","point","spot" */
757
    double         range;       /* Default: 0 (infinite) */
758
    tg3_spot_light spot;
759
    tg3_extras_ext ext;
760
} tg3_light;
761
762
/* --- File (glTF 2.1 unified file reference) [TG3_GLTF21_UNSTABLE] --- */
763
typedef struct tg3_file {
764
    tg3_str  uri;
765
    tg3_str  mime_type;
766
    tg3_extras_ext ext;
767
} tg3_file;
768
769
/* --- Audio (KHR_audio) --- */
770
typedef struct tg3_audio_source {
771
    tg3_str        name;
772
    tg3_str        uri;
773
    int32_t        buffer_view; /* -1 if absent */
774
    tg3_str        mime_type;
775
    tg3_extras_ext ext;
776
} tg3_audio_source;
777
778
typedef struct tg3_positional_emitter {
779
    double cone_inner_angle;   /* Default: 2*PI */
780
    double cone_outer_angle;   /* Default: 2*PI */
781
    double cone_outer_gain;    /* Default: 0 */
782
    double max_distance;       /* Default: 100 */
783
    double ref_distance;       /* Default: 1 */
784
    double rolloff_factor;     /* Default: 1 */
785
    tg3_extras_ext ext;
786
} tg3_positional_emitter;
787
788
typedef struct tg3_audio_emitter {
789
    tg3_str              name;
790
    double               gain;           /* Default: 1.0 */
791
    int32_t              loop;           /* Default: 0 */
792
    int32_t              playing;        /* Default: 0 */
793
    tg3_str              type;           /* "positional" or "global" */
794
    tg3_str              distance_model; /* "linear","inverse","exponential" */
795
    tg3_positional_emitter positional;
796
    int32_t              source;         /* -1 if absent */
797
    tg3_extras_ext       ext;
798
} tg3_audio_emitter;
799
800
/* ======================================================================
801
 * Section 10: Model Container
802
 * ====================================================================== */
803
804
/* Opaque arena type */
805
struct tg3_arena;
806
807
typedef struct tg3_model {
808
    struct tg3_arena *arena_;  /* Internal, all memory owned here */
809
810
    const tg3_accessor      *accessors;      uint32_t accessors_count;
811
    const tg3_animation     *animations;     uint32_t animations_count;
812
    const tg3_buffer        *buffers;        uint32_t buffers_count;
813
    const tg3_buffer_view   *buffer_views;   uint32_t buffer_views_count;
814
    const tg3_material      *materials;      uint32_t materials_count;
815
    const tg3_mesh          *meshes;         uint32_t meshes_count;
816
    const tg3_node          *nodes;          uint32_t nodes_count;
817
    const tg3_texture       *textures;       uint32_t textures_count;
818
    const tg3_image         *images;         uint32_t images_count;
819
    const tg3_skin          *skins;          uint32_t skins_count;
820
    const tg3_sampler       *samplers;       uint32_t samplers_count;
821
    const tg3_camera        *cameras;        uint32_t cameras_count;
822
    const tg3_scene         *scenes;         uint32_t scenes_count;
823
    const tg3_light         *lights;         uint32_t lights_count;
824
    const tg3_audio_emitter *audio_emitters; uint32_t audio_emitters_count;
825
    const tg3_audio_source  *audio_sources;  uint32_t audio_sources_count;
826
    const tg3_file          *files;          uint32_t files_count;
827
828
    /* glTF 2.1 thumbnails (image indices) [TG3_GLTF21_UNSTABLE] */
829
    const int32_t           *thumbnails;     uint32_t thumbnails_count;
830
831
    int32_t    default_scene;
832
    const tg3_str *extensions_used;      uint32_t extensions_used_count;
833
    const tg3_str *extensions_required;  uint32_t extensions_required_count;
834
    tg3_asset  asset;
835
    tg3_extras_ext ext;
836
} tg3_model;
837
838
/* ======================================================================
839
 * Section 11: Callback Typedefs
840
 * ====================================================================== */
841
842
/* --- Filesystem Callbacks --- */
843
844
typedef int32_t (*tg3_file_exists_fn)(const char *path, uint32_t path_len,
845
                                      void *user_data);
846
847
typedef int32_t (*tg3_read_file_fn)(uint8_t **out_data, uint64_t *out_size,
848
                                    const char *path, uint32_t path_len,
849
                                    void *user_data);
850
851
typedef void (*tg3_free_file_fn)(uint8_t *data, uint64_t size,
852
                                  void *user_data);
853
854
typedef int32_t (*tg3_write_file_fn)(const char *path, uint32_t path_len,
855
                                     const uint8_t *data, uint64_t size,
856
                                     void *user_data);
857
858
typedef int32_t (*tg3_resolve_path_fn)(char *out_path, uint32_t out_cap,
859
                                       uint32_t *out_len,
860
                                       const char *path, uint32_t path_len,
861
                                       void *user_data);
862
863
typedef int32_t (*tg3_get_file_size_fn)(uint64_t *out_size,
864
                                        const char *path, uint32_t path_len,
865
                                        void *user_data);
866
867
typedef struct tg3_fs_callbacks {
868
    tg3_file_exists_fn   file_exists;
869
    tg3_read_file_fn     read_file;
870
    tg3_free_file_fn     free_file;
871
    tg3_write_file_fn    write_file;
872
    tg3_resolve_path_fn  resolve_path;
873
    tg3_get_file_size_fn get_file_size;
874
    void                *user_data;
875
} tg3_fs_callbacks;
876
877
/* --- Image Callbacks --- */
878
879
typedef struct tg3_image_request {
880
    const uint8_t *data;
881
    uint64_t       data_size;
882
    int32_t        image_index;
883
    int32_t        req_width;
884
    int32_t        req_height;
885
    const char    *mime_type;
886
} tg3_image_request;
887
888
typedef struct tg3_image_result {
889
    uint8_t  *pixels;     /* Caller must allocate */
890
    int32_t   width;
891
    int32_t   height;
892
    int32_t   component;
893
    int32_t   bits;
894
    int32_t   pixel_type;
895
} tg3_image_result;
896
897
typedef int32_t (*tg3_load_image_fn)(tg3_image_result *result,
898
                                     const tg3_image_request *request,
899
                                     void *user_data);
900
901
typedef void (*tg3_free_image_fn)(uint8_t *pixels, void *user_data);
902
903
typedef struct tg3_image_callbacks {
904
    tg3_load_image_fn  load_image;
905
    tg3_free_image_fn  free_image;
906
    void              *user_data;
907
} tg3_image_callbacks;
908
909
/* --- URI Callbacks --- */
910
911
typedef int32_t (*tg3_uri_encode_fn)(char *out, uint32_t out_cap,
912
                                     uint32_t *out_len,
913
                                     const char *uri, uint32_t uri_len,
914
                                     const char *obj_type,
915
                                     void *user_data);
916
917
typedef int32_t (*tg3_uri_decode_fn)(char *out, uint32_t out_cap,
918
                                     uint32_t *out_len,
919
                                     const char *uri, uint32_t uri_len,
920
                                     void *user_data);
921
922
typedef struct tg3_uri_callbacks {
923
    tg3_uri_encode_fn encode;
924
    tg3_uri_decode_fn decode;
925
    void             *user_data;
926
} tg3_uri_callbacks;
927
928
/* --- Streaming Callbacks --- */
929
930
typedef enum tg3_stream_action {
931
    TG3_STREAM_CONTINUE = 0,
932
    TG3_STREAM_ABORT    = 1,
933
    TG3_STREAM_SKIP     = 2
934
} tg3_stream_action;
935
936
typedef tg3_stream_action (*tg3_on_asset_fn)(const tg3_asset *a, void *ud);
937
typedef tg3_stream_action (*tg3_on_buffer_fn)(const tg3_buffer *b, int32_t idx, void *ud);
938
typedef tg3_stream_action (*tg3_on_buffer_view_fn)(const tg3_buffer_view *bv, int32_t idx, void *ud);
939
typedef tg3_stream_action (*tg3_on_accessor_fn)(const tg3_accessor *a, int32_t idx, void *ud);
940
typedef tg3_stream_action (*tg3_on_mesh_fn)(const tg3_mesh *m, int32_t idx, void *ud);
941
typedef tg3_stream_action (*tg3_on_node_fn)(const tg3_node *n, int32_t idx, void *ud);
942
typedef tg3_stream_action (*tg3_on_material_fn)(const tg3_material *m, int32_t idx, void *ud);
943
typedef tg3_stream_action (*tg3_on_texture_fn)(const tg3_texture *t, int32_t idx, void *ud);
944
typedef tg3_stream_action (*tg3_on_image_fn)(const tg3_image *img, int32_t idx, void *ud);
945
typedef tg3_stream_action (*tg3_on_sampler_fn)(const tg3_sampler *s, int32_t idx, void *ud);
946
typedef tg3_stream_action (*tg3_on_animation_fn)(const tg3_animation *a, int32_t idx, void *ud);
947
typedef tg3_stream_action (*tg3_on_skin_fn)(const tg3_skin *s, int32_t idx, void *ud);
948
typedef tg3_stream_action (*tg3_on_camera_fn)(const tg3_camera *c, int32_t idx, void *ud);
949
typedef tg3_stream_action (*tg3_on_scene_fn)(const tg3_scene *s, int32_t idx, void *ud);
950
typedef tg3_stream_action (*tg3_on_light_fn)(const tg3_light *l, int32_t idx, void *ud);
951
952
typedef struct tg3_stream_callbacks {
953
    tg3_on_asset_fn       on_asset;
954
    tg3_on_buffer_fn      on_buffer;
955
    tg3_on_buffer_view_fn on_buffer_view;
956
    tg3_on_accessor_fn    on_accessor;
957
    tg3_on_mesh_fn        on_mesh;
958
    tg3_on_node_fn        on_node;
959
    tg3_on_material_fn    on_material;
960
    tg3_on_texture_fn     on_texture;
961
    tg3_on_image_fn       on_image;
962
    tg3_on_sampler_fn     on_sampler;
963
    tg3_on_animation_fn   on_animation;
964
    tg3_on_skin_fn        on_skin;
965
    tg3_on_camera_fn      on_camera;
966
    tg3_on_scene_fn       on_scene;
967
    tg3_on_light_fn       on_light;
968
    void                 *user_data;
969
} tg3_stream_callbacks;
970
971
/* --- Progress Callback --- */
972
973
typedef struct tg3_progress_info {
974
    uint64_t    bytes_processed;
975
    uint64_t    bytes_total;
976
    uint32_t    elements_parsed;
977
    const char *current_section; /* e.g. "meshes", "nodes" */
978
} tg3_progress_info;
979
980
typedef int32_t (*tg3_progress_fn)(const tg3_progress_info *info,
981
                                    void *user_data);
982
983
/* --- Write Chunk Callback (for streaming writer) --- */
984
985
typedef int32_t (*tg3_write_chunk_fn)(const uint8_t *data, uint64_t size,
986
                                      void *user_data);
987
988
/* ======================================================================
989
 * Section 12: Options Structs
990
 * ====================================================================== */
991
992
typedef struct tg3_memory_config {
993
    uint64_t       memory_budget;     /* 0 = use TINYGLTF3_MAX_MEMORY_BYTES */
994
    uint64_t       max_single_alloc;  /* 0 = no limit */
995
    uint32_t       arena_block_size;  /* 0 = default (256KB) */
996
    tg3_allocator  allocator;         /* All zero = use malloc/free */
997
} tg3_memory_config;
998
999
typedef struct tg3_parse_options {
1000
    uint32_t             required_sections; /* TG3_REQUIRE_* flags */
1001
    tg3_strictness       strictness;
1002
    tg3_memory_config    memory;
1003
1004
    tg3_fs_callbacks     fs;
1005
    tg3_uri_callbacks    uri;
1006
    tg3_image_callbacks  image;
1007
    tg3_stream_callbacks *stream;  /* NULL = no streaming */
1008
    tg3_progress_fn      progress;
1009
    void                *progress_user_data;
1010
1011
    int32_t  images_as_is;              /* 1 = don't decode images */
1012
    int32_t  preserve_image_channels;   /* 1 = keep original channels */
1013
    int32_t  store_original_json;       /* 1 = store raw JSON strings */
1014
    int32_t  skip_extras_values;        /* 1 = skip materializing extras and
1015
                                        *     unknown extension value trees */
1016
    int32_t  borrow_input_buffers;      /* 1 = GLB BIN buffer spans may point
1017
                                        *     into caller-owned input data */
1018
    int32_t  parse_float32;            /* 1 = parse JSON floats as float32 for speed
1019
                                        *     (breaks strict double-precision conformance
1020
                                        *      but sufficient for glTF data which is
1021
                                        *      typically single-precision anyway) */
1022
    int32_t  validate_indices;          /* 1 = reject out-of-range index fields
1023
                                        *     after parse so naive consumers cannot
1024
                                        *     dereference attacker-controlled indices.
1025
                                        *     Default: 1. Set to 0 to skip (raw mode). */
1026
    int32_t  validate_ranges;           /* 1 = reject out-of-range byte ranges
1027
                                         *     (buffer/bufferView/accessor/sparse)
1028
                                         *     and invalid component types.
1029
                                         *     Default: 1. Set to 0 only when the
1030
                                         *     caller performs its own checks. */
1031
    uint64_t max_external_file_size;    /* 0 = no limit */
1032
} tg3_parse_options;
1033
1034
typedef struct tg3_write_options {
1035
    int32_t          pretty_print;     /* 1 = indented JSON */
1036
    int32_t          write_binary;     /* 1 = GLB format */
1037
    int32_t          write_glb_64bit;  /* 1 = emit GLB container v3 with 64-bit
1038
                                        *     lengths (glTF 2.1) [TG3_GLTF21_UNSTABLE] */
1039
    int32_t          embed_images;     /* 1 = embed as data URIs */
1040
    int32_t          embed_buffers;    /* 1 = embed as data URIs */
1041
    int32_t          serialize_defaults; /* 1 = write default values */
1042
    tg3_fs_callbacks fs;
1043
    tg3_uri_callbacks uri;
1044
    tg3_memory_config memory;
1045
} tg3_write_options;
1046
1047
/* ======================================================================
1048
 * Section 13: Parser API
1049
 * ====================================================================== */
1050
1051
/* Parse JSON glTF from memory */
1052
TINYGLTF3_API tg3_error_code tg3_parse(
1053
    tg3_model *model, tg3_error_stack *errors,
1054
    const uint8_t *json_data, uint64_t json_size,
1055
    const char *base_dir, uint32_t base_dir_len,
1056
    const tg3_parse_options *options);
1057
1058
/* Parse GLB from memory */
1059
TINYGLTF3_API tg3_error_code tg3_parse_glb(
1060
    tg3_model *model, tg3_error_stack *errors,
1061
    const uint8_t *glb_data, uint64_t glb_size,
1062
    const char *base_dir, uint32_t base_dir_len,
1063
    const tg3_parse_options *options);
1064
1065
/* Auto-detect format (JSON or GLB) and parse */
1066
TINYGLTF3_API tg3_error_code tg3_parse_auto(
1067
    tg3_model *model, tg3_error_stack *errors,
1068
    const uint8_t *data, uint64_t size,
1069
    const char *base_dir, uint32_t base_dir_len,
1070
    const tg3_parse_options *options);
1071
1072
/* Parse from file (requires fs callbacks or TINYGLTF3_ENABLE_FS) */
1073
TINYGLTF3_API tg3_error_code tg3_parse_file(
1074
    tg3_model *model, tg3_error_stack *errors,
1075
    const char *filename, uint32_t filename_len,
1076
    const tg3_parse_options *options);
1077
1078
/* Free model and all arena memory */
1079
TINYGLTF3_API void tg3_model_free(tg3_model *model);
1080
1081
/* Initialize options to defaults */
1082
TINYGLTF3_API void tg3_parse_options_init(tg3_parse_options *options);
1083
TINYGLTF3_API void tg3_write_options_init(tg3_write_options *options);
1084
1085
/* Initialize error stack */
1086
TINYGLTF3_API void tg3_error_stack_init(tg3_error_stack *es);
1087
TINYGLTF3_API void tg3_error_stack_free(tg3_error_stack *es);
1088
1089
/* ======================================================================
1090
 * Section 14: Writer API
1091
 * ====================================================================== */
1092
1093
/* Write model to memory buffer */
1094
TINYGLTF3_API tg3_error_code tg3_write_to_memory(
1095
    const tg3_model *model, tg3_error_stack *errors,
1096
    uint8_t **out_data, uint64_t *out_size,
1097
    const tg3_write_options *options);
1098
1099
/* Write model to file */
1100
TINYGLTF3_API tg3_error_code tg3_write_to_file(
1101
    const tg3_model *model, tg3_error_stack *errors,
1102
    const char *filename, uint32_t filename_len,
1103
    const tg3_write_options *options);
1104
1105
/* Free memory from tg3_write_to_memory */
1106
TINYGLTF3_API void tg3_write_free(uint8_t *data, const tg3_write_options *options);
1107
1108
/* --- Streaming Writer --- */
1109
1110
typedef struct tg3_writer tg3_writer;
1111
1112
TINYGLTF3_API tg3_writer *tg3_writer_create(
1113
    tg3_write_chunk_fn chunk_fn, void *user_data,
1114
    const tg3_write_options *options);
1115
1116
TINYGLTF3_API tg3_error_code tg3_writer_begin(tg3_writer *w, const tg3_asset *asset);
1117
TINYGLTF3_API tg3_error_code tg3_writer_add_buffer(tg3_writer *w, const tg3_buffer *buf);
1118
TINYGLTF3_API tg3_error_code tg3_writer_add_buffer_view(tg3_writer *w, const tg3_buffer_view *bv);
1119
TINYGLTF3_API tg3_error_code tg3_writer_add_accessor(tg3_writer *w, const tg3_accessor *acc);
1120
TINYGLTF3_API tg3_error_code tg3_writer_add_mesh(tg3_writer *w, const tg3_mesh *mesh);
1121
TINYGLTF3_API tg3_error_code tg3_writer_add_node(tg3_writer *w, const tg3_node *node);
1122
TINYGLTF3_API tg3_error_code tg3_writer_add_material(tg3_writer *w, const tg3_material *mat);
1123
TINYGLTF3_API tg3_error_code tg3_writer_add_texture(tg3_writer *w, const tg3_texture *tex);
1124
TINYGLTF3_API tg3_error_code tg3_writer_add_image(tg3_writer *w, const tg3_image *img);
1125
TINYGLTF3_API tg3_error_code tg3_writer_add_sampler(tg3_writer *w, const tg3_sampler *samp);
1126
TINYGLTF3_API tg3_error_code tg3_writer_add_animation(tg3_writer *w, const tg3_animation *anim);
1127
TINYGLTF3_API tg3_error_code tg3_writer_add_skin(tg3_writer *w, const tg3_skin *skin);
1128
TINYGLTF3_API tg3_error_code tg3_writer_add_camera(tg3_writer *w, const tg3_camera *cam);
1129
TINYGLTF3_API tg3_error_code tg3_writer_add_scene(tg3_writer *w, const tg3_scene *scene);
1130
TINYGLTF3_API tg3_error_code tg3_writer_add_light(tg3_writer *w, const tg3_light *light);
1131
TINYGLTF3_API tg3_error_code tg3_writer_end(tg3_writer *w);
1132
TINYGLTF3_API void           tg3_writer_destroy(tg3_writer *w);
1133
1134
/* ======================================================================
1135
 * Section 15: Utility Functions
1136
 * ====================================================================== */
1137
1138
/* Get component size in bytes */
1139
TINYGLTF3_API int32_t tg3_component_size(int32_t component_type);
1140
1141
/* Get number of components for a type */
1142
TINYGLTF3_API int32_t tg3_num_components(int32_t type);
1143
1144
/* Compute byte stride for an accessor */
1145
TINYGLTF3_API int32_t tg3_accessor_byte_stride(const tg3_accessor *accessor,
1146
                                                const tg3_buffer_view *buffer_view);
1147
1148
/* Check if a string is a data URI */
1149
TINYGLTF3_API int32_t tg3_is_data_uri(const char *uri, uint32_t len);
1150
1151
/* Validate an already-parsed (or hand-built) model.
1152
 * Runs the same checks as tg3_parse: memory-safety rules (indices, byte
1153
 * ranges, component types) are always errors; spec-conformance rules are
1154
 * warnings under TG3_PERMISSIVE and errors under TG3_STRICT.
1155
 * Diagnostics are appended to `errors` (may be NULL). Returns TG3_OK when
1156
 * no error-severity diagnostic was produced, otherwise the code of the first
1157
 * failing rule class (TG3_ERR_INVALID_INDEX, TG3_ERR_INVALID_ACCESSOR,
1158
 * TG3_ERR_INVALID_VALUE). Messages are stored in the model's arena, so the
1159
 * error stack must not outlive the model when model->arena_ is non-NULL. */
1160
TINYGLTF3_API tg3_error_code tg3_validate(const tg3_model *model,
1161
                                          tg3_strictness strictness,
1162
                                          tg3_error_stack *errors);
1163
1164
/* Check if a glTF version string is supported ("2.0" .. "2.9") */
1165
TINYGLTF3_API int32_t tg3_gltf_version_supported(const char *version, uint32_t len);
1166
1167
/* tg3_str helpers */
1168
TINYGLTF3_API int32_t tg3_str_equals(tg3_str a, tg3_str b);
1169
TINYGLTF3_API int32_t tg3_str_equals_cstr(tg3_str a, const char *b);
1170
1171
#ifdef __cplusplus
1172
} /* extern "C" */
1173
#endif
1174
1175
/* ======================================================================
1176
 * Section 16: C++ Convenience Wrappers
1177
 * ====================================================================== */
1178
1179
#ifdef __cplusplus
1180
namespace tinygltf3 {
1181
1182
/* RAII model wrapper */
1183
class Model {
1184
public:
1185
0
    Model() { memset(&m_, 0, sizeof(m_)); m_.default_scene = -1; }
1186
0
    ~Model() { tg3_model_free(&m_); }
1187
1188
    Model(const Model &) = delete;
1189
    Model &operator=(const Model &) = delete;
1190
0
    Model(Model &&o) noexcept : m_(o.m_) { memset(&o.m_, 0, sizeof(o.m_)); }
1191
0
    Model &operator=(Model &&o) noexcept {
1192
0
        if (this != &o) { tg3_model_free(&m_); m_ = o.m_; memset(&o.m_, 0, sizeof(o.m_)); }
1193
0
        return *this;
1194
0
    }
1195
1196
0
    tg3_model       *get()       { return &m_; }
1197
0
    const tg3_model *get() const { return &m_; }
1198
0
    tg3_model       *operator->()       { return &m_; }
1199
0
    const tg3_model *operator->() const { return &m_; }
1200
1201
private:
1202
    tg3_model m_;
1203
};
1204
1205
/* RAII error stack wrapper */
1206
class ErrorStack {
1207
public:
1208
0
    ErrorStack()  { tg3_error_stack_init(&es_); }
1209
0
    ~ErrorStack() { tg3_error_stack_free(&es_); }
1210
1211
    ErrorStack(const ErrorStack &) = delete;
1212
    ErrorStack &operator=(const ErrorStack &) = delete;
1213
1214
0
    tg3_error_stack       *get()       { return &es_; }
1215
0
    const tg3_error_stack *get() const { return &es_; }
1216
1217
0
    bool has_error() const { return tg3_errors_has_error(&es_) != 0; }
1218
0
    uint32_t count() const { return tg3_errors_count(&es_); }
1219
0
    const tg3_error_entry *entry(uint32_t i) const { return tg3_errors_get(&es_, i); }
1220
1221
private:
1222
    tg3_error_stack es_;
1223
};
1224
1225
/* Parse helpers returning error code */
1226
inline tg3_error_code parse_file(Model &model, ErrorStack &errors,
1227
                                  const char *filename,
1228
0
                                  const tg3_parse_options *options = nullptr) {
1229
0
    tg3_parse_options opts;
1230
0
    if (!options) { tg3_parse_options_init(&opts); options = &opts; }
1231
0
    return tg3_parse_file(model.get(), errors.get(), filename,
1232
0
                          filename ? (uint32_t)strlen(filename) : 0, options);
1233
0
}
1234
1235
inline tg3_error_code parse(Model &model, ErrorStack &errors,
1236
                             const uint8_t *data, uint64_t size,
1237
                             const char *base_dir = "",
1238
0
                             const tg3_parse_options *options = nullptr) {
1239
0
    tg3_parse_options opts;
1240
0
    if (!options) { tg3_parse_options_init(&opts); options = &opts; }
1241
0
    return tg3_parse_auto(model.get(), errors.get(), data, size,
1242
0
                          base_dir, base_dir ? (uint32_t)strlen(base_dir) : 0,
1243
0
                          options);
1244
0
}
1245
1246
} /* namespace tinygltf3 */
1247
#endif /* __cplusplus */
1248
1249
/* ======================================================================
1250
 * Section 17: C++20 Coroutine Facade
1251
 * ====================================================================== */
1252
1253
#ifdef __cplusplus
1254
#if defined(TINYGLTF3_ENABLE_COROUTINES) || \
1255
    (defined(__cpp_impl_coroutine) && __cpp_impl_coroutine >= 201902L && \
1256
     defined(__cpp_lib_coroutine) && __cpp_lib_coroutine >= 201902L)
1257
1258
#include <coroutine>
1259
1260
namespace tinygltf3 {
1261
1262
struct ParsedElement {
1263
    enum Kind {
1264
        Asset, Buffer, BufferView, Accessor, Mesh, Node, Material,
1265
        Texture, Image, Sampler, Animation, Skin, Camera, Scene,
1266
        Light, Done, Error
1267
    };
1268
1269
    Kind    kind;
1270
    int32_t index;
1271
1272
    union {
1273
        const tg3_asset      *asset;
1274
        const tg3_buffer     *buffer;
1275
        const tg3_buffer_view *buffer_view;
1276
        const tg3_accessor   *accessor;
1277
        const tg3_mesh       *mesh;
1278
        const tg3_node       *node;
1279
        const tg3_material   *material;
1280
        const tg3_texture    *texture;
1281
        const tg3_image      *image;
1282
        const tg3_sampler    *sampler;
1283
        const tg3_animation  *animation;
1284
        const tg3_skin       *skin;
1285
        const tg3_camera     *camera;
1286
        const tg3_scene      *scene;
1287
        const tg3_light      *light;
1288
        const void           *ptr;
1289
    };
1290
1291
    tg3_error_code error_code;
1292
};
1293
1294
class ParseGenerator {
1295
public:
1296
    struct promise_type {
1297
        ParsedElement current_;
1298
        std::suspend_always initial_suspend() noexcept { return {}; }
1299
        std::suspend_always final_suspend() noexcept { return {}; }
1300
        ParseGenerator get_return_object() {
1301
            return ParseGenerator(
1302
                std::coroutine_handle<promise_type>::from_promise(*this));
1303
        }
1304
        std::suspend_always yield_value(ParsedElement elem) noexcept {
1305
            current_ = elem;
1306
            return {};
1307
        }
1308
        void return_void() {}
1309
        void unhandled_exception() {}
1310
    };
1311
1312
    ParseGenerator() : handle_(nullptr) {}
1313
    explicit ParseGenerator(std::coroutine_handle<promise_type> h) : handle_(h) {}
1314
    ~ParseGenerator() { if (handle_) handle_.destroy(); }
1315
1316
    ParseGenerator(const ParseGenerator &) = delete;
1317
    ParseGenerator &operator=(const ParseGenerator &) = delete;
1318
    ParseGenerator(ParseGenerator &&o) noexcept : handle_(o.handle_) { o.handle_ = nullptr; }
1319
    ParseGenerator &operator=(ParseGenerator &&o) noexcept {
1320
        if (this != &o) { if (handle_) handle_.destroy(); handle_ = o.handle_; o.handle_ = nullptr; }
1321
        return *this;
1322
    }
1323
1324
    bool next() {
1325
        if (!handle_ || handle_.done()) return false;
1326
        handle_.resume();
1327
        return !handle_.done();
1328
    }
1329
1330
    const ParsedElement &current() const { return handle_.promise().current_; }
1331
    bool done() const { return !handle_ || handle_.done(); }
1332
1333
private:
1334
    std::coroutine_handle<promise_type> handle_;
1335
};
1336
1337
/* Coroutine parse entry point — declaration only, implemented in TINYGLTF3_IMPLEMENTATION */
1338
ParseGenerator tg3_parse_coro(
1339
    const uint8_t *data, uint64_t size,
1340
    const char *base_dir, uint32_t base_dir_len,
1341
    tg3_model *model, tg3_error_stack *errors,
1342
    const tg3_parse_options *options);
1343
1344
} /* namespace tinygltf3 */
1345
1346
#endif /* coroutines */
1347
#endif /* __cplusplus */
1348
1349
/* ======================================================================
1350
 * Section 18: Implementation
1351
 * ====================================================================== */
1352
1353
#ifdef TINYGLTF3_IMPLEMENTATION
1354
#define TINYGLTF3_SOURCE_INCLUDED_FROM_HEADER 1
1355
#include "tiny_gltf_v3.c"
1356
#undef TINYGLTF3_SOURCE_INCLUDED_FROM_HEADER
1357
1358
#if 0
1359
1360
#if !defined(__cplusplus)
1361
#error "TINYGLTF3_IMPLEMENTATION requires a C++ translation unit (compile as .cpp)"
1362
#endif
1363
1364
/* Include JSON parser */
1365
#include "tinygltf_json.h"
1366
1367
#include <stdio.h>
1368
#include <math.h>
1369
1370
/* Implementation uses C++ features from tinygltf_json.h */
1371
#include <string>
1372
#include <algorithm>
1373
1374
/* Forward SIMD macros to tinygltf_json.h */
1375
#ifdef TINYGLTF3_JSON_SIMD_SSE2
1376
#ifndef TINYGLTF_JSON_SIMD_SSE2
1377
#define TINYGLTF_JSON_SIMD_SSE2
1378
#endif
1379
#endif
1380
#ifdef TINYGLTF3_JSON_SIMD_AVX2
1381
#ifndef TINYGLTF_JSON_SIMD_AVX2
1382
#define TINYGLTF_JSON_SIMD_AVX2
1383
#endif
1384
#endif
1385
#ifdef TINYGLTF3_JSON_SIMD_NEON
1386
#ifndef TINYGLTF_JSON_SIMD_NEON
1387
#define TINYGLTF_JSON_SIMD_NEON
1388
#endif
1389
#endif
1390
1391
/* ======================================================================
1392
 * Internal: Arena Allocator
1393
 * ====================================================================== */
1394
1395
#define TG3__ARENA_DEFAULT_BLOCK_SIZE (256u * 1024u) /* 256 KB */
1396
#define TG3__ARENA_ALIGNMENT 8
1397
1398
typedef struct tg3__arena_block {
1399
    struct tg3__arena_block *next;
1400
    uint8_t *base;
1401
    size_t   used;
1402
    size_t   capacity;
1403
} tg3__arena_block;
1404
1405
struct tg3_arena {
1406
    tg3__arena_block *head;
1407
    tg3__arena_block *current;
1408
    size_t            total_allocated;
1409
    size_t            memory_budget;
1410
    size_t            block_size;
1411
    tg3_allocator     alloc;
1412
};
1413
1414
static void *tg3__default_alloc(size_t size, void *ud) {
1415
    (void)ud;
1416
    return malloc(size);
1417
}
1418
static void *tg3__default_realloc(void *ptr, size_t old_size, size_t new_size, void *ud) {
1419
    (void)old_size; (void)ud;
1420
    return realloc(ptr, new_size);
1421
}
1422
static void tg3__default_free(void *ptr, size_t size, void *ud) {
1423
    (void)size; (void)ud;
1424
    free(ptr);
1425
}
1426
1427
static tg3_arena *tg3__arena_create(const tg3_memory_config *config) {
1428
    tg3_allocator alloc;
1429
    if (config && config->allocator.alloc) {
1430
        alloc = config->allocator;
1431
    } else {
1432
        alloc.alloc = tg3__default_alloc;
1433
        alloc.realloc = tg3__default_realloc;
1434
        alloc.free = tg3__default_free;
1435
        alloc.user_data = NULL;
1436
    }
1437
1438
    tg3_arena *arena = (tg3_arena *)alloc.alloc(sizeof(tg3_arena), alloc.user_data);
1439
    if (!arena) return NULL;
1440
1441
    memset(arena, 0, sizeof(tg3_arena));
1442
    arena->alloc = alloc;
1443
    arena->block_size = (config && config->arena_block_size > 0)
1444
        ? config->arena_block_size : TG3__ARENA_DEFAULT_BLOCK_SIZE;
1445
    arena->memory_budget = (config && config->memory_budget > 0)
1446
        ? (size_t)config->memory_budget : (size_t)TINYGLTF3_MAX_MEMORY_BYTES;
1447
1448
    return arena;
1449
}
1450
1451
static tg3__arena_block *tg3__arena_new_block(tg3_arena *arena, size_t min_size) {
1452
    size_t cap = arena->block_size;
1453
    if (cap < min_size) cap = min_size;
1454
1455
    if (arena->total_allocated + sizeof(tg3__arena_block) + cap > arena->memory_budget) {
1456
        return NULL; /* OOM */
1457
    }
1458
1459
    uint8_t *raw = (uint8_t *)arena->alloc.alloc(
1460
        sizeof(tg3__arena_block) + cap, arena->alloc.user_data);
1461
    if (!raw) return NULL;
1462
1463
    tg3__arena_block *block = (tg3__arena_block *)raw;
1464
    block->base = raw + sizeof(tg3__arena_block);
1465
    block->used = 0;
1466
    block->capacity = cap;
1467
    block->next = NULL;
1468
1469
    arena->total_allocated += sizeof(tg3__arena_block) + cap;
1470
1471
    if (arena->current) {
1472
        arena->current->next = block;
1473
    } else {
1474
        arena->head = block;
1475
    }
1476
    arena->current = block;
1477
1478
    return block;
1479
}
1480
1481
static void *tg3__arena_alloc(tg3_arena *arena, size_t size) {
1482
    if (size == 0) return NULL;
1483
1484
    /* Align up */
1485
    size = (size + (TG3__ARENA_ALIGNMENT - 1)) & ~(size_t)(TG3__ARENA_ALIGNMENT - 1);
1486
1487
    tg3__arena_block *block = arena->current;
1488
    if (!block || block->used + size > block->capacity) {
1489
        block = tg3__arena_new_block(arena, size);
1490
        if (!block) return NULL;
1491
    }
1492
1493
    void *ptr = block->base + block->used;
1494
    block->used += size;
1495
    return ptr;
1496
}
1497
1498
static char *tg3__arena_strdup(tg3_arena *arena, const char *s, size_t len) {
1499
    if (!s) return NULL;
1500
    /* Allocate len+1 bytes; when len==0 this produces a 1-byte "\0" buffer so
1501
     * that empty strings (data!=NULL, len==0) remain distinguishable from
1502
     * absent strings (data==NULL, len==0). */
1503
    char *dst = (char *)tg3__arena_alloc(arena, len + 1);
1504
    if (!dst) return NULL;
1505
    if (len > 0) memcpy(dst, s, len);
1506
    dst[len] = '\0';
1507
    return dst;
1508
}
1509
1510
static tg3_str tg3__arena_str(tg3_arena *arena, const char *s, uint32_t len) {
1511
    tg3_str result;
1512
    result.data = tg3__arena_strdup(arena, s, len);
1513
    result.len = result.data ? len : 0;
1514
    return result;
1515
}
1516
1517
static tg3_str tg3__arena_str_from_std(tg3_arena *arena, const std::string &s) {
1518
    return tg3__arena_str(arena, s.c_str(), (uint32_t)s.size());
1519
}
1520
1521
static void tg3__arena_destroy(tg3_arena *arena) {
1522
    if (!arena) return;
1523
    tg3_allocator alloc = arena->alloc;
1524
    tg3__arena_block *block = arena->head;
1525
    while (block) {
1526
        tg3__arena_block *next = block->next;
1527
        size_t block_total = sizeof(tg3__arena_block) + block->capacity;
1528
        alloc.free(block, block_total, alloc.user_data);
1529
        block = next;
1530
    }
1531
    alloc.free(arena, sizeof(tg3_arena), alloc.user_data);
1532
}
1533
1534
/* ======================================================================
1535
 * Internal: Error Stack Implementation
1536
 * ====================================================================== */
1537
1538
static void tg3__error_push(tg3_error_stack *es, tg3_severity sev,
1539
                             tg3_error_code code, const char *msg,
1540
                             const char *json_path, int64_t byte_offset) {
1541
    if (!es) return;
1542
1543
    if (es->count >= es->capacity) {
1544
        uint32_t new_cap = es->capacity ? es->capacity * 2 : 16;
1545
        tg3_error_entry *new_entries = (tg3_error_entry *)realloc(
1546
            es->entries, new_cap * sizeof(tg3_error_entry));
1547
        if (!new_entries) return; /* Drop error on OOM */
1548
        es->entries = new_entries;
1549
        es->capacity = new_cap;
1550
    }
1551
1552
    tg3_error_entry *e = &es->entries[es->count++];
1553
    e->severity = sev;
1554
    e->code = code;
1555
    e->message = msg; /* Caller must ensure lifetime (arena or static) */
1556
    e->json_path = json_path;
1557
    e->byte_offset = byte_offset;
1558
1559
    if (sev == TG3_SEVERITY_ERROR) es->has_error = 1;
1560
}
1561
1562
/* Push an error with a dynamically formatted message allocated from arena */
1563
static void tg3__error_pushf(tg3_error_stack *es, tg3_arena *arena,
1564
                              tg3_severity sev, tg3_error_code code,
1565
                              const char *json_path, const char *fmt, ...) {
1566
    if (!es) return;
1567
    char buf[1024];
1568
    va_list ap;
1569
    va_start(ap, fmt);
1570
    int n = vsnprintf(buf, sizeof(buf), fmt, ap);
1571
    va_end(ap);
1572
    if (n < 0) n = 0;
1573
    if ((size_t)n >= sizeof(buf)) n = (int)(sizeof(buf) - 1);
1574
1575
    const char *msg = buf;
1576
    if (arena) {
1577
        char *dup = tg3__arena_strdup(arena, buf, (size_t)n);
1578
        if (dup) msg = dup;
1579
    }
1580
    tg3__error_push(es, sev, code, msg, json_path, -1);
1581
}
1582
1583
/* ======================================================================
1584
 * Public: Error Stack API
1585
 * ====================================================================== */
1586
1587
TINYGLTF3_API int32_t tg3_errors_has_error(const tg3_error_stack *es) {
1588
    return es ? es->has_error : 0;
1589
}
1590
1591
TINYGLTF3_API uint32_t tg3_errors_count(const tg3_error_stack *es) {
1592
    return es ? es->count : 0;
1593
}
1594
1595
TINYGLTF3_API const tg3_error_entry *tg3_errors_get(const tg3_error_stack *es,
1596
                                                     uint32_t index) {
1597
    if (!es || index >= es->count) return NULL;
1598
    return &es->entries[index];
1599
}
1600
1601
TINYGLTF3_API void tg3_error_stack_init(tg3_error_stack *es) {
1602
    if (!es) return;
1603
    memset(es, 0, sizeof(tg3_error_stack));
1604
}
1605
1606
TINYGLTF3_API void tg3_error_stack_free(tg3_error_stack *es) {
1607
    if (!es) return;
1608
    free(es->entries);
1609
    memset(es, 0, sizeof(tg3_error_stack));
1610
}
1611
1612
/* ======================================================================
1613
 * Public: Options Init
1614
 * ====================================================================== */
1615
1616
TINYGLTF3_API void tg3_parse_options_init(tg3_parse_options *options) {
1617
    if (!options) return;
1618
    memset(options, 0, sizeof(tg3_parse_options));
1619
    options->required_sections = TG3_REQUIRE_VERSION;
1620
    options->strictness = TG3_PERMISSIVE;
1621
}
1622
1623
TINYGLTF3_API void tg3_write_options_init(tg3_write_options *options) {
1624
    if (!options) return;
1625
    memset(options, 0, sizeof(tg3_write_options));
1626
    options->pretty_print = 1;
1627
}
1628
1629
/* ======================================================================
1630
 * Public: Utility Functions
1631
 * ====================================================================== */
1632
1633
TINYGLTF3_API int32_t tg3_component_size(int32_t component_type) {
1634
    switch (component_type) {
1635
        case TG3_COMPONENT_TYPE_BYTE:           return 1;
1636
        case TG3_COMPONENT_TYPE_UNSIGNED_BYTE:  return 1;
1637
        case TG3_COMPONENT_TYPE_SHORT:          return 2;
1638
        case TG3_COMPONENT_TYPE_UNSIGNED_SHORT: return 2;
1639
        case TG3_COMPONENT_TYPE_INT:            return 4;
1640
        case TG3_COMPONENT_TYPE_UNSIGNED_INT:   return 4;
1641
        case TG3_COMPONENT_TYPE_FLOAT:          return 4;
1642
        case TG3_COMPONENT_TYPE_DOUBLE:         return 8;
1643
        default: return -1;
1644
    }
1645
}
1646
1647
TINYGLTF3_API int32_t tg3_num_components(int32_t type) {
1648
    switch (type) {
1649
        case TG3_TYPE_SCALAR: return 1;
1650
        case TG3_TYPE_VEC2:   return 2;
1651
        case TG3_TYPE_VEC3:   return 3;
1652
        case TG3_TYPE_VEC4:   return 4;
1653
        case TG3_TYPE_MAT2:   return 4;
1654
        case TG3_TYPE_MAT3:   return 9;
1655
        case TG3_TYPE_MAT4:   return 16;
1656
        default: return -1;
1657
    }
1658
}
1659
1660
TINYGLTF3_API int32_t tg3_accessor_byte_stride(const tg3_accessor *accessor,
1661
                                                const tg3_buffer_view *bv) {
1662
    if (bv && bv->byte_stride > 0) return (int32_t)bv->byte_stride;
1663
    int32_t comp = tg3_component_size(accessor->component_type);
1664
    int32_t num = tg3_num_components(accessor->type);
1665
    if (comp < 0 || num < 0) return -1;
1666
    return comp * num;
1667
}
1668
1669
TINYGLTF3_API int32_t tg3_str_equals(tg3_str a, tg3_str b) {
1670
    if (a.len != b.len) return 0;
1671
    if (a.len == 0) return 1;
1672
    return memcmp(a.data, b.data, a.len) == 0 ? 1 : 0;
1673
}
1674
1675
TINYGLTF3_API int32_t tg3_str_equals_cstr(tg3_str a, const char *b) {
1676
    if (!b) return a.len == 0 ? 1 : 0;
1677
    uint32_t blen = (uint32_t)strlen(b);
1678
    if (a.len != blen) return 0;
1679
    if (a.len == 0) return 1;
1680
    return memcmp(a.data, b, a.len) == 0 ? 1 : 0;
1681
}
1682
1683
/* ======================================================================
1684
 * Internal: Base64 Encode/Decode
1685
 * ====================================================================== */
1686
1687
static const char tg3__b64_chars[] =
1688
    "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";
1689
1690
static int tg3__b64_is_valid(unsigned char c) {
1691
    return (c >= 'A' && c <= 'Z') || (c >= 'a' && c <= 'z') ||
1692
           (c >= '0' && c <= '9') || c == '+' || c == '/' || c == '=';
1693
}
1694
1695
static int tg3__b64_decode_char(unsigned char c) {
1696
    if (c >= 'A' && c <= 'Z') return c - 'A';
1697
    if (c >= 'a' && c <= 'z') return c - 'a' + 26;
1698
    if (c >= '0' && c <= '9') return c - '0' + 52;
1699
    if (c == '+') return 62;
1700
    if (c == '/') return 63;
1701
    return -1;
1702
}
1703
1704
static uint8_t *tg3__b64_decode(const char *input, size_t input_len,
1705
                                 size_t *out_len, tg3_arena *arena) {
1706
    if (input_len == 0) { *out_len = 0; return NULL; }
1707
1708
    /* Strip trailing padding */
1709
    size_t pad = 0;
1710
    while (input_len > 0 && input[input_len - 1] == '=') { ++pad; --input_len; }
1711
1712
    size_t decoded_len = (input_len * 3) / 4;
1713
    uint8_t *out = (uint8_t *)tg3__arena_alloc(arena, decoded_len + 1);
1714
    if (!out) { *out_len = 0; return NULL; }
1715
1716
    size_t j = 0;
1717
    uint32_t accum = 0;
1718
    int bits = 0;
1719
1720
    for (size_t i = 0; i < input_len; ++i) {
1721
        int val = tg3__b64_decode_char((unsigned char)input[i]);
1722
        if (val < 0) continue; /* skip whitespace/invalid */
1723
        accum = (accum << 6) | (uint32_t)val;
1724
        bits += 6;
1725
        if (bits >= 8) {
1726
            bits -= 8;
1727
            out[j++] = (uint8_t)((accum >> bits) & 0xFF);
1728
        }
1729
    }
1730
1731
    *out_len = j;
1732
    return out;
1733
}
1734
1735
static char *tg3__b64_encode(const uint8_t *input, size_t input_len,
1736
                              size_t *out_len) {
1737
    size_t enc_len = ((input_len + 2) / 3) * 4;
1738
    char *out = (char *)malloc(enc_len + 1);
1739
    if (!out) { *out_len = 0; return NULL; }
1740
1741
    size_t j = 0;
1742
    for (size_t i = 0; i < input_len; i += 3) {
1743
        uint32_t a = input[i];
1744
        uint32_t b = (i + 1 < input_len) ? input[i + 1] : 0;
1745
        uint32_t c = (i + 2 < input_len) ? input[i + 2] : 0;
1746
        uint32_t triple = (a << 16) | (b << 8) | c;
1747
1748
        out[j++] = tg3__b64_chars[(triple >> 18) & 0x3F];
1749
        out[j++] = tg3__b64_chars[(triple >> 12) & 0x3F];
1750
        out[j++] = (i + 1 < input_len) ? tg3__b64_chars[(triple >> 6) & 0x3F] : '=';
1751
        out[j++] = (i + 2 < input_len) ? tg3__b64_chars[triple & 0x3F] : '=';
1752
    }
1753
    out[j] = '\0';
1754
    *out_len = j;
1755
    return out;
1756
}
1757
1758
/* ======================================================================
1759
 * Internal: Data URI Handling
1760
 * ====================================================================== */
1761
1762
TINYGLTF3_API int32_t tg3_is_data_uri(const char *uri, uint32_t len) {
1763
    if (len < 5) return 0;
1764
    return (memcmp(uri, "data:", 5) == 0) ? 1 : 0;
1765
}
1766
1767
typedef struct tg3__data_uri_result {
1768
    const char *data_start;
1769
    size_t      data_len;
1770
    char        mime_type[64];
1771
} tg3__data_uri_result;
1772
1773
static int tg3__parse_data_uri(const char *uri, uint32_t uri_len,
1774
                                tg3__data_uri_result *result) {
1775
    /* Expected format: data:<mime>;base64,<data> */
1776
    if (uri_len < 5 || memcmp(uri, "data:", 5) != 0) return 0;
1777
1778
    const char *p = uri + 5;
1779
    const char *end = uri + uri_len;
1780
1781
    /* Find semicolon */
1782
    const char *semi = p;
1783
    while (semi < end && *semi != ';') ++semi;
1784
    if (semi >= end) return 0;
1785
1786
    /* Extract MIME type */
1787
    size_t mime_len = (size_t)(semi - p);
1788
    if (mime_len >= sizeof(result->mime_type)) mime_len = sizeof(result->mime_type) - 1;
1789
    memcpy(result->mime_type, p, mime_len);
1790
    result->mime_type[mime_len] = '\0';
1791
1792
    /* Skip ";base64," */
1793
    p = semi + 1;
1794
    if (end - p < 7 || memcmp(p, "base64,", 7) != 0) return 0;
1795
    p += 7;
1796
1797
    result->data_start = p;
1798
    result->data_len = (size_t)(end - p);
1799
    return 1;
1800
}
1801
1802
static uint8_t *tg3__decode_data_uri(tg3_arena *arena, const char *uri,
1803
                                      uint32_t uri_len, size_t *out_len,
1804
                                      char *out_mime, size_t out_mime_cap) {
1805
    tg3__data_uri_result dr;
1806
    if (!tg3__parse_data_uri(uri, uri_len, &dr)) {
1807
        *out_len = 0;
1808
        return NULL;
1809
    }
1810
1811
    if (out_mime && out_mime_cap > 0) {
1812
        size_t mlen = strlen(dr.mime_type);
1813
        if (mlen >= out_mime_cap) mlen = out_mime_cap - 1;
1814
        memcpy(out_mime, dr.mime_type, mlen);
1815
        out_mime[mlen] = '\0';
1816
    }
1817
1818
    return tg3__b64_decode(dr.data_start, dr.data_len, out_len, arena);
1819
}
1820
1821
/* ======================================================================
1822
 * Internal: Parse Context
1823
 * ====================================================================== */
1824
1825
typedef struct tg3__parse_ctx {
1826
    tg3_arena        *arena;
1827
    tg3_error_stack  *errors;
1828
    tg3_parse_options opts;
1829
    const char       *base_dir;
1830
    uint32_t          base_dir_len;
1831
1832
    /* GLB binary chunk */
1833
    const uint8_t    *bin_data;
1834
    uint64_t          bin_size;
1835
    int32_t           is_binary;
1836
} tg3__parse_ctx;
1837
1838
/* ======================================================================
1839
 * Internal: JSON Property Helpers
1840
 * ====================================================================== */
1841
1842
/* Type alias for JSON */
1843
typedef tinygltf_json tg3__json;
1844
1845
static int tg3__json_has(const tg3__json &o, const char *key) {
1846
    auto it = o.find(key);
1847
    return (it != o.end()) ? 1 : 0;
1848
}
1849
1850
static int tg3__parse_string(tg3__parse_ctx *ctx, const tg3__json &o,
1851
                              const char *key, tg3_str *out,
1852
                              int required, const char *parent) {
1853
    auto it = o.find(key);
1854
    if (it == o.end()) {
1855
        if (required) {
1856
            tg3__error_pushf(ctx->errors, ctx->arena, TG3_SEVERITY_ERROR,
1857
                             TG3_ERR_JSON_MISSING_FIELD, parent,
1858
                             "Missing required field '%s'", key);
1859
            return 0;
1860
        }
1861
        out->data = NULL; out->len = 0;
1862
        return 1;
1863
    }
1864
    if (!it->is_string()) {
1865
        tg3__error_pushf(ctx->errors, ctx->arena, TG3_SEVERITY_ERROR,
1866
                         TG3_ERR_JSON_TYPE_MISMATCH, parent,
1867
                         "Field '%s' must be a string", key);
1868
        return 0;
1869
    }
1870
    std::string s = it->get<std::string>();
1871
    *out = tg3__arena_str_from_std(ctx->arena, s);
1872
    return 1;
1873
}
1874
1875
static int tg3__parse_int(tg3__parse_ctx *ctx, const tg3__json &o,
1876
                           const char *key, int32_t *out,
1877
                           int required, const char *parent) {
1878
    auto it = o.find(key);
1879
    if (it == o.end()) {
1880
        if (required) {
1881
            tg3__error_pushf(ctx->errors, ctx->arena, TG3_SEVERITY_ERROR,
1882
                             TG3_ERR_JSON_MISSING_FIELD, parent,
1883
                             "Missing required field '%s'", key);
1884
            return 0;
1885
        }
1886
        return 1;
1887
    }
1888
    if (!it->is_number()) {
1889
        tg3__error_pushf(ctx->errors, ctx->arena, TG3_SEVERITY_ERROR,
1890
                         TG3_ERR_JSON_TYPE_MISMATCH, parent,
1891
                         "Field '%s' must be a number", key);
1892
        return 0;
1893
    }
1894
    if (it->is_number_integer()) {
1895
        int64_t v = it->get<int64_t>();
1896
        if (v < (int64_t)INT32_MIN || v > (int64_t)INT32_MAX) {
1897
            tg3__error_pushf(ctx->errors, ctx->arena, TG3_SEVERITY_ERROR,
1898
                             TG3_ERR_JSON_TYPE_MISMATCH, parent,
1899
                             "Field '%s' value %" PRId64 " is out of range for int32", key, v);
1900
            return 0;
1901
        }
1902
        *out = (int32_t)v;
1903
    } else {
1904
        double d = it->get<double>();
1905
        if (d < (double)INT32_MIN || d > (double)INT32_MAX) {
1906
            tg3__error_pushf(ctx->errors, ctx->arena, TG3_SEVERITY_ERROR,
1907
                             TG3_ERR_JSON_TYPE_MISMATCH, parent,
1908
                             "Field '%s' value %f is out of range for int32", key, d);
1909
            return 0;
1910
        }
1911
        *out = (int32_t)d;
1912
    }
1913
    return 1;
1914
}
1915
1916
static int tg3__parse_uint64(tg3__parse_ctx *ctx, const tg3__json &o,
1917
                              const char *key, uint64_t *out,
1918
                              int required, const char *parent) {
1919
    auto it = o.find(key);
1920
    if (it == o.end()) {
1921
        if (required) {
1922
            tg3__error_pushf(ctx->errors, ctx->arena, TG3_SEVERITY_ERROR,
1923
                             TG3_ERR_JSON_MISSING_FIELD, parent,
1924
                             "Missing required field '%s'", key);
1925
            return 0;
1926
        }
1927
        return 1;
1928
    }
1929
    if (!it->is_number()) {
1930
        tg3__error_pushf(ctx->errors, ctx->arena, TG3_SEVERITY_ERROR,
1931
                         TG3_ERR_JSON_TYPE_MISMATCH, parent,
1932
                         "Field '%s' must be a number", key);
1933
        return 0;
1934
    }
1935
    if (it->is_number_integer()) {
1936
        int64_t v = it->get<int64_t>();
1937
        *out = (v >= 0) ? (uint64_t)v : 0;
1938
    } else {
1939
        *out = (uint64_t)it->get<double>();
1940
    }
1941
    return 1;
1942
}
1943
1944
static int tg3__parse_double(tg3__parse_ctx *ctx, const tg3__json &o,
1945
                              const char *key, double *out,
1946
                              int required, const char *parent) {
1947
    auto it = o.find(key);
1948
    if (it == o.end()) {
1949
        if (required) {
1950
            tg3__error_pushf(ctx->errors, ctx->arena, TG3_SEVERITY_ERROR,
1951
                             TG3_ERR_JSON_MISSING_FIELD, parent,
1952
                             "Missing required field '%s'", key);
1953
            return 0;
1954
        }
1955
        return 1;
1956
    }
1957
    if (!it->is_number()) {
1958
        tg3__error_pushf(ctx->errors, ctx->arena, TG3_SEVERITY_ERROR,
1959
                         TG3_ERR_JSON_TYPE_MISMATCH, parent,
1960
                         "Field '%s' must be a number", key);
1961
        return 0;
1962
    }
1963
    *out = it->get<double>();
1964
    return 1;
1965
}
1966
1967
static int tg3__parse_bool(tg3__parse_ctx *ctx, const tg3__json &o,
1968
                            const char *key, int32_t *out,
1969
                            int required, const char *parent) {
1970
    auto it = o.find(key);
1971
    if (it == o.end()) {
1972
        if (required) {
1973
            tg3__error_pushf(ctx->errors, ctx->arena, TG3_SEVERITY_ERROR,
1974
                             TG3_ERR_JSON_MISSING_FIELD, parent,
1975
                             "Missing required field '%s'", key);
1976
            return 0;
1977
        }
1978
        return 1;
1979
    }
1980
    if (!it->is_boolean()) {
1981
        tg3__error_pushf(ctx->errors, ctx->arena, TG3_SEVERITY_ERROR,
1982
                         TG3_ERR_JSON_TYPE_MISMATCH, parent,
1983
                         "Field '%s' must be a boolean", key);
1984
        return 0;
1985
    }
1986
    *out = it->get<bool>() ? 1 : 0;
1987
    return 1;
1988
}
1989
1990
static int tg3__parse_number_array(tg3__parse_ctx *ctx, const tg3__json &o,
1991
                                    const char *key, const double **out,
1992
                                    uint32_t *out_count,
1993
                                    int required, const char *parent) {
1994
    auto it = o.find(key);
1995
    if (it == o.end()) {
1996
        if (required) {
1997
            tg3__error_pushf(ctx->errors, ctx->arena, TG3_SEVERITY_ERROR,
1998
                             TG3_ERR_JSON_MISSING_FIELD, parent,
1999
                             "Missing required field '%s'", key);
2000
            return 0;
2001
        }
2002
        *out = NULL; *out_count = 0;
2003
        return 1;
2004
    }
2005
    if (!it->is_array()) {
2006
        tg3__error_pushf(ctx->errors, ctx->arena, TG3_SEVERITY_ERROR,
2007
                         TG3_ERR_JSON_TYPE_MISMATCH, parent,
2008
                         "Field '%s' must be an array", key);
2009
        return 0;
2010
    }
2011
    uint32_t count = (uint32_t)it->size();
2012
    if (count == 0) { *out = NULL; *out_count = 0; return 1; }
2013
2014
    double *arr = (double *)tg3__arena_alloc(ctx->arena, count * sizeof(double));
2015
    if (!arr) {
2016
        tg3__error_push(ctx->errors, TG3_SEVERITY_ERROR, TG3_ERR_OUT_OF_MEMORY,
2017
                        "OOM allocating number array", parent, -1);
2018
        return 0;
2019
    }
2020
    uint32_t i = 0;
2021
    for (auto eit = it->begin(); eit != it->end(); ++eit, ++i) {
2022
        arr[i] = eit->get<double>();
2023
    }
2024
    *out = arr;
2025
    *out_count = count;
2026
    return 1;
2027
}
2028
2029
static int tg3__parse_int_array(tg3__parse_ctx *ctx, const tg3__json &o,
2030
                                 const char *key, const int32_t **out,
2031
                                 uint32_t *out_count,
2032
                                 int required, const char *parent) {
2033
    auto it = o.find(key);
2034
    if (it == o.end()) {
2035
        if (required) {
2036
            tg3__error_pushf(ctx->errors, ctx->arena, TG3_SEVERITY_ERROR,
2037
                             TG3_ERR_JSON_MISSING_FIELD, parent,
2038
                             "Missing required field '%s'", key);
2039
            return 0;
2040
        }
2041
        *out = NULL; *out_count = 0;
2042
        return 1;
2043
    }
2044
    if (!it->is_array()) {
2045
        tg3__error_pushf(ctx->errors, ctx->arena, TG3_SEVERITY_ERROR,
2046
                         TG3_ERR_JSON_TYPE_MISMATCH, parent,
2047
                         "Field '%s' must be an array", key);
2048
        return 0;
2049
    }
2050
    uint32_t count = (uint32_t)it->size();
2051
    if (count == 0) { *out = NULL; *out_count = 0; return 1; }
2052
2053
    int32_t *arr = (int32_t *)tg3__arena_alloc(ctx->arena, count * sizeof(int32_t));
2054
    if (!arr) {
2055
        tg3__error_push(ctx->errors, TG3_SEVERITY_ERROR, TG3_ERR_OUT_OF_MEMORY,
2056
                        "OOM allocating int array", parent, -1);
2057
        return 0;
2058
    }
2059
    uint32_t i = 0;
2060
    for (auto eit = it->begin(); eit != it->end(); ++eit, ++i) {
2061
        arr[i] = eit->get<int>();
2062
    }
2063
    *out = arr;
2064
    *out_count = count;
2065
    return 1;
2066
}
2067
2068
static void tg3__parse_number_to_fixed(const tg3__json &o, const char *key,
2069
                                        double *out, uint32_t max_count) {
2070
    auto it = o.find(key);
2071
    if (it == o.end() || !it->is_array()) return;
2072
    uint32_t i = 0;
2073
    for (auto eit = it->begin(); eit != it->end() && i < max_count; ++eit, ++i) {
2074
        out[i] = eit->get<double>();
2075
    }
2076
}
2077
2078
/* Parse string array */
2079
static int tg3__parse_string_array(tg3__parse_ctx *ctx, const tg3__json &o,
2080
                                    const char *key, const tg3_str **out,
2081
                                    uint32_t *out_count,
2082
                                    int required, const char *parent) {
2083
    auto it = o.find(key);
2084
    if (it == o.end()) {
2085
        if (required) {
2086
            tg3__error_pushf(ctx->errors, ctx->arena, TG3_SEVERITY_ERROR,
2087
                             TG3_ERR_JSON_MISSING_FIELD, parent,
2088
                             "Missing required field '%s'", key);
2089
            return 0;
2090
        }
2091
        *out = NULL; *out_count = 0;
2092
        return 1;
2093
    }
2094
    if (!it->is_array()) return 0;
2095
    uint32_t count = (uint32_t)it->size();
2096
    if (count == 0) { *out = NULL; *out_count = 0; return 1; }
2097
2098
    tg3_str *arr = (tg3_str *)tg3__arena_alloc(ctx->arena, count * sizeof(tg3_str));
2099
    if (!arr) return 0;
2100
    uint32_t i = 0;
2101
    for (auto eit = it->begin(); eit != it->end(); ++eit, ++i) {
2102
        std::string s = eit->get<std::string>();
2103
        arr[i] = tg3__arena_str_from_std(ctx->arena, s);
2104
    }
2105
    *out = arr;
2106
    *out_count = count;
2107
    return 1;
2108
}
2109
2110
/* ======================================================================
2111
 * Internal: Value Conversion (JSON -> tg3_value)
2112
 * ====================================================================== */
2113
2114
static tg3_value tg3__json_to_value(tg3__parse_ctx *ctx, const tg3__json &j) {
2115
    tg3_value v;
2116
    memset(&v, 0, sizeof(v));
2117
2118
    if (j.is_null()) {
2119
        v.type = TG3_VALUE_NULL;
2120
    } else if (j.is_boolean()) {
2121
        v.type = TG3_VALUE_BOOL;
2122
        v.bool_val = j.get<bool>() ? 1 : 0;
2123
    } else if (j.is_number_integer()) {
2124
        v.type = TG3_VALUE_INT;
2125
        v.int_val = j.get<int64_t>();
2126
    } else if (j.is_number_float()) {
2127
        v.type = TG3_VALUE_REAL;
2128
        v.real_val = j.get<double>();
2129
    } else if (j.is_string()) {
2130
        v.type = TG3_VALUE_STRING;
2131
        std::string s = j.get<std::string>();
2132
        v.string_val = tg3__arena_str_from_std(ctx->arena, s);
2133
    } else if (j.is_array()) {
2134
        v.type = TG3_VALUE_ARRAY;
2135
        uint32_t count = (uint32_t)j.size();
2136
        if (count > 0) {
2137
            tg3_value *arr = (tg3_value *)tg3__arena_alloc(
2138
                ctx->arena, count * sizeof(tg3_value));
2139
            if (arr) {
2140
                uint32_t i = 0;
2141
                for (auto it = j.begin(); it != j.end(); ++it, ++i) {
2142
                    arr[i] = tg3__json_to_value(ctx, *it);
2143
                }
2144
                v.array_data = arr;
2145
                v.array_count = count;
2146
            }
2147
        }
2148
    } else if (j.is_object()) {
2149
        v.type = TG3_VALUE_OBJECT;
2150
        uint32_t count = (uint32_t)j.size();
2151
        if (count > 0) {
2152
            tg3_kv_pair *pairs = (tg3_kv_pair *)tg3__arena_alloc(
2153
                ctx->arena, count * sizeof(tg3_kv_pair));
2154
            if (pairs) {
2155
                uint32_t i = 0;
2156
                for (auto it = j.begin(); it != j.end(); ++it, ++i) {
2157
                    std::string k = it.key();
2158
                    pairs[i].key = tg3__arena_str_from_std(ctx->arena, k);
2159
                    pairs[i].value = tg3__json_to_value(ctx, *it);
2160
                }
2161
                v.object_data = pairs;
2162
                v.object_count = count;
2163
            }
2164
        }
2165
    }
2166
    return v;
2167
}
2168
2169
/* ======================================================================
2170
 * Internal: Parse Extras and Extensions
2171
 * ====================================================================== */
2172
2173
static void tg3__init_extras_ext(tg3_extras_ext *ee) {
2174
    memset(ee, 0, sizeof(tg3_extras_ext));
2175
}
2176
2177
static void tg3__parse_extras_and_extensions(tg3__parse_ctx *ctx,
2178
                                              const tg3__json &o,
2179
                                              tg3_extras_ext *ee) {
2180
    /* Extras */
2181
    auto extras_it = o.find("extras");
2182
    if (extras_it != o.end()) {
2183
        tg3_value *ev = (tg3_value *)tg3__arena_alloc(ctx->arena, sizeof(tg3_value));
2184
        if (ev) {
2185
            *ev = tg3__json_to_value(ctx, *extras_it);
2186
            ee->extras = ev;
2187
        }
2188
        if (ctx->opts.store_original_json) {
2189
            std::string raw = extras_it->dump();
2190
            ee->extras_json = tg3__arena_str_from_std(ctx->arena, raw);
2191
        }
2192
    }
2193
2194
    /* Extensions */
2195
    auto ext_it = o.find("extensions");
2196
    if (ext_it != o.end() && ext_it->is_object()) {
2197
        uint32_t count = (uint32_t)ext_it->size();
2198
        if (count > 0) {
2199
            tg3_extension *exts = (tg3_extension *)tg3__arena_alloc(
2200
                ctx->arena, count * sizeof(tg3_extension));
2201
            if (exts) {
2202
                uint32_t i = 0;
2203
                for (auto it = ext_it->begin(); it != ext_it->end(); ++it, ++i) {
2204
                    std::string k = it.key();
2205
                    exts[i].name = tg3__arena_str_from_std(ctx->arena, k);
2206
                    exts[i].value = tg3__json_to_value(ctx, *it);
2207
                }
2208
                ee->extensions = exts;
2209
                ee->extensions_count = count;
2210
            }
2211
        }
2212
        if (ctx->opts.store_original_json) {
2213
            std::string raw = ext_it->dump();
2214
            ee->extensions_json = tg3__arena_str_from_std(ctx->arena, raw);
2215
        }
2216
    }
2217
}
2218
2219
/* ======================================================================
2220
 * Internal: Init functions for default struct values
2221
 * ====================================================================== */
2222
2223
static void tg3__init_texture_info(tg3_texture_info *ti) {
2224
    memset(ti, 0, sizeof(tg3_texture_info));
2225
    ti->index = -1;
2226
    ti->tex_coord = 0;
2227
}
2228
2229
static void tg3__init_normal_texture_info(tg3_normal_texture_info *ti) {
2230
    memset(ti, 0, sizeof(tg3_normal_texture_info));
2231
    ti->index = -1;
2232
    ti->tex_coord = 0;
2233
    ti->scale = 1.0;
2234
}
2235
2236
static void tg3__init_occlusion_texture_info(tg3_occlusion_texture_info *ti) {
2237
    memset(ti, 0, sizeof(tg3_occlusion_texture_info));
2238
    ti->index = -1;
2239
    ti->tex_coord = 0;
2240
    ti->strength = 1.0;
2241
}
2242
2243
static void tg3__init_pbr(tg3_pbr_metallic_roughness *pbr) {
2244
    memset(pbr, 0, sizeof(tg3_pbr_metallic_roughness));
2245
    pbr->base_color_factor[0] = 1.0;
2246
    pbr->base_color_factor[1] = 1.0;
2247
    pbr->base_color_factor[2] = 1.0;
2248
    pbr->base_color_factor[3] = 1.0;
2249
    pbr->metallic_factor = 1.0;
2250
    pbr->roughness_factor = 1.0;
2251
    tg3__init_texture_info(&pbr->base_color_texture);
2252
    tg3__init_texture_info(&pbr->metallic_roughness_texture);
2253
}
2254
2255
static void tg3__init_node(tg3_node *n) {
2256
    memset(n, 0, sizeof(tg3_node));
2257
    n->camera = -1;
2258
    n->skin = -1;
2259
    n->mesh = -1;
2260
    n->light = -1;
2261
    n->emitter = -1;
2262
    n->rotation[3] = 1.0; /* w=1 identity quaternion */
2263
    n->scale[0] = 1.0;
2264
    n->scale[1] = 1.0;
2265
    n->scale[2] = 1.0;
2266
    /* Identity matrix */
2267
    n->matrix[0]  = 1.0;
2268
    n->matrix[5]  = 1.0;
2269
    n->matrix[10] = 1.0;
2270
    n->matrix[15] = 1.0;
2271
}
2272
2273
/* ======================================================================
2274
 * Internal: Entity Parse Functions
2275
 * ====================================================================== */
2276
2277
static int tg3__parse_asset(tg3__parse_ctx *ctx, const tg3__json &o,
2278
                             tg3_asset *asset) {
2279
    memset(asset, 0, sizeof(tg3_asset));
2280
    tg3__parse_string(ctx, o, "version", &asset->version, 0, "/asset");
2281
    tg3__parse_string(ctx, o, "generator", &asset->generator, 0, "/asset");
2282
    tg3__parse_string(ctx, o, "minVersion", &asset->min_version, 0, "/asset");
2283
    tg3__parse_string(ctx, o, "copyright", &asset->copyright, 0, "/asset");
2284
    tg3__parse_extras_and_extensions(ctx, o, &asset->ext);
2285
    return 1;
2286
}
2287
2288
static int tg3__parse_texture_info(tg3__parse_ctx *ctx, const tg3__json &o,
2289
                                    const char *key, tg3_texture_info *ti) {
2290
    tg3__init_texture_info(ti);
2291
    auto it = o.find(key);
2292
    if (it == o.end()) return 1; /* Optional */
2293
    if (!it->is_object()) return 0;
2294
    tg3__parse_int(ctx, *it, "index", &ti->index, 0, key);
2295
    tg3__parse_int(ctx, *it, "texCoord", &ti->tex_coord, 0, key);
2296
    tg3__parse_extras_and_extensions(ctx, *it, &ti->ext);
2297
    return 1;
2298
}
2299
2300
static int tg3__parse_normal_texture_info(tg3__parse_ctx *ctx, const tg3__json &o,
2301
                                           const char *key,
2302
                                           tg3_normal_texture_info *ti) {
2303
    tg3__init_normal_texture_info(ti);
2304
    auto it = o.find(key);
2305
    if (it == o.end()) return 1;
2306
    if (!it->is_object()) return 0;
2307
    tg3__parse_int(ctx, *it, "index", &ti->index, 0, key);
2308
    tg3__parse_int(ctx, *it, "texCoord", &ti->tex_coord, 0, key);
2309
    tg3__parse_double(ctx, *it, "scale", &ti->scale, 0, key);
2310
    tg3__parse_extras_and_extensions(ctx, *it, &ti->ext);
2311
    return 1;
2312
}
2313
2314
static int tg3__parse_occlusion_texture_info(tg3__parse_ctx *ctx,
2315
                                              const tg3__json &o,
2316
                                              const char *key,
2317
                                              tg3_occlusion_texture_info *ti) {
2318
    tg3__init_occlusion_texture_info(ti);
2319
    auto it = o.find(key);
2320
    if (it == o.end()) return 1;
2321
    if (!it->is_object()) return 0;
2322
    tg3__parse_int(ctx, *it, "index", &ti->index, 0, key);
2323
    tg3__parse_int(ctx, *it, "texCoord", &ti->tex_coord, 0, key);
2324
    tg3__parse_double(ctx, *it, "strength", &ti->strength, 0, key);
2325
    tg3__parse_extras_and_extensions(ctx, *it, &ti->ext);
2326
    return 1;
2327
}
2328
2329
static int tg3__accessor_type_from_string(const char *s, size_t len) {
2330
    if (len == 6 && memcmp(s, "SCALAR", 6) == 0) return TG3_TYPE_SCALAR;
2331
    if (len == 4 && memcmp(s, "VEC2", 4) == 0) return TG3_TYPE_VEC2;
2332
    if (len == 4 && memcmp(s, "VEC3", 4) == 0) return TG3_TYPE_VEC3;
2333
    if (len == 4 && memcmp(s, "VEC4", 4) == 0) return TG3_TYPE_VEC4;
2334
    if (len == 4 && memcmp(s, "MAT2", 4) == 0) return TG3_TYPE_MAT2;
2335
    if (len == 4 && memcmp(s, "MAT3", 4) == 0) return TG3_TYPE_MAT3;
2336
    if (len == 4 && memcmp(s, "MAT4", 4) == 0) return TG3_TYPE_MAT4;
2337
    return -1;
2338
}
2339
2340
static const char *tg3__accessor_type_to_string(int type) {
2341
    switch (type) {
2342
        case TG3_TYPE_SCALAR: return "SCALAR";
2343
        case TG3_TYPE_VEC2:   return "VEC2";
2344
        case TG3_TYPE_VEC3:   return "VEC3";
2345
        case TG3_TYPE_VEC4:   return "VEC4";
2346
        case TG3_TYPE_MAT2:   return "MAT2";
2347
        case TG3_TYPE_MAT3:   return "MAT3";
2348
        case TG3_TYPE_MAT4:   return "MAT4";
2349
        default: return "";
2350
    }
2351
}
2352
2353
static int tg3__parse_accessor_sparse(tg3__parse_ctx *ctx, const tg3__json &o,
2354
                                       tg3_accessor_sparse *sparse) {
2355
    memset(sparse, 0, sizeof(tg3_accessor_sparse));
2356
    sparse->indices.buffer_view = -1;
2357
    sparse->values.buffer_view = -1;
2358
2359
    auto it = o.find("sparse");
2360
    if (it == o.end()) return 1;
2361
    if (!it->is_object()) return 0;
2362
2363
    sparse->is_sparse = 1;
2364
    tg3__parse_int(ctx, *it, "count", &sparse->count, 1, "/sparse");
2365
2366
    auto idx_it = it->find("indices");
2367
    if (idx_it != it->end() && idx_it->is_object()) {
2368
        tg3__parse_int(ctx, *idx_it, "bufferView",
2369
                       &sparse->indices.buffer_view, 1, "/sparse/indices");
2370
        tg3__parse_int(ctx, *idx_it, "componentType",
2371
                       &sparse->indices.component_type, 1, "/sparse/indices");
2372
        uint64_t bo = 0;
2373
        tg3__parse_uint64(ctx, *idx_it, "byteOffset", &bo, 0, "/sparse/indices");
2374
        sparse->indices.byte_offset = bo;
2375
        tg3__parse_extras_and_extensions(ctx, *idx_it, &sparse->indices.ext);
2376
    }
2377
2378
    auto val_it = it->find("values");
2379
    if (val_it != it->end() && val_it->is_object()) {
2380
        tg3__parse_int(ctx, *val_it, "bufferView",
2381
                       &sparse->values.buffer_view, 1, "/sparse/values");
2382
        uint64_t bo = 0;
2383
        tg3__parse_uint64(ctx, *val_it, "byteOffset", &bo, 0, "/sparse/values");
2384
        sparse->values.byte_offset = bo;
2385
        tg3__parse_extras_and_extensions(ctx, *val_it, &sparse->values.ext);
2386
    }
2387
2388
    tg3__parse_extras_and_extensions(ctx, *it, &sparse->ext);
2389
    return 1;
2390
}
2391
2392
static int tg3__parse_accessor(tg3__parse_ctx *ctx, const tg3__json &o,
2393
                                tg3_accessor *acc) {
2394
    memset(acc, 0, sizeof(tg3_accessor));
2395
    acc->buffer_view = -1;
2396
    acc->component_type = -1;
2397
    acc->type = -1;
2398
2399
    tg3__parse_string(ctx, o, "name", &acc->name, 0, "/accessor");
2400
    tg3__parse_int(ctx, o, "bufferView", &acc->buffer_view, 0, "/accessor");
2401
2402
    uint64_t bo = 0;
2403
    tg3__parse_uint64(ctx, o, "byteOffset", &bo, 0, "/accessor");
2404
    acc->byte_offset = bo;
2405
2406
    tg3__parse_bool(ctx, o, "normalized", &acc->normalized, 0, "/accessor");
2407
    tg3__parse_int(ctx, o, "componentType", &acc->component_type, 1, "/accessor");
2408
2409
    uint64_t cnt = 0;
2410
    tg3__parse_uint64(ctx, o, "count", &cnt, 1, "/accessor");
2411
    acc->count = cnt;
2412
2413
    /* Parse type string */
2414
    tg3_str type_str = {0, 0};
2415
    tg3__parse_string(ctx, o, "type", &type_str, 1, "/accessor");
2416
    if (type_str.data) {
2417
        acc->type = tg3__accessor_type_from_string(type_str.data, type_str.len);
2418
    }
2419
2420
    tg3__parse_number_array(ctx, o, "min", &acc->min_values, &acc->min_values_count,
2421
                             0, "/accessor");
2422
    tg3__parse_number_array(ctx, o, "max", &acc->max_values, &acc->max_values_count,
2423
                             0, "/accessor");
2424
2425
    tg3__parse_accessor_sparse(ctx, o, &acc->sparse);
2426
    tg3__parse_extras_and_extensions(ctx, o, &acc->ext);
2427
    return 1;
2428
}
2429
2430
static int tg3__load_external_file(tg3__parse_ctx *ctx, uint8_t **out_data,
2431
                                    uint64_t *out_size, const char *uri,
2432
                                    uint32_t uri_len) {
2433
    if (!ctx->opts.fs.read_file) {
2434
        tg3__error_push(ctx->errors, TG3_SEVERITY_ERROR, TG3_ERR_FS_NOT_AVAILABLE,
2435
                        "No filesystem callbacks available", NULL, -1);
2436
        return 0;
2437
    }
2438
2439
    /* Build full path: base_dir + "/" + uri */
2440
    char path_buf[4096];
2441
    uint32_t path_len = 0;
2442
    if (ctx->base_dir_len > 0) {
2443
        if (ctx->base_dir_len + 1 + uri_len >= sizeof(path_buf)) return 0;
2444
        memcpy(path_buf, ctx->base_dir, ctx->base_dir_len);
2445
        path_len = ctx->base_dir_len;
2446
        if (path_buf[path_len - 1] != '/' && path_buf[path_len - 1] != '\\') {
2447
            path_buf[path_len++] = '/';
2448
        }
2449
    }
2450
    if (path_len + uri_len >= sizeof(path_buf)) return 0;
2451
    memcpy(path_buf + path_len, uri, uri_len);
2452
    path_len += uri_len;
2453
    path_buf[path_len] = '\0';
2454
2455
    int32_t ok = ctx->opts.fs.read_file(out_data, out_size, path_buf, path_len,
2456
                                         ctx->opts.fs.user_data);
2457
    if (!ok) {
2458
        tg3__error_pushf(ctx->errors, ctx->arena, TG3_SEVERITY_ERROR,
2459
                         TG3_ERR_FILE_READ, NULL, "Failed to read file: %s", path_buf);
2460
        return 0;
2461
    }
2462
    return 1;
2463
}
2464
2465
static int tg3__parse_buffer(tg3__parse_ctx *ctx, const tg3__json &o,
2466
                              tg3_buffer *buf, int32_t buf_idx) {
2467
    memset(buf, 0, sizeof(tg3_buffer));
2468
    tg3__parse_string(ctx, o, "name", &buf->name, 0, "/buffer");
2469
    tg3__parse_string(ctx, o, "uri", &buf->uri, 0, "/buffer");
2470
2471
    uint64_t byte_length = 0;
2472
    tg3__parse_uint64(ctx, o, "byteLength", &byte_length, 1, "/buffer");
2473
2474
    /* Load buffer data */
2475
    if (ctx->is_binary && buf_idx == 0 && buf->uri.len == 0) {
2476
        /* GLB: first buffer uses binary chunk */
2477
        if (!ctx->bin_data || ctx->bin_size < byte_length) {
2478
            tg3__error_push(ctx->errors, TG3_SEVERITY_ERROR,
2479
                            TG3_ERR_BUFFER_SIZE_MISMATCH,
2480
                            "GLB BIN chunk missing or smaller than buffer.byteLength",
2481
                            NULL, -1);
2482
            return 0;
2483
        }
2484
        uint8_t *data = (uint8_t *)tg3__arena_alloc(ctx->arena, (size_t)byte_length);
2485
        if (!data) {
2486
            tg3__error_push(ctx->errors, TG3_SEVERITY_ERROR,
2487
                            TG3_ERR_OUT_OF_MEMORY, "OOM for buffer data", NULL, -1);
2488
            return 0;
2489
        }
2490
        memcpy(data, ctx->bin_data, (size_t)byte_length);
2491
        buf->data.data = data;
2492
        buf->data.count = byte_length;
2493
    } else if (buf->uri.len > 0) {
2494
        if (tg3_is_data_uri(buf->uri.data, buf->uri.len)) {
2495
            /* Data URI */
2496
            size_t decoded_len = 0;
2497
            char mime[64] = {0};
2498
            uint8_t *decoded = tg3__decode_data_uri(ctx->arena, buf->uri.data,
2499
                                                     buf->uri.len, &decoded_len,
2500
                                                     mime, sizeof(mime));
2501
            if (!decoded && byte_length > 0) {
2502
                tg3__error_push(ctx->errors, TG3_SEVERITY_ERROR,
2503
                                TG3_ERR_DATA_URI_DECODE,
2504
                                "Failed to decode buffer data URI", NULL, -1);
2505
                return 0;
2506
            }
2507
            buf->data.data = decoded;
2508
            buf->data.count = decoded_len;
2509
        } else {
2510
            /* External file */
2511
            uint8_t *file_data = NULL;
2512
            uint64_t file_size = 0;
2513
            if (tg3__load_external_file(ctx, &file_data, &file_size,
2514
                                         buf->uri.data, buf->uri.len)) {
2515
                /* Copy into arena */
2516
                uint8_t *data = (uint8_t *)tg3__arena_alloc(ctx->arena, (size_t)file_size);
2517
                if (data) {
2518
                    memcpy(data, file_data, (size_t)file_size);
2519
                    buf->data.data = data;
2520
                    buf->data.count = file_size;
2521
                }
2522
                /* Free file data via callback */
2523
                if (ctx->opts.fs.free_file) {
2524
                    ctx->opts.fs.free_file(file_data, file_size,
2525
                                           ctx->opts.fs.user_data);
2526
                }
2527
            }
2528
        }
2529
    }
2530
2531
    tg3__parse_extras_and_extensions(ctx, o, &buf->ext);
2532
    return 1;
2533
}
2534
2535
static int tg3__parse_buffer_view(tg3__parse_ctx *ctx, const tg3__json &o,
2536
                                   tg3_buffer_view *bv) {
2537
    memset(bv, 0, sizeof(tg3_buffer_view));
2538
    bv->buffer = -1;
2539
2540
    tg3__parse_string(ctx, o, "name", &bv->name, 0, "/bufferView");
2541
    tg3__parse_int(ctx, o, "buffer", &bv->buffer, 1, "/bufferView");
2542
2543
    uint64_t val = 0;
2544
    tg3__parse_uint64(ctx, o, "byteOffset", &val, 0, "/bufferView");
2545
    bv->byte_offset = val;
2546
    val = 0;
2547
    tg3__parse_uint64(ctx, o, "byteLength", &val, 1, "/bufferView");
2548
    bv->byte_length = val;
2549
2550
    int32_t stride = 0;
2551
    tg3__parse_int(ctx, o, "byteStride", &stride, 0, "/bufferView");
2552
    bv->byte_stride = (uint32_t)stride;
2553
2554
    tg3__parse_int(ctx, o, "target", &bv->target, 0, "/bufferView");
2555
    tg3__parse_extras_and_extensions(ctx, o, &bv->ext);
2556
    return 1;
2557
}
2558
2559
static int tg3__parse_image(tg3__parse_ctx *ctx, const tg3__json &o,
2560
                             tg3_image *img, int32_t /*img_idx*/) {
2561
    memset(img, 0, sizeof(tg3_image));
2562
    img->width = -1;
2563
    img->height = -1;
2564
    img->component = -1;
2565
    img->bits = -1;
2566
    img->pixel_type = -1;
2567
    img->buffer_view = -1;
2568
2569
    tg3__parse_string(ctx, o, "name", &img->name, 0, "/image");
2570
    tg3__parse_string(ctx, o, "uri", &img->uri, 0, "/image");
2571
    tg3__parse_string(ctx, o, "mimeType", &img->mime_type, 0, "/image");
2572
    tg3__parse_int(ctx, o, "bufferView", &img->buffer_view, 0, "/image");
2573
2574
    if (ctx->opts.images_as_is) {
2575
        img->as_is = 1;
2576
    }
2577
2578
    tg3__parse_extras_and_extensions(ctx, o, &img->ext);
2579
    return 1;
2580
}
2581
2582
static int tg3__parse_sampler(tg3__parse_ctx *ctx, const tg3__json &o,
2583
                               tg3_sampler *samp) {
2584
    memset(samp, 0, sizeof(tg3_sampler));
2585
    samp->min_filter = -1;
2586
    samp->mag_filter = -1;
2587
    samp->wrap_s = TG3_TEXTURE_WRAP_REPEAT;
2588
    samp->wrap_t = TG3_TEXTURE_WRAP_REPEAT;
2589
2590
    tg3__parse_string(ctx, o, "name", &samp->name, 0, "/sampler");
2591
    tg3__parse_int(ctx, o, "minFilter", &samp->min_filter, 0, "/sampler");
2592
    tg3__parse_int(ctx, o, "magFilter", &samp->mag_filter, 0, "/sampler");
2593
    tg3__parse_int(ctx, o, "wrapS", &samp->wrap_s, 0, "/sampler");
2594
    tg3__parse_int(ctx, o, "wrapT", &samp->wrap_t, 0, "/sampler");
2595
    tg3__parse_extras_and_extensions(ctx, o, &samp->ext);
2596
    return 1;
2597
}
2598
2599
static int tg3__parse_texture(tg3__parse_ctx *ctx, const tg3__json &o,
2600
                               tg3_texture *tex) {
2601
    memset(tex, 0, sizeof(tg3_texture));
2602
    tex->sampler = -1;
2603
    tex->source = -1;
2604
2605
    tg3__parse_string(ctx, o, "name", &tex->name, 0, "/texture");
2606
    tg3__parse_int(ctx, o, "sampler", &tex->sampler, 0, "/texture");
2607
    tg3__parse_int(ctx, o, "source", &tex->source, 0, "/texture");
2608
    tg3__parse_extras_and_extensions(ctx, o, &tex->ext);
2609
    return 1;
2610
}
2611
2612
static int tg3__parse_material(tg3__parse_ctx *ctx, const tg3__json &o,
2613
                                tg3_material *mat) {
2614
    memset(mat, 0, sizeof(tg3_material));
2615
    tg3__init_pbr(&mat->pbr_metallic_roughness);
2616
    tg3__init_normal_texture_info(&mat->normal_texture);
2617
    tg3__init_occlusion_texture_info(&mat->occlusion_texture);
2618
    tg3__init_texture_info(&mat->emissive_texture);
2619
    mat->alpha_cutoff = 0.5;
2620
2621
    tg3__parse_string(ctx, o, "name", &mat->name, 0, "/material");
2622
2623
    /* Emissive factor */
2624
    tg3__parse_number_to_fixed(o, "emissiveFactor", mat->emissive_factor, 3);
2625
2626
    /* Alpha mode */
2627
    tg3_str alpha_mode = {0, 0};
2628
    tg3__parse_string(ctx, o, "alphaMode", &alpha_mode, 0, "/material");
2629
    if (alpha_mode.len > 0) {
2630
        mat->alpha_mode = alpha_mode;
2631
    } else {
2632
        mat->alpha_mode = tg3__arena_str(ctx->arena, "OPAQUE", 6);
2633
    }
2634
2635
    tg3__parse_double(ctx, o, "alphaCutoff", &mat->alpha_cutoff, 0, "/material");
2636
    tg3__parse_bool(ctx, o, "doubleSided", &mat->double_sided, 0, "/material");
2637
2638
    /* PBR */
2639
    auto pbr_it = o.find("pbrMetallicRoughness");
2640
    if (pbr_it != o.end() && pbr_it->is_object()) {
2641
        tg3__parse_number_to_fixed(*pbr_it, "baseColorFactor",
2642
                                    mat->pbr_metallic_roughness.base_color_factor, 4);
2643
        tg3__parse_double(ctx, *pbr_it, "metallicFactor",
2644
                          &mat->pbr_metallic_roughness.metallic_factor, 0,
2645
                          "/material/pbrMetallicRoughness");
2646
        tg3__parse_double(ctx, *pbr_it, "roughnessFactor",
2647
                          &mat->pbr_metallic_roughness.roughness_factor, 0,
2648
                          "/material/pbrMetallicRoughness");
2649
        tg3__parse_texture_info(ctx, *pbr_it, "baseColorTexture",
2650
                                &mat->pbr_metallic_roughness.base_color_texture);
2651
        tg3__parse_texture_info(ctx, *pbr_it, "metallicRoughnessTexture",
2652
                                &mat->pbr_metallic_roughness.metallic_roughness_texture);
2653
        tg3__parse_extras_and_extensions(ctx, *pbr_it,
2654
                                          &mat->pbr_metallic_roughness.ext);
2655
    }
2656
2657
    tg3__parse_normal_texture_info(ctx, o, "normalTexture", &mat->normal_texture);
2658
    tg3__parse_occlusion_texture_info(ctx, o, "occlusionTexture",
2659
                                       &mat->occlusion_texture);
2660
    tg3__parse_texture_info(ctx, o, "emissiveTexture", &mat->emissive_texture);
2661
2662
    /* MSFT_lod */
2663
    auto ext_it = o.find("extensions");
2664
    if (ext_it != o.end() && ext_it->is_object()) {
2665
        auto lod_it = ext_it->find("MSFT_lod");
2666
        if (lod_it != ext_it->end() && lod_it->is_object()) {
2667
            tg3__parse_int_array(ctx, *lod_it, "ids",
2668
                                 &mat->lods, &mat->lods_count, 0,
2669
                                 "/material/extensions/MSFT_lod");
2670
        }
2671
    }
2672
2673
    tg3__parse_extras_and_extensions(ctx, o, &mat->ext);
2674
    return 1;
2675
}
2676
2677
static int tg3__parse_primitive(tg3__parse_ctx *ctx, const tg3__json &o,
2678
                                 tg3_primitive *prim) {
2679
    memset(prim, 0, sizeof(tg3_primitive));
2680
    prim->material = -1;
2681
    prim->indices = -1;
2682
    prim->mode = TG3_MODE_TRIANGLES;
2683
2684
    tg3__parse_int(ctx, o, "material", &prim->material, 0, "/primitive");
2685
    tg3__parse_int(ctx, o, "indices", &prim->indices, 0, "/primitive");
2686
    tg3__parse_int(ctx, o, "mode", &prim->mode, 0, "/primitive");
2687
2688
    /* Attributes */
2689
    auto attr_it = o.find("attributes");
2690
    if (attr_it != o.end() && attr_it->is_object()) {
2691
        uint32_t count = (uint32_t)attr_it->size();
2692
        if (count > 0) {
2693
            tg3_str_int_pair *attrs = (tg3_str_int_pair *)tg3__arena_alloc(
2694
                ctx->arena, count * sizeof(tg3_str_int_pair));
2695
            if (attrs) {
2696
                uint32_t i = 0;
2697
                for (auto it = attr_it->begin(); it != attr_it->end(); ++it, ++i) {
2698
                    std::string k = it.key();
2699
                    attrs[i].key = tg3__arena_str_from_std(ctx->arena, k);
2700
                    attrs[i].value = it->get<int>();
2701
                }
2702
                prim->attributes = attrs;
2703
                prim->attributes_count = count;
2704
            }
2705
        }
2706
    }
2707
2708
    /* Morph targets */
2709
    auto targets_it = o.find("targets");
2710
    if (targets_it != o.end() && targets_it->is_array()) {
2711
        uint32_t tcount = (uint32_t)targets_it->size();
2712
        if (tcount > 0) {
2713
            const tg3_str_int_pair **target_arrays =
2714
                (const tg3_str_int_pair **)tg3__arena_alloc(
2715
                    ctx->arena, tcount * sizeof(tg3_str_int_pair *));
2716
            uint32_t *target_counts = (uint32_t *)tg3__arena_alloc(
2717
                ctx->arena, tcount * sizeof(uint32_t));
2718
            if (target_arrays && target_counts) {
2719
                uint32_t ti = 0;
2720
                for (auto tit = targets_it->begin(); tit != targets_it->end(); ++tit, ++ti) {
2721
                    if (!tit->is_object()) {
2722
                        target_arrays[ti] = NULL;
2723
                        target_counts[ti] = 0;
2724
                        continue;
2725
                    }
2726
                    uint32_t acount = (uint32_t)tit->size();
2727
                    tg3_str_int_pair *tattrs = (tg3_str_int_pair *)tg3__arena_alloc(
2728
                        ctx->arena, acount * sizeof(tg3_str_int_pair));
2729
                    if (tattrs) {
2730
                        uint32_t ai = 0;
2731
                        for (auto ait = tit->begin(); ait != tit->end(); ++ait, ++ai) {
2732
                            std::string k = ait.key();
2733
                            tattrs[ai].key = tg3__arena_str_from_std(ctx->arena, k);
2734
                            tattrs[ai].value = ait->get<int>();
2735
                        }
2736
                    }
2737
                    target_arrays[ti] = tattrs;
2738
                    target_counts[ti] = acount;
2739
                }
2740
                prim->targets = target_arrays;
2741
                prim->target_attribute_counts = target_counts;
2742
                prim->targets_count = tcount;
2743
            }
2744
        }
2745
    }
2746
2747
    tg3__parse_extras_and_extensions(ctx, o, &prim->ext);
2748
    return 1;
2749
}
2750
2751
static int tg3__parse_mesh(tg3__parse_ctx *ctx, const tg3__json &o,
2752
                            tg3_mesh *mesh) {
2753
    memset(mesh, 0, sizeof(tg3_mesh));
2754
    tg3__parse_string(ctx, o, "name", &mesh->name, 0, "/mesh");
2755
2756
    /* Primitives */
2757
    auto prim_it = o.find("primitives");
2758
    if (prim_it != o.end() && prim_it->is_array()) {
2759
        uint32_t count = (uint32_t)prim_it->size();
2760
        if (count > 0) {
2761
            tg3_primitive *prims = (tg3_primitive *)tg3__arena_alloc(
2762
                ctx->arena, count * sizeof(tg3_primitive));
2763
            if (prims) {
2764
                uint32_t i = 0;
2765
                for (auto it = prim_it->begin(); it != prim_it->end(); ++it, ++i) {
2766
                    tg3__parse_primitive(ctx, *it, &prims[i]);
2767
                }
2768
                mesh->primitives = prims;
2769
                mesh->primitives_count = count;
2770
            }
2771
        }
2772
    }
2773
2774
    tg3__parse_number_array(ctx, o, "weights", &mesh->weights,
2775
                             &mesh->weights_count, 0, "/mesh");
2776
    tg3__parse_extras_and_extensions(ctx, o, &mesh->ext);
2777
    return 1;
2778
}
2779
2780
static int tg3__parse_node(tg3__parse_ctx *ctx, const tg3__json &o,
2781
                            tg3_node *node) {
2782
    tg3__init_node(node);
2783
2784
    tg3__parse_string(ctx, o, "name", &node->name, 0, "/node");
2785
    tg3__parse_int(ctx, o, "camera", &node->camera, 0, "/node");
2786
    tg3__parse_int(ctx, o, "skin", &node->skin, 0, "/node");
2787
    tg3__parse_int(ctx, o, "mesh", &node->mesh, 0, "/node");
2788
2789
    tg3__parse_int_array(ctx, o, "children", &node->children,
2790
                          &node->children_count, 0, "/node");
2791
2792
    /* TRS */
2793
    if (tg3__json_has(o, "matrix")) {
2794
        tg3__parse_number_to_fixed(o, "matrix", node->matrix, 16);
2795
        node->has_matrix = 1;
2796
    }
2797
    if (tg3__json_has(o, "translation")) {
2798
        tg3__parse_number_to_fixed(o, "translation", node->translation, 3);
2799
    }
2800
    if (tg3__json_has(o, "rotation")) {
2801
        tg3__parse_number_to_fixed(o, "rotation", node->rotation, 4);
2802
    }
2803
    if (tg3__json_has(o, "scale")) {
2804
        tg3__parse_number_to_fixed(o, "scale", node->scale, 3);
2805
    }
2806
2807
    tg3__parse_number_array(ctx, o, "weights", &node->weights,
2808
                             &node->weights_count, 0, "/node");
2809
2810
    /* Extensions: KHR_lights_punctual, KHR_audio, MSFT_lod */
2811
    auto ext_it = o.find("extensions");
2812
    if (ext_it != o.end() && ext_it->is_object()) {
2813
        auto khr_lights = ext_it->find("KHR_lights_punctual");
2814
        if (khr_lights != ext_it->end() && khr_lights->is_object()) {
2815
            tg3__parse_int(ctx, *khr_lights, "light", &node->light, 0,
2816
                          "/node/extensions/KHR_lights_punctual");
2817
        }
2818
        auto khr_audio = ext_it->find("KHR_audio");
2819
        if (khr_audio != ext_it->end() && khr_audio->is_object()) {
2820
            tg3__parse_int(ctx, *khr_audio, "emitter", &node->emitter, 0,
2821
                          "/node/extensions/KHR_audio");
2822
        }
2823
        auto msft_lod = ext_it->find("MSFT_lod");
2824
        if (msft_lod != ext_it->end() && msft_lod->is_object()) {
2825
            tg3__parse_int_array(ctx, *msft_lod, "ids",
2826
                                 &node->lods, &node->lods_count, 0,
2827
                                 "/node/extensions/MSFT_lod");
2828
        }
2829
    }
2830
2831
    tg3__parse_extras_and_extensions(ctx, o, &node->ext);
2832
    return 1;
2833
}
2834
2835
static int tg3__parse_skin(tg3__parse_ctx *ctx, const tg3__json &o,
2836
                            tg3_skin *skin) {
2837
    memset(skin, 0, sizeof(tg3_skin));
2838
    skin->inverse_bind_matrices = -1;
2839
    skin->skeleton = -1;
2840
2841
    tg3__parse_string(ctx, o, "name", &skin->name, 0, "/skin");
2842
    tg3__parse_int(ctx, o, "inverseBindMatrices", &skin->inverse_bind_matrices,
2843
                   0, "/skin");
2844
    tg3__parse_int(ctx, o, "skeleton", &skin->skeleton, 0, "/skin");
2845
    tg3__parse_int_array(ctx, o, "joints", &skin->joints,
2846
                          &skin->joints_count, 1, "/skin");
2847
    tg3__parse_extras_and_extensions(ctx, o, &skin->ext);
2848
    return 1;
2849
}
2850
2851
static int tg3__parse_animation(tg3__parse_ctx *ctx, const tg3__json &o,
2852
                                 tg3_animation *anim) {
2853
    memset(anim, 0, sizeof(tg3_animation));
2854
    tg3__parse_string(ctx, o, "name", &anim->name, 0, "/animation");
2855
2856
    /* Channels */
2857
    auto ch_it = o.find("channels");
2858
    if (ch_it != o.end() && ch_it->is_array()) {
2859
        uint32_t count = (uint32_t)ch_it->size();
2860
        if (count > 0) {
2861
            tg3_animation_channel *channels = (tg3_animation_channel *)tg3__arena_alloc(
2862
                ctx->arena, count * sizeof(tg3_animation_channel));
2863
            if (channels) {
2864
                uint32_t i = 0;
2865
                for (auto it = ch_it->begin(); it != ch_it->end(); ++it, ++i) {
2866
                    memset(&channels[i], 0, sizeof(tg3_animation_channel));
2867
                    channels[i].sampler = -1;
2868
                    channels[i].target.node = -1;
2869
2870
                    tg3__parse_int(ctx, *it, "sampler", &channels[i].sampler,
2871
                                   1, "/animation/channel");
2872
2873
                    auto tgt_it = it->find("target");
2874
                    if (tgt_it != it->end() && tgt_it->is_object()) {
2875
                        tg3__parse_int(ctx, *tgt_it, "node",
2876
                                       &channels[i].target.node, 0,
2877
                                       "/animation/channel/target");
2878
                        tg3__parse_string(ctx, *tgt_it, "path",
2879
                                          &channels[i].target.path, 1,
2880
                                          "/animation/channel/target");
2881
                        tg3__parse_extras_and_extensions(ctx, *tgt_it,
2882
                                                          &channels[i].target.ext);
2883
                    }
2884
                    tg3__parse_extras_and_extensions(ctx, *it, &channels[i].ext);
2885
                }
2886
                anim->channels = channels;
2887
                anim->channels_count = count;
2888
            }
2889
        }
2890
    }
2891
2892
    /* Samplers */
2893
    auto samp_it = o.find("samplers");
2894
    if (samp_it != o.end() && samp_it->is_array()) {
2895
        uint32_t count = (uint32_t)samp_it->size();
2896
        if (count > 0) {
2897
            tg3_animation_sampler *samplers = (tg3_animation_sampler *)tg3__arena_alloc(
2898
                ctx->arena, count * sizeof(tg3_animation_sampler));
2899
            if (samplers) {
2900
                uint32_t i = 0;
2901
                for (auto it = samp_it->begin(); it != samp_it->end(); ++it, ++i) {
2902
                    memset(&samplers[i], 0, sizeof(tg3_animation_sampler));
2903
                    samplers[i].input = -1;
2904
                    samplers[i].output = -1;
2905
2906
                    tg3__parse_int(ctx, *it, "input", &samplers[i].input,
2907
                                   1, "/animation/sampler");
2908
                    tg3__parse_int(ctx, *it, "output", &samplers[i].output,
2909
                                   1, "/animation/sampler");
2910
2911
                    tg3_str interp = {0, 0};
2912
                    tg3__parse_string(ctx, *it, "interpolation", &interp,
2913
                                      0, "/animation/sampler");
2914
                    if (interp.len > 0) {
2915
                        samplers[i].interpolation = interp;
2916
                    } else {
2917
                        samplers[i].interpolation = tg3__arena_str(ctx->arena,
2918
                                                                     "LINEAR", 6);
2919
                    }
2920
                    tg3__parse_extras_and_extensions(ctx, *it, &samplers[i].ext);
2921
                }
2922
                anim->samplers = samplers;
2923
                anim->samplers_count = count;
2924
            }
2925
        }
2926
    }
2927
2928
    tg3__parse_extras_and_extensions(ctx, o, &anim->ext);
2929
    return 1;
2930
}
2931
2932
static int tg3__parse_camera(tg3__parse_ctx *ctx, const tg3__json &o,
2933
                              tg3_camera *cam) {
2934
    memset(cam, 0, sizeof(tg3_camera));
2935
    tg3__parse_string(ctx, o, "name", &cam->name, 0, "/camera");
2936
    tg3__parse_string(ctx, o, "type", &cam->type, 1, "/camera");
2937
2938
    if (cam->type.data && tg3_str_equals_cstr(cam->type, "perspective")) {
2939
        auto p_it = o.find("perspective");
2940
        if (p_it != o.end() && p_it->is_object()) {
2941
            tg3__parse_double(ctx, *p_it, "aspectRatio",
2942
                              &cam->perspective.aspect_ratio, 0, "/camera/perspective");
2943
            tg3__parse_double(ctx, *p_it, "yfov",
2944
                              &cam->perspective.yfov, 1, "/camera/perspective");
2945
            tg3__parse_double(ctx, *p_it, "zfar",
2946
                              &cam->perspective.zfar, 0, "/camera/perspective");
2947
            tg3__parse_double(ctx, *p_it, "znear",
2948
                              &cam->perspective.znear, 1, "/camera/perspective");
2949
            tg3__parse_extras_and_extensions(ctx, *p_it, &cam->perspective.ext);
2950
        }
2951
    } else if (cam->type.data && tg3_str_equals_cstr(cam->type, "orthographic")) {
2952
        auto o_it = o.find("orthographic");
2953
        if (o_it != o.end() && o_it->is_object()) {
2954
            tg3__parse_double(ctx, *o_it, "xmag",
2955
                              &cam->orthographic.xmag, 1, "/camera/orthographic");
2956
            tg3__parse_double(ctx, *o_it, "ymag",
2957
                              &cam->orthographic.ymag, 1, "/camera/orthographic");
2958
            tg3__parse_double(ctx, *o_it, "zfar",
2959
                              &cam->orthographic.zfar, 1, "/camera/orthographic");
2960
            tg3__parse_double(ctx, *o_it, "znear",
2961
                              &cam->orthographic.znear, 1, "/camera/orthographic");
2962
            tg3__parse_extras_and_extensions(ctx, *o_it, &cam->orthographic.ext);
2963
        }
2964
    }
2965
2966
    tg3__parse_extras_and_extensions(ctx, o, &cam->ext);
2967
    return 1;
2968
}
2969
2970
static int tg3__parse_scene(tg3__parse_ctx *ctx, const tg3__json &o,
2971
                             tg3_scene *scene) {
2972
    memset(scene, 0, sizeof(tg3_scene));
2973
    tg3__parse_string(ctx, o, "name", &scene->name, 0, "/scene");
2974
    tg3__parse_int_array(ctx, o, "nodes", &scene->nodes,
2975
                          &scene->nodes_count, 0, "/scene");
2976
2977
    /* KHR_audio emitters */
2978
    auto ext_it = o.find("extensions");
2979
    if (ext_it != o.end() && ext_it->is_object()) {
2980
        auto audio_it = ext_it->find("KHR_audio");
2981
        if (audio_it != ext_it->end() && audio_it->is_object()) {
2982
            tg3__parse_int_array(ctx, *audio_it, "emitters",
2983
                                 &scene->audio_emitters,
2984
                                 &scene->audio_emitters_count, 0,
2985
                                 "/scene/extensions/KHR_audio");
2986
        }
2987
    }
2988
2989
    tg3__parse_extras_and_extensions(ctx, o, &scene->ext);
2990
    return 1;
2991
}
2992
2993
static int tg3__parse_light(tg3__parse_ctx *ctx, const tg3__json &o,
2994
                             tg3_light *light) {
2995
    memset(light, 0, sizeof(tg3_light));
2996
    light->color[0] = 1.0;
2997
    light->color[1] = 1.0;
2998
    light->color[2] = 1.0;
2999
    light->intensity = 1.0;
3000
    light->spot.outer_cone_angle = 0.7853981634;
3001
3002
    tg3__parse_string(ctx, o, "name", &light->name, 0, "/light");
3003
    tg3__parse_string(ctx, o, "type", &light->type, 1, "/light");
3004
    tg3__parse_double(ctx, o, "intensity", &light->intensity, 0, "/light");
3005
    tg3__parse_double(ctx, o, "range", &light->range, 0, "/light");
3006
    tg3__parse_number_to_fixed(o, "color", light->color, 3);
3007
3008
    auto spot_it = o.find("spot");
3009
    if (spot_it != o.end() && spot_it->is_object()) {
3010
        tg3__parse_double(ctx, *spot_it, "innerConeAngle",
3011
                          &light->spot.inner_cone_angle, 0, "/light/spot");
3012
        tg3__parse_double(ctx, *spot_it, "outerConeAngle",
3013
                          &light->spot.outer_cone_angle, 0, "/light/spot");
3014
        tg3__parse_extras_and_extensions(ctx, *spot_it, &light->spot.ext);
3015
    }
3016
3017
    tg3__parse_extras_and_extensions(ctx, o, &light->ext);
3018
    return 1;
3019
}
3020
3021
static int tg3__parse_audio_source(tg3__parse_ctx *ctx, const tg3__json &o,
3022
                                    tg3_audio_source *src) {
3023
    memset(src, 0, sizeof(tg3_audio_source));
3024
    src->buffer_view = -1;
3025
3026
    tg3__parse_string(ctx, o, "name", &src->name, 0, "/audioSource");
3027
    tg3__parse_string(ctx, o, "uri", &src->uri, 0, "/audioSource");
3028
    tg3__parse_int(ctx, o, "bufferView", &src->buffer_view, 0, "/audioSource");
3029
    tg3__parse_string(ctx, o, "mimeType", &src->mime_type, 0, "/audioSource");
3030
    tg3__parse_extras_and_extensions(ctx, o, &src->ext);
3031
    return 1;
3032
}
3033
3034
static int tg3__parse_audio_emitter(tg3__parse_ctx *ctx, const tg3__json &o,
3035
                                     tg3_audio_emitter *emitter) {
3036
    memset(emitter, 0, sizeof(tg3_audio_emitter));
3037
    emitter->gain = 1.0;
3038
    emitter->source = -1;
3039
    emitter->positional.cone_inner_angle = 6.283185307179586;
3040
    emitter->positional.cone_outer_angle = 6.283185307179586;
3041
    emitter->positional.max_distance = 100.0;
3042
    emitter->positional.ref_distance = 1.0;
3043
    emitter->positional.rolloff_factor = 1.0;
3044
3045
    tg3__parse_string(ctx, o, "name", &emitter->name, 0, "/audioEmitter");
3046
    tg3__parse_double(ctx, o, "gain", &emitter->gain, 0, "/audioEmitter");
3047
    tg3__parse_bool(ctx, o, "loop", &emitter->loop, 0, "/audioEmitter");
3048
    tg3__parse_bool(ctx, o, "playing", &emitter->playing, 0, "/audioEmitter");
3049
    tg3__parse_string(ctx, o, "type", &emitter->type, 0, "/audioEmitter");
3050
    tg3__parse_string(ctx, o, "distanceModel", &emitter->distance_model,
3051
                       0, "/audioEmitter");
3052
    tg3__parse_int(ctx, o, "source", &emitter->source, 0, "/audioEmitter");
3053
3054
    auto pos_it = o.find("positional");
3055
    if (pos_it != o.end() && pos_it->is_object()) {
3056
        tg3__parse_double(ctx, *pos_it, "coneInnerAngle",
3057
                          &emitter->positional.cone_inner_angle, 0, "/positional");
3058
        tg3__parse_double(ctx, *pos_it, "coneOuterAngle",
3059
                          &emitter->positional.cone_outer_angle, 0, "/positional");
3060
        tg3__parse_double(ctx, *pos_it, "coneOuterGain",
3061
                          &emitter->positional.cone_outer_gain, 0, "/positional");
3062
        tg3__parse_double(ctx, *pos_it, "maxDistance",
3063
                          &emitter->positional.max_distance, 0, "/positional");
3064
        tg3__parse_double(ctx, *pos_it, "refDistance",
3065
                          &emitter->positional.ref_distance, 0, "/positional");
3066
        tg3__parse_double(ctx, *pos_it, "rolloffFactor",
3067
                          &emitter->positional.rolloff_factor, 0, "/positional");
3068
        tg3__parse_extras_and_extensions(ctx, *pos_it, &emitter->positional.ext);
3069
    }
3070
3071
    tg3__parse_extras_and_extensions(ctx, o, &emitter->ext);
3072
    return 1;
3073
}
3074
3075
/* ======================================================================
3076
 * Internal: Portable variadic-comma helper
3077
 *
3078
 * TG3__COMMA_VA_ARGS(__VA_ARGS__) expands to  , __VA_ARGS__  when the
3079
 * argument list is non-empty, and to nothing when it is empty.
3080
 *
3081
 * - C++20 and later: uses the standard __VA_OPT__(,) token.
3082
 * - C++17 and earlier: falls back to the widely-supported GNU/MSVC
3083
 *   ##__VA_ARGS__ extension.
3084
 * ====================================================================== */
3085
#if __cplusplus >= 202002L
3086
#  define TG3__COMMA_VA_ARGS(...) __VA_OPT__(,) __VA_ARGS__
3087
#else
3088
#  define TG3__COMMA_VA_ARGS(...) , ##__VA_ARGS__
3089
#endif
3090
3091
/* ======================================================================
3092
 * Internal: Array Parse Macro
3093
 * ====================================================================== */
3094
3095
#define TG3__PARSE_ARRAY(ctx, json_doc, json_key, Type, model_field, count_field, parse_fn, ...) \
3096
    do { \
3097
        auto _arr_it = (json_doc).find(json_key); \
3098
        if (_arr_it != (json_doc).end() && _arr_it->is_array()) { \
3099
            uint32_t _count = (uint32_t)_arr_it->size(); \
3100
            if (_count > 0) { \
3101
                Type *_items = (Type *)tg3__arena_alloc((ctx)->arena, \
3102
                    _count * sizeof(Type)); \
3103
                if (_items) { \
3104
                    uint32_t _i = 0; \
3105
                    for (auto _it = _arr_it->begin(); _it != _arr_it->end(); ++_it, ++_i) { \
3106
                        parse_fn((ctx), *_it, &_items[_i] TG3__COMMA_VA_ARGS(__VA_ARGS__)); \
3107
                    } \
3108
                    (model_field) = _items; \
3109
                    (count_field) = _count; \
3110
                } \
3111
            } \
3112
        } \
3113
    } while (0)
3114
3115
/* Variant without extra args and with index param */
3116
#define TG3__PARSE_ARRAY_IDX(ctx, json_doc, json_key, Type, model_field, count_field, parse_fn) \
3117
    do { \
3118
        auto _arr_it = (json_doc).find(json_key); \
3119
        if (_arr_it != (json_doc).end() && _arr_it->is_array()) { \
3120
            uint32_t _count = (uint32_t)_arr_it->size(); \
3121
            if (_count > 0) { \
3122
                Type *_items = (Type *)tg3__arena_alloc((ctx)->arena, \
3123
                    _count * sizeof(Type)); \
3124
                if (_items) { \
3125
                    uint32_t _i = 0; \
3126
                    for (auto _it = _arr_it->begin(); _it != _arr_it->end(); ++_it, ++_i) { \
3127
                        if (!_it->is_object()) { \
3128
                            tg3__error_pushf((ctx)->errors, (ctx)->arena, \
3129
                                TG3_SEVERITY_ERROR, TG3_ERR_JSON_TYPE_MISMATCH, \
3130
                                json_key, "Element %u must be an object", _i); \
3131
                            continue; \
3132
                        } \
3133
                        parse_fn((ctx), *_it, &_items[_i], (int32_t)_i); \
3134
                    } \
3135
                    (model_field) = _items; \
3136
                    (count_field) = _count; \
3137
                } \
3138
            } \
3139
        } \
3140
    } while (0)
3141
3142
/* Simpler variant for entities without index */
3143
#define TG3__PARSE_ARRAY_SIMPLE(ctx, json_doc, json_key, Type, model_field, count_field, parse_fn) \
3144
    do { \
3145
        auto _arr_it = (json_doc).find(json_key); \
3146
        if (_arr_it != (json_doc).end() && _arr_it->is_array()) { \
3147
            uint32_t _count = (uint32_t)_arr_it->size(); \
3148
            if (_count > 0) { \
3149
                Type *_items = (Type *)tg3__arena_alloc((ctx)->arena, \
3150
                    _count * sizeof(Type)); \
3151
                if (_items) { \
3152
                    uint32_t _i = 0; \
3153
                    for (auto _it = _arr_it->begin(); _it != _arr_it->end(); ++_it, ++_i) { \
3154
                        if (!_it->is_object()) { \
3155
                            tg3__error_pushf((ctx)->errors, (ctx)->arena, \
3156
                                TG3_SEVERITY_ERROR, TG3_ERR_JSON_TYPE_MISMATCH, \
3157
                                json_key, "Element %u must be an object", _i); \
3158
                            continue; \
3159
                        } \
3160
                        parse_fn((ctx), *_it, &_items[_i]); \
3161
                    } \
3162
                    (model_field) = _items; \
3163
                    (count_field) = _count; \
3164
                } \
3165
            } \
3166
        } \
3167
    } while (0)
3168
3169
/* ======================================================================
3170
 * Internal: Main Parse Orchestrator
3171
 * ====================================================================== */
3172
3173
static tg3_error_code tg3__parse_from_json(tg3__parse_ctx *ctx,
3174
                                            const tg3__json &json_doc,
3175
                                            tg3_model *model) {
3176
    /* Asset */
3177
    auto asset_it = json_doc.find("asset");
3178
    if (asset_it != json_doc.end() && asset_it->is_object()) {
3179
        tg3__parse_asset(ctx, *asset_it, &model->asset);
3180
    } else if (ctx->opts.required_sections & TG3_REQUIRE_VERSION) {
3181
        tg3__error_push(ctx->errors, TG3_SEVERITY_ERROR, TG3_ERR_MISSING_REQUIRED,
3182
                        "Missing required 'asset' property", "/", -1);
3183
        return TG3_ERR_MISSING_REQUIRED;
3184
    }
3185
3186
    /* Extensions used/required */
3187
    tg3__parse_string_array(ctx, json_doc, "extensionsUsed",
3188
                             &model->extensions_used,
3189
                             &model->extensions_used_count, 0, "/");
3190
    tg3__parse_string_array(ctx, json_doc, "extensionsRequired",
3191
                             &model->extensions_required,
3192
                             &model->extensions_required_count, 0, "/");
3193
3194
    /* Default scene */
3195
    model->default_scene = -1;
3196
    tg3__parse_int(ctx, json_doc, "scene", &model->default_scene, 0, "/");
3197
3198
    /* Streaming callback helper macro */
3199
    #define TG3__STREAM_CB(type_name, cb_name, model_arr, model_cnt) \
3200
        if (ctx->opts.stream && ctx->opts.stream->cb_name) { \
3201
            for (uint32_t _si = 0; _si < model_cnt; ++_si) { \
3202
                tg3_stream_action _sa = ctx->opts.stream->cb_name( \
3203
                    &model_arr[_si], (int32_t)_si, ctx->opts.stream->user_data); \
3204
                if (_sa == TG3_STREAM_ABORT) return TG3_ERR_STREAM_ABORTED; \
3205
            } \
3206
        }
3207
3208
    /* Parse all entity arrays */
3209
    TG3__PARSE_ARRAY_IDX(ctx, json_doc, "buffers", tg3_buffer,
3210
                         model->buffers, model->buffers_count, tg3__parse_buffer);
3211
    TG3__STREAM_CB(buffer, on_buffer, model->buffers, model->buffers_count);
3212
3213
    TG3__PARSE_ARRAY_SIMPLE(ctx, json_doc, "bufferViews", tg3_buffer_view,
3214
                            model->buffer_views, model->buffer_views_count,
3215
                            tg3__parse_buffer_view);
3216
    TG3__STREAM_CB(buffer_view, on_buffer_view, model->buffer_views,
3217
                   model->buffer_views_count);
3218
3219
    TG3__PARSE_ARRAY_SIMPLE(ctx, json_doc, "accessors", tg3_accessor,
3220
                            model->accessors, model->accessors_count,
3221
                            tg3__parse_accessor);
3222
    TG3__STREAM_CB(accessor, on_accessor, model->accessors, model->accessors_count);
3223
3224
    TG3__PARSE_ARRAY_SIMPLE(ctx, json_doc, "meshes", tg3_mesh,
3225
                            model->meshes, model->meshes_count, tg3__parse_mesh);
3226
    TG3__STREAM_CB(mesh, on_mesh, model->meshes, model->meshes_count);
3227
3228
    TG3__PARSE_ARRAY_SIMPLE(ctx, json_doc, "nodes", tg3_node,
3229
                            model->nodes, model->nodes_count, tg3__parse_node);
3230
    TG3__STREAM_CB(node, on_node, model->nodes, model->nodes_count);
3231
3232
    TG3__PARSE_ARRAY_SIMPLE(ctx, json_doc, "materials", tg3_material,
3233
                            model->materials, model->materials_count,
3234
                            tg3__parse_material);
3235
    TG3__STREAM_CB(material, on_material, model->materials, model->materials_count);
3236
3237
    TG3__PARSE_ARRAY_SIMPLE(ctx, json_doc, "textures", tg3_texture,
3238
                            model->textures, model->textures_count,
3239
                            tg3__parse_texture);
3240
    TG3__STREAM_CB(texture, on_texture, model->textures, model->textures_count);
3241
3242
    TG3__PARSE_ARRAY_SIMPLE(ctx, json_doc, "samplers", tg3_sampler,
3243
                            model->samplers, model->samplers_count,
3244
                            tg3__parse_sampler);
3245
    TG3__STREAM_CB(sampler, on_sampler, model->samplers, model->samplers_count);
3246
3247
    TG3__PARSE_ARRAY_IDX(ctx, json_doc, "images", tg3_image,
3248
                         model->images, model->images_count, tg3__parse_image);
3249
    TG3__STREAM_CB(image, on_image, model->images, model->images_count);
3250
3251
    TG3__PARSE_ARRAY_SIMPLE(ctx, json_doc, "skins", tg3_skin,
3252
                            model->skins, model->skins_count, tg3__parse_skin);
3253
    TG3__STREAM_CB(skin, on_skin, model->skins, model->skins_count);
3254
3255
    TG3__PARSE_ARRAY_SIMPLE(ctx, json_doc, "animations", tg3_animation,
3256
                            model->animations, model->animations_count,
3257
                            tg3__parse_animation);
3258
    TG3__STREAM_CB(animation, on_animation, model->animations,
3259
                   model->animations_count);
3260
3261
    TG3__PARSE_ARRAY_SIMPLE(ctx, json_doc, "cameras", tg3_camera,
3262
                            model->cameras, model->cameras_count,
3263
                            tg3__parse_camera);
3264
    TG3__STREAM_CB(camera, on_camera, model->cameras, model->cameras_count);
3265
3266
    TG3__PARSE_ARRAY_SIMPLE(ctx, json_doc, "scenes", tg3_scene,
3267
                            model->scenes, model->scenes_count,
3268
                            tg3__parse_scene);
3269
    TG3__STREAM_CB(scene, on_scene, model->scenes, model->scenes_count);
3270
3271
    /* KHR_lights_punctual */
3272
    auto ext_it = json_doc.find("extensions");
3273
    if (ext_it != json_doc.end() && ext_it->is_object()) {
3274
        auto lights_ext = ext_it->find("KHR_lights_punctual");
3275
        if (lights_ext != ext_it->end() && lights_ext->is_object()) {
3276
            TG3__PARSE_ARRAY_SIMPLE(ctx, *lights_ext, "lights", tg3_light,
3277
                                    model->lights, model->lights_count,
3278
                                    tg3__parse_light);
3279
            TG3__STREAM_CB(light, on_light, model->lights, model->lights_count);
3280
        }
3281
3282
        /* KHR_audio */
3283
        auto audio_ext = ext_it->find("KHR_audio");
3284
        if (audio_ext != ext_it->end() && audio_ext->is_object()) {
3285
            TG3__PARSE_ARRAY_SIMPLE(ctx, *audio_ext, "sources", tg3_audio_source,
3286
                                    model->audio_sources, model->audio_sources_count,
3287
                                    tg3__parse_audio_source);
3288
            TG3__PARSE_ARRAY_SIMPLE(ctx, *audio_ext, "emitters", tg3_audio_emitter,
3289
                                    model->audio_emitters, model->audio_emitters_count,
3290
                                    tg3__parse_audio_emitter);
3291
        }
3292
    }
3293
3294
    /* Root extras/extensions */
3295
    tg3__parse_extras_and_extensions(ctx, json_doc, &model->ext);
3296
3297
    #undef TG3__STREAM_CB
3298
3299
    return ctx->errors->has_error ? TG3_ERR_JSON_PARSE : TG3_OK;
3300
}
3301
3302
/* ======================================================================
3303
 * Internal: GLB Parsing
3304
 * ====================================================================== */
3305
3306
static tg3_error_code tg3__parse_glb_header(const uint8_t *data, uint64_t size,
3307
                                             const uint8_t **json_out,
3308
                                             uint64_t *json_size_out,
3309
                                             const uint8_t **bin_out,
3310
                                             uint64_t *bin_size_out,
3311
                                             tg3_error_stack *errors) {
3312
    *json_out = NULL; *json_size_out = 0;
3313
    *bin_out = NULL; *bin_size_out = 0;
3314
3315
    if (size < 12) {
3316
        tg3__error_push(errors, TG3_SEVERITY_ERROR, TG3_ERR_GLB_INVALID_HEADER,
3317
                        "GLB data too small for header", NULL, -1);
3318
        return TG3_ERR_GLB_INVALID_HEADER;
3319
    }
3320
3321
    /* Check magic: 'glTF' */
3322
    if (data[0] != 'g' || data[1] != 'l' || data[2] != 'T' || data[3] != 'F') {
3323
        tg3__error_push(errors, TG3_SEVERITY_ERROR, TG3_ERR_GLB_INVALID_MAGIC,
3324
                        "Invalid GLB magic bytes", NULL, -1);
3325
        return TG3_ERR_GLB_INVALID_MAGIC;
3326
    }
3327
3328
    /* Version */
3329
    uint32_t version;
3330
    memcpy(&version, data + 4, 4);
3331
    if (version != 2) {
3332
        tg3__error_push(errors, TG3_SEVERITY_ERROR, TG3_ERR_GLB_INVALID_VERSION,
3333
                        "Unsupported GLB version (expected 2)", NULL, -1);
3334
        return TG3_ERR_GLB_INVALID_VERSION;
3335
    }
3336
3337
    /* Total length */
3338
    uint32_t total_length;
3339
    memcpy(&total_length, data + 8, 4);
3340
    if ((uint64_t)total_length > size) {
3341
        tg3__error_push(errors, TG3_SEVERITY_ERROR, TG3_ERR_GLB_SIZE_MISMATCH,
3342
                        "GLB total length exceeds data size", NULL, -1);
3343
        return TG3_ERR_GLB_SIZE_MISMATCH;
3344
    }
3345
3346
    if (total_length < 20) {
3347
        tg3__error_push(errors, TG3_SEVERITY_ERROR, TG3_ERR_GLB_INVALID_HEADER,
3348
                        "GLB too small for JSON chunk header", NULL, -1);
3349
        return TG3_ERR_GLB_INVALID_HEADER;
3350
    }
3351
3352
    /* Chunk 0: JSON */
3353
    uint32_t chunk0_length, chunk0_type;
3354
    memcpy(&chunk0_length, data + 12, 4);
3355
    memcpy(&chunk0_type, data + 16, 4);
3356
3357
    if (chunk0_type != 0x4E4F534A) { /* 'JSON' in LE */
3358
        tg3__error_push(errors, TG3_SEVERITY_ERROR, TG3_ERR_GLB_CHUNK_ERROR,
3359
                        "First GLB chunk is not JSON", NULL, -1);
3360
        return TG3_ERR_GLB_CHUNK_ERROR;
3361
    }
3362
3363
    if (20 + (uint64_t)chunk0_length > total_length) {
3364
        tg3__error_push(errors, TG3_SEVERITY_ERROR, TG3_ERR_GLB_CHUNK_ERROR,
3365
                        "JSON chunk length exceeds GLB size", NULL, -1);
3366
        return TG3_ERR_GLB_CHUNK_ERROR;
3367
    }
3368
3369
    *json_out = data + 20;
3370
    *json_size_out = chunk0_length;
3371
3372
    /* Chunk 1: BIN (optional) */
3373
    uint64_t bin_offset = 20 + (uint64_t)chunk0_length;
3374
    /* Align to 4 bytes */
3375
    bin_offset = (bin_offset + 3) & ~(uint64_t)3;
3376
3377
    if (bin_offset + 8 <= total_length) {
3378
        uint32_t chunk1_length, chunk1_type;
3379
        memcpy(&chunk1_length, data + bin_offset, 4);
3380
        memcpy(&chunk1_type, data + bin_offset + 4, 4);
3381
3382
        if (chunk1_type == 0x004E4942) { /* 'BIN\0' in LE */
3383
            if (bin_offset + 8 + chunk1_length <= total_length) {
3384
                *bin_out = data + bin_offset + 8;
3385
                *bin_size_out = chunk1_length;
3386
            }
3387
        }
3388
    }
3389
3390
    return TG3_OK;
3391
}
3392
3393
/* ======================================================================
3394
 * Optional: Default FS Callbacks
3395
 * ====================================================================== */
3396
3397
#ifdef TINYGLTF3_ENABLE_FS
3398
3399
static int32_t tg3__fs_file_exists(const char *path, uint32_t path_len,
3400
                                    void *ud) {
3401
    (void)ud; (void)path_len;
3402
    FILE *f = fopen(path, "rb");
3403
    if (f) { fclose(f); return 1; }
3404
    return 0;
3405
}
3406
3407
static int32_t tg3__fs_read_file(uint8_t **out_data, uint64_t *out_size,
3408
                                  const char *path, uint32_t path_len,
3409
                                  void *ud) {
3410
    (void)ud; (void)path_len;
3411
    FILE *f = fopen(path, "rb");
3412
    if (!f) return 0;
3413
3414
    fseek(f, 0, SEEK_END);
3415
    long sz = ftell(f);
3416
    fseek(f, 0, SEEK_SET);
3417
    if (sz < 0) { fclose(f); return 0; }
3418
3419
    uint8_t *data = (uint8_t *)malloc((size_t)sz);
3420
    if (!data) { fclose(f); return 0; }
3421
3422
    size_t read = fread(data, 1, (size_t)sz, f);
3423
    fclose(f);
3424
3425
    if ((long)read != sz) { free(data); return 0; }
3426
3427
    *out_data = data;
3428
    *out_size = (uint64_t)sz;
3429
    return 1;
3430
}
3431
3432
static void tg3__fs_free_file(uint8_t *data, uint64_t size, void *ud) {
3433
    (void)size; (void)ud;
3434
    free(data);
3435
}
3436
3437
static int32_t tg3__fs_write_file(const char *path, uint32_t path_len,
3438
                                   const uint8_t *data, uint64_t size,
3439
                                   void *ud) {
3440
    (void)ud; (void)path_len;
3441
    FILE *f = fopen(path, "wb");
3442
    if (!f) return 0;
3443
    size_t written = fwrite(data, 1, (size_t)size, f);
3444
    fclose(f);
3445
    return (written == (size_t)size) ? 1 : 0;
3446
}
3447
3448
static void tg3__set_default_fs(tg3_fs_callbacks *fs) {
3449
    if (!fs->read_file) fs->read_file = tg3__fs_read_file;
3450
    if (!fs->free_file) fs->free_file = tg3__fs_free_file;
3451
    if (!fs->file_exists) fs->file_exists = tg3__fs_file_exists;
3452
    if (!fs->write_file) fs->write_file = tg3__fs_write_file;
3453
}
3454
3455
#endif /* TINYGLTF3_ENABLE_FS */
3456
3457
/* ======================================================================
3458
 * Internal: Model Init Helper
3459
 * ====================================================================== */
3460
3461
static void tg3__model_init(tg3_model *model) {
3462
    memset(model, 0, sizeof(tg3_model));
3463
    model->default_scene = -1;
3464
}
3465
3466
/* ======================================================================
3467
 * Public: Parser API Implementation
3468
 * ====================================================================== */
3469
3470
TINYGLTF3_API tg3_error_code tg3_parse(
3471
    tg3_model *model, tg3_error_stack *errors,
3472
    const uint8_t *json_data, uint64_t json_size,
3473
    const char *base_dir, uint32_t base_dir_len,
3474
    const tg3_parse_options *options) {
3475
3476
    tg3_parse_options default_opts;
3477
    if (!options) {
3478
        tg3_parse_options_init(&default_opts);
3479
        options = &default_opts;
3480
    }
3481
3482
    tg3__model_init(model);
3483
3484
    tg3_arena *arena = tg3__arena_create(&options->memory);
3485
    if (!arena) {
3486
        tg3__error_push(errors, TG3_SEVERITY_ERROR, TG3_ERR_OUT_OF_MEMORY,
3487
                        "Failed to create arena", NULL, -1);
3488
        return TG3_ERR_OUT_OF_MEMORY;
3489
    }
3490
    model->arena_ = arena;
3491
3492
    /* Parse JSON */
3493
    tg3__json json_doc = options->parse_float32
3494
        ? tg3__json::parse_float32(
3495
              (const char *)json_data, (const char *)json_data + json_size)
3496
        : tg3__json::parse(
3497
              (const char *)json_data, (const char *)json_data + json_size,
3498
              nullptr, false);
3499
3500
    if (json_doc.is_null()) {
3501
        tg3__error_push(errors, TG3_SEVERITY_ERROR, TG3_ERR_JSON_PARSE,
3502
                        "Failed to parse JSON", NULL, -1);
3503
        return TG3_ERR_JSON_PARSE;
3504
    }
3505
3506
    if (!json_doc.is_object()) {
3507
        tg3__error_push(errors, TG3_SEVERITY_ERROR, TG3_ERR_JSON_PARSE,
3508
                        "JSON root must be an object", NULL, -1);
3509
        return TG3_ERR_JSON_PARSE;
3510
    }
3511
3512
    tg3__parse_ctx ctx;
3513
    memset(&ctx, 0, sizeof(ctx));
3514
    ctx.arena = arena;
3515
    ctx.errors = errors;
3516
    ctx.opts = *options;
3517
    ctx.base_dir = base_dir;
3518
    ctx.base_dir_len = base_dir_len;
3519
    ctx.is_binary = 0;
3520
3521
#ifdef TINYGLTF3_ENABLE_FS
3522
    tg3__set_default_fs(&ctx.opts.fs);
3523
#endif
3524
3525
    return tg3__parse_from_json(&ctx, json_doc, model);
3526
}
3527
3528
TINYGLTF3_API tg3_error_code tg3_parse_glb(
3529
    tg3_model *model, tg3_error_stack *errors,
3530
    const uint8_t *glb_data, uint64_t glb_size,
3531
    const char *base_dir, uint32_t base_dir_len,
3532
    const tg3_parse_options *options) {
3533
3534
    const uint8_t *json_chunk = NULL;
3535
    uint64_t json_chunk_size = 0;
3536
    const uint8_t *bin_chunk = NULL;
3537
    uint64_t bin_chunk_size = 0;
3538
3539
    tg3_error_code err = tg3__parse_glb_header(glb_data, glb_size,
3540
                                                &json_chunk, &json_chunk_size,
3541
                                                &bin_chunk, &bin_chunk_size,
3542
                                                errors);
3543
    if (err != TG3_OK) return err;
3544
3545
    tg3_parse_options default_opts;
3546
    if (!options) {
3547
        tg3_parse_options_init(&default_opts);
3548
        options = &default_opts;
3549
    }
3550
3551
    tg3__model_init(model);
3552
3553
    tg3_arena *arena = tg3__arena_create(&options->memory);
3554
    if (!arena) {
3555
        tg3__error_push(errors, TG3_SEVERITY_ERROR, TG3_ERR_OUT_OF_MEMORY,
3556
                        "Failed to create arena", NULL, -1);
3557
        return TG3_ERR_OUT_OF_MEMORY;
3558
    }
3559
    model->arena_ = arena;
3560
3561
    /* Parse JSON chunk */
3562
    tg3__json json_doc = options->parse_float32
3563
        ? tg3__json::parse_float32(
3564
              (const char *)json_chunk, (const char *)json_chunk + json_chunk_size)
3565
        : tg3__json::parse(
3566
              (const char *)json_chunk, (const char *)json_chunk + json_chunk_size,
3567
              nullptr, false);
3568
3569
    if (json_doc.is_null() || !json_doc.is_object()) {
3570
        tg3__error_push(errors, TG3_SEVERITY_ERROR, TG3_ERR_JSON_PARSE,
3571
                        "Failed to parse GLB JSON chunk", NULL, -1);
3572
        return TG3_ERR_JSON_PARSE;
3573
    }
3574
3575
    tg3__parse_ctx ctx;
3576
    memset(&ctx, 0, sizeof(ctx));
3577
    ctx.arena = arena;
3578
    ctx.errors = errors;
3579
    ctx.opts = *options;
3580
    ctx.base_dir = base_dir;
3581
    ctx.base_dir_len = base_dir_len;
3582
    ctx.is_binary = 1;
3583
    ctx.bin_data = bin_chunk;
3584
    ctx.bin_size = bin_chunk_size;
3585
3586
#ifdef TINYGLTF3_ENABLE_FS
3587
    tg3__set_default_fs(&ctx.opts.fs);
3588
#endif
3589
3590
    return tg3__parse_from_json(&ctx, json_doc, model);
3591
}
3592
3593
TINYGLTF3_API tg3_error_code tg3_parse_auto(
3594
    tg3_model *model, tg3_error_stack *errors,
3595
    const uint8_t *data, uint64_t size,
3596
    const char *base_dir, uint32_t base_dir_len,
3597
    const tg3_parse_options *options) {
3598
3599
    /* Check for GLB magic */
3600
    if (size >= 4 && data[0] == 'g' && data[1] == 'l' &&
3601
        data[2] == 'T' && data[3] == 'F') {
3602
        return tg3_parse_glb(model, errors, data, size,
3603
                              base_dir, base_dir_len, options);
3604
    }
3605
    return tg3_parse(model, errors, data, size,
3606
                      base_dir, base_dir_len, options);
3607
}
3608
3609
TINYGLTF3_API tg3_error_code tg3_parse_file(
3610
    tg3_model *model, tg3_error_stack *errors,
3611
    const char *filename, uint32_t filename_len,
3612
    const tg3_parse_options *options) {
3613
3614
    tg3_parse_options opts;
3615
    if (options) {
3616
        opts = *options;
3617
    } else {
3618
        tg3_parse_options_init(&opts);
3619
    }
3620
3621
#ifdef TINYGLTF3_ENABLE_FS
3622
    tg3__set_default_fs(&opts.fs);
3623
#endif
3624
3625
    if (!opts.fs.read_file) {
3626
        tg3__error_push(errors, TG3_SEVERITY_ERROR, TG3_ERR_FS_NOT_AVAILABLE,
3627
                        "No filesystem callbacks. Define TINYGLTF3_ENABLE_FS "
3628
                        "or provide fs callbacks.", NULL, -1);
3629
        return TG3_ERR_FS_NOT_AVAILABLE;
3630
    }
3631
3632
    /* Read file */
3633
    uint8_t *file_data = NULL;
3634
    uint64_t file_size = 0;
3635
    int32_t ok = opts.fs.read_file(&file_data, &file_size, filename,
3636
                                    filename_len, opts.fs.user_data);
3637
    if (!ok || !file_data) {
3638
        tg3__error_push(errors, TG3_SEVERITY_ERROR, TG3_ERR_FILE_NOT_FOUND,
3639
                        "Failed to read file", NULL, -1);
3640
        return TG3_ERR_FILE_NOT_FOUND;
3641
    }
3642
3643
    /* Extract base directory */
3644
    char base_dir_buf[4096] = {0};
3645
    uint32_t base_dir_len = 0;
3646
    if (filename && filename_len > 0) {
3647
        /* Find last separator */
3648
        const char *last_sep = NULL;
3649
        for (uint32_t i = 0; i < filename_len; ++i) {
3650
            if (filename[i] == '/' || filename[i] == '\\') {
3651
                last_sep = filename + i;
3652
            }
3653
        }
3654
        if (last_sep) {
3655
            base_dir_len = (uint32_t)(last_sep - filename);
3656
            if (base_dir_len >= sizeof(base_dir_buf))
3657
                base_dir_len = (uint32_t)(sizeof(base_dir_buf) - 1);
3658
            memcpy(base_dir_buf, filename, base_dir_len);
3659
            base_dir_buf[base_dir_len] = '\0';
3660
        }
3661
    }
3662
3663
    tg3_error_code result = tg3_parse_auto(model, errors, file_data, file_size,
3664
                                            base_dir_buf, base_dir_len, &opts);
3665
3666
    /* Free file data */
3667
    if (opts.fs.free_file) {
3668
        opts.fs.free_file(file_data, file_size, opts.fs.user_data);
3669
    }
3670
3671
    return result;
3672
}
3673
3674
TINYGLTF3_API void tg3_model_free(tg3_model *model) {
3675
    if (!model) return;
3676
    if (model->arena_) {
3677
        tg3__arena_destroy(model->arena_);
3678
    }
3679
    memset(model, 0, sizeof(tg3_model));
3680
    model->default_scene = -1;
3681
}
3682
3683
/* ======================================================================
3684
 * Internal: JSON Serialization Helpers
3685
 * ====================================================================== */
3686
3687
static void tg3__serialize_str(tg3__json &o, const char *key, tg3_str s) {
3688
    if (s.data && s.len > 0) {
3689
        o[key] = std::string(s.data, s.len);
3690
    }
3691
}
3692
3693
static void tg3__serialize_int(tg3__json &o, const char *key, int32_t val,
3694
                                int32_t default_val, int write_defaults) {
3695
    if (val != default_val || write_defaults) {
3696
        o[key] = val;
3697
    }
3698
}
3699
3700
static void tg3__serialize_uint64(tg3__json &o, const char *key, uint64_t val,
3701
                                   uint64_t default_val, int write_defaults) {
3702
    if (val != default_val || write_defaults) {
3703
        o[key] = (int64_t)val;
3704
    }
3705
}
3706
3707
static void tg3__serialize_double(tg3__json &o, const char *key, double val,
3708
                                   double default_val, int write_defaults) {
3709
    if (fabs(val - default_val) > 1e-12 || write_defaults) {
3710
        o[key] = val;
3711
    }
3712
}
3713
3714
static void tg3__serialize_bool(tg3__json &o, const char *key, int32_t val,
3715
                                 int32_t default_val, int write_defaults) {
3716
    if (val != default_val || write_defaults) {
3717
        o[key] = (val != 0);
3718
    }
3719
}
3720
3721
static void tg3__serialize_double_array(tg3__json &o, const char *key,
3722
                                         const double *arr, uint32_t count) {
3723
    if (!arr || count == 0) return;
3724
    tg3__json jarr;
3725
    jarr.set_array();
3726
    for (uint32_t i = 0; i < count; ++i) {
3727
        jarr.push_back(tg3__json(arr[i]));
3728
    }
3729
    o[key] = static_cast<tg3__json&&>(jarr);
3730
}
3731
3732
static void tg3__serialize_int_array(tg3__json &o, const char *key,
3733
                                      const int32_t *arr, uint32_t count) {
3734
    if (!arr || count == 0) return;
3735
    tg3__json jarr;
3736
    jarr.set_array();
3737
    for (uint32_t i = 0; i < count; ++i) {
3738
        jarr.push_back(tg3__json(arr[i]));
3739
    }
3740
    o[key] = static_cast<tg3__json&&>(jarr);
3741
}
3742
3743
static void tg3__serialize_string_array(tg3__json &o, const char *key,
3744
                                         const tg3_str *arr, uint32_t count) {
3745
    if (!arr || count == 0) return;
3746
    tg3__json jarr;
3747
    jarr.set_array();
3748
    for (uint32_t i = 0; i < count; ++i) {
3749
        if (arr[i].data) {
3750
            jarr.push_back(tg3__json(std::string(arr[i].data, arr[i].len)));
3751
        }
3752
    }
3753
    o[key] = static_cast<tg3__json&&>(jarr);
3754
}
3755
3756
static tg3__json tg3__value_to_json(const tg3_value *v) {
3757
    if (!v) return tg3__json();
3758
    switch (v->type) {
3759
        case TG3_VALUE_NULL:   return tg3__json();
3760
        case TG3_VALUE_BOOL:   return tg3__json(v->bool_val != 0);
3761
        case TG3_VALUE_INT:    return tg3__json(v->int_val);
3762
        case TG3_VALUE_REAL:   return tg3__json(v->real_val);
3763
        case TG3_VALUE_STRING:
3764
            return tg3__json(std::string(v->string_val.data ? v->string_val.data : "",
3765
                                          v->string_val.len));
3766
        case TG3_VALUE_ARRAY: {
3767
            tg3__json arr;
3768
            arr.set_array();
3769
            for (uint32_t i = 0; i < v->array_count; ++i) {
3770
                arr.push_back(tg3__value_to_json(&v->array_data[i]));
3771
            }
3772
            return arr;
3773
        }
3774
        case TG3_VALUE_OBJECT: {
3775
            tg3__json obj = tg3__json::object();
3776
            for (uint32_t i = 0; i < v->object_count; ++i) {
3777
                std::string k(v->object_data[i].key.data ? v->object_data[i].key.data : "",
3778
                              v->object_data[i].key.len);
3779
                obj[k.c_str()] = tg3__value_to_json(&v->object_data[i].value);
3780
            }
3781
            return obj;
3782
        }
3783
        default: return tg3__json();
3784
    }
3785
}
3786
3787
static void tg3__serialize_extras_ext(tg3__json &o, const tg3_extras_ext *ee) {
3788
    if (!ee) return;
3789
    if (ee->extras) {
3790
        o["extras"] = tg3__value_to_json(ee->extras);
3791
    }
3792
    if (ee->extensions && ee->extensions_count > 0) {
3793
        tg3__json exts = tg3__json::object();
3794
        for (uint32_t i = 0; i < ee->extensions_count; ++i) {
3795
            std::string name(ee->extensions[i].name.data ? ee->extensions[i].name.data : "",
3796
                             ee->extensions[i].name.len);
3797
            exts[name.c_str()] = tg3__value_to_json(&ee->extensions[i].value);
3798
        }
3799
        o["extensions"] = static_cast<tg3__json&&>(exts);
3800
    }
3801
}
3802
3803
/* ======================================================================
3804
 * Internal: Entity Serialize Functions
3805
 * ====================================================================== */
3806
3807
static void tg3__serialize_texture_info(tg3__json &parent, const char *key,
3808
                                         const tg3_texture_info *ti, int wd) {
3809
    if (ti->index < 0) return;
3810
    tg3__json o = tg3__json::object();
3811
    o["index"] = ti->index;
3812
    tg3__serialize_int(o, "texCoord", ti->tex_coord, 0, wd);
3813
    tg3__serialize_extras_ext(o, &ti->ext);
3814
    parent[key] = static_cast<tg3__json&&>(o);
3815
}
3816
3817
static void tg3__serialize_normal_texture_info(tg3__json &parent, const char *key,
3818
                                                const tg3_normal_texture_info *ti,
3819
                                                int wd) {
3820
    if (ti->index < 0) return;
3821
    tg3__json o = tg3__json::object();
3822
    o["index"] = ti->index;
3823
    tg3__serialize_int(o, "texCoord", ti->tex_coord, 0, wd);
3824
    tg3__serialize_double(o, "scale", ti->scale, 1.0, wd);
3825
    tg3__serialize_extras_ext(o, &ti->ext);
3826
    parent[key] = static_cast<tg3__json&&>(o);
3827
}
3828
3829
static void tg3__serialize_occlusion_texture_info(tg3__json &parent, const char *key,
3830
                                                   const tg3_occlusion_texture_info *ti,
3831
                                                   int wd) {
3832
    if (ti->index < 0) return;
3833
    tg3__json o = tg3__json::object();
3834
    o["index"] = ti->index;
3835
    tg3__serialize_int(o, "texCoord", ti->tex_coord, 0, wd);
3836
    tg3__serialize_double(o, "strength", ti->strength, 1.0, wd);
3837
    tg3__serialize_extras_ext(o, &ti->ext);
3838
    parent[key] = static_cast<tg3__json&&>(o);
3839
}
3840
3841
static tg3__json tg3__serialize_asset(const tg3_asset *a, int wd) {
3842
    (void)wd;
3843
    tg3__json o = tg3__json::object();
3844
    tg3__serialize_str(o, "version", a->version);
3845
    tg3__serialize_str(o, "generator", a->generator);
3846
    tg3__serialize_str(o, "minVersion", a->min_version);
3847
    tg3__serialize_str(o, "copyright", a->copyright);
3848
    tg3__serialize_extras_ext(o, &a->ext);
3849
    return o;
3850
}
3851
3852
static tg3__json tg3__serialize_buffer(const tg3_buffer *b, int wd,
3853
                                        int embed) {
3854
    (void)wd;
3855
    tg3__json o = tg3__json::object();
3856
    tg3__serialize_str(o, "name", b->name);
3857
    o["byteLength"] = (int64_t)b->data.count;
3858
3859
    if (b->uri.data && b->uri.len > 0) {
3860
        tg3__serialize_str(o, "uri", b->uri);
3861
    } else if (embed && b->data.data && b->data.count > 0) {
3862
        /* Encode as data URI */
3863
        size_t enc_len = 0;
3864
        char *encoded = tg3__b64_encode(b->data.data, (size_t)b->data.count,
3865
                                         &enc_len);
3866
        if (encoded) {
3867
            std::string uri = "data:application/octet-stream;base64,";
3868
            uri.append(encoded, enc_len);
3869
            o["uri"] = uri;
3870
            free(encoded);
3871
        }
3872
    }
3873
3874
    tg3__serialize_extras_ext(o, &b->ext);
3875
    return o;
3876
}
3877
3878
static tg3__json tg3__serialize_buffer_view(const tg3_buffer_view *bv, int wd) {
3879
    tg3__json o = tg3__json::object();
3880
    tg3__serialize_str(o, "name", bv->name);
3881
    o["buffer"] = bv->buffer;
3882
    o["byteLength"] = (int64_t)bv->byte_length;
3883
    tg3__serialize_uint64(o, "byteOffset", bv->byte_offset, 0, wd);
3884
    if (bv->byte_stride > 0) o["byteStride"] = (int)bv->byte_stride;
3885
    tg3__serialize_int(o, "target", bv->target, 0, wd);
3886
    tg3__serialize_extras_ext(o, &bv->ext);
3887
    return o;
3888
}
3889
3890
static tg3__json tg3__serialize_accessor(const tg3_accessor *acc, int wd) {
3891
    tg3__json o = tg3__json::object();
3892
    tg3__serialize_str(o, "name", acc->name);
3893
    if (acc->buffer_view >= 0) o["bufferView"] = acc->buffer_view;
3894
    tg3__serialize_uint64(o, "byteOffset", acc->byte_offset, 0, wd);
3895
    o["componentType"] = acc->component_type;
3896
    o["count"] = (int64_t)acc->count;
3897
    o["type"] = tg3__accessor_type_to_string(acc->type);
3898
    tg3__serialize_bool(o, "normalized", acc->normalized, 0, wd);
3899
3900
    tg3__serialize_double_array(o, "min", acc->min_values, acc->min_values_count);
3901
    tg3__serialize_double_array(o, "max", acc->max_values, acc->max_values_count);
3902
3903
    if (acc->sparse.is_sparse) {
3904
        tg3__json sparse = tg3__json::object();
3905
        sparse["count"] = acc->sparse.count;
3906
3907
        tg3__json indices = tg3__json::object();
3908
        indices["bufferView"] = acc->sparse.indices.buffer_view;
3909
        indices["componentType"] = acc->sparse.indices.component_type;
3910
        tg3__serialize_uint64(indices, "byteOffset",
3911
                              acc->sparse.indices.byte_offset, 0, wd);
3912
        tg3__serialize_extras_ext(indices, &acc->sparse.indices.ext);
3913
        sparse["indices"] = static_cast<tg3__json&&>(indices);
3914
3915
        tg3__json values = tg3__json::object();
3916
        values["bufferView"] = acc->sparse.values.buffer_view;
3917
        tg3__serialize_uint64(values, "byteOffset",
3918
                              acc->sparse.values.byte_offset, 0, wd);
3919
        tg3__serialize_extras_ext(values, &acc->sparse.values.ext);
3920
        sparse["values"] = static_cast<tg3__json&&>(values);
3921
3922
        tg3__serialize_extras_ext(sparse, &acc->sparse.ext);
3923
        o["sparse"] = static_cast<tg3__json&&>(sparse);
3924
    }
3925
3926
    tg3__serialize_extras_ext(o, &acc->ext);
3927
    return o;
3928
}
3929
3930
static tg3__json tg3__serialize_image(const tg3_image *img, int wd, int embed) {
3931
    (void)wd; (void)embed;
3932
    tg3__json o = tg3__json::object();
3933
    tg3__serialize_str(o, "name", img->name);
3934
    tg3__serialize_str(o, "uri", img->uri);
3935
    tg3__serialize_str(o, "mimeType", img->mime_type);
3936
    if (img->buffer_view >= 0) o["bufferView"] = img->buffer_view;
3937
    tg3__serialize_extras_ext(o, &img->ext);
3938
    return o;
3939
}
3940
3941
static tg3__json tg3__serialize_sampler(const tg3_sampler *s, int wd) {
3942
    tg3__json o = tg3__json::object();
3943
    tg3__serialize_str(o, "name", s->name);
3944
    if (s->min_filter >= 0) o["minFilter"] = s->min_filter;
3945
    if (s->mag_filter >= 0) o["magFilter"] = s->mag_filter;
3946
    tg3__serialize_int(o, "wrapS", s->wrap_s, TG3_TEXTURE_WRAP_REPEAT, wd);
3947
    tg3__serialize_int(o, "wrapT", s->wrap_t, TG3_TEXTURE_WRAP_REPEAT, wd);
3948
    tg3__serialize_extras_ext(o, &s->ext);
3949
    return o;
3950
}
3951
3952
static tg3__json tg3__serialize_texture(const tg3_texture *t, int wd) {
3953
    (void)wd;
3954
    tg3__json o = tg3__json::object();
3955
    tg3__serialize_str(o, "name", t->name);
3956
    if (t->sampler >= 0) o["sampler"] = t->sampler;
3957
    if (t->source >= 0) o["source"] = t->source;
3958
    tg3__serialize_extras_ext(o, &t->ext);
3959
    return o;
3960
}
3961
3962
static tg3__json tg3__serialize_material(const tg3_material *m, int wd) {
3963
    tg3__json o = tg3__json::object();
3964
    tg3__serialize_str(o, "name", m->name);
3965
3966
    /* PBR */
3967
    tg3__json pbr = tg3__json::object();
3968
    int has_pbr = 0;
3969
3970
    const tg3_pbr_metallic_roughness *p = &m->pbr_metallic_roughness;
3971
    if (p->base_color_factor[0] != 1.0 || p->base_color_factor[1] != 1.0 ||
3972
        p->base_color_factor[2] != 1.0 || p->base_color_factor[3] != 1.0 || wd) {
3973
        tg3__serialize_double_array(pbr, "baseColorFactor",
3974
                                    p->base_color_factor, 4);
3975
        has_pbr = 1;
3976
    }
3977
    tg3__serialize_double(pbr, "metallicFactor", p->metallic_factor, 1.0, wd);
3978
    if (fabs(p->metallic_factor - 1.0) > 1e-12 || wd) has_pbr = 1;
3979
    tg3__serialize_double(pbr, "roughnessFactor", p->roughness_factor, 1.0, wd);
3980
    if (fabs(p->roughness_factor - 1.0) > 1e-12 || wd) has_pbr = 1;
3981
3982
    if (p->base_color_texture.index >= 0) {
3983
        tg3__serialize_texture_info(pbr, "baseColorTexture",
3984
                                    &p->base_color_texture, wd);
3985
        has_pbr = 1;
3986
    }
3987
    if (p->metallic_roughness_texture.index >= 0) {
3988
        tg3__serialize_texture_info(pbr, "metallicRoughnessTexture",
3989
                                    &p->metallic_roughness_texture, wd);
3990
        has_pbr = 1;
3991
    }
3992
    tg3__serialize_extras_ext(pbr, &p->ext);
3993
    if (has_pbr || wd) {
3994
        o["pbrMetallicRoughness"] = static_cast<tg3__json&&>(pbr);
3995
    }
3996
3997
    tg3__serialize_normal_texture_info(o, "normalTexture", &m->normal_texture, wd);
3998
    tg3__serialize_occlusion_texture_info(o, "occlusionTexture",
3999
                                           &m->occlusion_texture, wd);
4000
    tg3__serialize_texture_info(o, "emissiveTexture", &m->emissive_texture, wd);
4001
4002
    if (m->emissive_factor[0] != 0.0 || m->emissive_factor[1] != 0.0 ||
4003
        m->emissive_factor[2] != 0.0 || wd) {
4004
        tg3__serialize_double_array(o, "emissiveFactor", m->emissive_factor, 3);
4005
    }
4006
4007
    if (m->alpha_mode.data && !tg3_str_equals_cstr(m->alpha_mode, "OPAQUE")) {
4008
        tg3__serialize_str(o, "alphaMode", m->alpha_mode);
4009
    }
4010
    tg3__serialize_double(o, "alphaCutoff", m->alpha_cutoff, 0.5, wd);
4011
    tg3__serialize_bool(o, "doubleSided", m->double_sided, 0, wd);
4012
4013
    tg3__serialize_extras_ext(o, &m->ext);
4014
    return o;
4015
}
4016
4017
static tg3__json tg3__serialize_primitive(const tg3_primitive *p, int wd) {
4018
    tg3__json o = tg3__json::object();
4019
4020
    /* Attributes */
4021
    if (p->attributes && p->attributes_count > 0) {
4022
        tg3__json attrs = tg3__json::object();
4023
        for (uint32_t i = 0; i < p->attributes_count; ++i) {
4024
            std::string k(p->attributes[i].key.data ? p->attributes[i].key.data : "",
4025
                          p->attributes[i].key.len);
4026
            attrs[k.c_str()] = p->attributes[i].value;
4027
        }
4028
        o["attributes"] = static_cast<tg3__json&&>(attrs);
4029
    }
4030
4031
    if (p->indices >= 0) o["indices"] = p->indices;
4032
    if (p->material >= 0) o["material"] = p->material;
4033
    tg3__serialize_int(o, "mode", p->mode, TG3_MODE_TRIANGLES, wd);
4034
4035
    /* Morph targets */
4036
    if (p->targets && p->targets_count > 0) {
4037
        tg3__json targets;
4038
        targets.set_array();
4039
        for (uint32_t t = 0; t < p->targets_count; ++t) {
4040
            tg3__json tgt = tg3__json::object();
4041
            uint32_t acount = p->target_attribute_counts ?
4042
                              p->target_attribute_counts[t] : 0;
4043
            const tg3_str_int_pair *tattrs = p->targets[t];
4044
            for (uint32_t a = 0; a < acount; ++a) {
4045
                std::string k(tattrs[a].key.data ? tattrs[a].key.data : "",
4046
                              tattrs[a].key.len);
4047
                tgt[k.c_str()] = tattrs[a].value;
4048
            }
4049
            targets.push_back(static_cast<tg3__json&&>(tgt));
4050
        }
4051
        o["targets"] = static_cast<tg3__json&&>(targets);
4052
    }
4053
4054
    tg3__serialize_extras_ext(o, &p->ext);
4055
    return o;
4056
}
4057
4058
static tg3__json tg3__serialize_mesh(const tg3_mesh *m, int wd) {
4059
    tg3__json o = tg3__json::object();
4060
    tg3__serialize_str(o, "name", m->name);
4061
4062
    if (m->primitives && m->primitives_count > 0) {
4063
        tg3__json prims;
4064
        prims.set_array();
4065
        for (uint32_t i = 0; i < m->primitives_count; ++i) {
4066
            prims.push_back(tg3__serialize_primitive(&m->primitives[i], wd));
4067
        }
4068
        o["primitives"] = static_cast<tg3__json&&>(prims);
4069
    }
4070
4071
    tg3__serialize_double_array(o, "weights", m->weights, m->weights_count);
4072
    tg3__serialize_extras_ext(o, &m->ext);
4073
    return o;
4074
}
4075
4076
static tg3__json tg3__serialize_node(const tg3_node *n, int wd) {
4077
    tg3__json o = tg3__json::object();
4078
    tg3__serialize_str(o, "name", n->name);
4079
4080
    if (n->camera >= 0) o["camera"] = n->camera;
4081
    if (n->skin >= 0) o["skin"] = n->skin;
4082
    if (n->mesh >= 0) o["mesh"] = n->mesh;
4083
4084
    tg3__serialize_int_array(o, "children", n->children, n->children_count);
4085
4086
    if (n->has_matrix) {
4087
        tg3__serialize_double_array(o, "matrix", n->matrix, 16);
4088
    } else {
4089
        int has_t = (n->translation[0] != 0.0 || n->translation[1] != 0.0 ||
4090
                     n->translation[2] != 0.0);
4091
        int has_r = (n->rotation[0] != 0.0 || n->rotation[1] != 0.0 ||
4092
                     n->rotation[2] != 0.0 || n->rotation[3] != 1.0);
4093
        int has_s = (n->scale[0] != 1.0 || n->scale[1] != 1.0 ||
4094
                     n->scale[2] != 1.0);
4095
4096
        if (has_t || wd) tg3__serialize_double_array(o, "translation", n->translation, 3);
4097
        if (has_r || wd) tg3__serialize_double_array(o, "rotation", n->rotation, 4);
4098
        if (has_s || wd) tg3__serialize_double_array(o, "scale", n->scale, 3);
4099
    }
4100
4101
    tg3__serialize_double_array(o, "weights", n->weights, n->weights_count);
4102
4103
    /* Extensions for lights / audio / lod */
4104
    int has_ext = (n->light >= 0 || n->emitter >= 0 ||
4105
                   (n->lods && n->lods_count > 0));
4106
    if (has_ext) {
4107
        /* Check if extensions already set by extras_ext */
4108
        auto existing = o.find("extensions");
4109
        tg3__json exts = (existing != o.end()) ?
4110
                         tg3__json(*existing) : tg3__json::object();
4111
4112
        if (n->light >= 0) {
4113
            tg3__json lp = tg3__json::object();
4114
            lp["light"] = n->light;
4115
            exts["KHR_lights_punctual"] = static_cast<tg3__json&&>(lp);
4116
        }
4117
        if (n->emitter >= 0) {
4118
            tg3__json ae = tg3__json::object();
4119
            ae["emitter"] = n->emitter;
4120
            exts["KHR_audio"] = static_cast<tg3__json&&>(ae);
4121
        }
4122
        if (n->lods && n->lods_count > 0) {
4123
            tg3__json lod = tg3__json::object();
4124
            tg3__serialize_int_array(lod, "ids", n->lods, n->lods_count);
4125
            exts["MSFT_lod"] = static_cast<tg3__json&&>(lod);
4126
        }
4127
        o["extensions"] = static_cast<tg3__json&&>(exts);
4128
    }
4129
4130
    tg3__serialize_extras_ext(o, &n->ext);
4131
    return o;
4132
}
4133
4134
static tg3__json tg3__serialize_skin(const tg3_skin *s, int wd) {
4135
    (void)wd;
4136
    tg3__json o = tg3__json::object();
4137
    tg3__serialize_str(o, "name", s->name);
4138
    if (s->inverse_bind_matrices >= 0) o["inverseBindMatrices"] = s->inverse_bind_matrices;
4139
    if (s->skeleton >= 0) o["skeleton"] = s->skeleton;
4140
    tg3__serialize_int_array(o, "joints", s->joints, s->joints_count);
4141
    tg3__serialize_extras_ext(o, &s->ext);
4142
    return o;
4143
}
4144
4145
static tg3__json tg3__serialize_animation(const tg3_animation *a, int wd) {
4146
    (void)wd;
4147
    tg3__json o = tg3__json::object();
4148
    tg3__serialize_str(o, "name", a->name);
4149
4150
    if (a->channels && a->channels_count > 0) {
4151
        tg3__json channels;
4152
        channels.set_array();
4153
        for (uint32_t i = 0; i < a->channels_count; ++i) {
4154
            tg3__json ch = tg3__json::object();
4155
            ch["sampler"] = a->channels[i].sampler;
4156
            tg3__json tgt = tg3__json::object();
4157
            if (a->channels[i].target.node >= 0)
4158
                tgt["node"] = a->channels[i].target.node;
4159
            tg3__serialize_str(tgt, "path", a->channels[i].target.path);
4160
            tg3__serialize_extras_ext(tgt, &a->channels[i].target.ext);
4161
            ch["target"] = static_cast<tg3__json&&>(tgt);
4162
            tg3__serialize_extras_ext(ch, &a->channels[i].ext);
4163
            channels.push_back(static_cast<tg3__json&&>(ch));
4164
        }
4165
        o["channels"] = static_cast<tg3__json&&>(channels);
4166
    }
4167
4168
    if (a->samplers && a->samplers_count > 0) {
4169
        tg3__json samplers;
4170
        samplers.set_array();
4171
        for (uint32_t i = 0; i < a->samplers_count; ++i) {
4172
            tg3__json s = tg3__json::object();
4173
            s["input"] = a->samplers[i].input;
4174
            s["output"] = a->samplers[i].output;
4175
            tg3__serialize_str(s, "interpolation", a->samplers[i].interpolation);
4176
            tg3__serialize_extras_ext(s, &a->samplers[i].ext);
4177
            samplers.push_back(static_cast<tg3__json&&>(s));
4178
        }
4179
        o["samplers"] = static_cast<tg3__json&&>(samplers);
4180
    }
4181
4182
    tg3__serialize_extras_ext(o, &a->ext);
4183
    return o;
4184
}
4185
4186
static tg3__json tg3__serialize_camera(const tg3_camera *c, int wd) {
4187
    (void)wd;
4188
    tg3__json o = tg3__json::object();
4189
    tg3__serialize_str(o, "name", c->name);
4190
    tg3__serialize_str(o, "type", c->type);
4191
4192
    if (c->type.data && tg3_str_equals_cstr(c->type, "perspective")) {
4193
        tg3__json p = tg3__json::object();
4194
        if (c->perspective.aspect_ratio > 0)
4195
            p["aspectRatio"] = c->perspective.aspect_ratio;
4196
        p["yfov"] = c->perspective.yfov;
4197
        if (c->perspective.zfar > 0) p["zfar"] = c->perspective.zfar;
4198
        p["znear"] = c->perspective.znear;
4199
        tg3__serialize_extras_ext(p, &c->perspective.ext);
4200
        o["perspective"] = static_cast<tg3__json&&>(p);
4201
    } else if (c->type.data && tg3_str_equals_cstr(c->type, "orthographic")) {
4202
        tg3__json orth = tg3__json::object();
4203
        orth["xmag"] = c->orthographic.xmag;
4204
        orth["ymag"] = c->orthographic.ymag;
4205
        orth["zfar"] = c->orthographic.zfar;
4206
        orth["znear"] = c->orthographic.znear;
4207
        tg3__serialize_extras_ext(orth, &c->orthographic.ext);
4208
        o["orthographic"] = static_cast<tg3__json&&>(orth);
4209
    }
4210
4211
    tg3__serialize_extras_ext(o, &c->ext);
4212
    return o;
4213
}
4214
4215
static tg3__json tg3__serialize_scene(const tg3_scene *s, int wd) {
4216
    (void)wd;
4217
    tg3__json o = tg3__json::object();
4218
    tg3__serialize_str(o, "name", s->name);
4219
    tg3__serialize_int_array(o, "nodes", s->nodes, s->nodes_count);
4220
    tg3__serialize_extras_ext(o, &s->ext);
4221
    return o;
4222
}
4223
4224
static tg3__json tg3__serialize_light(const tg3_light *l, int wd) {
4225
    tg3__json o = tg3__json::object();
4226
    tg3__serialize_str(o, "name", l->name);
4227
    tg3__serialize_str(o, "type", l->type);
4228
    tg3__serialize_double(o, "intensity", l->intensity, 1.0, wd);
4229
    tg3__serialize_double(o, "range", l->range, 0.0, wd);
4230
4231
    if (l->color[0] != 1.0 || l->color[1] != 1.0 || l->color[2] != 1.0 || wd) {
4232
        tg3__serialize_double_array(o, "color", l->color, 3);
4233
    }
4234
4235
    if (l->type.data && tg3_str_equals_cstr(l->type, "spot")) {
4236
        tg3__json spot = tg3__json::object();
4237
        tg3__serialize_double(spot, "innerConeAngle", l->spot.inner_cone_angle, 0.0, wd);
4238
        tg3__serialize_double(spot, "outerConeAngle", l->spot.outer_cone_angle,
4239
                              0.7853981634, wd);
4240
        tg3__serialize_extras_ext(spot, &l->spot.ext);
4241
        o["spot"] = static_cast<tg3__json&&>(spot);
4242
    }
4243
4244
    tg3__serialize_extras_ext(o, &l->ext);
4245
    return o;
4246
}
4247
4248
/* ======================================================================
4249
 * Internal: Main Model Serializer
4250
 * ====================================================================== */
4251
4252
static tg3__json tg3__serialize_model(const tg3_model *model, int wd,
4253
                                       int embed_images, int embed_buffers) {
4254
    tg3__json root = tg3__json::object();
4255
4256
    /* Asset */
4257
    root["asset"] = tg3__serialize_asset(&model->asset, wd);
4258
4259
    /* Default scene */
4260
    if (model->default_scene >= 0) {
4261
        root["scene"] = model->default_scene;
4262
    }
4263
4264
    /* Extensions used/required */
4265
    tg3__serialize_string_array(root, "extensionsUsed",
4266
                                 model->extensions_used,
4267
                                 model->extensions_used_count);
4268
    tg3__serialize_string_array(root, "extensionsRequired",
4269
                                 model->extensions_required,
4270
                                 model->extensions_required_count);
4271
4272
    /* Entity arrays */
4273
    #define TG3__SERIALIZE_ARRAY(key, arr, cnt, fn, ...) \
4274
        if ((arr) && (cnt) > 0) { \
4275
            tg3__json jarr; jarr.set_array(); \
4276
            for (uint32_t _i = 0; _i < (cnt); ++_i) { \
4277
                jarr.push_back(fn(&(arr)[_i] TG3__COMMA_VA_ARGS(__VA_ARGS__))); \
4278
            } \
4279
            root[key] = static_cast<tg3__json&&>(jarr); \
4280
        }
4281
4282
    TG3__SERIALIZE_ARRAY("buffers", model->buffers, model->buffers_count,
4283
                         tg3__serialize_buffer, wd, embed_buffers);
4284
    TG3__SERIALIZE_ARRAY("bufferViews", model->buffer_views,
4285
                         model->buffer_views_count, tg3__serialize_buffer_view, wd);
4286
    TG3__SERIALIZE_ARRAY("accessors", model->accessors, model->accessors_count,
4287
                         tg3__serialize_accessor, wd);
4288
    TG3__SERIALIZE_ARRAY("meshes", model->meshes, model->meshes_count,
4289
                         tg3__serialize_mesh, wd);
4290
    TG3__SERIALIZE_ARRAY("nodes", model->nodes, model->nodes_count,
4291
                         tg3__serialize_node, wd);
4292
    TG3__SERIALIZE_ARRAY("materials", model->materials, model->materials_count,
4293
                         tg3__serialize_material, wd);
4294
    TG3__SERIALIZE_ARRAY("textures", model->textures, model->textures_count,
4295
                         tg3__serialize_texture, wd);
4296
    TG3__SERIALIZE_ARRAY("samplers", model->samplers, model->samplers_count,
4297
                         tg3__serialize_sampler, wd);
4298
    TG3__SERIALIZE_ARRAY("images", model->images, model->images_count,
4299
                         tg3__serialize_image, wd, embed_images);
4300
    TG3__SERIALIZE_ARRAY("skins", model->skins, model->skins_count,
4301
                         tg3__serialize_skin, wd);
4302
    TG3__SERIALIZE_ARRAY("animations", model->animations, model->animations_count,
4303
                         tg3__serialize_animation, wd);
4304
    TG3__SERIALIZE_ARRAY("cameras", model->cameras, model->cameras_count,
4305
                         tg3__serialize_camera, wd);
4306
    TG3__SERIALIZE_ARRAY("scenes", model->scenes, model->scenes_count,
4307
                         tg3__serialize_scene, wd);
4308
4309
    /* KHR_lights_punctual */
4310
    if (model->lights && model->lights_count > 0) {
4311
        tg3__json lights_ext = tg3__json::object();
4312
        tg3__json lights;
4313
        lights.set_array();
4314
        for (uint32_t i = 0; i < model->lights_count; ++i) {
4315
            lights.push_back(tg3__serialize_light(&model->lights[i], wd));
4316
        }
4317
        lights_ext["lights"] = static_cast<tg3__json&&>(lights);
4318
4319
        auto ext_it = root.find("extensions");
4320
        tg3__json exts = (ext_it != root.end()) ?
4321
                         tg3__json(*ext_it) : tg3__json::object();
4322
        exts["KHR_lights_punctual"] = static_cast<tg3__json&&>(lights_ext);
4323
        root["extensions"] = static_cast<tg3__json&&>(exts);
4324
    }
4325
4326
    /* Root extras/extensions */
4327
    tg3__serialize_extras_ext(root, &model->ext);
4328
4329
    #undef TG3__SERIALIZE_ARRAY
4330
    return root;
4331
}
4332
4333
/* ======================================================================
4334
 * Public: Writer API Implementation
4335
 * ====================================================================== */
4336
4337
TINYGLTF3_API tg3_error_code tg3_write_to_memory(
4338
    const tg3_model *model, tg3_error_stack *errors,
4339
    uint8_t **out_data, uint64_t *out_size,
4340
    const tg3_write_options *options) {
4341
4342
    tg3_write_options default_opts;
4343
    if (!options) {
4344
        tg3_write_options_init(&default_opts);
4345
        options = &default_opts;
4346
    }
4347
4348
    int wd = options->serialize_defaults;
4349
    tg3__json root = tg3__serialize_model(model, wd,
4350
                                           options->embed_images,
4351
                                           options->embed_buffers);
4352
4353
    int indent = options->pretty_print ? 2 : -1;
4354
    std::string json_str = root.dump(indent);
4355
4356
    if (options->write_binary) {
4357
        /* GLB format */
4358
        uint32_t json_len = (uint32_t)json_str.size();
4359
        /* Pad JSON to 4-byte alignment with spaces */
4360
        uint32_t json_padded = (json_len + 3) & ~3u;
4361
4362
        /* Collect binary buffer data */
4363
        const uint8_t *bin_data = NULL;
4364
        uint64_t bin_len = 0;
4365
        if (model->buffers_count > 0 && model->buffers[0].data.data) {
4366
            bin_data = model->buffers[0].data.data;
4367
            bin_len = model->buffers[0].data.count;
4368
        }
4369
        uint32_t bin_padded = ((uint32_t)bin_len + 3) & ~3u;
4370
4371
        uint32_t total = 12; /* Header */
4372
        total += 8 + json_padded; /* JSON chunk */
4373
        if (bin_data && bin_len > 0) {
4374
            total += 8 + bin_padded; /* BIN chunk */
4375
        }
4376
4377
        uint8_t *glb = (uint8_t *)malloc(total);
4378
        if (!glb) {
4379
            tg3__error_push(errors, TG3_SEVERITY_ERROR, TG3_ERR_OUT_OF_MEMORY,
4380
                            "OOM allocating GLB output", NULL, -1);
4381
            return TG3_ERR_OUT_OF_MEMORY;
4382
        }
4383
4384
        /* Header */
4385
        memcpy(glb, "glTF", 4);
4386
        uint32_t version = 2;
4387
        memcpy(glb + 4, &version, 4);
4388
        memcpy(glb + 8, &total, 4);
4389
4390
        /* JSON chunk */
4391
        memcpy(glb + 12, &json_padded, 4);
4392
        uint32_t json_type = 0x4E4F534A;
4393
        memcpy(glb + 16, &json_type, 4);
4394
        memcpy(glb + 20, json_str.c_str(), json_len);
4395
        /* Pad with spaces */
4396
        for (uint32_t i = json_len; i < json_padded; ++i) {
4397
            glb[20 + i] = ' ';
4398
        }
4399
4400
        /* BIN chunk */
4401
        if (bin_data && bin_len > 0) {
4402
            uint32_t bin_off = 20 + json_padded;
4403
            memcpy(glb + bin_off, &bin_padded, 4);
4404
            uint32_t bin_type = 0x004E4942;
4405
            memcpy(glb + bin_off + 4, &bin_type, 4);
4406
            memcpy(glb + bin_off + 8, bin_data, (size_t)bin_len);
4407
            /* Pad with zeros */
4408
            for (uint32_t i = (uint32_t)bin_len; i < bin_padded; ++i) {
4409
                glb[bin_off + 8 + i] = 0;
4410
            }
4411
        }
4412
4413
        *out_data = glb;
4414
        *out_size = total;
4415
    } else {
4416
        /* JSON format */
4417
        uint64_t sz = json_str.size();
4418
        uint8_t *data = (uint8_t *)malloc((size_t)sz);
4419
        if (!data) {
4420
            tg3__error_push(errors, TG3_SEVERITY_ERROR, TG3_ERR_OUT_OF_MEMORY,
4421
                            "OOM allocating JSON output", NULL, -1);
4422
            return TG3_ERR_OUT_OF_MEMORY;
4423
        }
4424
        memcpy(data, json_str.c_str(), (size_t)sz);
4425
        *out_data = data;
4426
        *out_size = sz;
4427
    }
4428
4429
    return TG3_OK;
4430
}
4431
4432
TINYGLTF3_API tg3_error_code tg3_write_to_file(
4433
    const tg3_model *model, tg3_error_stack *errors,
4434
    const char *filename, uint32_t filename_len,
4435
    const tg3_write_options *options) {
4436
4437
    tg3_write_options opts;
4438
    if (options) {
4439
        opts = *options;
4440
    } else {
4441
        tg3_write_options_init(&opts);
4442
    }
4443
4444
#ifdef TINYGLTF3_ENABLE_FS
4445
    tg3__set_default_fs(&opts.fs);
4446
#endif
4447
4448
    if (!opts.fs.write_file) {
4449
        tg3__error_push(errors, TG3_SEVERITY_ERROR, TG3_ERR_FS_NOT_AVAILABLE,
4450
                        "No filesystem write callback", NULL, -1);
4451
        return TG3_ERR_FS_NOT_AVAILABLE;
4452
    }
4453
4454
    uint8_t *data = NULL;
4455
    uint64_t size = 0;
4456
    tg3_error_code err = tg3_write_to_memory(model, errors, &data, &size, &opts);
4457
    if (err != TG3_OK) return err;
4458
4459
    int32_t ok = opts.fs.write_file(filename, filename_len, data, size,
4460
                                     opts.fs.user_data);
4461
    free(data);
4462
4463
    if (!ok) {
4464
        tg3__error_push(errors, TG3_SEVERITY_ERROR, TG3_ERR_FILE_WRITE,
4465
                        "Failed to write file", NULL, -1);
4466
        return TG3_ERR_FILE_WRITE;
4467
    }
4468
4469
    return TG3_OK;
4470
}
4471
4472
TINYGLTF3_API void tg3_write_free(uint8_t *data, const tg3_write_options *options) {
4473
    (void)options;
4474
    free(data);
4475
}
4476
4477
/* ======================================================================
4478
 * Streaming Writer (stub implementation)
4479
 * ====================================================================== */
4480
4481
struct tg3_writer {
4482
    tg3_write_chunk_fn chunk_fn;
4483
    void              *user_data;
4484
    tg3_write_options  options;
4485
    tg3__json          root;
4486
    int                begun;
4487
};
4488
4489
TINYGLTF3_API tg3_writer *tg3_writer_create(
4490
    tg3_write_chunk_fn chunk_fn, void *user_data,
4491
    const tg3_write_options *options) {
4492
    tg3_writer *w = new (std::nothrow) tg3_writer();
4493
    if (!w) return NULL;
4494
    w->chunk_fn = chunk_fn;
4495
    w->user_data = user_data;
4496
    if (options) w->options = *options;
4497
    else tg3_write_options_init(&w->options);
4498
    w->root = tg3__json::object();
4499
    return w;
4500
}
4501
4502
TINYGLTF3_API tg3_error_code tg3_writer_begin(tg3_writer *w, const tg3_asset *asset) {
4503
    if (!w) return TG3_ERR_WRITE_FAILED;
4504
    w->root["asset"] = tg3__serialize_asset(asset, w->options.serialize_defaults);
4505
    w->begun = 1;
4506
    return TG3_OK;
4507
}
4508
4509
#define TG3__WRITER_ADD_IMPL(name, Type, json_key, serialize_fn, ...) \
4510
    TINYGLTF3_API tg3_error_code tg3_writer_add_##name(tg3_writer *w, const Type *item) { \
4511
        if (!w || !w->begun) return TG3_ERR_WRITE_FAILED; \
4512
        auto it = w->root.find(json_key); \
4513
        if (it == w->root.end()) { \
4514
            tg3__json arr; arr.set_array(); \
4515
            w->root[json_key] = static_cast<tg3__json&&>(arr); \
4516
        } \
4517
        w->root[json_key].push_back( \
4518
            serialize_fn(item, w->options.serialize_defaults TG3__COMMA_VA_ARGS(__VA_ARGS__))); \
4519
        return TG3_OK; \
4520
    }
4521
4522
#define TG3__WRITER_ADD_SIMPLE(name, Type, json_key, serialize_fn) \
4523
    TINYGLTF3_API tg3_error_code tg3_writer_add_##name(tg3_writer *w, const Type *item) { \
4524
        if (!w || !w->begun) return TG3_ERR_WRITE_FAILED; \
4525
        auto it = w->root.find(json_key); \
4526
        if (it == w->root.end()) { \
4527
            tg3__json arr; arr.set_array(); \
4528
            w->root[json_key] = static_cast<tg3__json&&>(arr); \
4529
        } \
4530
        w->root[json_key].push_back( \
4531
            serialize_fn(item, w->options.serialize_defaults)); \
4532
        return TG3_OK; \
4533
    }
4534
4535
TG3__WRITER_ADD_IMPL(buffer, tg3_buffer, "buffers", tg3__serialize_buffer,
4536
                     w->options.embed_buffers)
4537
TG3__WRITER_ADD_SIMPLE(buffer_view, tg3_buffer_view, "bufferViews",
4538
                       tg3__serialize_buffer_view)
4539
TG3__WRITER_ADD_SIMPLE(accessor, tg3_accessor, "accessors", tg3__serialize_accessor)
4540
TG3__WRITER_ADD_SIMPLE(mesh, tg3_mesh, "meshes", tg3__serialize_mesh)
4541
TG3__WRITER_ADD_SIMPLE(node, tg3_node, "nodes", tg3__serialize_node)
4542
TG3__WRITER_ADD_SIMPLE(material, tg3_material, "materials", tg3__serialize_material)
4543
TG3__WRITER_ADD_SIMPLE(texture, tg3_texture, "textures", tg3__serialize_texture)
4544
TG3__WRITER_ADD_IMPL(image, tg3_image, "images", tg3__serialize_image,
4545
                     w->options.embed_images)
4546
TG3__WRITER_ADD_SIMPLE(sampler, tg3_sampler, "samplers", tg3__serialize_sampler)
4547
TG3__WRITER_ADD_SIMPLE(animation, tg3_animation, "animations", tg3__serialize_animation)
4548
TG3__WRITER_ADD_SIMPLE(skin, tg3_skin, "skins", tg3__serialize_skin)
4549
TG3__WRITER_ADD_SIMPLE(camera, tg3_camera, "cameras", tg3__serialize_camera)
4550
TG3__WRITER_ADD_SIMPLE(scene, tg3_scene, "scenes", tg3__serialize_scene)
4551
TG3__WRITER_ADD_SIMPLE(light, tg3_light, "lights", tg3__serialize_light)
4552
4553
#undef TG3__WRITER_ADD_IMPL
4554
#undef TG3__WRITER_ADD_SIMPLE
4555
4556
TINYGLTF3_API tg3_error_code tg3_writer_end(tg3_writer *w) {
4557
    if (!w || !w->begun || !w->chunk_fn) return TG3_ERR_WRITE_FAILED;
4558
4559
    int indent = w->options.pretty_print ? 2 : -1;
4560
    std::string json_str = w->root.dump(indent);
4561
4562
    int32_t ok = w->chunk_fn((const uint8_t *)json_str.c_str(),
4563
                              json_str.size(), w->user_data);
4564
    return ok ? TG3_OK : TG3_ERR_WRITE_FAILED;
4565
}
4566
4567
TINYGLTF3_API void tg3_writer_destroy(tg3_writer *w) {
4568
    delete w;
4569
}
4570
4571
#endif /* legacy header-only v3 implementation */
4572
#endif /* TINYGLTF3_IMPLEMENTATION */
4573
4574
#endif /* TINY_GLTF_V3_H_ */