commit 42045742df6098703755c7a495d63325913f1e4e Author: Rune Date: Mon Jun 29 16:34:42 2026 +0200 add bindings diff --git a/.gitignore b/.gitignore new file mode 100644 index 0000000..3bd6ad9 --- /dev/null +++ b/.gitignore @@ -0,0 +1,4 @@ +build +recovery +BeefSpace_User.toml +BeefSpace_Lock.toml diff --git a/BeefProj.toml b/BeefProj.toml new file mode 100644 index 0000000..a965f29 --- /dev/null +++ b/BeefProj.toml @@ -0,0 +1,70 @@ +FileVersion = 1 + +[Project] +Name = "TinyglTF" +TargetType = "BeefLib" +StartupObject = "TinyglTF.Program" + +[Dependencies] +corlib = "*" +"CxxBuildTool.git" = {Git = "https://git.unicon-gmbh.de/Rune/CxxBuildTool.git"} + +[Configs.Debug.Win32] +LibPaths = ["$(BuildDir)/tiny_gltf_v3.lib"] + +[Configs.Debug.Win64] +LibPaths = ["$(BuildDir)/tiny_gltf_v3.lib"] + +[Configs.Debug.Linux32] +LibPaths = ["$(BuildDir)/tiny_gltf_v3.a"] + +[Configs.Debug.Linux64] +LibPaths = ["$(BuildDir)/tiny_gltf_v3.a"] + +[Configs.Debug.macOS] +LibPaths = ["$(BuildDir)/tiny_gltf_v3.a"] + +[Configs.Release.Win32] +LibPaths = ["$(BuildDir)/tiny_gltf_v3.lib"] + +[Configs.Release.Win64] +LibPaths = ["$(BuildDir)/tiny_gltf_v3.lib"] + +[Configs.Release.Linux32] +LibPaths = ["$(BuildDir)/tiny_gltf_v3.a"] + +[Configs.Release.Linux64] +LibPaths = ["$(BuildDir)/tiny_gltf_v3.a"] + +[Configs.Release.macOS] +LibPaths = ["$(BuildDir)/tiny_gltf_v3.a"] + +[Configs.Paranoid.Win32] +LibPaths = ["$(BuildDir)/tiny_gltf_v3.lib"] + +[Configs.Paranoid.Win64] +LibPaths = ["$(BuildDir)/tiny_gltf_v3.lib"] + +[Configs.Paranoid.Linux32] +LibPaths = ["$(BuildDir)/tiny_gltf_v3.a"] + +[Configs.Paranoid.Linux64] +LibPaths = ["$(BuildDir)/tiny_gltf_v3.a"] + +[Configs.Paranoid.macOS] +LibPaths = ["$(BuildDir)/tiny_gltf_v3.a"] + +[Configs.Test.Win32] +LibPaths = ["$(BuildDir)/tiny_gltf_v3.lib"] + +[Configs.Test.Win64] +LibPaths = ["$(BuildDir)/tiny_gltf_v3.lib"] + +[Configs.Test.Linux32] +LibPaths = ["$(BuildDir)/tiny_gltf_v3.a"] + +[Configs.Test.Linux64] +LibPaths = ["$(BuildDir)/tiny_gltf_v3.a"] + +[Configs.Test.macOS] +LibPaths = ["$(BuildDir)/tiny_gltf_v3.a"] diff --git a/BeefSpace.toml b/BeefSpace.toml new file mode 100644 index 0000000..045f4c8 --- /dev/null +++ b/BeefSpace.toml @@ -0,0 +1,9 @@ +FileVersion = 1 +ExtraPlatforms = ["Linux32", "Linux64", "macOS"] + +[Workspace] +StartupProject = "TinyglTF" + +[Projects] +TinyglTF = {Path = "."} +"CxxBuildTool.git" = {Git = "https://git.unicon-gmbh.de/Rune/CxxBuildTool.git"} diff --git a/Setup/BeefProj.toml b/Setup/BeefProj.toml new file mode 100644 index 0000000..b6a0a4d --- /dev/null +++ b/Setup/BeefProj.toml @@ -0,0 +1,9 @@ +FileVersion = 1 + +[Project] +Name = "TinyglTF.Setup" +StartupObject = "TinyglTF.Setup.Program" + +[Dependencies] +corlib = "*" +"Cpp2Beef.git" = {Git = "https://git.unicon-gmbh.de/Rune/Cpp2Beef.git"} diff --git a/Setup/BeefSpace.toml b/Setup/BeefSpace.toml new file mode 100644 index 0000000..63e4321 --- /dev/null +++ b/Setup/BeefSpace.toml @@ -0,0 +1,8 @@ +FileVersion = 1 + +[Workspace] +StartupProject = "TinyglTF.Setup" + +[Projects] +"TinyglTF.Setup" = {Path = "."} +"Cpp2Beef.git" = {Git = "https://git.unicon-gmbh.de/Rune/Cpp2Beef.git"} diff --git a/Setup/BeefSpace_Lock.toml b/Setup/BeefSpace_Lock.toml new file mode 100644 index 0000000..7dde36c --- /dev/null +++ b/Setup/BeefSpace_Lock.toml @@ -0,0 +1,11 @@ +FileVersion = 1 + +[Locks."Clang-C.git".Git] +URL = "https://git.unicon-gmbh.de/BeefBindings/Clang-C.git" +Tag = "" +Hash = "86db0167f15d08a63a91a19e46f983a5511bac1a" + +[Locks."Cpp2Beef.git".Git] +URL = "https://git.unicon-gmbh.de/Rune/Cpp2Beef.git" +Tag = "" +Hash = "e9242f157093963d56a16382fad9ca654e3d86ce" diff --git a/Setup/src/Program.bf b/Setup/src/Program.bf new file mode 100644 index 0000000..a3af012 --- /dev/null +++ b/Setup/src/Program.bf @@ -0,0 +1,204 @@ +using System; +using System.IO; +using System.Collections; +using System.Diagnostics; + +using Cpp2Beef; +using LibClang; + +namespace TinyglTF.Setup; + +class TinyglTFGenerator : Cpp2BeefGenerator, this(Span args) +{ + protected override Span Args => args; + protected override Flags Flags => .None; + + // You can have your binding in one file or in multiple, file management is up to you + StreamWriter writer = new .()..Create("../src/TinyglTF_v3.bf")..Write(""" + // This file was generated by Cpp2Beef + + using System; + using System.Interop; + + namespace TinyglTF; + + + """) ~ delete _; + + protected override StreamWriter GetWriterForHeader(StringView header) + { + if (header.EndsWith("tiny_gltf_v3.h")) + return writer; + return null; + } + + protected override Block GetCursorBlock(CXCursor cursor) + { + if (cursor.kind == .FunctionDecl) + return .CustomBlock("TinyglTF"); + if (cursor.kind == .MacroDefinition && GetMacroEnum(GetCursorSpelling!(cursor)) != -1) + return .NoBlock; + return base.GetCursorBlock(cursor); + } + + protected override void Record(CXCursor cursor, bool attributes = true) + { + base.Record(cursor, attributes); + + StringView spelling = GetCursorSpelling!(cursor); + bool isStr = spelling == "tg3_str"; + if (isStr || spelling.StartsWith("tg3_span_")) + { + str.Append("\n", cursorIndent, "public static operator "); + if (isStr) + str.Append("StringView"); + else + { + str.Append("Span<"); + Clang.VisitChildren(cursor, (cursor, parent, client_data) => + { + Self self = (.)Internal.UnsafeCastToObject(client_data); + self.Type(Clang.GetPointeeType(Clang.GetCursorType(cursor))); + return .Break; + }, Internal.UnsafeCastToPtr(this)); + str.Append('>'); + } + str.Append("(Self self) => .(self.data, (.)self.", isStr ? "len" : "count", ");"); + } + } + + const String[?] macroEnumNames = .("tg3_PrimitiveMode", "tg3_ComponentType", "tg3_AccessorType", "tg3_TextureFilter", "tg3_TextureWrapMode", + "tg3_ImageFormat", "tg3_TextureFormat", "tg3_BufferTarget", "tg3_SectionCheckFlags"); + const String[?] macroEnumPrefixes = .("mode", "component_type", "type", "texture_filter", "texture_wrap", "image_format", "texture_format", "target", "required_sections"); + StringView currentMacroEnum = null; + + static int GetMacroEnum(StringView spelling) + { + if (!spelling.StartsWith("TG3_")) + return -1; + if (spelling == "TG3_NO_REQUIRE" || spelling.StartsWith("TG3_REQUIRE_")) + return macroEnumPrefixes.Count-1; + var spelling; + spelling.RemoveFromStart(4); + for (let prefix in macroEnumPrefixes) + if (spelling.StartsWith(prefix, .OrdinalIgnoreCase) && spelling[prefix.Length] == '_') + return @prefix; + return -1; + } + + protected override void MacroDefinition(CXCursor cursor) + { + StringView spelling = GetCursorSpelling!(cursor); + int idx = GetMacroEnum(spelling); + if (idx == -1) + { + if (!currentMacroEnum.IsNull) + { + str.Insert(0, "\n}"); + currentMacroEnum = null; + } + base.MacroDefinition(cursor); + return; + } + + if (currentMacroEnum != macroEnumNames[idx]) + { + if (!currentMacroEnum.IsNull) str.Insert(0, "\n}"); + str.Append("[CRepr] enum ", macroEnumNames[idx], "\n{\n"); + currentMacroEnum = macroEnumNames[idx]; + } + + int prefixLen = macroEnumPrefixes[idx].Length + 5; + if (idx == macroEnumPrefixes.Count-1) + prefixLen = 4; + + str.Append('\t'); + UpperSnakeCase2PascalCase(spelling[prefixLen...], str); + str.Append(" = "); + WriteTokens(ScopeTokenize!(cursor, unit)[1...], Clang.GetNullLocation(), .Punctuation); + str.Append(','); + } + + protected override void Type(CXType type, TypeParamMode paramMode = .None) + { + if (currentCursor.kind == .FieldDecl && GetTypeSpelling!(type) == "int32_t") + { + let spelling = GetCursorSpelling!(currentCursor); + if (spelling.StartsWith("wrap_")) + { + str.Append("tg3_TextureWrapMode"); + return; + } + for (let prefix in macroEnumPrefixes) + if (prefix == spelling) + { + str.Append(macroEnumNames[@prefix]); + return; + } + } + base.Type(type, paramMode); + } + + protected override void Enum(CXCursor cursor) + { + if (!currentMacroEnum.IsNull) + { + str.Insert(0, "\n}"); + currentMacroEnum = null; + } + base.Enum(cursor); + } + + protected override void GetNameInBindings(CXCursor cursor, String outString) + { + switch (cursor.kind) + { + case .EnumConstantDecl: + StringView parent = GetCursorSpelling!(Clang.GetCursorSemanticParent(cursor)); + StringView spelling = GetCursorSpelling!(cursor); + int index = parent[4...].IndexOf('_'); + if (index >= 0) parent = parent[...(index + 4)]; + if (spelling.StartsWith(parent, .OrdinalIgnoreCase)) + spelling.RemoveFromStart(parent.Length); + else if (spelling.StartsWith("TG3_")) + spelling.RemoveFromStart(4); + if (spelling.StartsWith('_')) + spelling.RemoveFromStart(1); + UpperSnakeCase2PascalCase(spelling, outString); + return; + case .EnumDecl, .StructDecl, .UnionDecl, .TypedefDecl: + if (!GetCursorSpelling!(cursor).StartsWith("tg3_")) + break; + outString.Append("tg3_"); + fallthrough; + case .FunctionDecl: + StringView spelling = GetCursorSpelling!(cursor); + Runtime.Assert(spelling.StartsWith("tg3_")); + spelling.RemoveFromStart(4); + UpperSnakeCase2PascalCase(spelling, outString); + return; + default: + } + base.GetNameInBindings(cursor, outString); + } +} + +class Program +{ + [CLink] static extern int32 system(char8*); + + public static int Main(String[] args) + { + void Download(String file) + { + if (system(scope $"wget -O ../src/{file} https://raw.githubusercontent.com/syoyo/tinygltf/refs/heads/release/{file}") != 0) + Runtime.FatalError(scope $"Failed to download {file}"); + } + Download("tiny_gltf_v3.h"); + Download("tiny_gltf_v3.c"); + Download("tinygltf_json_c.h"); + + scope TinyglTFGenerator(char8*[?]("--language=c")).Generate("../src/tiny_gltf_v3.h"); + return 0; + } +} \ No newline at end of file diff --git a/src/Library.bf b/src/Library.bf new file mode 100644 index 0000000..fc6f99f --- /dev/null +++ b/src/Library.bf @@ -0,0 +1,14 @@ +using System; +using CxxBuildTool; + +namespace TinyglTF; + +static class TinyglTF +{ + [OnCompile(.TypeDone)] + private static void Build() + { + if (!Compiler.IsBuilding) return; + CxxBuildTool.Ninja(Compiler.ProjectDir + "/src", Compiler.BuildDir + "/" + Compiler.ProjectName, "tiny_gltf_v3", "", "tiny_gltf_v3.c"); + } +} diff --git a/src/TinyglTF_v3.bf b/src/TinyglTF_v3.bf new file mode 100644 index 0000000..b7a10a1 --- /dev/null +++ b/src/TinyglTF_v3.bf @@ -0,0 +1,4523 @@ +// This file was generated by Cpp2Beef + +using System; +using System.Interop; + +namespace TinyglTF; + +static +{ +/* + * tiny_gltf_v3.h - C-first glTF 2.0 loader and writer API (v3) + * + * The MIT License (MIT) + * Copyright (c) 2026 - Present: Syoyo Fujita + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to deal + * in the Software without restriction, including without limitation the rights + * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + * copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in + * all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN + * THE SOFTWARE. + */ + +/* + * Version: v3.0.0-alpha + * + * Ground-up C-centric API rewrite of tinygltf. + * The default runtime implementation lives in tiny_gltf_v3.c. + * + * Key differences from v2: + * - Pure C POD structs (no STL containers in public API) + * - Arena-based memory management (single tg3_model_free() frees all) + * - Filesystem and image decoding OFF by default (opt-in) + * - Structured error reporting via tg3_error_stack + * - Streaming parse/write via callbacks + * - No RTTI, no exceptions required + * - C++20 coroutine facade (optional) + * + * Security considerations (read before processing untrusted glTF): + * + * 1. External URI loading. When TINYGLTF3_ENABLE_FS is defined and no custom + * tg3_fs_callbacks are supplied, the parser opens external buffer/image + * URIs through the libc default fopen(). The parser rejects URIs that + * contain '..' segments, leading '/' or '\\', Windows drive prefixes + * (e.g. "C:"), or NUL bytes — but it does NOT chroot or canonicalize the + * result. Production callers SHOULD provide a tg3_fs_callbacks with a + * read_file callback that confines reads to a known directory (e.g. via + * openat(AT_FDCWD, path, O_NOFOLLOW) plus a realpath() prefix check) when + * the input glTF is attacker-controlled. + * + * 2. Index validation. Many glTF fields are integer indices into model + * arrays (accessor.bufferView, primitive.material, scene.nodes[], etc.). + * With opts.validate_indices = 1 (the default) the parser rejects every + * out-of-range index after the structural parse and returns + * TG3_ERR_INVALID_INDEX. Set opts.validate_indices = 0 only when you + * need to round-trip raw or extension data and have your own validator. + * + * 3. Image decoding. The parser does not decode image bytes by default. + * Set opts.images_as_is = 1 (already the safe default for untrusted + * input) to skip any decoder and store raw bytes only. + * + * 4. Memory budget. The arena is capped at TINYGLTF3_MAX_MEMORY_BYTES + * (1 GB by default; configurable per-parse via tg3_memory_config). + * The parser returns TG3_ERR_OUT_OF_MEMORY rather than overcommitting. + * + * 5. Error message lifetime. Error strings on tg3_error_stack are + * arena-allocated and remain valid until tg3_model_free() is called. + * Read or copy them BEFORE freeing the model. + */ + + + + +/* ====================================================================== + * Section 2: Configuration Macros + * ====================================================================== */ + +/* Legacy single-translation-unit build mode: define in ONE C or C++ file */ +/* #define TINYGLTF3_IMPLEMENTATION */ + +/* Opt-in features (OFF by default) */ +/* #define TINYGLTF3_ENABLE_FS */ +/* #define TINYGLTF3_ENABLE_STB_IMAGE */ +/* #define TINYGLTF3_ENABLE_STB_IMAGE_WRITE */ + +/* Opt-out */ +/* #define TINYGLTF3_NO_IMAGE_DECODE */ + +/* C++20 coroutines (auto-detected, or force) */ +/* #define TINYGLTF3_ENABLE_COROUTINES */ + +/* SIMD for JSON parsing (forwarded to tinygltf_json.h) */ +/* #define TINYGLTF3_JSON_SIMD_SSE2 */ +/* #define TINYGLTF3_JSON_SIMD_AVX2 */ +/* #define TINYGLTF3_JSON_SIMD_NEON */ + +/* Memory limits */ + +public const let TINYGLTF3_MAX_MEMORY_BYTES = (1UL << 30);/* 1 GB */ + + + +public const let TINYGLTF3_MAX_NESTING_DEPTH = 512; + + + +public const let TINYGLTF3_MAX_STRING_LENGTH = (64 * 1024 * 1024);/* 64 MB */ + + +/* Linkage control */ + + + + +/* Assert override */ + + + + + + + + + +/* ====================================================================== + * Section 3: C Includes + * ====================================================================== */ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +/* ====================================================================== + * Section 4: Constants and Enums + * ====================================================================== */ + + + + + +/* Primitive modes */ +} + +[CRepr] enum tg3_PrimitiveMode +{ + Points = 0, + Line = 1, + LineLoop = 2, + LineStrip = 3, + Triangles = 4, + TriangleStrip = 5, + TriangleFan = 6, + +/* Component types */ +} +[CRepr] enum tg3_ComponentType +{ + Byte = 5120, + UnsignedByte = 5121, + Short = 5122, + UnsignedShort = 5123, + Int = 5124, + UnsignedInt = 5125, + Float = 5126, + Double = 5130, + +/* Accessor types */ +} +[CRepr] enum tg3_AccessorType +{ + Vec2 = 2, + Vec3 = 3, + Vec4 = 4, + Mat2 = (32 + 2), + Mat3 = (32 + 3), + Mat4 = (32 + 4), + Scalar = (64 + 1), + Vector = (64 + 4), + Matrix = (64 + 16), + +/* Texture filter */ +} +[CRepr] enum tg3_TextureFilter +{ + Nearest = 9728, + Linear = 9729, + NearestMipmapNearest = 9984, + LinearMipmapNearest = 9985, + NearestMipmapLinear = 9986, + LinearMipmapLinear = 9987, + +/* Texture wrap */ +} +[CRepr] enum tg3_TextureWrapMode +{ + Repeat = 10497, + ClampToEdge = 33071, + MirroredRepeat = 33648, + +/* Image format */ +} +[CRepr] enum tg3_ImageFormat +{ + Jpeg = 0, + Png = 1, + Bmp = 2, + Gif = 3, + +/* Texture format */ +} +[CRepr] enum tg3_TextureFormat +{ + Alpha = 6406, + Rgb = 6407, + Rgba = 6408, + Luminance = 6409, + LuminanceAlpha = 6410, + +/* Texture target / type */ +} +static +{ +public const let TG3_TEXTURE_TARGET_TEXTURE2D = 3553; +public const let TG3_TEXTURE_TYPE_UNSIGNED_BYTE = 5121; + +/* Buffer targets */ +} + +[CRepr] enum tg3_BufferTarget +{ + ArrayBuffer = 34962, + ElementArrayBuffer = 34963, + +/* Sentinel for absent index */ +} +static +{ +public const let TG3_INDEX_NONE = (-1); + +/* Section check flags */ +} + +[CRepr] enum tg3_SectionCheckFlags +{ + NoRequire = 0x00, + RequireVersion = 0x01, + RequireScene = 0x02, + RequireScenes = 0x04, + RequireNodes = 0x08, + RequireAccessors = 0x10, + RequireBuffers = 0x20, + RequireBufferViews = 0x40, + RequireAll = 0x7f, + +/* Parse strictness */ +} +[AllowDuplicates] public enum tg3_Strictness : c_int { + Permissive = 0, + Strict = 1, +} + +/* ====================================================================== + * Section 5: Foundation Types + * ====================================================================== */ + +[CRepr] public struct tg3_Str { + public c_char* data; + public uint32 len; + public static operator StringView(Self self) => .(self.data, (.)self.len); +} + +[CRepr] public struct tg3_SpanI32 { + public int32* data; + public uint32 count; + public static operator Span(Self self) => .(self.data, (.)self.count); +} + +[CRepr] public struct tg3_SpanF64 { + public double* data; + public uint32 count; + public static operator Span(Self self) => .(self.data, (.)self.count); +} + +[CRepr] public struct tg3_SpanU8 { + public uint8* data; + public uint64 count; + public static operator Span(Self self) => .(self.data, (.)self.count); +} + +[CRepr] public struct tg3_StrIntPair { + public tg3_Str key; + public int32 value; +} + +/* ====================================================================== + * Section 6: Allocator Interface + * ====================================================================== */ + +[CRepr] public struct tg3_Allocator { + public function void*(c_size size, void* user_data) alloc; + public function void*(void* ptr, c_size old_size, c_size new_size, void* user_data) realloc; + public function void(void* ptr, c_size size, void* user_data) free; + public void* user_data; +} + +/* ====================================================================== + * Section 7: Error Reporting + * ====================================================================== */ + +[AllowDuplicates] public enum tg3_Severity : c_int { + Info = 0, + Warning = 1, + Error = 2, +} + +[AllowDuplicates] public enum tg3_ErrorCode : c_int { + Ok = 0, + + /* I/O errors: 1-9 */ + ErrFileNotFound = 1, + ErrFileRead = 2, + ErrFileWrite = 3, + ErrFileTooLarge = 4, + + /* JSON errors: 10-19 */ + ErrJsonParse = 10, + ErrJsonTypeMismatch = 11, + ErrJsonMissingField = 12, + ErrJsonInvalidValue = 13, + + /* GLB errors: 20-29 */ + ErrGlbInvalidMagic = 20, + ErrGlbInvalidVersion = 21, + ErrGlbInvalidHeader = 22, + ErrGlbChunkError = 23, + ErrGlbSizeMismatch = 24, + + /* Schema / validation errors: 30-49 */ + ErrMissingRequired = 30, + ErrInvalidIndex = 31, + ErrInvalidType = 32, + ErrInvalidValue = 33, + ErrInvalidAccessor = 34, + ErrInvalidBuffer = 35, + ErrInvalidBufferView = 36, + ErrInvalidImage = 37, + ErrInvalidMaterial = 38, + ErrInvalidMesh = 39, + ErrInvalidNode = 40, + ErrInvalidAnimation = 41, + ErrInvalidSkin = 42, + ErrInvalidCamera = 43, + ErrInvalidScene = 44, + ErrBufferSizeMismatch = 45, + + /* Resource errors: 50-59 */ + ErrOutOfMemory = 50, + ErrDataUriDecode = 51, + ErrBase64Decode = 52, + ErrExternalResource = 53, + ErrImageDecode = 54, + + /* Callback errors: 60-69 */ + ErrCallbackFailed = 60, + ErrFsNotAvailable = 61, + + /* Streaming errors: 70-79 */ + ErrStreamAborted = 70, + + /* Writer errors: 80-89 */ + ErrWriteFailed = 80, + ErrSerializeFailed = 81, +} + +[CRepr] public struct tg3_ErrorEntry { + public tg3_Severity severity; + public tg3_ErrorCode code; + public c_char* message; /* Arena-owned, null-terminated */ + public c_char* json_path; /* e.g. "/meshes/0/primitives/1" or NULL */ + public int64 byte_offset; /* -1 if unknown */ +} + +[CRepr] public struct tg3_ErrorStack { + public tg3_ErrorEntry* entries; + public uint32 count; + public uint32 capacity; + public int32 has_error; /* 1 if any entry with severity == ERROR */ +} + +/* Error stack query functions */ +extension TinyglTF +{ +[LinkName("tg3_errors_has_error")] public static extern int32 ErrorsHasError(tg3_ErrorStack* es); +[LinkName("tg3_errors_count")] public static extern uint32 ErrorsCount(tg3_ErrorStack* es); +[LinkName("tg3_errors_get")] public static extern tg3_ErrorEntry* ErrorsGet(tg3_ErrorStack* es, uint32 index); +} + +/* ====================================================================== + * Section 8: Generic Value Type (for extras/extensions) + * ====================================================================== */ + +[AllowDuplicates] public enum tg3_ValueType : c_int { + Null = 0, + Bool = 1, + Int = 2, + Real = 3, + String = 4, + Array = 5, + Binary = 6, + Object = 7, +} + +[CRepr] public struct tg3_KvPair; + +[CRepr] public struct tg3_Value { + public tg3_ValueType type; + [CRepr, Union] public using public struct { + public int32 bool_val; + public int64 int_val; + public double real_val; + }; + public tg3_Str string_val; + public tg3_Value* array_data; + public uint32 array_count; + public tg3_KvPair* object_data; + public uint32 object_count; + public tg3_SpanU8 binary_val; +} + + + + + + +[CRepr] public struct tg3_Extension { + public tg3_Str name; + public tg3_Value value; +} + +[CRepr] public struct tg3_ExtrasExt { + public tg3_Value* extras; /* NULL if absent */ + public tg3_Extension* extensions; /* Array */ + public uint32 extensions_count; + public tg3_Str extras_json; /* Raw JSON if store_original_json */ + public tg3_Str extensions_json; +} + +/* ====================================================================== + * Section 9: Core POD Structs + * ====================================================================== */ + +/* --- Asset --- */ +[CRepr] public struct tg3_Asset { + public tg3_Str version; /* Required, e.g. "2.0" */ + public tg3_Str generator; + public tg3_Str min_version; + public tg3_Str copyright; + public tg3_ExtrasExt ext; +} + +/* --- Buffer --- */ +[CRepr] public struct tg3_Buffer { + public tg3_Str name; + public uint64 byte_length; /* Declared buffer.byteLength */ + public tg3_SpanU8 data; + public tg3_Str uri; + public tg3_ExtrasExt ext; +} + +/* --- BufferView --- */ +[CRepr] public struct tg3_BufferView { + public tg3_Str name; + public int32 buffer; /* Index, required */ + public uint64 byte_offset; + public uint64 byte_length; /* Required */ + public uint32 byte_stride; /* 0 = tightly packed */ + public tg3_BufferTarget target; /* 0 = unspecified */ + public int32 draco_decoded; + public tg3_ExtrasExt ext; +} + +/* --- Accessor Sparse --- */ +[CRepr] public struct tg3_AccessorSparseIndices { + public uint64 byte_offset; + public int32 buffer_view; /* Required */ + public tg3_ComponentType component_type; /* Required */ + public tg3_ExtrasExt ext; +} + +[CRepr] public struct tg3_AccessorSparseValues { + public int32 buffer_view; /* Required */ + public uint64 byte_offset; + public tg3_ExtrasExt ext; +} + +[CRepr] public struct tg3_AccessorSparse { + public int32 count; /* Required if sparse */ + public int32 is_sparse; /* 0 or 1 */ + public tg3_AccessorSparseIndices indices; + public tg3_AccessorSparseValues values; + public tg3_ExtrasExt ext; +} + +/* --- Accessor --- */ +[CRepr] public struct tg3_Accessor { + public tg3_Str name; + public int32 buffer_view; /* -1 if absent */ + public uint64 byte_offset; + public int32 normalized; /* 0 or 1 */ + public tg3_ComponentType component_type; /* Required */ + public uint64 count; /* Required */ + public tg3_AccessorType type; /* Required: TG3_TYPE_* */ + public double* min_values; + public uint32 min_values_count; + public double* max_values; + public uint32 max_values_count; + public tg3_AccessorSparse sparse; + public tg3_ExtrasExt ext; +} + +/* --- Image --- */ +[CRepr] public struct tg3_Image { + public tg3_Str name; + public int32 width; + public int32 height; + public int32 component; /* Channels */ + public int32 bits; /* Bits per channel */ + public int32 pixel_type; /* Component type */ + public tg3_SpanU8 image; /* Decoded pixel data (or raw if as_is) */ + public int32 buffer_view; /* -1 if absent */ + public tg3_Str mime_type; + public tg3_Str uri; + public int32 as_is; + public tg3_ExtrasExt ext; +} + +/* --- Sampler --- */ +[CRepr] public struct tg3_Sampler { + public tg3_Str name; + public int32 min_filter; /* -1 = unspecified */ + public int32 mag_filter; /* -1 = unspecified */ + public tg3_TextureWrapMode wrap_s; /* Default: TG3_TEXTURE_WRAP_REPEAT */ + public tg3_TextureWrapMode wrap_t; /* Default: TG3_TEXTURE_WRAP_REPEAT */ + public tg3_ExtrasExt ext; +} + +/* --- Texture --- */ +[CRepr] public struct tg3_Texture { + public tg3_Str name; + public int32 sampler; /* -1 if absent */ + public int32 source; /* -1 if absent */ + public tg3_ExtrasExt ext; +} + +/* --- TextureInfo --- */ +[CRepr] public struct tg3_TextureInfo { + public int32 index; /* -1 if absent */ + public int32 tex_coord; /* Default: 0 */ + public tg3_ExtrasExt ext; +} + +/* --- NormalTextureInfo --- */ +[CRepr] public struct tg3_NormalTextureInfo { + public int32 index; + public int32 tex_coord; + public double scale; /* Default: 1.0 */ + public tg3_ExtrasExt ext; +} + +/* --- OcclusionTextureInfo --- */ +[CRepr] public struct tg3_OcclusionTextureInfo { + public int32 index; + public int32 tex_coord; + public double strength; /* Default: 1.0 */ + public tg3_ExtrasExt ext; +} + +/* --- PBR Metallic Roughness --- */ +[CRepr] public struct tg3_PbrMetallicRoughness { + public double[4] base_color_factor; /* Default: {1,1,1,1} */ + public tg3_TextureInfo base_color_texture; + public double metallic_factor; /* Default: 1.0 */ + public double roughness_factor; /* Default: 1.0 */ + public tg3_TextureInfo metallic_roughness_texture; + public tg3_ExtrasExt ext; +} + +/* --- Material --- */ +[CRepr] public struct tg3_Material { + public tg3_Str name; + public double[3] emissive_factor; /* Default: {0,0,0} */ + public tg3_Str alpha_mode; /* "OPAQUE","MASK","BLEND" */ + public double alpha_cutoff; /* Default: 0.5 */ + public int32 double_sided; /* 0 or 1 */ + public int32* lods; + public uint32 lods_count; + public tg3_PbrMetallicRoughness pbr_metallic_roughness; + public tg3_NormalTextureInfo normal_texture; + public tg3_OcclusionTextureInfo occlusion_texture; + public tg3_TextureInfo emissive_texture; + public tg3_ExtrasExt ext; +} + +/* --- Primitive --- */ +[CRepr] public struct tg3_Primitive { + public tg3_StrIntPair* attributes; + public uint32 attributes_count; + public int32 material; /* -1 if absent */ + public int32 indices; /* -1 if absent */ + public tg3_PrimitiveMode mode; /* -1 = default (TRIANGLES) */ + + /* Morph targets: array of arrays of attribute pairs */ + public tg3_StrIntPair** targets; + public uint32* target_attribute_counts; + public uint32 targets_count; + + public tg3_ExtrasExt ext; +} + +/* --- Mesh --- */ +[CRepr] public struct tg3_Mesh { + public tg3_Str name; + public tg3_Primitive* primitives; + public uint32 primitives_count; + public double* weights; + public uint32 weights_count; + public tg3_ExtrasExt ext; +} + +/* --- Node --- */ +[CRepr] public struct tg3_Node { + public tg3_Str name; + public int32 camera; /* -1 if absent */ + public int32 skin; /* -1 if absent */ + public int32 mesh; /* -1 if absent */ + public int32 light; /* -1 if absent (KHR_lights_punctual) */ + public int32 emitter; /* -1 if absent (KHR_audio) */ + + public int32* lods; + public uint32 lods_count; + public int32* children; + public uint32 children_count; + + public double[4] rotation; /* Default: {0,0,0,1} */ + public double[3] scale; /* Default: {1,1,1} */ + public double[3] translation; /* Default: {0,0,0} */ + public double[16] matrix; /* Identity if not set */ + public int32 has_matrix; /* 1 if matrix was specified */ + + public double* weights; + public uint32 weights_count; + + public tg3_ExtrasExt ext; +} + +/* --- Skin --- */ +[CRepr] public struct tg3_Skin { + public tg3_Str name; + public int32 inverse_bind_matrices; /* -1 if absent */ + public int32 skeleton; /* -1 if absent */ + public int32* joints; + public uint32 joints_count; + public tg3_ExtrasExt ext; +} + +/* --- Animation --- */ +[CRepr] public struct tg3_AnimationChannelTarget { + public int32 node; /* -1 if absent */ + public tg3_Str path; /* "translation","rotation","scale","weights" */ + public tg3_ExtrasExt ext; +} + +[CRepr] public struct tg3_AnimationChannel { + public int32 sampler; /* Required */ + public tg3_AnimationChannelTarget target; + public tg3_ExtrasExt ext; +} + +[CRepr] public struct tg3_AnimationSampler { + public int32 input; /* Required */ + public int32 output; /* Required */ + public tg3_Str interpolation; /* "LINEAR","STEP","CUBICSPLINE" */ + public tg3_ExtrasExt ext; +} + +[CRepr] public struct tg3_Animation { + public tg3_Str name; + public tg3_AnimationChannel* channels; + public uint32 channels_count; + public tg3_AnimationSampler* samplers; + public uint32 samplers_count; + public tg3_ExtrasExt ext; +} + +/* --- Camera --- */ +[CRepr] public struct tg3_PerspectiveCamera { + public double aspect_ratio; + public double yfov; + public double zfar; /* 0 = infinite */ + public double znear; + public tg3_ExtrasExt ext; +} + +[CRepr] public struct tg3_OrthographicCamera { + public double xmag; + public double ymag; + public double zfar; + public double znear; + public tg3_ExtrasExt ext; +} + +[CRepr] public struct tg3_Camera { + public tg3_Str name; + public tg3_Str type; /* "perspective" or "orthographic" */ + public tg3_PerspectiveCamera perspective; + public tg3_OrthographicCamera orthographic; + public tg3_ExtrasExt ext; +} + +/* --- Scene --- */ +[CRepr] public struct tg3_Scene { + public tg3_Str name; + public int32* nodes; + public uint32 nodes_count; + public int32* audio_emitters; + public uint32 audio_emitters_count; + public tg3_ExtrasExt ext; +} + +/* --- Light (KHR_lights_punctual) --- */ +[CRepr] public struct tg3_SpotLight { + public double inner_cone_angle; /* Default: 0 */ + public double outer_cone_angle; /* Default: PI/4 */ + public tg3_ExtrasExt ext; +} + +[CRepr] public struct tg3_Light { + public tg3_Str name; + public double[3] color; /* Default: {1,1,1} */ + public double intensity; /* Default: 1.0 */ + public tg3_Str type; /* "directional","point","spot" */ + public double range; /* Default: 0 (infinite) */ + public tg3_SpotLight spot; + public tg3_ExtrasExt ext; +} + +/* --- Audio (KHR_audio) --- */ +[CRepr] public struct tg3_AudioSource { + public tg3_Str name; + public tg3_Str uri; + public int32 buffer_view; /* -1 if absent */ + public tg3_Str mime_type; + public tg3_ExtrasExt ext; +} + +[CRepr] public struct tg3_PositionalEmitter { + public double cone_inner_angle; /* Default: 2*PI */ + public double cone_outer_angle; /* Default: 2*PI */ + public double cone_outer_gain; /* Default: 0 */ + public double max_distance; /* Default: 100 */ + public double ref_distance; /* Default: 1 */ + public double rolloff_factor; /* Default: 1 */ + public tg3_ExtrasExt ext; +} + +[CRepr] public struct tg3_AudioEmitter { + public tg3_Str name; + public double gain; /* Default: 1.0 */ + public int32 loop; /* Default: 0 */ + public int32 playing; /* Default: 0 */ + public tg3_Str type; /* "positional" or "global" */ + public tg3_Str distance_model; /* "linear","inverse","exponential" */ + public tg3_PositionalEmitter positional; + public int32 source; /* -1 if absent */ + public tg3_ExtrasExt ext; +} + +/* ====================================================================== + * Section 10: Model Container + * ====================================================================== */ + +/* Opaque arena type */ +[CRepr] public struct tg3_Arena; + +[CRepr] public struct tg3_Model { + public tg3_Arena* arena_; /* Internal, all memory owned here */ + + public tg3_Accessor* accessors; public uint32 accessors_count; + public tg3_Animation* animations; public uint32 animations_count; + public tg3_Buffer* buffers; public uint32 buffers_count; + public tg3_BufferView* buffer_views; public uint32 buffer_views_count; + public tg3_Material* materials; public uint32 materials_count; + public tg3_Mesh* meshes; public uint32 meshes_count; + public tg3_Node* nodes; public uint32 nodes_count; + public tg3_Texture* textures; public uint32 textures_count; + public tg3_Image* images; public uint32 images_count; + public tg3_Skin* skins; public uint32 skins_count; + public tg3_Sampler* samplers; public uint32 samplers_count; + public tg3_Camera* cameras; public uint32 cameras_count; + public tg3_Scene* scenes; public uint32 scenes_count; + public tg3_Light* lights; public uint32 lights_count; + public tg3_AudioEmitter* audio_emitters; public uint32 audio_emitters_count; + public tg3_AudioSource* audio_sources; public uint32 audio_sources_count; + + public int32 default_scene; + public tg3_Str* extensions_used; public uint32 extensions_used_count; + public tg3_Str* extensions_required; public uint32 extensions_required_count; + public tg3_Asset asset; + public tg3_ExtrasExt ext; +} + +/* ====================================================================== + * Section 11: Callback Typedefs + * ====================================================================== */ + +/* --- Filesystem Callbacks --- */ + +public function int32 tg3_FileExistsFn(c_char* path, uint32 path_len, void* user_data); + +public function int32 tg3_ReadFileFn(uint8** out_data, uint64* out_size, c_char* path, uint32 path_len, void* user_data); + +public function void tg3_FreeFileFn(uint8* data, uint64 size, void* user_data); + +public function int32 tg3_WriteFileFn(c_char* path, uint32 path_len, uint8* data, uint64 size, void* user_data); + +public function int32 tg3_ResolvePathFn(c_char* out_path, uint32 out_cap, uint32* out_len, c_char* path, uint32 path_len, void* user_data); + +public function int32 tg3_GetFileSizeFn(uint64* out_size, c_char* path, uint32 path_len, void* user_data); + +[CRepr] public struct tg3_FsCallbacks { + public tg3_FileExistsFn file_exists; + public tg3_ReadFileFn read_file; + public tg3_FreeFileFn free_file; + public tg3_WriteFileFn write_file; + public tg3_ResolvePathFn resolve_path; + public tg3_GetFileSizeFn get_file_size; + public void* user_data; +} + +/* --- Image Callbacks --- */ + +[CRepr] public struct tg3_ImageRequest { + public uint8* data; + public uint64 data_size; + public int32 image_index; + public int32 req_width; + public int32 req_height; + public c_char* mime_type; +} + +[CRepr] public struct tg3_ImageResult { + public uint8* pixels; /* Caller must allocate */ + public int32 width; + public int32 height; + public int32 component; + public int32 bits; + public int32 pixel_type; +} + +public function int32 tg3_LoadImageFn(tg3_ImageResult* result, tg3_ImageRequest* request, void* user_data); + +public function void tg3_FreeImageFn(uint8* pixels, void* user_data); + +[CRepr] public struct tg3_ImageCallbacks { + public tg3_LoadImageFn load_image; + public tg3_FreeImageFn free_image; + public void* user_data; +} + +/* --- URI Callbacks --- */ + +public function int32 tg3_UriEncodeFn(c_char* @out, uint32 out_cap, uint32* out_len, c_char* uri, uint32 uri_len, c_char* obj_type, void* user_data); + +public function int32 tg3_UriDecodeFn(c_char* @out, uint32 out_cap, uint32* out_len, c_char* uri, uint32 uri_len, void* user_data); + +[CRepr] public struct tg3_UriCallbacks { + public tg3_UriEncodeFn encode; + public tg3_UriDecodeFn decode; + public void* user_data; +} + +/* --- Streaming Callbacks --- */ + +[AllowDuplicates] public enum tg3_StreamAction : c_int { + Continue = 0, + Abort = 1, + Skip = 2, +} + +public function tg3_StreamAction tg3_OnAssetFn(tg3_Asset* a, void* ud); +public function tg3_StreamAction tg3_OnBufferFn(tg3_Buffer* b, int32 idx, void* ud); +public function tg3_StreamAction tg3_OnBufferViewFn(tg3_BufferView* bv, int32 idx, void* ud); +public function tg3_StreamAction tg3_OnAccessorFn(tg3_Accessor* a, int32 idx, void* ud); +public function tg3_StreamAction tg3_OnMeshFn(tg3_Mesh* m, int32 idx, void* ud); +public function tg3_StreamAction tg3_OnNodeFn(tg3_Node* n, int32 idx, void* ud); +public function tg3_StreamAction tg3_OnMaterialFn(tg3_Material* m, int32 idx, void* ud); +public function tg3_StreamAction tg3_OnTextureFn(tg3_Texture* t, int32 idx, void* ud); +public function tg3_StreamAction tg3_OnImageFn(tg3_Image* img, int32 idx, void* ud); +public function tg3_StreamAction tg3_OnSamplerFn(tg3_Sampler* s, int32 idx, void* ud); +public function tg3_StreamAction tg3_OnAnimationFn(tg3_Animation* a, int32 idx, void* ud); +public function tg3_StreamAction tg3_OnSkinFn(tg3_Skin* s, int32 idx, void* ud); +public function tg3_StreamAction tg3_OnCameraFn(tg3_Camera* c, int32 idx, void* ud); +public function tg3_StreamAction tg3_OnSceneFn(tg3_Scene* s, int32 idx, void* ud); +public function tg3_StreamAction tg3_OnLightFn(tg3_Light* l, int32 idx, void* ud); + +[CRepr] public struct tg3_StreamCallbacks { + public tg3_OnAssetFn on_asset; + public tg3_OnBufferFn on_buffer; + public tg3_OnBufferViewFn on_buffer_view; + public tg3_OnAccessorFn on_accessor; + public tg3_OnMeshFn on_mesh; + public tg3_OnNodeFn on_node; + public tg3_OnMaterialFn on_material; + public tg3_OnTextureFn on_texture; + public tg3_OnImageFn on_image; + public tg3_OnSamplerFn on_sampler; + public tg3_OnAnimationFn on_animation; + public tg3_OnSkinFn on_skin; + public tg3_OnCameraFn on_camera; + public tg3_OnSceneFn on_scene; + public tg3_OnLightFn on_light; + public void* user_data; +} + +/* --- Progress Callback --- */ + +[CRepr] public struct tg3_ProgressInfo { + public uint64 bytes_processed; + public uint64 bytes_total; + public uint32 elements_parsed; + public c_char* current_section; /* e.g. "meshes", "nodes" */ +} + +public function int32 tg3_ProgressFn(tg3_ProgressInfo* info, void* user_data); + +/* --- Write Chunk Callback (for streaming writer) --- */ + +public function int32 tg3_WriteChunkFn(uint8* data, uint64 size, void* user_data); + +/* ====================================================================== + * Section 12: Options Structs + * ====================================================================== */ + +[CRepr] public struct tg3_MemoryConfig { + public uint64 memory_budget; /* 0 = use TINYGLTF3_MAX_MEMORY_BYTES */ + public uint64 max_single_alloc; /* 0 = no limit */ + public uint32 arena_block_size; /* 0 = default (256KB) */ + public tg3_Allocator allocator; /* All zero = use malloc/free */ +} + +[CRepr] public struct tg3_ParseOptions { + public uint32 required_sections; /* TG3_REQUIRE_* flags */ + public tg3_Strictness strictness; + public tg3_MemoryConfig memory; + + public tg3_FsCallbacks fs; + public tg3_UriCallbacks uri; + public tg3_ImageCallbacks image; + public tg3_StreamCallbacks* stream; /* NULL = no streaming */ + public tg3_ProgressFn progress; + public void* progress_user_data; + + public int32 images_as_is; /* 1 = don't decode images */ + public int32 preserve_image_channels; /* 1 = keep original channels */ + public int32 store_original_json; /* 1 = store raw JSON strings */ + public int32 skip_extras_values; /* 1 = skip materializing extras and + * unknown extension value trees */ + public int32 borrow_input_buffers; /* 1 = GLB BIN buffer spans may point + * into caller-owned input data */ + public int32 parse_float32; /* 1 = parse JSON floats as float32 for speed + * (breaks strict double-precision conformance + * but sufficient for glTF data which is + * typically single-precision anyway) */ + public int32 validate_indices; /* 1 = reject out-of-range index fields + * after parse so naive consumers cannot + * dereference attacker-controlled indices. + * Default: 1. Set to 0 to skip (raw mode). */ + public uint64 max_external_file_size; /* 0 = no limit */ +} + +[CRepr] public struct tg3_WriteOptions { + public int32 pretty_print; /* 1 = indented JSON */ + public int32 write_binary; /* 1 = GLB format */ + public int32 embed_images; /* 1 = embed as data URIs */ + public int32 embed_buffers; /* 1 = embed as data URIs */ + public int32 serialize_defaults; /* 1 = write default values */ + public tg3_FsCallbacks fs; + public tg3_UriCallbacks uri; + public tg3_MemoryConfig memory; +} + +extension TinyglTF +{ +/* ====================================================================== + * Section 13: Parser API + * ====================================================================== */ + +/* Parse JSON glTF from memory */ +[LinkName("tg3_parse")] public static extern tg3_ErrorCode Parse(tg3_Model* model, tg3_ErrorStack* errors, uint8* json_data, uint64 json_size, c_char* base_dir, uint32 base_dir_len, tg3_ParseOptions* options); + +/* Parse GLB from memory */ +[LinkName("tg3_parse_glb")] public static extern tg3_ErrorCode ParseGlb(tg3_Model* model, tg3_ErrorStack* errors, uint8* glb_data, uint64 glb_size, c_char* base_dir, uint32 base_dir_len, tg3_ParseOptions* options); + +/* Auto-detect format (JSON or GLB) and parse */ +[LinkName("tg3_parse_auto")] public static extern tg3_ErrorCode ParseAuto(tg3_Model* model, tg3_ErrorStack* errors, uint8* data, uint64 size, c_char* base_dir, uint32 base_dir_len, tg3_ParseOptions* options); + +/* Parse from file (requires fs callbacks or TINYGLTF3_ENABLE_FS) */ +[LinkName("tg3_parse_file")] public static extern tg3_ErrorCode ParseFile(tg3_Model* model, tg3_ErrorStack* errors, c_char* filename, uint32 filename_len, tg3_ParseOptions* options); + +/* Free model and all arena memory */ +[LinkName("tg3_model_free")] public static extern void ModelFree(tg3_Model* model); + +/* Initialize options to defaults */ +[LinkName("tg3_parse_options_init")] public static extern void ParseOptionsInit(tg3_ParseOptions* options); +[LinkName("tg3_write_options_init")] public static extern void WriteOptionsInit(tg3_WriteOptions* options); + +/* Initialize error stack */ +[LinkName("tg3_error_stack_init")] public static extern void ErrorStackInit(tg3_ErrorStack* es); +[LinkName("tg3_error_stack_free")] public static extern void ErrorStackFree(tg3_ErrorStack* es); + +/* ====================================================================== + * Section 14: Writer API + * ====================================================================== */ + +/* Write model to memory buffer */ +[LinkName("tg3_write_to_memory")] public static extern tg3_ErrorCode WriteToMemory(tg3_Model* model, tg3_ErrorStack* errors, uint8** out_data, uint64* out_size, tg3_WriteOptions* options); + +/* Write model to file */ +[LinkName("tg3_write_to_file")] public static extern tg3_ErrorCode WriteToFile(tg3_Model* model, tg3_ErrorStack* errors, c_char* filename, uint32 filename_len, tg3_WriteOptions* options); + +/* Free memory from tg3_write_to_memory */ +[LinkName("tg3_write_free")] public static extern void WriteFree(uint8* data, tg3_WriteOptions* options); +} + +/* --- Streaming Writer --- */ + +[CRepr] public struct tg3_Writer; + +extension TinyglTF +{ +[LinkName("tg3_writer_create")] public static extern tg3_Writer* WriterCreate(tg3_WriteChunkFn chunk_fn, void* user_data, tg3_WriteOptions* options); + +[LinkName("tg3_writer_begin")] public static extern tg3_ErrorCode WriterBegin(tg3_Writer* w, tg3_Asset* asset); +[LinkName("tg3_writer_add_buffer")] public static extern tg3_ErrorCode WriterAddBuffer(tg3_Writer* w, tg3_Buffer* buf); +[LinkName("tg3_writer_add_buffer_view")] public static extern tg3_ErrorCode WriterAddBufferView(tg3_Writer* w, tg3_BufferView* bv); +[LinkName("tg3_writer_add_accessor")] public static extern tg3_ErrorCode WriterAddAccessor(tg3_Writer* w, tg3_Accessor* acc); +[LinkName("tg3_writer_add_mesh")] public static extern tg3_ErrorCode WriterAddMesh(tg3_Writer* w, tg3_Mesh* mesh); +[LinkName("tg3_writer_add_node")] public static extern tg3_ErrorCode WriterAddNode(tg3_Writer* w, tg3_Node* node); +[LinkName("tg3_writer_add_material")] public static extern tg3_ErrorCode WriterAddMaterial(tg3_Writer* w, tg3_Material* mat); +[LinkName("tg3_writer_add_texture")] public static extern tg3_ErrorCode WriterAddTexture(tg3_Writer* w, tg3_Texture* tex); +[LinkName("tg3_writer_add_image")] public static extern tg3_ErrorCode WriterAddImage(tg3_Writer* w, tg3_Image* img); +[LinkName("tg3_writer_add_sampler")] public static extern tg3_ErrorCode WriterAddSampler(tg3_Writer* w, tg3_Sampler* samp); +[LinkName("tg3_writer_add_animation")] public static extern tg3_ErrorCode WriterAddAnimation(tg3_Writer* w, tg3_Animation* anim); +[LinkName("tg3_writer_add_skin")] public static extern tg3_ErrorCode WriterAddSkin(tg3_Writer* w, tg3_Skin* skin); +[LinkName("tg3_writer_add_camera")] public static extern tg3_ErrorCode WriterAddCamera(tg3_Writer* w, tg3_Camera* cam); +[LinkName("tg3_writer_add_scene")] public static extern tg3_ErrorCode WriterAddScene(tg3_Writer* w, tg3_Scene* scene); +[LinkName("tg3_writer_add_light")] public static extern tg3_ErrorCode WriterAddLight(tg3_Writer* w, tg3_Light* light); +[LinkName("tg3_writer_end")] public static extern tg3_ErrorCode WriterEnd(tg3_Writer* w); +[LinkName("tg3_writer_destroy")] public static extern void WriterDestroy(tg3_Writer* w); + +/* ====================================================================== + * Section 15: Utility Functions + * ====================================================================== */ + +/* Get component size in bytes */ +[LinkName("tg3_component_size")] public static extern int32 ComponentSize(int32 component_type); + +/* Get number of components for a type */ +[LinkName("tg3_num_components")] public static extern int32 NumComponents(int32 type); + +/* Compute byte stride for an accessor */ +[LinkName("tg3_accessor_byte_stride")] public static extern int32 AccessorByteStride(tg3_Accessor* accessor, tg3_BufferView* buffer_view); + +/* Check if a string is a data URI */ +[LinkName("tg3_is_data_uri")] public static extern int32 IsDataUri(c_char* uri, uint32 len); + +/* tg3_str helpers */ +[LinkName("tg3_str_equals")] public static extern int32 StrEquals(tg3_Str a, tg3_Str b); +[LinkName("tg3_str_equals_cstr")] public static extern int32 StrEqualsCstr(tg3_Str a, c_char* b); +} + +/* extern "C" */ + + +/* ====================================================================== + * Section 16: C++ Convenience Wrappers + * ====================================================================== */ + + + + +/* RAII model wrapper */ + + + + + + + + + + + + + + + + + + + + + + +/* RAII error stack wrapper */ + + + + + + + + + + + + + + + + + + + +/* Parse helpers returning error code */ + + + + + + + + + + + + + + + + + + + + +/* namespace tinygltf3 */ +/* __cplusplus */ + +/* ====================================================================== + * Section 17: C++20 Coroutine Facade + * ====================================================================== */ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +/* Coroutine parse entry point — declaration only, implemented in TINYGLTF3_IMPLEMENTATION */ + + + + + + +/* namespace tinygltf3 */ + +/* coroutines */ +/* __cplusplus */ + +/* ====================================================================== + * Section 18: Implementation + * ====================================================================== */ + + + + + + + + + + + + +/* Include JSON parser */ + + + + + +/* Implementation uses C++ features from tinygltf_json.h */ + + + +/* Forward SIMD macros to tinygltf_json.h */ + + + + + + + + + + + + + + + + +/* ====================================================================== + * Internal: Arena Allocator + * ====================================================================== */ + +/* 256 KB */ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + /* OOM */ + + + + + + + + + + + + + + + + + + + + + + + + + + + + /* Align up */ + + + + + + + + + + + + + + + + /* Allocate len+1 bytes; when len==0 this produces a 1-byte "\0" buffer so + * that empty strings (data!=NULL, len==0) remain distinguishable from + * absent strings (data==NULL, len==0). */ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +/* ====================================================================== + * Internal: Error Stack Implementation + * ====================================================================== */ + + + + + + + + + + + /* Drop error on OOM */ + + + + + + + + /* Caller must ensure lifetime (arena or static) */ + + + + + + +/* Push an error with a dynamically formatted message allocated from arena */ + + + + + + + + + + + + + + + + + + + + +/* ====================================================================== + * Public: Error Stack API + * ====================================================================== */ + + + + + + + + + + + + + + + + + + + + + + + + + + +/* ====================================================================== + * Public: Options Init + * ====================================================================== */ + + + + + + + + + + + + + + +/* ====================================================================== + * Public: Utility Functions + * ====================================================================== */ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +/* ====================================================================== + * Internal: Base64 Encode/Decode + * ====================================================================== */ + + + + + + + + + + + + + + + + + + + + + + + /* Strip trailing padding */ + + + + + + + + + + + + + + /* skip whitespace/invalid */ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +/* ====================================================================== + * Internal: Data URI Handling + * ====================================================================== */ + + + + + + + + + + + + + + + /* Expected format: data:;base64, */ + + + + + + /* Find semicolon */ + + + + + /* Extract MIME type */ + + + + + + /* Skip ";base64," */ + + + + + + + + + + + + + + + + + + + + + + + + + + + + +/* ====================================================================== + * Internal: Parse Context + * ====================================================================== */ + + + + + + + + + /* GLB binary chunk */ + + + + + +/* ====================================================================== + * Internal: JSON Property Helpers + * ====================================================================== */ + +/* Type alias for JSON */ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +/* Parse string array */ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +/* ====================================================================== + * Internal: Value Conversion (JSON -> tg3_value) + * ====================================================================== */ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +/* ====================================================================== + * Internal: Parse Extras and Extensions + * ====================================================================== */ + + + + + + + + + /* Extras */ + + + + + + + + + + + + + + /* Extensions */ + + + + + + + + + + + + + + + + + + + + + + + + +/* ====================================================================== + * Internal: Init functions for default struct values + * ====================================================================== */ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + /* w=1 identity quaternion */ + + + + /* Identity matrix */ + + + + + + +/* ====================================================================== + * Internal: Entity Parse Functions + * ====================================================================== */ + + + + + + + + + + + + + + + + + /* Optional */ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + /* Parse type string */ + + + + + + + + + + + + + + + + + + + + + + + + + + /* Build full path: base_dir + "/" + uri */ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + /* Load buffer data */ + + /* GLB: first buffer uses binary chunk */ + + + + + + + + + + + + + + + + + + + /* Data URI */ + + + + + + + + + + + + + + + /* External file */ + + + + + /* Copy into arena */ + + + + + + + /* Free file data via callback */ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + /*img_idx*/ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + /* Emissive factor */ + + + /* Alpha mode */ + + + + + + + + + + + + /* PBR */ + + + + + + + + + + + + + + + + + + + + + + + + /* MSFT_lod */ + + + + + + + + + + + + + + + + + + + + + + + + + + /* Attributes */ + + + + + + + + + + + + + + + + + + + + /* Morph targets */ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + /* Primitives */ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + /* TRS */ + + + + + + + + + + + + + + + + + + /* Extensions: KHR_lights_punctual, KHR_audio, MSFT_lod */ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + /* Channels */ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + /* Samplers */ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + /* KHR_audio emitters */ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +/* ====================================================================== + * Internal: Portable variadic-comma helper + * + * TG3__COMMA_VA_ARGS(__VA_ARGS__) expands to , __VA_ARGS__ when the + * argument list is non-empty, and to nothing when it is empty. + * + * - C++20 and later: uses the standard __VA_OPT__(,) token. + * - C++17 and earlier: falls back to the widely-supported GNU/MSVC + * ##__VA_ARGS__ extension. + * ====================================================================== */ + + + + + + +/* ====================================================================== + * Internal: Array Parse Macro + * ====================================================================== */ + + + + + + + + + + + + + + + + + + + + + +/* Variant without extra args and with index param */ + + + + + + + + + + + + + + + + + + + + + + + + + + +/* Simpler variant for entities without index */ + + + + + + + + + + + + + + + + + + + + + + + + + + +/* ====================================================================== + * Internal: Main Parse Orchestrator + * ====================================================================== */ + + + + + /* Asset */ + + + + + + + + + + /* Extensions used/required */ + + + + + + + + /* Default scene */ + + + + /* Streaming callback helper macro */ + + + + + + + + + + /* Parse all entity arrays */ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + /* KHR_lights_punctual */ + + + + + + + + + + + /* KHR_audio */ + + + + + + + + + + + + /* Root extras/extensions */ + + + + + + + +/* ====================================================================== + * Internal: GLB Parsing + * ====================================================================== */ + + + + + + + + + + + + + + + + + /* Check magic: 'glTF' */ + + + + + + + /* Version */ + + + + + + + + + /* Total length */ + + + + + + + + + + + + + + + /* Chunk 0: JSON */ + + + + + /* 'JSON' in LE */ + + + + + + + + + + + + + + + /* Chunk 1: BIN (optional) */ + + /* Align to 4 bytes */ + + + + + + + + /* 'BIN\0' in LE */ + + + + + + + + + + +/* ====================================================================== + * Optional: Default FS Callbacks + * ====================================================================== */ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +/* TINYGLTF3_ENABLE_FS */ + +/* ====================================================================== + * Internal: Model Init Helper + * ====================================================================== */ + + + + + + +/* ====================================================================== + * Public: Parser API Implementation + * ====================================================================== */ + + + + + + + + + + + + + + + + + + + + + + + + /* Parse JSON */ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + /* Parse JSON chunk */ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + /* Check for GLB magic */ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + /* Read file */ + + + + + + + + + + + /* Extract base directory */ + + + + /* Find last separator */ + + + + + + + + + + + + + + + + + + + /* Free file data */ + + + + + + + + + + + + + + + + +/* ====================================================================== + * Internal: JSON Serialization Helpers + * ====================================================================== */ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +/* ====================================================================== + * Internal: Entity Serialize Functions + * ====================================================================== */ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + /* Encode as data URI */ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + /* PBR */ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + /* Attributes */ + + + + + + + + + + + + + + + /* Morph targets */ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + /* Extensions for lights / audio / lod */ + + + + /* Check if extensions already set by extras_ext */ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +/* ====================================================================== + * Internal: Main Model Serializer + * ====================================================================== */ + + + + + + /* Asset */ + + + /* Default scene */ + + + + + /* Extensions used/required */ + + + + + + + + /* Entity arrays */ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + /* KHR_lights_punctual */ + + + + + + + + + + + + + + + + + /* Root extras/extensions */ + + + + + + +/* ====================================================================== + * Public: Writer API Implementation + * ====================================================================== */ + + + + + + + + + + + + + + + + + + + + + + /* GLB format */ + + /* Pad JSON to 4-byte alignment with spaces */ + + + /* Collect binary buffer data */ + + + + + + + + + /* Header */ + /* JSON chunk */ + + /* BIN chunk */ + + + + + + + + + + /* Header */ + + + + + + /* JSON chunk */ + + + + + /* Pad with spaces */ + + + + + /* BIN chunk */ + + + + + + + /* Pad with zeros */ + + + + + + + + + /* JSON format */ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +/* ====================================================================== + * Streaming Writer (stub implementation) + * ====================================================================== */ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +/* legacy header-only v3 implementation */ +/* TINYGLTF3_IMPLEMENTATION */ + +/* TINY_GLTF_V3_H_ */ \ No newline at end of file diff --git a/src/tiny_gltf_v3.c b/src/tiny_gltf_v3.c new file mode 100644 index 0000000..da515b3 --- /dev/null +++ b/src/tiny_gltf_v3.c @@ -0,0 +1,3653 @@ +#ifndef TINYGLTF3_SOURCE_INCLUDED_FROM_HEADER +#include "tiny_gltf_v3.h" +#endif +#ifdef TINYGLTF3_NO_STDLIB +#ifndef TINYGLTF_JSON_NO_STDLIB +#define TINYGLTF_JSON_NO_STDLIB +#endif +#endif +#ifndef TINYGLTF_JSON_MALLOC +#define TINYGLTF_JSON_MALLOC(sz) TINYGLTF3_MALLOC(sz) +#endif +#ifndef TINYGLTF_JSON_REALLOC +#define TINYGLTF_JSON_REALLOC(ptr, sz) TINYGLTF3_REALLOC((ptr), (sz)) +#endif +#ifndef TINYGLTF_JSON_FREE +#define TINYGLTF_JSON_FREE(ptr) TINYGLTF3_FREE(ptr) +#endif +#define TINYGLTF_JSON_C_IMPLEMENTATION +#include "tinygltf_json_c.h" + +#include +#ifndef TINYGLTF3_NO_STDLIB +#include +#include +#include +#include +#endif + +static void *tg3__memcpy(void *dst, const void *src, size_t size) { +#ifndef TINYGLTF3_NO_STDLIB + return memcpy(dst, src, size); +#else + unsigned char *d = (unsigned char *)dst; + const unsigned char *s = (const unsigned char *)src; + while (size--) *d++ = *s++; + return dst; +#endif +} + +static void *tg3__memset(void *dst, int value, size_t size) { +#ifndef TINYGLTF3_NO_STDLIB + return memset(dst, value, size); +#else + unsigned char *d = (unsigned char *)dst; + while (size--) *d++ = (unsigned char)value; + return dst; +#endif +} + +static int tg3__memcmp(const void *a, const void *b, size_t size) { +#ifndef TINYGLTF3_NO_STDLIB + return memcmp(a, b, size); +#else + const unsigned char *pa = (const unsigned char *)a; + const unsigned char *pb = (const unsigned char *)b; + while (size--) { + if (*pa != *pb) return (int)*pa - (int)*pb; + ++pa; + ++pb; + } + return 0; +#endif +} + +static size_t tg3__strlen(const char *s) { +#ifndef TINYGLTF3_NO_STDLIB + return strlen(s); +#else + const char *p = s; + while (*p) ++p; + return (size_t)(p - s); +#endif +} + +static void *tg3__memchr(const void *s, int c, size_t size) { +#ifndef TINYGLTF3_NO_STDLIB + return (void *)memchr(s, c, size); +#else + const unsigned char *p = (const unsigned char *)s; + unsigned char ch = (unsigned char)c; + while (size--) { + if (*p == ch) return (void *)p; + ++p; + } + return NULL; +#endif +} + +static int tg3__isfinite(double v) { + uint64_t bits = 0; + tg3__memcpy(&bits, &v, sizeof(bits)); + return (bits & 0x7ff0000000000000ULL) != 0x7ff0000000000000ULL; +} + +static double tg3__fabs(double v) { + uint64_t bits = 0; + tg3__memcpy(&bits, &v, sizeof(bits)); + bits &= 0x7fffffffffffffffULL; + tg3__memcpy(&v, &bits, sizeof(v)); + return v; +} + +static int tg3__vsnprintf(char *buf, size_t size, const char *fmt, va_list ap) { +#ifndef TINYGLTF3_NO_STDLIB + return vsnprintf(buf, size, fmt, ap); +#else + size_t i = 0; + (void)ap; + if (size == 0) return 0; + while (fmt[i] && i + 1u < size) { + buf[i] = fmt[i]; + ++i; + } + buf[i] = '\0'; + return (int)i; +#endif +} + +#ifndef TINYGLTF3_MEMCPY +#define TINYGLTF3_MEMCPY(dst, src, size) tg3__memcpy((dst), (src), (size)) +#endif +#ifndef TINYGLTF3_MEMSET +#define TINYGLTF3_MEMSET(dst, value, size) tg3__memset((dst), (value), (size)) +#endif +#ifndef TINYGLTF3_MEMCMP +#define TINYGLTF3_MEMCMP(a, b, size) tg3__memcmp((a), (b), (size)) +#endif +#ifndef TINYGLTF3_STRLEN +#define TINYGLTF3_STRLEN(s) tg3__strlen((s)) +#endif +#ifndef TINYGLTF3_MEMCHR +#define TINYGLTF3_MEMCHR(s, c, size) tg3__memchr((s), (c), (size)) +#endif + +#define TG3__ARENA_DEFAULT_BLOCK_SIZE (256u * 1024u) +#define TG3__ARENA_ALIGNMENT 8u + +typedef struct tg3__arena_block { + struct tg3__arena_block *next; + uint8_t *base; + size_t used; + size_t capacity; +} tg3__arena_block; + +typedef struct tg3_arena tg3_arena; + +struct tg3_arena { + tg3__arena_block *head; + tg3__arena_block *current; + size_t total_allocated; + size_t memory_budget; + size_t max_single_alloc; + size_t block_size; + tg3_allocator alloc; +}; + +typedef struct tg3__parse_ctx { + tg3_arena *arena; + tg3_error_stack *errors; + tg3_parse_options opts; + const char *base_dir; + uint32_t base_dir_len; + const uint8_t *bin_data; + uint64_t bin_size; + int32_t is_binary; +} tg3__parse_ctx; + +struct tg3_writer { + tg3_write_chunk_fn chunk_fn; + void *user_data; + tg3_write_options options; + tg3json_value root; + int begun; +}; + +static void *tg3__default_alloc(size_t size, void *ud) { + (void)size; + (void)ud; + return TINYGLTF3_MALLOC(size); +} + +static void *tg3__default_realloc(void *ptr, size_t old_size, size_t new_size, void *ud) { + (void)ptr; + (void)old_size; + (void)new_size; + (void)ud; + return TINYGLTF3_REALLOC(ptr, new_size); +} + +static void tg3__default_free(void *ptr, size_t size, void *ud) { + (void)size; + (void)ud; + TINYGLTF3_FREE(ptr); +} + +static tg3_arena *tg3__arena_create(const tg3_memory_config *config) { + tg3_allocator alloc; + tg3_arena *arena; + if (config && config->allocator.alloc) { + alloc = config->allocator; + } else { + alloc.alloc = tg3__default_alloc; + alloc.realloc = tg3__default_realloc; + alloc.free = tg3__default_free; + alloc.user_data = NULL; + } + + arena = (tg3_arena *)alloc.alloc(sizeof(tg3_arena), alloc.user_data); + if (!arena) return NULL; + TINYGLTF3_MEMSET(arena, 0, sizeof(*arena)); + arena->alloc = alloc; + arena->block_size = (config && config->arena_block_size > 0) + ? (size_t)config->arena_block_size + : (size_t)TG3__ARENA_DEFAULT_BLOCK_SIZE; + arena->memory_budget = (config && config->memory_budget > 0) + ? (size_t)config->memory_budget + : (size_t)TINYGLTF3_MAX_MEMORY_BYTES; + arena->max_single_alloc = (config && config->max_single_alloc > 0) + ? (size_t)config->max_single_alloc + : 0; + return arena; +} + +static tg3__arena_block *tg3__arena_new_block(tg3_arena *arena, size_t min_size) { + size_t cap = arena->block_size; + void *raw; + tg3__arena_block *block; + if (cap < min_size) cap = min_size; + if (arena->max_single_alloc && cap > arena->max_single_alloc) return NULL; + if (arena->total_allocated + sizeof(tg3__arena_block) + cap > arena->memory_budget) return NULL; + + raw = arena->alloc.alloc(sizeof(tg3__arena_block) + cap, arena->alloc.user_data); + if (!raw) return NULL; + block = (tg3__arena_block *)raw; + block->next = NULL; + block->base = (uint8_t *)raw + sizeof(tg3__arena_block); + block->used = 0; + block->capacity = cap; + arena->total_allocated += sizeof(tg3__arena_block) + cap; + + if (arena->current) arena->current->next = block; + else arena->head = block; + arena->current = block; + return block; +} + +static void *tg3__arena_alloc(tg3_arena *arena, size_t size) { + tg3__arena_block *block; + void *ptr; + if (!arena || size == 0) return NULL; + if (arena->max_single_alloc && size > arena->max_single_alloc) return NULL; + size = (size + (TG3__ARENA_ALIGNMENT - 1u)) & ~(size_t)(TG3__ARENA_ALIGNMENT - 1u); + block = arena->current; + if (!block || (block->used + size > block->capacity)) { + block = tg3__arena_new_block(arena, size); + if (!block) return NULL; + } + ptr = block->base + block->used; + block->used += size; + return ptr; +} + +static char *tg3__arena_strdup(tg3_arena *arena, const char *s, size_t len) { + char *dst; + if (!s) return NULL; + dst = (char *)tg3__arena_alloc(arena, len + 1); + if (!dst) return NULL; + if (len > 0) TINYGLTF3_MEMCPY(dst, s, len); + dst[len] = '\0'; + return dst; +} + +static tg3_str tg3__arena_str(tg3_arena *arena, const char *s, uint32_t len) { + tg3_str out; + out.data = tg3__arena_strdup(arena, s, len); + out.len = out.data ? len : 0; + return out; +} + +static void tg3__arena_destroy(tg3_arena *arena) { + tg3_allocator alloc; + tg3__arena_block *block; + if (!arena) return; + alloc = arena->alloc; + block = arena->head; + while (block) { + tg3__arena_block *next = block->next; + alloc.free(block, sizeof(tg3__arena_block) + block->capacity, alloc.user_data); + block = next; + } + alloc.free(arena, sizeof(*arena), alloc.user_data); +} + +static void tg3__error_push(tg3_error_stack *es, tg3_severity sev, + tg3_error_code code, const char *msg, + const char *json_path, int64_t byte_offset) { + tg3_error_entry *entry; + tg3_error_entry *new_entries; + uint32_t new_cap; + if (!es) return; + if (es->count >= es->capacity) { + new_cap = es->capacity ? es->capacity * 2u : 16u; + new_entries = (tg3_error_entry *)TINYGLTF3_REALLOC(es->entries, new_cap * sizeof(tg3_error_entry)); + if (!new_entries) return; + es->entries = new_entries; + es->capacity = new_cap; + } + entry = &es->entries[es->count++]; + entry->severity = sev; + entry->code = code; + entry->message = msg; + entry->json_path = json_path; + entry->byte_offset = byte_offset; + if (sev == TG3_SEVERITY_ERROR) es->has_error = 1; +} + +static void tg3__error_pushf(tg3_error_stack *es, tg3_arena *arena, + tg3_severity sev, tg3_error_code code, + const char *json_path, const char *fmt, ...) { + char buf[1024]; + int n; + va_list ap; + const char *msg = buf; + if (!es) return; + va_start(ap, fmt); + n = tg3__vsnprintf(buf, sizeof(buf), fmt, ap); + va_end(ap); + if (n < 0) n = 0; + if ((size_t)n >= sizeof(buf)) n = (int)(sizeof(buf) - 1u); + if (arena) { + char *dup = tg3__arena_strdup(arena, buf, (size_t)n); + if (dup) msg = dup; + } + tg3__error_push(es, sev, code, msg, json_path, -1); +} + +TINYGLTF3_API int32_t tg3_errors_has_error(const tg3_error_stack *es) { return es ? es->has_error : 0; } +TINYGLTF3_API uint32_t tg3_errors_count(const tg3_error_stack *es) { return es ? es->count : 0; } +TINYGLTF3_API const tg3_error_entry *tg3_errors_get(const tg3_error_stack *es, uint32_t index) { + if (!es || index >= es->count) return NULL; + return &es->entries[index]; +} +TINYGLTF3_API void tg3_error_stack_init(tg3_error_stack *es) { if (es) TINYGLTF3_MEMSET(es, 0, sizeof(*es)); } +TINYGLTF3_API void tg3_error_stack_free(tg3_error_stack *es) { + if (!es) return; + TINYGLTF3_FREE(es->entries); + TINYGLTF3_MEMSET(es, 0, sizeof(*es)); +} + +TINYGLTF3_API void tg3_parse_options_init(tg3_parse_options *options) { + if (!options) return; + TINYGLTF3_MEMSET(options, 0, sizeof(*options)); + options->required_sections = TG3_REQUIRE_VERSION; + options->strictness = TG3_PERMISSIVE; + options->memory.memory_budget = TINYGLTF3_MAX_MEMORY_BYTES; + options->memory.arena_block_size = TG3__ARENA_DEFAULT_BLOCK_SIZE; + options->max_external_file_size = 0; + options->validate_indices = 1; +} + +TINYGLTF3_API void tg3_write_options_init(tg3_write_options *options) { + if (!options) return; + TINYGLTF3_MEMSET(options, 0, sizeof(*options)); + options->pretty_print = 1; + options->memory.memory_budget = TINYGLTF3_MAX_MEMORY_BYTES; + options->memory.arena_block_size = TG3__ARENA_DEFAULT_BLOCK_SIZE; +} + +TINYGLTF3_API int32_t tg3_component_size(int32_t component_type) { + switch (component_type) { + case TG3_COMPONENT_TYPE_BYTE: + case TG3_COMPONENT_TYPE_UNSIGNED_BYTE: return 1; + case TG3_COMPONENT_TYPE_SHORT: + case TG3_COMPONENT_TYPE_UNSIGNED_SHORT: return 2; + case TG3_COMPONENT_TYPE_INT: + case TG3_COMPONENT_TYPE_UNSIGNED_INT: + case TG3_COMPONENT_TYPE_FLOAT: return 4; + case TG3_COMPONENT_TYPE_DOUBLE: return 8; + default: return -1; + } +} + +TINYGLTF3_API int32_t tg3_num_components(int32_t type) { + switch (type) { + case TG3_TYPE_SCALAR: return 1; + case TG3_TYPE_VEC2: return 2; + case TG3_TYPE_VEC3: return 3; + case TG3_TYPE_VEC4: return 4; + case TG3_TYPE_MAT2: return 4; + case TG3_TYPE_MAT3: return 9; + case TG3_TYPE_MAT4: return 16; + default: return -1; + } +} + +TINYGLTF3_API int32_t tg3_accessor_byte_stride(const tg3_accessor *accessor, const tg3_buffer_view *bv) { + int32_t comp; + int32_t num; + if (bv && bv->byte_stride > 0) return (int32_t)bv->byte_stride; + comp = tg3_component_size(accessor->component_type); + num = tg3_num_components(accessor->type); + if (comp < 0 || num < 0) return -1; + return comp * num; +} + +TINYGLTF3_API int32_t tg3_str_equals(tg3_str a, tg3_str b) { + if (a.len != b.len) return 0; + if (a.len == 0) return 1; + return TINYGLTF3_MEMCMP(a.data, b.data, a.len) == 0 ? 1 : 0; +} + +TINYGLTF3_API int32_t tg3_str_equals_cstr(tg3_str a, const char *b) { + uint32_t blen; + if (!b) return a.len == 0 ? 1 : 0; + blen = (uint32_t)TINYGLTF3_STRLEN(b); + if (a.len != blen) return 0; + if (a.len == 0) return 1; + return TINYGLTF3_MEMCMP(a.data, b, a.len) == 0 ? 1 : 0; +} + +static int tg3__b64_decode_char(unsigned char c) { + if (c >= 'A' && c <= 'Z') return c - 'A'; + if (c >= 'a' && c <= 'z') return c - 'a' + 26; + if (c >= '0' && c <= '9') return c - '0' + 52; + if (c == '+') return 62; + if (c == '/') return 63; + return -1; +} + +static uint8_t *tg3__b64_decode(const char *input, size_t input_len, size_t *out_len, tg3_arena *arena) { + uint8_t *out; + size_t decoded_len; + size_t i; + size_t j = 0; + uint32_t accum = 0; + int bits = 0; + if (input_len == 0) { + *out_len = 0; + return NULL; + } + while (input_len > 0 && input[input_len - 1] == '=') --input_len; + decoded_len = (input_len * 3u) / 4u; + out = (uint8_t *)tg3__arena_alloc(arena, decoded_len + 1u); + if (!out) { + *out_len = 0; + return NULL; + } + for (i = 0; i < input_len; ++i) { + int val = tg3__b64_decode_char((unsigned char)input[i]); + if (val < 0) continue; + accum = (accum << 6) | (uint32_t)val; + bits += 6; + if (bits >= 8) { + bits -= 8; + out[j++] = (uint8_t)((accum >> bits) & 0xFFu); + } + } + *out_len = j; + return out; +} + +TINYGLTF3_API int32_t tg3_is_data_uri(const char *uri, uint32_t len) { + return (uri && len >= 5u && TINYGLTF3_MEMCMP(uri, "data:", 5) == 0) ? 1 : 0; +} + +typedef struct tg3__data_uri_result { + const char *data_start; + size_t data_len; + char mime_type[64]; +} tg3__data_uri_result; + +static int tg3__parse_data_uri(const char *uri, uint32_t uri_len, tg3__data_uri_result *result) { + const char *p; + const char *end; + const char *semi; + size_t mime_len; + if (!uri || uri_len < 5u || TINYGLTF3_MEMCMP(uri, "data:", 5) != 0) return 0; + p = uri + 5; + end = uri + uri_len; + semi = p; + while (semi < end && *semi != ';') ++semi; + if (semi >= end) return 0; + mime_len = (size_t)(semi - p); + if (mime_len >= sizeof(result->mime_type)) mime_len = sizeof(result->mime_type) - 1u; + TINYGLTF3_MEMCPY(result->mime_type, p, mime_len); + result->mime_type[mime_len] = '\0'; + p = semi + 1; + if ((size_t)(end - p) < 7u || TINYGLTF3_MEMCMP(p, "base64,", 7) != 0) return 0; + p += 7; + result->data_start = p; + result->data_len = (size_t)(end - p); + return 1; +} + +static uint8_t *tg3__decode_data_uri(tg3_arena *arena, const char *uri, uint32_t uri_len, + size_t *out_len, char *out_mime, size_t out_mime_cap) { + tg3__data_uri_result dr; + size_t mlen; + if (!tg3__parse_data_uri(uri, uri_len, &dr)) { + *out_len = 0; + return NULL; + } + if (out_mime && out_mime_cap > 0) { + mlen = TINYGLTF3_STRLEN(dr.mime_type); + if (mlen >= out_mime_cap) mlen = out_mime_cap - 1u; + TINYGLTF3_MEMCPY(out_mime, dr.mime_type, mlen); + out_mime[mlen] = '\0'; + } + return tg3__b64_decode(dr.data_start, dr.data_len, out_len, arena); +} + +#if defined(TINYGLTF3_ENABLE_FS) && !defined(TINYGLTF3_NO_STDLIB) +static int32_t tg3__fs_file_exists(const char *path, uint32_t path_len, void *ud) { + FILE *fp; + (void)path_len; (void)ud; + fp = fopen(path, "rb"); + if (!fp) return 0; + fclose(fp); + return 1; +} + +static int32_t tg3__fs_read_file(uint8_t **out_data, uint64_t *out_size, + const char *path, uint32_t path_len, void *ud) { + FILE *fp; + long size; + uint8_t *data; + size_t nread; + (void)path_len; (void)ud; + *out_data = NULL; + *out_size = 0; + fp = fopen(path, "rb"); + if (!fp) return 0; + if (fseek(fp, 0, SEEK_END) != 0) { fclose(fp); return 0; } + size = ftell(fp); + if (size < 0) { fclose(fp); return 0; } + if (fseek(fp, 0, SEEK_SET) != 0) { fclose(fp); return 0; } + data = (uint8_t *)TINYGLTF3_MALLOC((size_t)size); + if (!data) { fclose(fp); return 0; } + nread = fread(data, 1, (size_t)size, fp); + fclose(fp); + if (nread != (size_t)size) { TINYGLTF3_FREE(data); return 0; } + *out_data = data; + *out_size = (uint64_t)size; + return 1; +} + +static void tg3__fs_free_file(uint8_t *data, uint64_t size, void *ud) { + (void)size; (void)ud; TINYGLTF3_FREE(data); +} + +static int32_t tg3__fs_write_file(const char *path, uint32_t path_len, + const uint8_t *data, uint64_t size, void *ud) { + FILE *fp; + size_t nwritten; + (void)path_len; (void)ud; + fp = fopen(path, "wb"); + if (!fp) return 0; + nwritten = fwrite(data, 1, (size_t)size, fp); + fclose(fp); + return nwritten == (size_t)size ? 1 : 0; +} + +static void tg3__set_default_fs(tg3_fs_callbacks *fs) { + if (!fs->read_file) fs->read_file = tg3__fs_read_file; + if (!fs->free_file) fs->free_file = tg3__fs_free_file; + if (!fs->file_exists) fs->file_exists = tg3__fs_file_exists; + if (!fs->write_file) fs->write_file = tg3__fs_write_file; +} +#endif + +static void tg3__model_init(tg3_model *model) { + TINYGLTF3_MEMSET(model, 0, sizeof(*model)); + model->default_scene = -1; +} + +static int tg3__json_is_number(const tg3json_value *v) { + return v && (v->type == TG3JSON_INT || v->type == TG3JSON_REAL); +} + +static int tg3__json_number_to_int32(const tg3json_value *v, int32_t *out) { + double real; + int32_t converted; + if (!tg3__json_is_number(v) || !out) return 0; + if (v->type == TG3JSON_INT) { + if (v->u.integer < INT32_MIN || v->u.integer > INT32_MAX) return 0; + *out = (int32_t)v->u.integer; + return 1; + } + real = v->u.real; + if (!tg3__isfinite(real) || real < (double)INT32_MIN || real > (double)INT32_MAX) { + return 0; + } + converted = (int32_t)real; + if ((double)converted != real) return 0; + *out = converted; + return 1; +} + +static int tg3__json_number_to_uint64(const tg3json_value *v, uint64_t *out) { + double real; + uint64_t converted; + /* Doubles have a 53-bit mantissa, so 2^64 itself rounds up and would be UB + on cast to uint64_t. Cap at the largest representable value strictly + below 2^64 (== 2^64 - 2^11). */ + const double max_safe_uint64_real = 18446744073709547520.0; + if (!tg3__json_is_number(v) || !out) return 0; + if (v->type == TG3JSON_INT) { + if (v->u.integer < 0) return 0; + *out = (uint64_t)v->u.integer; + return 1; + } + real = v->u.real; + if (!tg3__isfinite(real) || real < 0.0 || real > max_safe_uint64_real) { + return 0; + } + converted = (uint64_t)real; + if ((double)converted != real) return 0; + *out = converted; + return 1; +} + +static double tg3__json_number_to_double(const tg3json_value *v) { + if (!v) return 0.0; + if (v->type == TG3JSON_INT) return (double)v->u.integer; + if (v->type == TG3JSON_REAL) return v->u.real; + return 0.0; +} + +static int tg3__json_is_object(const tg3json_value *v) { return v && v->type == TG3JSON_OBJECT; } +static int tg3__json_is_array(const tg3json_value *v) { return v && v->type == TG3JSON_ARRAY; } + +static int tg3__u64_add_overflow(uint64_t a, uint64_t b, uint64_t *out) { + if (a > UINT64_MAX - b) return 1; + *out = a + b; + return 0; +} + +static int tg3__u64_mul_overflow(uint64_t a, uint64_t b, uint64_t *out) { + if (a != 0 && b > UINT64_MAX / a) return 1; + *out = a * b; + return 0; +} + +static int tg3__u64_fits_size(uint64_t v) { +#if SIZE_MAX < UINT64_MAX + return v <= (uint64_t)SIZE_MAX; +#else + (void)v; + return 1; +#endif +} + +static int tg3__json_has(const tg3json_value *o, const char *key) { + return tg3json_object_get(o, key) ? 1 : 0; +} + +static const tg3json_value *tg3__json_get(const tg3json_value *o, const char *key) { + return tg3json_object_get(o, key); +} + +static int tg3__parse_string(tg3__parse_ctx *ctx, const tg3json_value *o, const char *key, + tg3_str *out, int required, const char *parent) { + const tg3json_value *it = tg3__json_get(o, key); + if (!it) { + if (required) { + tg3__error_pushf(ctx->errors, ctx->arena, TG3_SEVERITY_ERROR, TG3_ERR_JSON_MISSING_FIELD, + parent, "Missing required field '%s'", key); + return 0; + } + out->data = NULL; + out->len = 0; + return 1; + } + if (it->type != TG3JSON_STRING) { + tg3__error_pushf(ctx->errors, ctx->arena, TG3_SEVERITY_ERROR, TG3_ERR_JSON_TYPE_MISMATCH, + parent, "Field '%s' must be a string", key); + return 0; + } + *out = tg3__arena_str(ctx->arena, it->u.string.ptr, (uint32_t)it->u.string.len); + return out->data != NULL || it->u.string.len == 0; +} + +static int tg3__parse_int(tg3__parse_ctx *ctx, const tg3json_value *o, const char *key, + int32_t *out, int required, const char *parent) { + const tg3json_value *it = tg3__json_get(o, key); + if (!it) { + if (required) { + tg3__error_pushf(ctx->errors, ctx->arena, TG3_SEVERITY_ERROR, TG3_ERR_JSON_MISSING_FIELD, + parent, "Missing required field '%s'", key); + return 0; + } + return 1; + } + if (!tg3__json_is_number(it)) { + tg3__error_pushf(ctx->errors, ctx->arena, TG3_SEVERITY_ERROR, TG3_ERR_JSON_TYPE_MISMATCH, + parent, "Field '%s' must be a number", key); + return 0; + } + if (!tg3__json_number_to_int32(it, out)) { + tg3__error_pushf(ctx->errors, ctx->arena, TG3_SEVERITY_ERROR, TG3_ERR_JSON_TYPE_MISMATCH, + parent, "Field '%s' must be a finite int32-valued number", key); + return 0; + } + return 1; +} + +static int tg3__parse_uint64(tg3__parse_ctx *ctx, const tg3json_value *o, const char *key, + uint64_t *out, int required, const char *parent) { + const tg3json_value *it = tg3__json_get(o, key); + if (!it) { + if (required) { + tg3__error_pushf(ctx->errors, ctx->arena, TG3_SEVERITY_ERROR, TG3_ERR_JSON_MISSING_FIELD, + parent, "Missing required field '%s'", key); + return 0; + } + return 1; + } + if (!tg3__json_is_number(it)) { + tg3__error_pushf(ctx->errors, ctx->arena, TG3_SEVERITY_ERROR, TG3_ERR_JSON_TYPE_MISMATCH, + parent, "Field '%s' must be a number", key); + return 0; + } + if (!tg3__json_number_to_uint64(it, out)) { + tg3__error_pushf(ctx->errors, ctx->arena, TG3_SEVERITY_ERROR, TG3_ERR_JSON_TYPE_MISMATCH, + parent, "Field '%s' must be a finite uint64-valued number", key); + return 0; + } + return 1; +} + +static int tg3__parse_double(tg3__parse_ctx *ctx, const tg3json_value *o, const char *key, + double *out, int required, const char *parent) { + const tg3json_value *it = tg3__json_get(o, key); + if (!it) { + if (required) { + tg3__error_pushf(ctx->errors, ctx->arena, TG3_SEVERITY_ERROR, TG3_ERR_JSON_MISSING_FIELD, + parent, "Missing required field '%s'", key); + return 0; + } + return 1; + } + if (!tg3__json_is_number(it)) { + tg3__error_pushf(ctx->errors, ctx->arena, TG3_SEVERITY_ERROR, TG3_ERR_JSON_TYPE_MISMATCH, + parent, "Field '%s' must be a number", key); + return 0; + } + *out = tg3__json_number_to_double(it); + return 1; +} + +static int tg3__parse_bool(tg3__parse_ctx *ctx, const tg3json_value *o, const char *key, + int32_t *out, int required, const char *parent) { + const tg3json_value *it = tg3__json_get(o, key); + if (!it) { + if (required) { + tg3__error_pushf(ctx->errors, ctx->arena, TG3_SEVERITY_ERROR, TG3_ERR_JSON_MISSING_FIELD, + parent, "Missing required field '%s'", key); + return 0; + } + return 1; + } + if (it->type != TG3JSON_BOOL) { + tg3__error_pushf(ctx->errors, ctx->arena, TG3_SEVERITY_ERROR, TG3_ERR_JSON_TYPE_MISMATCH, + parent, "Field '%s' must be a boolean", key); + return 0; + } + *out = it->u.boolean ? 1 : 0; + return 1; +} + +static int tg3__parse_number_array(tg3__parse_ctx *ctx, const tg3json_value *o, const char *key, + const double **out, uint32_t *out_count, + int required, const char *parent) { + const tg3json_value *it = tg3__json_get(o, key); + size_t count; + size_t i; + double *arr; + if (!it) { + if (required) { + tg3__error_pushf(ctx->errors, ctx->arena, TG3_SEVERITY_ERROR, TG3_ERR_JSON_MISSING_FIELD, + parent, "Missing required field '%s'", key); + return 0; + } + *out = NULL; + *out_count = 0; + return 1; + } + if (!tg3__json_is_array(it)) { + tg3__error_pushf(ctx->errors, ctx->arena, TG3_SEVERITY_ERROR, TG3_ERR_JSON_TYPE_MISMATCH, + parent, "Field '%s' must be an array", key); + return 0; + } + count = tg3json_array_size(it); + if (count == 0) { + *out = NULL; + *out_count = 0; + return 1; + } + arr = (double *)tg3__arena_alloc(ctx->arena, count * sizeof(double)); + if (!arr) { + tg3__error_push(ctx->errors, TG3_SEVERITY_ERROR, TG3_ERR_OUT_OF_MEMORY, + "OOM allocating number array", parent, -1); + return 0; + } + for (i = 0; i < count; ++i) { + arr[i] = tg3__json_number_to_double(tg3json_array_get(it, i)); + } + *out = arr; + *out_count = (uint32_t)count; + return 1; +} + +static int tg3__parse_int_array(tg3__parse_ctx *ctx, const tg3json_value *o, const char *key, + const int32_t **out, uint32_t *out_count, + int required, const char *parent) { + const tg3json_value *it = tg3__json_get(o, key); + size_t count; + size_t i; + int32_t *arr; + if (!it) { + if (required) { + tg3__error_pushf(ctx->errors, ctx->arena, TG3_SEVERITY_ERROR, TG3_ERR_JSON_MISSING_FIELD, + parent, "Missing required field '%s'", key); + return 0; + } + *out = NULL; + *out_count = 0; + return 1; + } + if (!tg3__json_is_array(it)) { + tg3__error_pushf(ctx->errors, ctx->arena, TG3_SEVERITY_ERROR, TG3_ERR_JSON_TYPE_MISMATCH, + parent, "Field '%s' must be an array", key); + return 0; + } + count = tg3json_array_size(it); + if (count == 0) { + *out = NULL; + *out_count = 0; + return 1; + } + arr = (int32_t *)tg3__arena_alloc(ctx->arena, count * sizeof(int32_t)); + if (!arr) { + tg3__error_push(ctx->errors, TG3_SEVERITY_ERROR, TG3_ERR_OUT_OF_MEMORY, + "OOM allocating int array", parent, -1); + return 0; + } + for (i = 0; i < count; ++i) { + const tg3json_value *item = tg3json_array_get(it, i); + if (!item || !tg3__json_number_to_int32(item, &arr[i])) { + tg3__error_pushf(ctx->errors, ctx->arena, TG3_SEVERITY_ERROR, + TG3_ERR_JSON_TYPE_MISMATCH, parent, + "Field '%s' element %u must be a finite int32-valued number", + key, (unsigned)i); + return 0; + } + } + *out = arr; + *out_count = (uint32_t)count; + return 1; +} + +static void tg3__parse_number_to_fixed(const tg3json_value *o, const char *key, + double *out, uint32_t max_count) { + const tg3json_value *it = tg3__json_get(o, key); + size_t count; + size_t i; + if (!tg3__json_is_array(it)) return; + count = tg3json_array_size(it); + if (count > max_count) count = max_count; + for (i = 0; i < count; ++i) { + const tg3json_value *item = tg3json_array_get(it, i); + if (!item) continue; + out[i] = tg3__json_number_to_double(item); + } +} + +static int tg3__parse_string_array(tg3__parse_ctx *ctx, const tg3json_value *o, const char *key, + const tg3_str **out, uint32_t *out_count, + int required, const char *parent) { + const tg3json_value *it = tg3__json_get(o, key); + size_t count; + size_t i; + tg3_str *arr; + if (!it) { + if (required) { + tg3__error_pushf(ctx->errors, ctx->arena, TG3_SEVERITY_ERROR, TG3_ERR_JSON_MISSING_FIELD, + parent, "Missing required field '%s'", key); + return 0; + } + *out = NULL; + *out_count = 0; + return 1; + } + if (!tg3__json_is_array(it)) return 0; + count = tg3json_array_size(it); + if (count == 0) { + *out = NULL; + *out_count = 0; + return 1; + } + arr = (tg3_str *)tg3__arena_alloc(ctx->arena, count * sizeof(tg3_str)); + if (!arr) return 0; + for (i = 0; i < count; ++i) { + const tg3json_value *item = tg3json_array_get(it, i); + if (!item || item->type != TG3JSON_STRING) { + arr[i].data = NULL; + arr[i].len = 0; + continue; + } + arr[i] = tg3__arena_str(ctx->arena, item->u.string.ptr, (uint32_t)item->u.string.len); + } + *out = arr; + *out_count = (uint32_t)count; + return 1; +} + +static tg3_value tg3__json_to_value(tg3__parse_ctx *ctx, const tg3json_value *j) { + tg3_value v; + size_t i; + TINYGLTF3_MEMSET(&v, 0, sizeof(v)); + if (!j) return v; + switch (j->type) { + case TG3JSON_NULL: + v.type = TG3_VALUE_NULL; + break; + case TG3JSON_BOOL: + v.type = TG3_VALUE_BOOL; + v.bool_val = j->u.boolean ? 1 : 0; + break; + case TG3JSON_INT: + v.type = TG3_VALUE_INT; + v.int_val = j->u.integer; + break; + case TG3JSON_REAL: + v.type = TG3_VALUE_REAL; + v.real_val = j->u.real; + break; + case TG3JSON_STRING: + v.type = TG3_VALUE_STRING; + v.string_val = tg3__arena_str(ctx->arena, j->u.string.ptr, (uint32_t)j->u.string.len); + break; + case TG3JSON_ARRAY: + v.type = TG3_VALUE_ARRAY; + if (j->u.array.count > 0) { + tg3_value *arr = (tg3_value *)tg3__arena_alloc(ctx->arena, j->u.array.count * sizeof(tg3_value)); + if (arr) { + for (i = 0; i < j->u.array.count; ++i) arr[i] = tg3__json_to_value(ctx, &j->u.array.items[i]); + v.array_data = arr; + v.array_count = (uint32_t)j->u.array.count; + } + } + break; + case TG3JSON_OBJECT: + v.type = TG3_VALUE_OBJECT; + if (j->u.object.count > 0) { + tg3_kv_pair *pairs = (tg3_kv_pair *)tg3__arena_alloc(ctx->arena, j->u.object.count * sizeof(tg3_kv_pair)); + if (pairs) { + for (i = 0; i < j->u.object.count; ++i) { + pairs[i].key = tg3__arena_str(ctx->arena, j->u.object.items[i].key, + (uint32_t)j->u.object.items[i].key_len); + pairs[i].value = tg3__json_to_value(ctx, j->u.object.items[i].value); + } + v.object_data = pairs; + v.object_count = (uint32_t)j->u.object.count; + } + } + break; + } + return v; +} + +static void tg3__parse_extras_and_extensions(tg3__parse_ctx *ctx, const tg3json_value *o, + tg3_extras_ext *ee) { + const tg3json_value *extras_it; + const tg3json_value *ext_it; + TINYGLTF3_MEMSET(ee, 0, sizeof(*ee)); + extras_it = tg3__json_get(o, "extras"); + if (extras_it) { + if (!ctx->opts.skip_extras_values) { + tg3_value *ev = (tg3_value *)tg3__arena_alloc(ctx->arena, sizeof(tg3_value)); + if (ev) { + *ev = tg3__json_to_value(ctx, extras_it); + ee->extras = ev; + } + } + if (ctx->opts.store_original_json) { + size_t raw_len = 0; + char *raw = tg3json_stringify(extras_it, &raw_len); + if (raw) { + ee->extras_json = tg3__arena_str(ctx->arena, raw, (uint32_t)raw_len); + TINYGLTF3_FREE(raw); + } + } + } + ext_it = tg3__json_get(o, "extensions"); + if (tg3__json_is_object(ext_it)) { + size_t count = tg3json_object_size(ext_it); + size_t i; + if (count > 0) { + tg3_extension *exts = (tg3_extension *)tg3__arena_alloc(ctx->arena, count * sizeof(tg3_extension)); + if (exts) { + for (i = 0; i < count; ++i) { + const tg3json_object_entry *entry = tg3json_object_at(ext_it, i); + TINYGLTF3_MEMSET(&exts[i], 0, sizeof(exts[i])); + exts[i].name = tg3__arena_str(ctx->arena, entry->key, (uint32_t)entry->key_len); + if (!ctx->opts.skip_extras_values) { + exts[i].value = tg3__json_to_value(ctx, entry->value); + } else { + exts[i].value.type = TG3_VALUE_NULL; + } + } + ee->extensions = exts; + ee->extensions_count = (uint32_t)count; + } + } + if (ctx->opts.store_original_json) { + size_t raw_len = 0; + char *raw = tg3json_stringify(ext_it, &raw_len); + if (raw) { + ee->extensions_json = tg3__arena_str(ctx->arena, raw, (uint32_t)raw_len); + TINYGLTF3_FREE(raw); + } + } + } +} + +static void tg3__init_texture_info(tg3_texture_info *ti) { TINYGLTF3_MEMSET(ti, 0, sizeof(*ti)); ti->index = -1; } +static void tg3__init_normal_texture_info(tg3_normal_texture_info *ti) { TINYGLTF3_MEMSET(ti, 0, sizeof(*ti)); ti->index = -1; ti->scale = 1.0; } +static void tg3__init_occlusion_texture_info(tg3_occlusion_texture_info *ti) { TINYGLTF3_MEMSET(ti, 0, sizeof(*ti)); ti->index = -1; ti->strength = 1.0; } +static void tg3__init_pbr(tg3_pbr_metallic_roughness *pbr) { + TINYGLTF3_MEMSET(pbr, 0, sizeof(*pbr)); + pbr->base_color_factor[0] = 1.0; pbr->base_color_factor[1] = 1.0; + pbr->base_color_factor[2] = 1.0; pbr->base_color_factor[3] = 1.0; + pbr->metallic_factor = 1.0; pbr->roughness_factor = 1.0; + tg3__init_texture_info(&pbr->base_color_texture); + tg3__init_texture_info(&pbr->metallic_roughness_texture); +} +static void tg3__init_node(tg3_node *n) { + TINYGLTF3_MEMSET(n, 0, sizeof(*n)); + n->camera = -1; n->skin = -1; n->mesh = -1; n->light = -1; n->emitter = -1; + n->rotation[3] = 1.0; n->scale[0] = 1.0; n->scale[1] = 1.0; n->scale[2] = 1.0; + n->matrix[0] = 1.0; n->matrix[5] = 1.0; n->matrix[10] = 1.0; n->matrix[15] = 1.0; +} + +static int tg3__parse_asset(tg3__parse_ctx *ctx, const tg3json_value *o, tg3_asset *asset) { + TINYGLTF3_MEMSET(asset, 0, sizeof(*asset)); + tg3__parse_string(ctx, o, "version", &asset->version, 0, "/asset"); + tg3__parse_string(ctx, o, "generator", &asset->generator, 0, "/asset"); + tg3__parse_string(ctx, o, "minVersion", &asset->min_version, 0, "/asset"); + tg3__parse_string(ctx, o, "copyright", &asset->copyright, 0, "/asset"); + tg3__parse_extras_and_extensions(ctx, o, &asset->ext); + return 1; +} + +static int tg3__parse_texture_info(tg3__parse_ctx *ctx, const tg3json_value *o, + const char *key, tg3_texture_info *ti) { + const tg3json_value *it = tg3__json_get(o, key); + tg3__init_texture_info(ti); + if (!it) return 1; + if (!tg3__json_is_object(it)) return 0; + tg3__parse_int(ctx, it, "index", &ti->index, 0, key); + tg3__parse_int(ctx, it, "texCoord", &ti->tex_coord, 0, key); + tg3__parse_extras_and_extensions(ctx, it, &ti->ext); + return 1; +} + +static int tg3__parse_normal_texture_info(tg3__parse_ctx *ctx, const tg3json_value *o, + const char *key, tg3_normal_texture_info *ti) { + const tg3json_value *it = tg3__json_get(o, key); + tg3__init_normal_texture_info(ti); + if (!it) return 1; + if (!tg3__json_is_object(it)) return 0; + tg3__parse_int(ctx, it, "index", &ti->index, 0, key); + tg3__parse_int(ctx, it, "texCoord", &ti->tex_coord, 0, key); + tg3__parse_double(ctx, it, "scale", &ti->scale, 0, key); + tg3__parse_extras_and_extensions(ctx, it, &ti->ext); + return 1; +} + +static int tg3__parse_occlusion_texture_info(tg3__parse_ctx *ctx, const tg3json_value *o, + const char *key, tg3_occlusion_texture_info *ti) { + const tg3json_value *it = tg3__json_get(o, key); + tg3__init_occlusion_texture_info(ti); + if (!it) return 1; + if (!tg3__json_is_object(it)) return 0; + tg3__parse_int(ctx, it, "index", &ti->index, 0, key); + tg3__parse_int(ctx, it, "texCoord", &ti->tex_coord, 0, key); + tg3__parse_double(ctx, it, "strength", &ti->strength, 0, key); + tg3__parse_extras_and_extensions(ctx, it, &ti->ext); + return 1; +} + +static int tg3__accessor_type_from_string(const char *s, size_t len) { + if (len == 6 && TINYGLTF3_MEMCMP(s, "SCALAR", 6) == 0) return TG3_TYPE_SCALAR; + if (len == 4 && TINYGLTF3_MEMCMP(s, "VEC2", 4) == 0) return TG3_TYPE_VEC2; + if (len == 4 && TINYGLTF3_MEMCMP(s, "VEC3", 4) == 0) return TG3_TYPE_VEC3; + if (len == 4 && TINYGLTF3_MEMCMP(s, "VEC4", 4) == 0) return TG3_TYPE_VEC4; + if (len == 4 && TINYGLTF3_MEMCMP(s, "MAT2", 4) == 0) return TG3_TYPE_MAT2; + if (len == 4 && TINYGLTF3_MEMCMP(s, "MAT3", 4) == 0) return TG3_TYPE_MAT3; + if (len == 4 && TINYGLTF3_MEMCMP(s, "MAT4", 4) == 0) return TG3_TYPE_MAT4; + return -1; +} + +static int tg3__parse_accessor_sparse(tg3__parse_ctx *ctx, const tg3json_value *o, + tg3_accessor_sparse *sparse) { + const tg3json_value *it = tg3__json_get(o, "sparse"); + TINYGLTF3_MEMSET(sparse, 0, sizeof(*sparse)); + sparse->indices.buffer_view = -1; + sparse->values.buffer_view = -1; + if (!it) return 1; + if (!tg3__json_is_object(it)) return 0; + sparse->is_sparse = 1; + tg3__parse_int(ctx, it, "count", &sparse->count, 1, "/sparse"); + { + const tg3json_value *idx_it = tg3__json_get(it, "indices"); + if (tg3__json_is_object(idx_it)) { + uint64_t bo = 0; + tg3__parse_int(ctx, idx_it, "bufferView", &sparse->indices.buffer_view, 1, "/sparse/indices"); + tg3__parse_int(ctx, idx_it, "componentType", &sparse->indices.component_type, 1, "/sparse/indices"); + tg3__parse_uint64(ctx, idx_it, "byteOffset", &bo, 0, "/sparse/indices"); + sparse->indices.byte_offset = bo; + tg3__parse_extras_and_extensions(ctx, idx_it, &sparse->indices.ext); + } + } + { + const tg3json_value *val_it = tg3__json_get(it, "values"); + if (tg3__json_is_object(val_it)) { + uint64_t bo = 0; + tg3__parse_int(ctx, val_it, "bufferView", &sparse->values.buffer_view, 1, "/sparse/values"); + tg3__parse_uint64(ctx, val_it, "byteOffset", &bo, 0, "/sparse/values"); + sparse->values.byte_offset = bo; + tg3__parse_extras_and_extensions(ctx, val_it, &sparse->values.ext); + } + } + tg3__parse_extras_and_extensions(ctx, it, &sparse->ext); + return 1; +} + +static int tg3__parse_accessor(tg3__parse_ctx *ctx, const tg3json_value *o, tg3_accessor *acc) { + tg3_str type_str; + uint64_t bo = 0; + uint64_t cnt = 0; + TINYGLTF3_MEMSET(acc, 0, sizeof(*acc)); + acc->buffer_view = -1; + acc->component_type = -1; + acc->type = -1; + tg3__parse_string(ctx, o, "name", &acc->name, 0, "/accessor"); + tg3__parse_int(ctx, o, "bufferView", &acc->buffer_view, 0, "/accessor"); + tg3__parse_uint64(ctx, o, "byteOffset", &bo, 0, "/accessor"); + acc->byte_offset = bo; + tg3__parse_bool(ctx, o, "normalized", &acc->normalized, 0, "/accessor"); + tg3__parse_int(ctx, o, "componentType", &acc->component_type, 1, "/accessor"); + tg3__parse_uint64(ctx, o, "count", &cnt, 1, "/accessor"); + acc->count = cnt; + type_str.data = NULL; type_str.len = 0; + tg3__parse_string(ctx, o, "type", &type_str, 1, "/accessor"); + if (type_str.data) acc->type = tg3__accessor_type_from_string(type_str.data, type_str.len); + tg3__parse_number_array(ctx, o, "min", &acc->min_values, &acc->min_values_count, 0, "/accessor"); + tg3__parse_number_array(ctx, o, "max", &acc->max_values, &acc->max_values_count, 0, "/accessor"); + tg3__parse_accessor_sparse(ctx, o, &acc->sparse); + tg3__parse_extras_and_extensions(ctx, o, &acc->ext); + return 1; +} + +/* Reject URIs that could escape base_dir or smuggle a different path through + * path-resolution layers. Returns 1 if the URI is safe to concatenate with + * base_dir, 0 if it must be rejected. */ +static int tg3__uri_is_safe(const char *uri, uint32_t uri_len) { + uint32_t i; + if (!uri || uri_len == 0) return 0; + /* No NUL bytes — fopen would truncate; protects against smuggling. */ + if (TINYGLTF3_MEMCHR(uri, '\0', uri_len) != NULL) return 0; + /* Reject absolute paths (POSIX and Windows). */ + if (uri[0] == '/' || uri[0] == '\\') return 0; + /* Reject Windows drive prefixes like "C:". */ + if (uri_len >= 2 && uri[1] == ':' && + ((uri[0] >= 'A' && uri[0] <= 'Z') || (uri[0] >= 'a' && uri[0] <= 'z'))) { + return 0; + } + /* Reject any ".." segment, separator-aware on both / and \. */ + for (i = 0; i + 1 < uri_len; ++i) { + if (uri[i] == '.' && uri[i + 1] == '.') { + int at_start = (i == 0) || uri[i - 1] == '/' || uri[i - 1] == '\\'; + int at_end = (i + 2 == uri_len) || uri[i + 2] == '/' || uri[i + 2] == '\\'; + if (at_start && at_end) return 0; + } + } + return 1; +} + +static int tg3__load_external_file(tg3__parse_ctx *ctx, uint8_t **out_data, uint64_t *out_size, + const char *uri, uint32_t uri_len) { + char path_buf[4096]; + uint32_t path_len = 0; + int32_t ok; + if (!ctx->opts.fs.read_file) { + tg3__error_push(ctx->errors, TG3_SEVERITY_ERROR, TG3_ERR_FS_NOT_AVAILABLE, + "No filesystem callbacks available", NULL, -1); + return 0; + } + if (!tg3__uri_is_safe(uri, uri_len)) { + tg3__error_push(ctx->errors, TG3_SEVERITY_ERROR, TG3_ERR_INVALID_VALUE, + "External URI rejected (absolute path, '..' segment, or NUL byte)", + NULL, -1); + return 0; + } + /* Saturating bounds check: path_buf is fixed-size; subtract instead of add + * so 32-bit size_t cannot wrap. */ + if (uri_len >= sizeof(path_buf)) return 0; + if (ctx->base_dir_len > 0) { + if (ctx->base_dir_len >= sizeof(path_buf) - uri_len - 1u) return 0; + TINYGLTF3_MEMCPY(path_buf, ctx->base_dir, ctx->base_dir_len); + path_len = ctx->base_dir_len; + if (path_len > 0 && path_buf[path_len - 1u] != '/' && path_buf[path_len - 1u] != '\\') { + path_buf[path_len++] = '/'; + } + } + if (path_len + uri_len >= sizeof(path_buf)) return 0; + TINYGLTF3_MEMCPY(path_buf + path_len, uri, uri_len); + path_len += uri_len; + path_buf[path_len] = '\0'; + ok = ctx->opts.fs.read_file(out_data, out_size, path_buf, path_len, ctx->opts.fs.user_data); + if (!ok) { + tg3__error_pushf(ctx->errors, ctx->arena, TG3_SEVERITY_ERROR, TG3_ERR_FILE_READ, + NULL, "Failed to read file: %s", path_buf); + return 0; + } + if (ctx->opts.max_external_file_size > 0 && + *out_size > ctx->opts.max_external_file_size) { + if (ctx->opts.fs.free_file) { + ctx->opts.fs.free_file(*out_data, *out_size, ctx->opts.fs.user_data); + } + tg3__error_pushf(ctx->errors, ctx->arena, TG3_SEVERITY_ERROR, + TG3_ERR_FILE_TOO_LARGE, NULL, + "External file %s exceeds max_external_file_size (%llu > %llu)", + path_buf, (unsigned long long)*out_size, + (unsigned long long)ctx->opts.max_external_file_size); + *out_data = NULL; + *out_size = 0; + return 0; + } + return 1; +} + +static int tg3__parse_buffer(tg3__parse_ctx *ctx, const tg3json_value *o, + tg3_buffer *buf, int32_t buf_idx) { + uint64_t byte_length = 0; + TINYGLTF3_MEMSET(buf, 0, sizeof(*buf)); + tg3__parse_string(ctx, o, "name", &buf->name, 0, "/buffer"); + tg3__parse_string(ctx, o, "uri", &buf->uri, 0, "/buffer"); + tg3__parse_uint64(ctx, o, "byteLength", &byte_length, 1, "/buffer"); + buf->byte_length = byte_length; + if (ctx->is_binary && buf_idx == 0 && buf->uri.len == 0) { + uint8_t *data; + if (!ctx->bin_data || ctx->bin_size < byte_length) { + tg3__error_push(ctx->errors, TG3_SEVERITY_ERROR, TG3_ERR_BUFFER_SIZE_MISMATCH, + "GLB BIN chunk missing or smaller than buffer.byteLength", NULL, -1); + return 0; + } + if (ctx->opts.borrow_input_buffers) { + buf->data.data = ctx->bin_data; + buf->data.count = byte_length; + tg3__parse_extras_and_extensions(ctx, o, &buf->ext); + return 1; + } + if (!tg3__u64_fits_size(byte_length)) { + tg3__error_push(ctx->errors, TG3_SEVERITY_ERROR, TG3_ERR_OUT_OF_MEMORY, + "buffer.byteLength exceeds addressable size", NULL, -1); + return 0; + } + data = (uint8_t *)tg3__arena_alloc(ctx->arena, (size_t)byte_length); + if (!data && byte_length > 0) { + tg3__error_push(ctx->errors, TG3_SEVERITY_ERROR, TG3_ERR_OUT_OF_MEMORY, + "OOM for buffer data", NULL, -1); + return 0; + } + if (byte_length > 0) TINYGLTF3_MEMCPY(data, ctx->bin_data, (size_t)byte_length); + buf->data.data = data; + buf->data.count = byte_length; + } else if (buf->uri.len > 0) { + if (tg3_is_data_uri(buf->uri.data, buf->uri.len)) { + size_t decoded_len = 0; + char mime[64]; + uint8_t *decoded; + TINYGLTF3_MEMSET(mime, 0, sizeof(mime)); + decoded = tg3__decode_data_uri(ctx->arena, buf->uri.data, buf->uri.len, &decoded_len, mime, sizeof(mime)); + if (!decoded && byte_length > 0) { + tg3__error_push(ctx->errors, TG3_SEVERITY_ERROR, TG3_ERR_DATA_URI_DECODE, + "Failed to decode buffer data URI", NULL, -1); + return 0; + } + buf->data.data = decoded; + buf->data.count = decoded_len; + } else { + uint8_t *file_data = NULL; + uint64_t file_size = 0; + if (tg3__load_external_file(ctx, &file_data, &file_size, buf->uri.data, buf->uri.len)) { + uint8_t *data = NULL; + if (!tg3__u64_fits_size(file_size)) { + tg3__error_push(ctx->errors, TG3_SEVERITY_ERROR, TG3_ERR_OUT_OF_MEMORY, + "external buffer exceeds addressable size", NULL, -1); + if (ctx->opts.fs.free_file) ctx->opts.fs.free_file(file_data, file_size, ctx->opts.fs.user_data); + tg3__parse_extras_and_extensions(ctx, o, &buf->ext); + return 0; + } + data = (uint8_t *)tg3__arena_alloc(ctx->arena, (size_t)file_size); + if (data) { + TINYGLTF3_MEMCPY(data, file_data, (size_t)file_size); + buf->data.data = data; + buf->data.count = file_size; + } else if (file_size > 0) { + tg3__error_push(ctx->errors, TG3_SEVERITY_ERROR, TG3_ERR_OUT_OF_MEMORY, + "OOM for external buffer data", NULL, -1); + } + if (ctx->opts.fs.free_file) ctx->opts.fs.free_file(file_data, file_size, ctx->opts.fs.user_data); + } + } + } + tg3__parse_extras_and_extensions(ctx, o, &buf->ext); + return 1; +} + +static int tg3__parse_buffer_view(tg3__parse_ctx *ctx, const tg3json_value *o, tg3_buffer_view *bv) { + uint64_t val = 0; + int32_t stride = 0; + TINYGLTF3_MEMSET(bv, 0, sizeof(*bv)); + bv->buffer = -1; + tg3__parse_string(ctx, o, "name", &bv->name, 0, "/bufferView"); + tg3__parse_int(ctx, o, "buffer", &bv->buffer, 1, "/bufferView"); + tg3__parse_uint64(ctx, o, "byteOffset", &val, 0, "/bufferView"); + bv->byte_offset = val; + val = 0; + tg3__parse_uint64(ctx, o, "byteLength", &val, 1, "/bufferView"); + bv->byte_length = val; + tg3__parse_int(ctx, o, "byteStride", &stride, 0, "/bufferView"); + /* glTF spec: byteStride is 0 (tightly packed) or in [4, 252]. Reject + * negatives so the (uint32_t) cast cannot wrap to 2^32-1 and propagate + * into downstream size math; reject 1..3 so consumers that pre-allocate + * `count * stride` cannot underallocate against a spec-non-conforming + * stride. */ + if (stride != 0 && (stride < 4 || stride > 252)) { + tg3__error_pushf(ctx->errors, ctx->arena, TG3_SEVERITY_ERROR, + TG3_ERR_INVALID_VALUE, "/bufferView", + "byteStride %d must be 0 or in [4, 252]", stride); + return 0; + } + bv->byte_stride = (uint32_t)stride; + tg3__parse_int(ctx, o, "target", &bv->target, 0, "/bufferView"); + tg3__parse_extras_and_extensions(ctx, o, &bv->ext); + return 1; +} + +static int tg3__parse_image(tg3__parse_ctx *ctx, const tg3json_value *o, tg3_image *img, int32_t img_idx) { + (void)img_idx; + TINYGLTF3_MEMSET(img, 0, sizeof(*img)); + img->width = -1; img->height = -1; img->component = -1; img->bits = -1; img->pixel_type = -1; img->buffer_view = -1; + tg3__parse_string(ctx, o, "name", &img->name, 0, "/image"); + tg3__parse_string(ctx, o, "uri", &img->uri, 0, "/image"); + tg3__parse_string(ctx, o, "mimeType", &img->mime_type, 0, "/image"); + tg3__parse_int(ctx, o, "bufferView", &img->buffer_view, 0, "/image"); + if (ctx->opts.images_as_is) img->as_is = 1; + tg3__parse_extras_and_extensions(ctx, o, &img->ext); + return 1; +} + +static int tg3__parse_sampler(tg3__parse_ctx *ctx, const tg3json_value *o, tg3_sampler *samp) { + TINYGLTF3_MEMSET(samp, 0, sizeof(*samp)); + samp->min_filter = -1; samp->mag_filter = -1; + samp->wrap_s = TG3_TEXTURE_WRAP_REPEAT; samp->wrap_t = TG3_TEXTURE_WRAP_REPEAT; + tg3__parse_string(ctx, o, "name", &samp->name, 0, "/sampler"); + tg3__parse_int(ctx, o, "minFilter", &samp->min_filter, 0, "/sampler"); + tg3__parse_int(ctx, o, "magFilter", &samp->mag_filter, 0, "/sampler"); + tg3__parse_int(ctx, o, "wrapS", &samp->wrap_s, 0, "/sampler"); + tg3__parse_int(ctx, o, "wrapT", &samp->wrap_t, 0, "/sampler"); + tg3__parse_extras_and_extensions(ctx, o, &samp->ext); + return 1; +} + +static int tg3__parse_texture(tg3__parse_ctx *ctx, const tg3json_value *o, tg3_texture *tex) { + TINYGLTF3_MEMSET(tex, 0, sizeof(*tex)); + tex->sampler = -1; tex->source = -1; + tg3__parse_string(ctx, o, "name", &tex->name, 0, "/texture"); + tg3__parse_int(ctx, o, "sampler", &tex->sampler, 0, "/texture"); + tg3__parse_int(ctx, o, "source", &tex->source, 0, "/texture"); + tg3__parse_extras_and_extensions(ctx, o, &tex->ext); + return 1; +} + +static int tg3__parse_material(tg3__parse_ctx *ctx, const tg3json_value *o, tg3_material *mat) { + const tg3json_value *pbr_it; + const tg3json_value *ext_it; + TINYGLTF3_MEMSET(mat, 0, sizeof(*mat)); + tg3__init_pbr(&mat->pbr_metallic_roughness); + tg3__init_normal_texture_info(&mat->normal_texture); + tg3__init_occlusion_texture_info(&mat->occlusion_texture); + tg3__init_texture_info(&mat->emissive_texture); + mat->alpha_cutoff = 0.5; + tg3__parse_string(ctx, o, "name", &mat->name, 0, "/material"); + tg3__parse_number_to_fixed(o, "emissiveFactor", mat->emissive_factor, 3); + { + tg3_str alpha_mode; + alpha_mode.data = NULL; alpha_mode.len = 0; + tg3__parse_string(ctx, o, "alphaMode", &alpha_mode, 0, "/material"); + mat->alpha_mode = alpha_mode.len > 0 ? alpha_mode : tg3__arena_str(ctx->arena, "OPAQUE", 6); + } + tg3__parse_double(ctx, o, "alphaCutoff", &mat->alpha_cutoff, 0, "/material"); + tg3__parse_bool(ctx, o, "doubleSided", &mat->double_sided, 0, "/material"); + pbr_it = tg3__json_get(o, "pbrMetallicRoughness"); + if (tg3__json_is_object(pbr_it)) { + tg3__parse_number_to_fixed(pbr_it, "baseColorFactor", mat->pbr_metallic_roughness.base_color_factor, 4); + tg3__parse_double(ctx, pbr_it, "metallicFactor", &mat->pbr_metallic_roughness.metallic_factor, 0, "/material/pbrMetallicRoughness"); + tg3__parse_double(ctx, pbr_it, "roughnessFactor", &mat->pbr_metallic_roughness.roughness_factor, 0, "/material/pbrMetallicRoughness"); + tg3__parse_texture_info(ctx, pbr_it, "baseColorTexture", &mat->pbr_metallic_roughness.base_color_texture); + tg3__parse_texture_info(ctx, pbr_it, "metallicRoughnessTexture", &mat->pbr_metallic_roughness.metallic_roughness_texture); + tg3__parse_extras_and_extensions(ctx, pbr_it, &mat->pbr_metallic_roughness.ext); + } + tg3__parse_normal_texture_info(ctx, o, "normalTexture", &mat->normal_texture); + tg3__parse_occlusion_texture_info(ctx, o, "occlusionTexture", &mat->occlusion_texture); + tg3__parse_texture_info(ctx, o, "emissiveTexture", &mat->emissive_texture); + ext_it = tg3__json_get(o, "extensions"); + if (tg3__json_is_object(ext_it)) { + const tg3json_value *lod_it = tg3json_object_get(ext_it, "MSFT_lod"); + if (tg3__json_is_object(lod_it)) { + tg3__parse_int_array(ctx, lod_it, "ids", &mat->lods, &mat->lods_count, 0, "/material/extensions/MSFT_lod"); + } + } + tg3__parse_extras_and_extensions(ctx, o, &mat->ext); + return 1; +} + +static int tg3__parse_primitive(tg3__parse_ctx *ctx, const tg3json_value *o, tg3_primitive *prim) { + const tg3json_value *attr_it; + const tg3json_value *targets_it; + TINYGLTF3_MEMSET(prim, 0, sizeof(*prim)); + prim->material = -1; prim->indices = -1; prim->mode = TG3_MODE_TRIANGLES; + tg3__parse_int(ctx, o, "material", &prim->material, 0, "/primitive"); + tg3__parse_int(ctx, o, "indices", &prim->indices, 0, "/primitive"); + tg3__parse_int(ctx, o, "mode", &prim->mode, 0, "/primitive"); + attr_it = tg3__json_get(o, "attributes"); + if (tg3__json_is_object(attr_it)) { + size_t count = tg3json_object_size(attr_it); + if (count > 0) { + size_t i; + tg3_str_int_pair *attrs = (tg3_str_int_pair *)tg3__arena_alloc(ctx->arena, count * sizeof(tg3_str_int_pair)); + if (attrs) { + for (i = 0; i < count; ++i) { + const tg3json_object_entry *entry = tg3json_object_at(attr_it, i); + attrs[i].key = tg3__arena_str(ctx->arena, entry->key, (uint32_t)entry->key_len); + if (!tg3__json_number_to_int32(entry->value, &attrs[i].value)) { + tg3__error_pushf(ctx->errors, ctx->arena, TG3_SEVERITY_ERROR, + TG3_ERR_JSON_TYPE_MISMATCH, "/primitive/attributes", + "Attribute '%s' must be a finite int32-valued number", + entry->key ? entry->key : ""); + attrs[i].value = 0; + } + } + prim->attributes = attrs; + prim->attributes_count = (uint32_t)count; + } + } + } + targets_it = tg3__json_get(o, "targets"); + if (tg3__json_is_array(targets_it)) { + size_t tcount = tg3json_array_size(targets_it); + if (tcount > 0) { + size_t ti; + const tg3_str_int_pair **target_arrays = (const tg3_str_int_pair **)tg3__arena_alloc(ctx->arena, tcount * sizeof(tg3_str_int_pair *)); + uint32_t *target_counts = (uint32_t *)tg3__arena_alloc(ctx->arena, tcount * sizeof(uint32_t)); + if (target_arrays && target_counts) { + for (ti = 0; ti < tcount; ++ti) { + const tg3json_value *target_obj = tg3json_array_get(targets_it, ti); + size_t acount; + size_t ai; + tg3_str_int_pair *tattrs; + if (!tg3__json_is_object(target_obj)) { + target_arrays[ti] = NULL; + target_counts[ti] = 0; + continue; + } + acount = tg3json_object_size(target_obj); + tattrs = (tg3_str_int_pair *)tg3__arena_alloc(ctx->arena, acount * sizeof(tg3_str_int_pair)); + if (tattrs) { + for (ai = 0; ai < acount; ++ai) { + const tg3json_object_entry *entry = tg3json_object_at(target_obj, ai); + tattrs[ai].key = tg3__arena_str(ctx->arena, entry->key, (uint32_t)entry->key_len); + if (!tg3__json_number_to_int32(entry->value, &tattrs[ai].value)) { + tg3__error_pushf(ctx->errors, ctx->arena, TG3_SEVERITY_ERROR, + TG3_ERR_JSON_TYPE_MISMATCH, "/primitive/targets", + "Target attribute '%s' must be a finite int32-valued number", + entry->key ? entry->key : ""); + tattrs[ai].value = 0; + } + } + } + target_arrays[ti] = tattrs; + /* On arena OOM tattrs may be NULL; keep count consistent so + * the index validator and downstream consumers don't deref. */ + target_counts[ti] = tattrs ? (uint32_t)acount : 0u; + } + prim->targets = target_arrays; + prim->target_attribute_counts = target_counts; + prim->targets_count = (uint32_t)tcount; + } + } + } + tg3__parse_extras_and_extensions(ctx, o, &prim->ext); + return 1; +} + +static int tg3__parse_mesh(tg3__parse_ctx *ctx, const tg3json_value *o, tg3_mesh *mesh) { + const tg3json_value *prim_it = tg3__json_get(o, "primitives"); + TINYGLTF3_MEMSET(mesh, 0, sizeof(*mesh)); + tg3__parse_string(ctx, o, "name", &mesh->name, 0, "/mesh"); + if (tg3__json_is_array(prim_it)) { + size_t count = tg3json_array_size(prim_it); + if (count > 0) { + size_t i; + tg3_primitive *prims = (tg3_primitive *)tg3__arena_alloc(ctx->arena, count * sizeof(tg3_primitive)); + if (prims) { + for (i = 0; i < count; ++i) tg3__parse_primitive(ctx, tg3json_array_get(prim_it, i), &prims[i]); + mesh->primitives = prims; + mesh->primitives_count = (uint32_t)count; + } + } + } + tg3__parse_number_array(ctx, o, "weights", &mesh->weights, &mesh->weights_count, 0, "/mesh"); + tg3__parse_extras_and_extensions(ctx, o, &mesh->ext); + return 1; +} + +static int tg3__parse_node(tg3__parse_ctx *ctx, const tg3json_value *o, tg3_node *node) { + const tg3json_value *ext_it; + tg3__init_node(node); + tg3__parse_string(ctx, o, "name", &node->name, 0, "/node"); + tg3__parse_int(ctx, o, "camera", &node->camera, 0, "/node"); + tg3__parse_int(ctx, o, "skin", &node->skin, 0, "/node"); + tg3__parse_int(ctx, o, "mesh", &node->mesh, 0, "/node"); + tg3__parse_int_array(ctx, o, "children", &node->children, &node->children_count, 0, "/node"); + if (tg3__json_has(o, "matrix")) { tg3__parse_number_to_fixed(o, "matrix", node->matrix, 16); node->has_matrix = 1; } + if (tg3__json_has(o, "translation")) tg3__parse_number_to_fixed(o, "translation", node->translation, 3); + if (tg3__json_has(o, "rotation")) tg3__parse_number_to_fixed(o, "rotation", node->rotation, 4); + if (tg3__json_has(o, "scale")) tg3__parse_number_to_fixed(o, "scale", node->scale, 3); + tg3__parse_number_array(ctx, o, "weights", &node->weights, &node->weights_count, 0, "/node"); + ext_it = tg3__json_get(o, "extensions"); + if (tg3__json_is_object(ext_it)) { + const tg3json_value *khr_lights = tg3json_object_get(ext_it, "KHR_lights_punctual"); + const tg3json_value *khr_audio = tg3json_object_get(ext_it, "KHR_audio"); + const tg3json_value *msft_lod = tg3json_object_get(ext_it, "MSFT_lod"); + if (tg3__json_is_object(khr_lights)) tg3__parse_int(ctx, khr_lights, "light", &node->light, 0, "/node/extensions/KHR_lights_punctual"); + if (tg3__json_is_object(khr_audio)) tg3__parse_int(ctx, khr_audio, "emitter", &node->emitter, 0, "/node/extensions/KHR_audio"); + if (tg3__json_is_object(msft_lod)) tg3__parse_int_array(ctx, msft_lod, "ids", &node->lods, &node->lods_count, 0, "/node/extensions/MSFT_lod"); + } + tg3__parse_extras_and_extensions(ctx, o, &node->ext); + return 1; +} + +static int tg3__parse_skin(tg3__parse_ctx *ctx, const tg3json_value *o, tg3_skin *skin) { + TINYGLTF3_MEMSET(skin, 0, sizeof(*skin)); + skin->inverse_bind_matrices = -1; skin->skeleton = -1; + tg3__parse_string(ctx, o, "name", &skin->name, 0, "/skin"); + tg3__parse_int(ctx, o, "inverseBindMatrices", &skin->inverse_bind_matrices, 0, "/skin"); + tg3__parse_int(ctx, o, "skeleton", &skin->skeleton, 0, "/skin"); + tg3__parse_int_array(ctx, o, "joints", &skin->joints, &skin->joints_count, 1, "/skin"); + tg3__parse_extras_and_extensions(ctx, o, &skin->ext); + return 1; +} + +static int tg3__parse_animation(tg3__parse_ctx *ctx, const tg3json_value *o, tg3_animation *anim) { + const tg3json_value *ch_it = tg3__json_get(o, "channels"); + const tg3json_value *samp_it = tg3__json_get(o, "samplers"); + TINYGLTF3_MEMSET(anim, 0, sizeof(*anim)); + tg3__parse_string(ctx, o, "name", &anim->name, 0, "/animation"); + if (tg3__json_is_array(ch_it)) { + size_t count = tg3json_array_size(ch_it); + if (count > 0) { + size_t i; + tg3_animation_channel *channels = (tg3_animation_channel *)tg3__arena_alloc(ctx->arena, count * sizeof(tg3_animation_channel)); + if (channels) { + for (i = 0; i < count; ++i) { + const tg3json_value *item = tg3json_array_get(ch_it, i); + const tg3json_value *tgt_it; + TINYGLTF3_MEMSET(&channels[i], 0, sizeof(channels[i])); + channels[i].sampler = -1; + channels[i].target.node = -1; + tg3__parse_int(ctx, item, "sampler", &channels[i].sampler, 1, "/animation/channel"); + tgt_it = tg3__json_get(item, "target"); + if (tg3__json_is_object(tgt_it)) { + tg3__parse_int(ctx, tgt_it, "node", &channels[i].target.node, 0, "/animation/channel/target"); + tg3__parse_string(ctx, tgt_it, "path", &channels[i].target.path, 1, "/animation/channel/target"); + tg3__parse_extras_and_extensions(ctx, tgt_it, &channels[i].target.ext); + } + tg3__parse_extras_and_extensions(ctx, item, &channels[i].ext); + } + anim->channels = channels; + anim->channels_count = (uint32_t)count; + } + } + } + if (tg3__json_is_array(samp_it)) { + size_t count = tg3json_array_size(samp_it); + if (count > 0) { + size_t i; + tg3_animation_sampler *samplers = (tg3_animation_sampler *)tg3__arena_alloc(ctx->arena, count * sizeof(tg3_animation_sampler)); + if (samplers) { + for (i = 0; i < count; ++i) { + const tg3json_value *item = tg3json_array_get(samp_it, i); + tg3_str interp; + TINYGLTF3_MEMSET(&samplers[i], 0, sizeof(samplers[i])); + samplers[i].input = -1; samplers[i].output = -1; + tg3__parse_int(ctx, item, "input", &samplers[i].input, 1, "/animation/sampler"); + tg3__parse_int(ctx, item, "output", &samplers[i].output, 1, "/animation/sampler"); + interp.data = NULL; interp.len = 0; + tg3__parse_string(ctx, item, "interpolation", &interp, 0, "/animation/sampler"); + samplers[i].interpolation = interp.len > 0 ? interp : tg3__arena_str(ctx->arena, "LINEAR", 6); + tg3__parse_extras_and_extensions(ctx, item, &samplers[i].ext); + } + anim->samplers = samplers; + anim->samplers_count = (uint32_t)count; + } + } + } + tg3__parse_extras_and_extensions(ctx, o, &anim->ext); + return 1; +} + +static int tg3__parse_camera(tg3__parse_ctx *ctx, const tg3json_value *o, tg3_camera *cam) { + const tg3json_value *it; + TINYGLTF3_MEMSET(cam, 0, sizeof(*cam)); + tg3__parse_string(ctx, o, "name", &cam->name, 0, "/camera"); + tg3__parse_string(ctx, o, "type", &cam->type, 1, "/camera"); + if (cam->type.data && tg3_str_equals_cstr(cam->type, "perspective")) { + it = tg3__json_get(o, "perspective"); + if (tg3__json_is_object(it)) { + tg3__parse_double(ctx, it, "aspectRatio", &cam->perspective.aspect_ratio, 0, "/camera/perspective"); + tg3__parse_double(ctx, it, "yfov", &cam->perspective.yfov, 1, "/camera/perspective"); + tg3__parse_double(ctx, it, "zfar", &cam->perspective.zfar, 0, "/camera/perspective"); + tg3__parse_double(ctx, it, "znear", &cam->perspective.znear, 1, "/camera/perspective"); + tg3__parse_extras_and_extensions(ctx, it, &cam->perspective.ext); + } + } else if (cam->type.data && tg3_str_equals_cstr(cam->type, "orthographic")) { + it = tg3__json_get(o, "orthographic"); + if (tg3__json_is_object(it)) { + tg3__parse_double(ctx, it, "xmag", &cam->orthographic.xmag, 1, "/camera/orthographic"); + tg3__parse_double(ctx, it, "ymag", &cam->orthographic.ymag, 1, "/camera/orthographic"); + tg3__parse_double(ctx, it, "zfar", &cam->orthographic.zfar, 1, "/camera/orthographic"); + tg3__parse_double(ctx, it, "znear", &cam->orthographic.znear, 1, "/camera/orthographic"); + tg3__parse_extras_and_extensions(ctx, it, &cam->orthographic.ext); + } + } + tg3__parse_extras_and_extensions(ctx, o, &cam->ext); + return 1; +} + +static int tg3__parse_scene(tg3__parse_ctx *ctx, const tg3json_value *o, tg3_scene *scene) { + const tg3json_value *ext_it; + TINYGLTF3_MEMSET(scene, 0, sizeof(*scene)); + tg3__parse_string(ctx, o, "name", &scene->name, 0, "/scene"); + tg3__parse_int_array(ctx, o, "nodes", &scene->nodes, &scene->nodes_count, 0, "/scene"); + ext_it = tg3__json_get(o, "extensions"); + if (tg3__json_is_object(ext_it)) { + const tg3json_value *audio_it = tg3json_object_get(ext_it, "KHR_audio"); + if (tg3__json_is_object(audio_it)) { + tg3__parse_int_array(ctx, audio_it, "emitters", &scene->audio_emitters, &scene->audio_emitters_count, 0, "/scene/extensions/KHR_audio"); + } + } + tg3__parse_extras_and_extensions(ctx, o, &scene->ext); + return 1; +} + +static int tg3__parse_light(tg3__parse_ctx *ctx, const tg3json_value *o, tg3_light *light) { + const tg3json_value *spot_it; + TINYGLTF3_MEMSET(light, 0, sizeof(*light)); + light->color[0] = 1.0; light->color[1] = 1.0; light->color[2] = 1.0; + light->intensity = 1.0; light->spot.outer_cone_angle = 0.7853981634; + tg3__parse_string(ctx, o, "name", &light->name, 0, "/light"); + tg3__parse_string(ctx, o, "type", &light->type, 1, "/light"); + tg3__parse_double(ctx, o, "intensity", &light->intensity, 0, "/light"); + tg3__parse_double(ctx, o, "range", &light->range, 0, "/light"); + tg3__parse_number_to_fixed(o, "color", light->color, 3); + spot_it = tg3__json_get(o, "spot"); + if (tg3__json_is_object(spot_it)) { + tg3__parse_double(ctx, spot_it, "innerConeAngle", &light->spot.inner_cone_angle, 0, "/light/spot"); + tg3__parse_double(ctx, spot_it, "outerConeAngle", &light->spot.outer_cone_angle, 0, "/light/spot"); + tg3__parse_extras_and_extensions(ctx, spot_it, &light->spot.ext); + } + tg3__parse_extras_and_extensions(ctx, o, &light->ext); + return 1; +} + +static int tg3__parse_audio_source(tg3__parse_ctx *ctx, const tg3json_value *o, tg3_audio_source *src) { + TINYGLTF3_MEMSET(src, 0, sizeof(*src)); + src->buffer_view = -1; + tg3__parse_string(ctx, o, "name", &src->name, 0, "/audioSource"); + tg3__parse_string(ctx, o, "uri", &src->uri, 0, "/audioSource"); + tg3__parse_int(ctx, o, "bufferView", &src->buffer_view, 0, "/audioSource"); + tg3__parse_string(ctx, o, "mimeType", &src->mime_type, 0, "/audioSource"); + tg3__parse_extras_and_extensions(ctx, o, &src->ext); + return 1; +} + +static int tg3__parse_audio_emitter(tg3__parse_ctx *ctx, const tg3json_value *o, tg3_audio_emitter *emitter) { + const tg3json_value *pos_it; + TINYGLTF3_MEMSET(emitter, 0, sizeof(*emitter)); + emitter->gain = 1.0; emitter->source = -1; + emitter->positional.cone_inner_angle = 6.283185307179586; + emitter->positional.cone_outer_angle = 6.283185307179586; + emitter->positional.max_distance = 100.0; emitter->positional.ref_distance = 1.0; emitter->positional.rolloff_factor = 1.0; + tg3__parse_string(ctx, o, "name", &emitter->name, 0, "/audioEmitter"); + tg3__parse_double(ctx, o, "gain", &emitter->gain, 0, "/audioEmitter"); + tg3__parse_bool(ctx, o, "loop", &emitter->loop, 0, "/audioEmitter"); + tg3__parse_bool(ctx, o, "playing", &emitter->playing, 0, "/audioEmitter"); + tg3__parse_string(ctx, o, "type", &emitter->type, 0, "/audioEmitter"); + tg3__parse_string(ctx, o, "distanceModel", &emitter->distance_model, 0, "/audioEmitter"); + tg3__parse_int(ctx, o, "source", &emitter->source, 0, "/audioEmitter"); + pos_it = tg3__json_get(o, "positional"); + if (tg3__json_is_object(pos_it)) { + tg3__parse_double(ctx, pos_it, "coneInnerAngle", &emitter->positional.cone_inner_angle, 0, "/positional"); + tg3__parse_double(ctx, pos_it, "coneOuterAngle", &emitter->positional.cone_outer_angle, 0, "/positional"); + tg3__parse_double(ctx, pos_it, "coneOuterGain", &emitter->positional.cone_outer_gain, 0, "/positional"); + tg3__parse_double(ctx, pos_it, "maxDistance", &emitter->positional.max_distance, 0, "/positional"); + tg3__parse_double(ctx, pos_it, "refDistance", &emitter->positional.ref_distance, 0, "/positional"); + tg3__parse_double(ctx, pos_it, "rolloffFactor", &emitter->positional.rolloff_factor, 0, "/positional"); + tg3__parse_extras_and_extensions(ctx, pos_it, &emitter->positional.ext); + } + tg3__parse_extras_and_extensions(ctx, o, &emitter->ext); + return 1; +} + +#define TG3__STREAM_CB(cb_name, model_arr, model_cnt) \ + do { \ + if ((ctx)->opts.stream && (ctx)->opts.stream->cb_name) { \ + uint32_t _si; \ + for (_si = 0; _si < (model_cnt); ++_si) { \ + tg3_stream_action _sa = (ctx)->opts.stream->cb_name(&(model_arr)[_si], (int32_t)_si, (ctx)->opts.stream->user_data); \ + if (_sa == TG3_STREAM_ABORT) return TG3_ERR_STREAM_ABORTED; \ + } \ + } \ + } while (0) + +#define TG3__PARSE_ARRAY_SIMPLE(ctx, json_doc, json_key, Type, model_field, count_field, parse_fn) \ + do { \ + const tg3json_value *_arr = tg3json_object_get((json_doc), (json_key)); \ + if (tg3__json_is_array(_arr)) { \ + size_t _count = tg3json_array_size(_arr); \ + if (_count > 0) { \ + size_t _i; \ + Type *_items = (Type *)tg3__arena_alloc((ctx)->arena, _count * sizeof(Type)); \ + if (_items) { \ + for (_i = 0; _i < _count; ++_i) { \ + const tg3json_value *_it = tg3json_array_get(_arr, _i); \ + if (!tg3__json_is_object(_it)) { \ + tg3__error_pushf((ctx)->errors, (ctx)->arena, TG3_SEVERITY_ERROR, TG3_ERR_JSON_TYPE_MISMATCH, (json_key), "Element %u must be an object", (unsigned)_i); \ + continue; \ + } \ + parse_fn((ctx), _it, &_items[_i]); \ + } \ + (model_field) = _items; \ + (count_field) = (uint32_t)_count; \ + } \ + } \ + } \ + } while (0) + +#define TG3__PARSE_ARRAY_IDX(ctx, json_doc, json_key, Type, model_field, count_field, parse_fn) \ + do { \ + const tg3json_value *_arr = tg3json_object_get((json_doc), (json_key)); \ + if (tg3__json_is_array(_arr)) { \ + size_t _count = tg3json_array_size(_arr); \ + if (_count > 0) { \ + size_t _i; \ + Type *_items = (Type *)tg3__arena_alloc((ctx)->arena, _count * sizeof(Type)); \ + if (_items) { \ + for (_i = 0; _i < _count; ++_i) { \ + const tg3json_value *_it = tg3json_array_get(_arr, _i); \ + if (!tg3__json_is_object(_it)) { \ + tg3__error_pushf((ctx)->errors, (ctx)->arena, TG3_SEVERITY_ERROR, TG3_ERR_JSON_TYPE_MISMATCH, (json_key), "Element %u must be an object", (unsigned)_i); \ + continue; \ + } \ + parse_fn((ctx), _it, &_items[_i], (int32_t)_i); \ + } \ + (model_field) = _items; \ + (count_field) = (uint32_t)_count; \ + } \ + } \ + } \ + } while (0) + +/* Post-parse index validation. Walks every int32_t index field populated from + * JSON and rejects out-of-range values so naive consumers cannot dereference + * attacker-controlled indices into model arrays. Caps reported errors so a + * pathological input does not flood the error stack. Returns 1 on success. */ +#define TG3__IDX_ERR_CAP 64 +static int tg3__validate_indices(tg3__parse_ctx *ctx, const tg3_model *m) { + uint32_t i, j; + int errs = 0; + /* Helper macros — push with format and bump error counter. Every call + * site passes at least one variadic arg, so plain __VA_ARGS__ (C11) is + * sufficient and avoids the GNU `, ##__VA_ARGS__` extension. */ + #define TG3__IDX_BAD(path_str, fmt, ...) do { \ + if (errs < TG3__IDX_ERR_CAP) { \ + tg3__error_pushf(ctx->errors, ctx->arena, TG3_SEVERITY_ERROR, \ + TG3_ERR_INVALID_INDEX, (path_str), fmt, __VA_ARGS__); \ + } \ + ++errs; \ + } while (0) + #define TG3__CHECK_REQ(idx, max, path_str, fmt, ...) do { \ + if ((idx) < 0 || (uint32_t)(idx) >= (max)) { \ + TG3__IDX_BAD(path_str, fmt, __VA_ARGS__); \ + } \ + } while (0) + #define TG3__CHECK_OPT(idx, max, path_str, fmt, ...) do { \ + if ((idx) != -1 && ((idx) < 0 || (uint32_t)(idx) >= (max))) { \ + TG3__IDX_BAD(path_str, fmt, __VA_ARGS__); \ + } \ + } while (0) + + if (m->default_scene != -1) { + TG3__CHECK_OPT(m->default_scene, m->scenes_count, "/scene", + "default scene %d out of range [0,%u)", + m->default_scene, m->scenes_count); + } + for (i = 0; i < m->buffer_views_count && errs < TG3__IDX_ERR_CAP; ++i) { + TG3__CHECK_REQ(m->buffer_views[i].buffer, m->buffers_count, + "/bufferViews", "bufferViews[%u].buffer %d out of range [0,%u)", + i, m->buffer_views[i].buffer, m->buffers_count); + } + for (i = 0; i < m->accessors_count && errs < TG3__IDX_ERR_CAP; ++i) { + const tg3_accessor *a = &m->accessors[i]; + TG3__CHECK_OPT(a->buffer_view, m->buffer_views_count, "/accessors", + "accessors[%u].bufferView %d out of range [0,%u)", + i, a->buffer_view, m->buffer_views_count); + if (a->sparse.is_sparse) { + TG3__CHECK_REQ(a->sparse.indices.buffer_view, m->buffer_views_count, + "/accessors", "accessors[%u].sparse.indices.bufferView %d out of range [0,%u)", + i, a->sparse.indices.buffer_view, m->buffer_views_count); + TG3__CHECK_REQ(a->sparse.values.buffer_view, m->buffer_views_count, + "/accessors", "accessors[%u].sparse.values.bufferView %d out of range [0,%u)", + i, a->sparse.values.buffer_view, m->buffer_views_count); + } + } + for (i = 0; i < m->meshes_count && errs < TG3__IDX_ERR_CAP; ++i) { + const tg3_mesh *me = &m->meshes[i]; + for (j = 0; j < me->primitives_count && errs < TG3__IDX_ERR_CAP; ++j) { + const tg3_primitive *p = &me->primitives[j]; + uint32_t ai; + TG3__CHECK_OPT(p->indices, m->accessors_count, "/meshes", + "meshes[%u].primitives[%u].indices %d out of range [0,%u)", + i, j, p->indices, m->accessors_count); + TG3__CHECK_OPT(p->material, m->materials_count, "/meshes", + "meshes[%u].primitives[%u].material %d out of range [0,%u)", + i, j, p->material, m->materials_count); + for (ai = 0; ai < p->attributes_count && errs < TG3__IDX_ERR_CAP; ++ai) { + TG3__CHECK_REQ(p->attributes[ai].value, m->accessors_count, "/meshes", + "meshes[%u].primitives[%u].attributes[%u] %d out of range [0,%u)", + i, j, ai, p->attributes[ai].value, m->accessors_count); + } + { + uint32_t ti; + for (ti = 0; ti < p->targets_count && errs < TG3__IDX_ERR_CAP; ++ti) { + uint32_t tk; + uint32_t tcount = p->target_attribute_counts ? p->target_attribute_counts[ti] : 0; + const tg3_str_int_pair *tarr = p->targets ? p->targets[ti] : NULL; + if (!tarr) continue; + for (tk = 0; tk < tcount && errs < TG3__IDX_ERR_CAP; ++tk) { + TG3__CHECK_REQ(tarr[tk].value, m->accessors_count, "/meshes", + "meshes[%u].primitives[%u].targets[%u][%u] %d out of range [0,%u)", + i, j, ti, tk, tarr[tk].value, m->accessors_count); + } + } + } + } + } + for (i = 0; i < m->nodes_count && errs < TG3__IDX_ERR_CAP; ++i) { + const tg3_node *n = &m->nodes[i]; + uint32_t k; + TG3__CHECK_OPT(n->mesh, m->meshes_count, "/nodes", "nodes[%u].mesh %d out of range [0,%u)", i, n->mesh, m->meshes_count); + TG3__CHECK_OPT(n->skin, m->skins_count, "/nodes", "nodes[%u].skin %d out of range [0,%u)", i, n->skin, m->skins_count); + TG3__CHECK_OPT(n->camera, m->cameras_count, "/nodes", "nodes[%u].camera %d out of range [0,%u)", i, n->camera, m->cameras_count); + TG3__CHECK_OPT(n->light, m->lights_count, "/nodes", "nodes[%u].light %d out of range [0,%u)", i, n->light, m->lights_count); + for (k = 0; k < n->children_count && errs < TG3__IDX_ERR_CAP; ++k) { + TG3__CHECK_REQ(n->children[k], m->nodes_count, "/nodes", + "nodes[%u].children[%u] %d out of range [0,%u)", + i, k, n->children[k], m->nodes_count); + } + } + for (i = 0; i < m->textures_count && errs < TG3__IDX_ERR_CAP; ++i) { + TG3__CHECK_OPT(m->textures[i].source, m->images_count, "/textures", + "textures[%u].source %d out of range [0,%u)", i, m->textures[i].source, m->images_count); + TG3__CHECK_OPT(m->textures[i].sampler, m->samplers_count, "/textures", + "textures[%u].sampler %d out of range [0,%u)", i, m->textures[i].sampler, m->samplers_count); + } + for (i = 0; i < m->images_count && errs < TG3__IDX_ERR_CAP; ++i) { + TG3__CHECK_OPT(m->images[i].buffer_view, m->buffer_views_count, "/images", + "images[%u].bufferView %d out of range [0,%u)", + i, m->images[i].buffer_view, m->buffer_views_count); + } + for (i = 0; i < m->skins_count && errs < TG3__IDX_ERR_CAP; ++i) { + const tg3_skin *s = &m->skins[i]; + uint32_t k; + TG3__CHECK_OPT(s->inverse_bind_matrices, m->accessors_count, "/skins", + "skins[%u].inverseBindMatrices %d out of range [0,%u)", + i, s->inverse_bind_matrices, m->accessors_count); + TG3__CHECK_OPT(s->skeleton, m->nodes_count, "/skins", + "skins[%u].skeleton %d out of range [0,%u)", + i, s->skeleton, m->nodes_count); + for (k = 0; k < s->joints_count && errs < TG3__IDX_ERR_CAP; ++k) { + TG3__CHECK_REQ(s->joints[k], m->nodes_count, "/skins", + "skins[%u].joints[%u] %d out of range [0,%u)", + i, k, s->joints[k], m->nodes_count); + } + } + for (i = 0; i < m->animations_count && errs < TG3__IDX_ERR_CAP; ++i) { + const tg3_animation *an = &m->animations[i]; + uint32_t k; + for (k = 0; k < an->channels_count && errs < TG3__IDX_ERR_CAP; ++k) { + TG3__CHECK_REQ(an->channels[k].sampler, an->samplers_count, "/animations", + "animations[%u].channels[%u].sampler %d out of range [0,%u)", + i, k, an->channels[k].sampler, an->samplers_count); + TG3__CHECK_OPT(an->channels[k].target.node, m->nodes_count, "/animations", + "animations[%u].channels[%u].target.node %d out of range [0,%u)", + i, k, an->channels[k].target.node, m->nodes_count); + } + for (k = 0; k < an->samplers_count && errs < TG3__IDX_ERR_CAP; ++k) { + TG3__CHECK_REQ(an->samplers[k].input, m->accessors_count, "/animations", + "animations[%u].samplers[%u].input %d out of range [0,%u)", + i, k, an->samplers[k].input, m->accessors_count); + TG3__CHECK_REQ(an->samplers[k].output, m->accessors_count, "/animations", + "animations[%u].samplers[%u].output %d out of range [0,%u)", + i, k, an->samplers[k].output, m->accessors_count); + } + } + for (i = 0; i < m->scenes_count && errs < TG3__IDX_ERR_CAP; ++i) { + uint32_t k; + const tg3_scene *s = &m->scenes[i]; + for (k = 0; k < s->nodes_count && errs < TG3__IDX_ERR_CAP; ++k) { + TG3__CHECK_REQ(s->nodes[k], m->nodes_count, "/scenes", + "scenes[%u].nodes[%u] %d out of range [0,%u)", + i, k, s->nodes[k], m->nodes_count); + } + for (k = 0; k < s->audio_emitters_count && errs < TG3__IDX_ERR_CAP; ++k) { + TG3__CHECK_REQ(s->audio_emitters[k], m->audio_emitters_count, "/scenes", + "scenes[%u].audio_emitters[%u] %d out of range [0,%u)", + i, k, s->audio_emitters[k], m->audio_emitters_count); + } + } + /* Extension index fields (KHR_audio, MSFT_lod). */ + for (i = 0; i < m->nodes_count && errs < TG3__IDX_ERR_CAP; ++i) { + const tg3_node *n = &m->nodes[i]; + uint32_t k; + TG3__CHECK_OPT(n->emitter, m->audio_emitters_count, "/nodes", + "nodes[%u].emitter %d out of range [0,%u)", + i, n->emitter, m->audio_emitters_count); + for (k = 0; k < n->lods_count && errs < TG3__IDX_ERR_CAP; ++k) { + TG3__CHECK_REQ(n->lods[k], m->nodes_count, "/nodes", + "nodes[%u].lods[%u] %d out of range [0,%u)", + i, k, n->lods[k], m->nodes_count); + } + } + for (i = 0; i < m->materials_count && errs < TG3__IDX_ERR_CAP; ++i) { + const tg3_material *mat = &m->materials[i]; + uint32_t k; + for (k = 0; k < mat->lods_count && errs < TG3__IDX_ERR_CAP; ++k) { + TG3__CHECK_REQ(mat->lods[k], m->materials_count, "/materials", + "materials[%u].lods[%u] %d out of range [0,%u)", + i, k, mat->lods[k], m->materials_count); + } + } + for (i = 0; i < m->audio_sources_count && errs < TG3__IDX_ERR_CAP; ++i) { + TG3__CHECK_OPT(m->audio_sources[i].buffer_view, m->buffer_views_count, + "/extensions/KHR_audio/sources", + "audio_sources[%u].bufferView %d out of range [0,%u)", + i, m->audio_sources[i].buffer_view, m->buffer_views_count); + } + for (i = 0; i < m->audio_emitters_count && errs < TG3__IDX_ERR_CAP; ++i) { + TG3__CHECK_OPT(m->audio_emitters[i].source, m->audio_sources_count, + "/extensions/KHR_audio/emitters", + "audio_emitters[%u].source %d out of range [0,%u)", + i, m->audio_emitters[i].source, m->audio_sources_count); + } + + #undef TG3__CHECK_OPT + #undef TG3__CHECK_REQ + #undef TG3__IDX_BAD + return errs == 0; +} + +static int tg3__valid_accessor_component_type(int32_t component_type) { + switch (component_type) { + case TG3_COMPONENT_TYPE_BYTE: + case TG3_COMPONENT_TYPE_UNSIGNED_BYTE: + case TG3_COMPONENT_TYPE_SHORT: + case TG3_COMPONENT_TYPE_UNSIGNED_SHORT: + case TG3_COMPONENT_TYPE_UNSIGNED_INT: + case TG3_COMPONENT_TYPE_FLOAT: + return 1; + default: + return 0; + } +} + +static int tg3__valid_sparse_index_component_type(int32_t component_type) { + return component_type == TG3_COMPONENT_TYPE_UNSIGNED_BYTE || + component_type == TG3_COMPONENT_TYPE_UNSIGNED_SHORT || + component_type == TG3_COMPONENT_TYPE_UNSIGNED_INT; +} + +static int tg3__validate_range_in_buffer_view(tg3__parse_ctx *ctx, + const tg3_buffer_view *bv, + uint64_t byte_offset, + uint64_t byte_length, + const char *what) { + uint64_t end; + int overflow = tg3__u64_add_overflow(byte_offset, byte_length, &end); + if (overflow || end > bv->byte_length) { + tg3__error_pushf(ctx->errors, ctx->arena, TG3_SEVERITY_ERROR, + TG3_ERR_INVALID_ACCESSOR, "/accessors", + "%s byte range [%llu,%llu) exceeds bufferView length %llu", + what, + (unsigned long long)byte_offset, + (unsigned long long)(overflow ? UINT64_MAX : end), + (unsigned long long)bv->byte_length); + return 0; + } + return 1; +} + +static int tg3__validate_resources(tg3__parse_ctx *ctx, const tg3_model *m) { + uint32_t i; + int ok = 1; + + for (i = 0; i < m->buffers_count; ++i) { + const tg3_buffer *b = &m->buffers[i]; + if (b->data.count > 0 && b->byte_length > b->data.count) { + tg3__error_pushf(ctx->errors, ctx->arena, TG3_SEVERITY_ERROR, + TG3_ERR_BUFFER_SIZE_MISMATCH, "/buffers", + "buffers[%u].byteLength %llu exceeds loaded data size %llu", + i, (unsigned long long)b->byte_length, + (unsigned long long)b->data.count); + ok = 0; + } + } + + for (i = 0; i < m->buffer_views_count; ++i) { + const tg3_buffer_view *bv = &m->buffer_views[i]; + const tg3_buffer *b; + uint64_t buffer_size; + uint64_t end; + if (bv->buffer < 0 || (uint32_t)bv->buffer >= m->buffers_count) { + continue; + } + b = &m->buffers[bv->buffer]; + buffer_size = b->byte_length ? b->byte_length : b->data.count; + if (tg3__u64_add_overflow(bv->byte_offset, bv->byte_length, &end) || + end > buffer_size) { + tg3__error_pushf(ctx->errors, ctx->arena, TG3_SEVERITY_ERROR, + TG3_ERR_INVALID_BUFFER_VIEW, "/bufferViews", + "bufferViews[%u] byte range exceeds buffers[%d].byteLength", + i, bv->buffer); + ok = 0; + } + } + + for (i = 0; i < m->accessors_count; ++i) { + const tg3_accessor *a = &m->accessors[i]; + int32_t comp_size; + int32_t num_comp; + uint64_t elem_size; + if (!tg3__valid_accessor_component_type(a->component_type)) { + tg3__error_pushf(ctx->errors, ctx->arena, TG3_SEVERITY_ERROR, + TG3_ERR_INVALID_ACCESSOR, "/accessors", + "accessors[%u].componentType %d is invalid", + i, a->component_type); + ok = 0; + continue; + } + comp_size = tg3_component_size(a->component_type); + num_comp = tg3_num_components(a->type); + if (comp_size <= 0 || num_comp <= 0) { + tg3__error_pushf(ctx->errors, ctx->arena, TG3_SEVERITY_ERROR, + TG3_ERR_INVALID_ACCESSOR, "/accessors", + "accessors[%u].type %d is invalid", i, a->type); + ok = 0; + continue; + } + if (tg3__u64_mul_overflow((uint64_t)comp_size, (uint64_t)num_comp, &elem_size)) { + tg3__error_pushf(ctx->errors, ctx->arena, TG3_SEVERITY_ERROR, + TG3_ERR_INVALID_ACCESSOR, "/accessors", + "accessors[%u] element size overflows", i); + ok = 0; + continue; + } + if (a->buffer_view >= 0 && (uint32_t)a->buffer_view < m->buffer_views_count) { + const tg3_buffer_view *bv = &m->buffer_views[a->buffer_view]; + uint64_t stride = bv->byte_stride ? (uint64_t)bv->byte_stride : elem_size; + uint64_t last_offset = 0; + uint64_t span = 0; + if (stride < elem_size || + (a->count > 0 && + (tg3__u64_mul_overflow(a->count - 1u, stride, &last_offset) || + tg3__u64_add_overflow(last_offset, elem_size, &span)))) { + tg3__error_pushf(ctx->errors, ctx->arena, TG3_SEVERITY_ERROR, + TG3_ERR_INVALID_ACCESSOR, "/accessors", + "accessors[%u] byte stride/count overflows", i); + ok = 0; + } else if (!tg3__validate_range_in_buffer_view(ctx, bv, a->byte_offset, + a->count > 0 ? span : 0, + "accessor")) { + ok = 0; + } + } + if (a->sparse.is_sparse) { + uint64_t sparse_count; + if (a->sparse.count < 0 || (uint64_t)a->sparse.count > a->count) { + tg3__error_pushf(ctx->errors, ctx->arena, TG3_SEVERITY_ERROR, + TG3_ERR_INVALID_ACCESSOR, "/accessors", + "accessors[%u].sparse.count %d is invalid", + i, a->sparse.count); + ok = 0; + continue; + } + sparse_count = (uint64_t)a->sparse.count; + if (!tg3__valid_sparse_index_component_type(a->sparse.indices.component_type)) { + tg3__error_pushf(ctx->errors, ctx->arena, TG3_SEVERITY_ERROR, + TG3_ERR_INVALID_ACCESSOR, "/accessors", + "accessors[%u].sparse.indices.componentType %d is invalid", + i, a->sparse.indices.component_type); + ok = 0; + } + if (a->sparse.indices.buffer_view >= 0 && + (uint32_t)a->sparse.indices.buffer_view < m->buffer_views_count) { + const tg3_buffer_view *bv = &m->buffer_views[a->sparse.indices.buffer_view]; + uint64_t bytes = 0; + int32_t idx_size_i = tg3_component_size(a->sparse.indices.component_type); + if (idx_size_i <= 0 || + tg3__u64_mul_overflow(sparse_count, (uint64_t)idx_size_i, &bytes) || + !tg3__validate_range_in_buffer_view(ctx, bv, a->sparse.indices.byte_offset, + bytes, "sparse indices")) { + ok = 0; + } + } + if (a->sparse.values.buffer_view >= 0 && + (uint32_t)a->sparse.values.buffer_view < m->buffer_views_count) { + const tg3_buffer_view *bv = &m->buffer_views[a->sparse.values.buffer_view]; + uint64_t bytes = 0; + if (tg3__u64_mul_overflow(sparse_count, elem_size, &bytes) || + !tg3__validate_range_in_buffer_view(ctx, bv, a->sparse.values.byte_offset, + bytes, "sparse values")) { + ok = 0; + } + } + } + } + + return ok; +} + +static tg3_error_code tg3__parse_from_json(tg3__parse_ctx *ctx, const tg3json_value *json_doc, tg3_model *model) { + const tg3json_value *asset_it = tg3json_object_get(json_doc, "asset"); + const tg3json_value *ext_it; + if (tg3__json_is_object(asset_it)) { + tg3__parse_asset(ctx, asset_it, &model->asset); + } else if (ctx->opts.required_sections & TG3_REQUIRE_VERSION) { + tg3__error_push(ctx->errors, TG3_SEVERITY_ERROR, TG3_ERR_MISSING_REQUIRED, + "Missing required 'asset' property", "/", -1); + return TG3_ERR_MISSING_REQUIRED; + } + if (ctx->opts.stream && ctx->opts.stream->on_asset) { + tg3_stream_action sa = ctx->opts.stream->on_asset(&model->asset, ctx->opts.stream->user_data); + if (sa == TG3_STREAM_ABORT) return TG3_ERR_STREAM_ABORTED; + } + tg3__parse_string_array(ctx, json_doc, "extensionsUsed", &model->extensions_used, &model->extensions_used_count, 0, "/"); + tg3__parse_string_array(ctx, json_doc, "extensionsRequired", &model->extensions_required, &model->extensions_required_count, 0, "/"); + model->default_scene = -1; + tg3__parse_int(ctx, json_doc, "scene", &model->default_scene, 0, "/"); + + TG3__PARSE_ARRAY_IDX(ctx, json_doc, "buffers", tg3_buffer, model->buffers, model->buffers_count, tg3__parse_buffer); + TG3__STREAM_CB(on_buffer, model->buffers, model->buffers_count); + TG3__PARSE_ARRAY_SIMPLE(ctx, json_doc, "bufferViews", tg3_buffer_view, model->buffer_views, model->buffer_views_count, tg3__parse_buffer_view); + TG3__STREAM_CB(on_buffer_view, model->buffer_views, model->buffer_views_count); + TG3__PARSE_ARRAY_SIMPLE(ctx, json_doc, "accessors", tg3_accessor, model->accessors, model->accessors_count, tg3__parse_accessor); + TG3__STREAM_CB(on_accessor, model->accessors, model->accessors_count); + TG3__PARSE_ARRAY_SIMPLE(ctx, json_doc, "meshes", tg3_mesh, model->meshes, model->meshes_count, tg3__parse_mesh); + TG3__STREAM_CB(on_mesh, model->meshes, model->meshes_count); + TG3__PARSE_ARRAY_SIMPLE(ctx, json_doc, "nodes", tg3_node, model->nodes, model->nodes_count, tg3__parse_node); + TG3__STREAM_CB(on_node, model->nodes, model->nodes_count); + TG3__PARSE_ARRAY_SIMPLE(ctx, json_doc, "materials", tg3_material, model->materials, model->materials_count, tg3__parse_material); + TG3__STREAM_CB(on_material, model->materials, model->materials_count); + TG3__PARSE_ARRAY_SIMPLE(ctx, json_doc, "textures", tg3_texture, model->textures, model->textures_count, tg3__parse_texture); + TG3__STREAM_CB(on_texture, model->textures, model->textures_count); + TG3__PARSE_ARRAY_SIMPLE(ctx, json_doc, "samplers", tg3_sampler, model->samplers, model->samplers_count, tg3__parse_sampler); + TG3__STREAM_CB(on_sampler, model->samplers, model->samplers_count); + TG3__PARSE_ARRAY_IDX(ctx, json_doc, "images", tg3_image, model->images, model->images_count, tg3__parse_image); + TG3__STREAM_CB(on_image, model->images, model->images_count); + TG3__PARSE_ARRAY_SIMPLE(ctx, json_doc, "skins", tg3_skin, model->skins, model->skins_count, tg3__parse_skin); + TG3__STREAM_CB(on_skin, model->skins, model->skins_count); + TG3__PARSE_ARRAY_SIMPLE(ctx, json_doc, "animations", tg3_animation, model->animations, model->animations_count, tg3__parse_animation); + TG3__STREAM_CB(on_animation, model->animations, model->animations_count); + TG3__PARSE_ARRAY_SIMPLE(ctx, json_doc, "cameras", tg3_camera, model->cameras, model->cameras_count, tg3__parse_camera); + TG3__STREAM_CB(on_camera, model->cameras, model->cameras_count); + TG3__PARSE_ARRAY_SIMPLE(ctx, json_doc, "scenes", tg3_scene, model->scenes, model->scenes_count, tg3__parse_scene); + TG3__STREAM_CB(on_scene, model->scenes, model->scenes_count); + + ext_it = tg3json_object_get(json_doc, "extensions"); + if (tg3__json_is_object(ext_it)) { + const tg3json_value *lights_ext = tg3json_object_get(ext_it, "KHR_lights_punctual"); + const tg3json_value *audio_ext = tg3json_object_get(ext_it, "KHR_audio"); + if (tg3__json_is_object(lights_ext)) { + TG3__PARSE_ARRAY_SIMPLE(ctx, lights_ext, "lights", tg3_light, model->lights, model->lights_count, tg3__parse_light); + TG3__STREAM_CB(on_light, model->lights, model->lights_count); + } + if (tg3__json_is_object(audio_ext)) { + TG3__PARSE_ARRAY_SIMPLE(ctx, audio_ext, "sources", tg3_audio_source, model->audio_sources, model->audio_sources_count, tg3__parse_audio_source); + TG3__PARSE_ARRAY_SIMPLE(ctx, audio_ext, "emitters", tg3_audio_emitter, model->audio_emitters, model->audio_emitters_count, tg3__parse_audio_emitter); + } + } + tg3__parse_extras_and_extensions(ctx, json_doc, &model->ext); + if (ctx->opts.validate_indices) { + if (!tg3__validate_indices(ctx, model)) { + return TG3_ERR_INVALID_INDEX; + } + } + if (!tg3__validate_resources(ctx, model)) { + return TG3_ERR_INVALID_ACCESSOR; + } + return (ctx->errors && ctx->errors->has_error) ? TG3_ERR_JSON_PARSE : TG3_OK; +} + +static void tg3__json_parse_options_from_tg3(const tg3_parse_options *options, + tg3json_parse_options *json_options) { + TINYGLTF3_MEMSET(json_options, 0, sizeof(*json_options)); + json_options->depth_limit = TINYGLTF3_MAX_NESTING_DEPTH; + json_options->memory_budget = options ? (size_t)options->memory.memory_budget : 0; + json_options->max_single_alloc = options ? (size_t)options->memory.max_single_alloc : 0; + json_options->max_string_length = TINYGLTF3_MAX_STRING_LENGTH; + json_options->parse_float32 = options ? options->parse_float32 : 0; +} + +static tg3_error_code tg3__parse_glb_header(const uint8_t *data, uint64_t size, + const uint8_t **json_out, uint64_t *json_size_out, + const uint8_t **bin_out, uint64_t *bin_size_out, + tg3_error_stack *errors) { + uint32_t version; + uint32_t total_length; + uint64_t offset = 12; + *json_out = NULL; *json_size_out = 0; *bin_out = NULL; *bin_size_out = 0; + if (size < 12) { + tg3__error_push(errors, TG3_SEVERITY_ERROR, TG3_ERR_GLB_INVALID_HEADER, + "GLB data too small for header", NULL, -1); + return TG3_ERR_GLB_INVALID_HEADER; + } + if (data[0] != 'g' || data[1] != 'l' || data[2] != 'T' || data[3] != 'F') { + tg3__error_push(errors, TG3_SEVERITY_ERROR, TG3_ERR_GLB_INVALID_MAGIC, + "Invalid GLB magic bytes", NULL, -1); + return TG3_ERR_GLB_INVALID_MAGIC; + } + TINYGLTF3_MEMCPY(&version, data + 4, 4); + if (version != 2) { + tg3__error_push(errors, TG3_SEVERITY_ERROR, TG3_ERR_GLB_INVALID_VERSION, + "Unsupported GLB version (expected 2)", NULL, -1); + return TG3_ERR_GLB_INVALID_VERSION; + } + TINYGLTF3_MEMCPY(&total_length, data + 8, 4); + if ((uint64_t)total_length != size) { + tg3__error_push(errors, TG3_SEVERITY_ERROR, TG3_ERR_GLB_SIZE_MISMATCH, + "GLB total length does not match data size", NULL, -1); + return TG3_ERR_GLB_SIZE_MISMATCH; + } + while (offset + 8 <= (uint64_t)total_length) { + uint32_t chunk_length; + uint32_t chunk_type; + TINYGLTF3_MEMCPY(&chunk_length, data + offset, 4); offset += 4; + TINYGLTF3_MEMCPY(&chunk_type, data + offset, 4); offset += 4; + if (offset + chunk_length > (uint64_t)total_length) { + tg3__error_push(errors, TG3_SEVERITY_ERROR, TG3_ERR_GLB_CHUNK_ERROR, + "GLB chunk exceeds data size", NULL, -1); + return TG3_ERR_GLB_CHUNK_ERROR; + } + if (chunk_type == 0x4E4F534Au) { + *json_out = data + offset; + *json_size_out = chunk_length; + } else if (chunk_type == 0x004E4942u) { + *bin_out = data + offset; + *bin_size_out = chunk_length; + } + offset += chunk_length; + while ((offset & 3u) != 0u && offset < size) ++offset; + } + if (!*json_out) { + tg3__error_push(errors, TG3_SEVERITY_ERROR, TG3_ERR_GLB_CHUNK_ERROR, + "GLB missing JSON chunk", NULL, -1); + return TG3_ERR_GLB_CHUNK_ERROR; + } + return TG3_OK; +} + +TINYGLTF3_API tg3_error_code tg3_parse(tg3_model *model, tg3_error_stack *errors, + const uint8_t *json_data, uint64_t json_size, + const char *base_dir, uint32_t base_dir_len, + const tg3_parse_options *options) { + tg3_parse_options default_opts; + tg3_arena *arena; + tg3__parse_ctx ctx; + tg3json_value json_doc; + tg3json_parse_options json_options; + const char *error_pos = NULL; + tg3_error_code ret; + int parsed_ok; + if (!model) return TG3_ERR_JSON_PARSE; + tg3__model_init(model); + if (!json_data) return TG3_ERR_JSON_PARSE; + if (!options) { tg3_parse_options_init(&default_opts); options = &default_opts; } + arena = tg3__arena_create(&options->memory); + if (!arena) { + tg3__error_push(errors, TG3_SEVERITY_ERROR, TG3_ERR_OUT_OF_MEMORY, "Failed to create arena", NULL, -1); + return TG3_ERR_OUT_OF_MEMORY; + } + model->arena_ = arena; + tg3__json_parse_options_from_tg3(options, &json_options); + parsed_ok = tg3json_parse_n_opts((const char *)json_data, (size_t)json_size, + &json_options, &json_doc, &error_pos); + if (!parsed_ok || json_doc.type != TG3JSON_OBJECT) { + tg3__error_push(errors, TG3_SEVERITY_ERROR, TG3_ERR_JSON_PARSE, "Failed to parse JSON", NULL, + error_pos ? (int64_t)(error_pos - (const char *)json_data) : -1); + if (parsed_ok) tg3json_value_free(&json_doc); + /* Keep arena alive so error messages (arena-allocated) stay valid for + * the caller; tg3_model_free is the sole arena owner on the error path. */ + return TG3_ERR_JSON_PARSE; + } + TINYGLTF3_MEMSET(&ctx, 0, sizeof(ctx)); + ctx.arena = arena; + ctx.errors = errors; + ctx.opts = *options; + ctx.base_dir = base_dir; + ctx.base_dir_len = base_dir_len; +#if defined(TINYGLTF3_ENABLE_FS) && !defined(TINYGLTF3_NO_STDLIB) + tg3__set_default_fs(&ctx.opts.fs); +#endif + ret = tg3__parse_from_json(&ctx, &json_doc, model); + tg3json_value_free(&json_doc); + /* Arena stays attached to model->arena_ on both success and failure; + * tg3_model_free reclaims it. Destroying here would dangle arena-allocated + * error messages on the user-facing tg3_error_stack. */ + return ret; +} + +TINYGLTF3_API tg3_error_code tg3_parse_glb(tg3_model *model, tg3_error_stack *errors, + const uint8_t *glb_data, uint64_t glb_size, + const char *base_dir, uint32_t base_dir_len, + const tg3_parse_options *options) { + const uint8_t *json_chunk = NULL; + uint64_t json_chunk_size = 0; + const uint8_t *bin_chunk = NULL; + uint64_t bin_chunk_size = 0; + tg3_parse_options default_opts; + tg3_arena *arena; + tg3__parse_ctx ctx; + tg3json_value json_doc; + tg3json_parse_options json_options; + const char *error_pos = NULL; + tg3_error_code err; + int parsed_ok; + /* Initialize model before any failure-return so callers can safely call + * tg3_model_free() on the error path; the GLB header parse must not run + * against a model whose arena_ field is uninitialized garbage. */ + if (!model) return TG3_ERR_GLB_INVALID_HEADER; + tg3__model_init(model); + if (!glb_data) return TG3_ERR_GLB_INVALID_HEADER; + err = tg3__parse_glb_header(glb_data, glb_size, &json_chunk, &json_chunk_size, &bin_chunk, &bin_chunk_size, errors); + if (err != TG3_OK) return err; + if (!options) { tg3_parse_options_init(&default_opts); options = &default_opts; } + arena = tg3__arena_create(&options->memory); + if (!arena) { + tg3__error_push(errors, TG3_SEVERITY_ERROR, TG3_ERR_OUT_OF_MEMORY, "Failed to create arena", NULL, -1); + return TG3_ERR_OUT_OF_MEMORY; + } + model->arena_ = arena; + tg3__json_parse_options_from_tg3(options, &json_options); + parsed_ok = tg3json_parse_n_opts((const char *)json_chunk, (size_t)json_chunk_size, + &json_options, &json_doc, &error_pos); + if (!parsed_ok || json_doc.type != TG3JSON_OBJECT) { + tg3__error_push(errors, TG3_SEVERITY_ERROR, TG3_ERR_JSON_PARSE, "Failed to parse GLB JSON chunk", NULL, + error_pos ? (int64_t)(error_pos - (const char *)json_chunk) : -1); + if (parsed_ok) tg3json_value_free(&json_doc); + /* Keep arena alive so error messages stay valid; model_free owns it. */ + return TG3_ERR_JSON_PARSE; + } + TINYGLTF3_MEMSET(&ctx, 0, sizeof(ctx)); + ctx.arena = arena; + ctx.errors = errors; + ctx.opts = *options; + ctx.base_dir = base_dir; + ctx.base_dir_len = base_dir_len; + ctx.is_binary = 1; + ctx.bin_data = bin_chunk; + ctx.bin_size = bin_chunk_size; +#if defined(TINYGLTF3_ENABLE_FS) && !defined(TINYGLTF3_NO_STDLIB) + tg3__set_default_fs(&ctx.opts.fs); +#endif + err = tg3__parse_from_json(&ctx, &json_doc, model); + tg3json_value_free(&json_doc); + /* Arena stays attached to model->arena_ on both paths; model_free owns it. */ + return err; +} + +TINYGLTF3_API tg3_error_code tg3_parse_auto(tg3_model *model, tg3_error_stack *errors, + const uint8_t *data, uint64_t size, + const char *base_dir, uint32_t base_dir_len, + const tg3_parse_options *options) { + if (!model) return TG3_ERR_JSON_PARSE; + if (!data && size > 0) { + tg3__model_init(model); + return TG3_ERR_JSON_PARSE; + } + if (size >= 4 && data[0] == 'g' && data[1] == 'l' && data[2] == 'T' && data[3] == 'F') { + return tg3_parse_glb(model, errors, data, size, base_dir, base_dir_len, options); + } + return tg3_parse(model, errors, data, size, base_dir, base_dir_len, options); +} + +TINYGLTF3_API tg3_error_code tg3_parse_file(tg3_model *model, tg3_error_stack *errors, + const char *filename, uint32_t filename_len, + const tg3_parse_options *options) { + tg3_parse_options opts; + uint8_t *file_data = NULL; + uint64_t file_size = 0; + char base_dir_buf[4096]; + uint32_t base_dir_len = 0; + tg3_error_code result; + uint32_t i; + if (!model) return TG3_ERR_FILE_NOT_FOUND; + tg3__model_init(model); + if (!filename) return TG3_ERR_FILE_NOT_FOUND; + if (options) opts = *options; + else tg3_parse_options_init(&opts); +#if defined(TINYGLTF3_ENABLE_FS) && !defined(TINYGLTF3_NO_STDLIB) + tg3__set_default_fs(&opts.fs); +#endif + if (!opts.fs.read_file) { + tg3__error_push(errors, TG3_SEVERITY_ERROR, TG3_ERR_FS_NOT_AVAILABLE, + "No filesystem callbacks. Define TINYGLTF3_ENABLE_FS or provide fs callbacks.", NULL, -1); + return TG3_ERR_FS_NOT_AVAILABLE; + } + if (!opts.fs.read_file(&file_data, &file_size, filename, filename_len, opts.fs.user_data) || !file_data) { + tg3__error_push(errors, TG3_SEVERITY_ERROR, TG3_ERR_FILE_NOT_FOUND, + "Failed to read file", NULL, -1); + return TG3_ERR_FILE_NOT_FOUND; + } + TINYGLTF3_MEMSET(base_dir_buf, 0, sizeof(base_dir_buf)); + for (i = 0; i < filename_len; ++i) { + if (filename[i] == '/' || filename[i] == '\\') base_dir_len = i; + } + if (base_dir_len > 0) { + TINYGLTF3_MEMCPY(base_dir_buf, filename, base_dir_len); + base_dir_buf[base_dir_len] = '\0'; + } + result = tg3_parse_auto(model, errors, file_data, file_size, base_dir_buf, base_dir_len, &opts); + if (opts.fs.free_file) opts.fs.free_file(file_data, file_size, opts.fs.user_data); + return result; +} + +TINYGLTF3_API void tg3_model_free(tg3_model *model) { + if (!model) return; + if (model->arena_) tg3__arena_destroy(model->arena_); + TINYGLTF3_MEMSET(model, 0, sizeof(*model)); + model->default_scene = -1; +} + +static char *tg3__b64_encode(const uint8_t *input, size_t input_len, size_t *out_len) { + static const char chars[] = + "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/"; + size_t enc_len = ((input_len + 2u) / 3u) * 4u; + char *out = (char *)TINYGLTF3_MALLOC(enc_len + 1u); + size_t i; + size_t j = 0; + if (!out) return NULL; + for (i = 0; i < input_len; i += 3u) { + uint32_t a = input[i]; + uint32_t b = (i + 1u < input_len) ? input[i + 1u] : 0u; + uint32_t c = (i + 2u < input_len) ? input[i + 2u] : 0u; + uint32_t triple = (a << 16u) | (b << 8u) | c; + out[j++] = chars[(triple >> 18u) & 0x3Fu]; + out[j++] = chars[(triple >> 12u) & 0x3Fu]; + out[j++] = (i + 1u < input_len) ? chars[(triple >> 6u) & 0x3Fu] : '='; + out[j++] = (i + 2u < input_len) ? chars[triple & 0x3Fu] : '='; + } + out[j] = '\0'; + if (out_len) *out_len = enc_len; + return out; +} + +static const char *tg3__accessor_type_to_string(int type) { + switch (type) { + case TG3_TYPE_SCALAR: return "SCALAR"; + case TG3_TYPE_VEC2: return "VEC2"; + case TG3_TYPE_VEC3: return "VEC3"; + case TG3_TYPE_VEC4: return "VEC4"; + case TG3_TYPE_MAT2: return "MAT2"; + case TG3_TYPE_MAT3: return "MAT3"; + case TG3_TYPE_MAT4: return "MAT4"; + default: return ""; + } +} + +static int tg3__json_set_take(tg3json_value *obj, const char *key, tg3json_value *value) { + if (!tg3json_object_set_take(obj, key, value)) { + tg3json_value_free(value); + return 0; + } + return 1; +} + +static int tg3__json_push_take(tg3json_value *arr, tg3json_value *value) { + if (!tg3json_array_append_take(arr, value)) { + tg3json_value_free(value); + return 0; + } + return 1; +} + +static int tg3__json_set_int(tg3json_value *obj, const char *key, int64_t value) { + tg3json_value tmp; + tg3json_value_init_int(&tmp, value); + return tg3__json_set_take(obj, key, &tmp); +} + +static int tg3__json_set_real(tg3json_value *obj, const char *key, double value) { + tg3json_value tmp; + tg3json_value_init_real(&tmp, value); + return tg3__json_set_take(obj, key, &tmp); +} + +static int tg3__json_set_bool(tg3json_value *obj, const char *key, int value) { + tg3json_value tmp; + tg3json_value_init_bool(&tmp, value); + return tg3__json_set_take(obj, key, &tmp); +} + +static int tg3__json_set_string_n(tg3json_value *obj, const char *key, const char *str, size_t len) { + tg3json_value tmp; + if (!tg3json_value_init_string_n(&tmp, str, len)) return 0; + return tg3__json_set_take(obj, key, &tmp); +} + +static int tg3__json_set_string(tg3json_value *obj, const char *key, const char *str) { + return tg3__json_set_string_n(obj, key, str, str ? TINYGLTF3_STRLEN(str) : 0); +} + +static int tg3__json_array_append_int(tg3json_value *arr, int64_t value) { + tg3json_value tmp; + tg3json_value_init_int(&tmp, value); + return tg3__json_push_take(arr, &tmp); +} + +static int tg3__json_array_append_real(tg3json_value *arr, double value) { + tg3json_value tmp; + tg3json_value_init_real(&tmp, value); + return tg3__json_push_take(arr, &tmp); +} + +static int tg3__json_ensure_object(tg3json_value *obj, const char *key, tg3json_value **out_child) { + tg3json_value *existing = tg3json_object_get_mut(obj, key); + if (existing) { + if (existing->type != TG3JSON_OBJECT) return 0; + *out_child = existing; + return 1; + } + { + tg3json_value tmp; + tg3json_value_init_object(&tmp); + if (!tg3__json_set_take(obj, key, &tmp)) return 0; + } + existing = tg3json_object_get_mut(obj, key); + if (!existing || existing->type != TG3JSON_OBJECT) return 0; + *out_child = existing; + return 1; +} + +static int tg3__json_ensure_array(tg3json_value *obj, const char *key, tg3json_value **out_child) { + tg3json_value *existing = tg3json_object_get_mut(obj, key); + if (existing) { + if (existing->type != TG3JSON_ARRAY) return 0; + *out_child = existing; + return 1; + } + { + tg3json_value tmp; + tg3json_value_init_array(&tmp); + if (!tg3__json_set_take(obj, key, &tmp)) return 0; + } + existing = tg3json_object_get_mut(obj, key); + if (!existing || existing->type != TG3JSON_ARRAY) return 0; + *out_child = existing; + return 1; +} + +static int tg3__serialize_str(tg3json_value *o, const char *key, tg3_str val) { + if (!val.data || val.len == 0) return 1; + return tg3__json_set_string_n(o, key, val.data, val.len); +} + +static int tg3__serialize_int(tg3json_value *o, const char *key, int32_t val, + int32_t default_val, int write_defaults) { + if (val == default_val && !write_defaults) return 1; + return tg3__json_set_int(o, key, val); +} + +static int tg3__serialize_uint64(tg3json_value *o, const char *key, uint64_t val, + uint64_t default_val, int write_defaults) { + if (val == default_val && !write_defaults) return 1; + return tg3__json_set_int(o, key, (int64_t)val); +} + +static int tg3__serialize_double(tg3json_value *o, const char *key, double val, + double default_val, int write_defaults) { + if (tg3__fabs(val - default_val) <= 1e-12 && !write_defaults) return 1; + return tg3__json_set_real(o, key, val); +} + +static int tg3__serialize_bool(tg3json_value *o, const char *key, int32_t val, + int32_t default_val, int write_defaults) { + if (val == default_val && !write_defaults) return 1; + return tg3__json_set_bool(o, key, val != 0); +} + +static int tg3__json_from_double_array(const double *arr, uint32_t count, tg3json_value *out) { + uint32_t i; + tg3json_value_init_array(out); + for (i = 0; i < count; ++i) { + if (!tg3__json_array_append_real(out, arr[i])) { + tg3json_value_free(out); + return 0; + } + } + return 1; +} + +static int tg3__json_from_int_array(const int32_t *arr, uint32_t count, tg3json_value *out) { + uint32_t i; + tg3json_value_init_array(out); + for (i = 0; i < count; ++i) { + if (!tg3__json_array_append_int(out, arr[i])) { + tg3json_value_free(out); + return 0; + } + } + return 1; +} + +static int tg3__json_from_string_array(const tg3_str *arr, uint32_t count, tg3json_value *out) { + uint32_t i; + tg3json_value_init_array(out); + for (i = 0; i < count; ++i) { + tg3json_value tmp; + if (!arr[i].data) continue; + if (!tg3json_value_init_string_n(&tmp, arr[i].data, arr[i].len)) { + tg3json_value_free(out); + return 0; + } + if (!tg3__json_push_take(out, &tmp)) { + tg3json_value_free(out); + return 0; + } + } + return 1; +} + +static int tg3__serialize_double_array(tg3json_value *o, const char *key, + const double *arr, uint32_t count) { + tg3json_value tmp; + if (!arr || count == 0) return 1; + if (!tg3__json_from_double_array(arr, count, &tmp)) return 0; + return tg3__json_set_take(o, key, &tmp); +} + +static int tg3__serialize_int_array(tg3json_value *o, const char *key, + const int32_t *arr, uint32_t count) { + tg3json_value tmp; + if (!arr || count == 0) return 1; + if (!tg3__json_from_int_array(arr, count, &tmp)) return 0; + return tg3__json_set_take(o, key, &tmp); +} + +static int tg3__serialize_string_array(tg3json_value *o, const char *key, + const tg3_str *arr, uint32_t count) { + tg3json_value tmp; + if (!arr || count == 0) return 1; + if (!tg3__json_from_string_array(arr, count, &tmp)) return 0; + return tg3__json_set_take(o, key, &tmp); +} + +static int tg3__value_to_json(const tg3_value *v, tg3json_value *out) { + uint32_t i; + tg3json_value_init_null(out); + if (!v) return 1; + switch (v->type) { + case TG3_VALUE_NULL: + return 1; + case TG3_VALUE_BOOL: + tg3json_value_init_bool(out, v->bool_val != 0); + return 1; + case TG3_VALUE_INT: + tg3json_value_init_int(out, v->int_val); + return 1; + case TG3_VALUE_REAL: + tg3json_value_init_real(out, v->real_val); + return 1; + case TG3_VALUE_STRING: + return tg3json_value_init_string_n(out, + v->string_val.data ? v->string_val.data : "", + v->string_val.data ? v->string_val.len : 0); + case TG3_VALUE_ARRAY: + tg3json_value_init_array(out); + for (i = 0; i < v->array_count; ++i) { + tg3json_value item; + if (!tg3__value_to_json(&v->array_data[i], &item)) { + tg3json_value_free(out); + return 0; + } + if (!tg3__json_push_take(out, &item)) { + tg3json_value_free(out); + return 0; + } + } + return 1; + case TG3_VALUE_OBJECT: + tg3json_value_init_object(out); + for (i = 0; i < v->object_count; ++i) { + tg3json_value item; + if (!tg3__value_to_json(&v->object_data[i].value, &item)) { + tg3json_value_free(out); + return 0; + } + if (!tg3json_object_set_take_n(out, + v->object_data[i].key.data ? v->object_data[i].key.data : "", + v->object_data[i].key.data ? v->object_data[i].key.len : 0, + &item)) { + tg3json_value_free(&item); + tg3json_value_free(out); + return 0; + } + } + return 1; + case TG3_VALUE_BINARY: + /* Binary blobs cannot be represented as JSON; emit null. */ + return 1; + } + return 0; /* unreachable: all enum cases handled above. */ +} + +static int tg3__serialize_extras_ext(tg3json_value *o, const tg3_extras_ext *ee) { + uint32_t i; + if (!ee) return 1; + if (ee->extras) { + tg3json_value extras; + if (!tg3__value_to_json(ee->extras, &extras)) return 0; + if (!tg3__json_set_take(o, "extras", &extras)) return 0; + } + if (ee->extensions && ee->extensions_count > 0) { + tg3json_value *exts = NULL; + if (!tg3__json_ensure_object(o, "extensions", &exts)) return 0; + for (i = 0; i < ee->extensions_count; ++i) { + tg3json_value item; + if (!tg3__value_to_json(&ee->extensions[i].value, &item)) return 0; + if (!tg3json_object_set_take_n(exts, + ee->extensions[i].name.data ? ee->extensions[i].name.data : "", + ee->extensions[i].name.data ? ee->extensions[i].name.len : 0, + &item)) { + tg3json_value_free(&item); + return 0; + } + } + } + return 1; +} + +static int tg3__serialize_texture_info(tg3json_value *parent, const char *key, + const tg3_texture_info *ti, int wd) { + tg3json_value o; + if (ti->index < 0) return 1; + tg3json_value_init_object(&o); + if (!tg3__json_set_int(&o, "index", ti->index) || + !tg3__serialize_int(&o, "texCoord", ti->tex_coord, 0, wd) || + !tg3__serialize_extras_ext(&o, &ti->ext) || + !tg3__json_set_take(parent, key, &o)) { + tg3json_value_free(&o); + return 0; + } + return 1; +} + +static int tg3__serialize_normal_texture_info(tg3json_value *parent, const char *key, + const tg3_normal_texture_info *ti, int wd) { + tg3json_value o; + if (ti->index < 0) return 1; + tg3json_value_init_object(&o); + if (!tg3__json_set_int(&o, "index", ti->index) || + !tg3__serialize_int(&o, "texCoord", ti->tex_coord, 0, wd) || + !tg3__serialize_double(&o, "scale", ti->scale, 1.0, wd) || + !tg3__serialize_extras_ext(&o, &ti->ext) || + !tg3__json_set_take(parent, key, &o)) { + tg3json_value_free(&o); + return 0; + } + return 1; +} + +static int tg3__serialize_occlusion_texture_info(tg3json_value *parent, const char *key, + const tg3_occlusion_texture_info *ti, int wd) { + tg3json_value o; + if (ti->index < 0) return 1; + tg3json_value_init_object(&o); + if (!tg3__json_set_int(&o, "index", ti->index) || + !tg3__serialize_int(&o, "texCoord", ti->tex_coord, 0, wd) || + !tg3__serialize_double(&o, "strength", ti->strength, 1.0, wd) || + !tg3__serialize_extras_ext(&o, &ti->ext) || + !tg3__json_set_take(parent, key, &o)) { + tg3json_value_free(&o); + return 0; + } + return 1; +} + +static int tg3__serialize_asset(const tg3_asset *a, int wd, tg3json_value *out) { + (void)wd; + tg3json_value_init_object(out); + if (!tg3__serialize_str(out, "version", a->version) || + !tg3__serialize_str(out, "generator", a->generator) || + !tg3__serialize_str(out, "minVersion", a->min_version) || + !tg3__serialize_str(out, "copyright", a->copyright) || + !tg3__serialize_extras_ext(out, &a->ext)) { + tg3json_value_free(out); + return 0; + } + return 1; +} + +static int tg3__serialize_buffer(const tg3_buffer *b, int wd, int embed, tg3json_value *out) { + (void)wd; + tg3json_value_init_object(out); + if (!tg3__serialize_str(out, "name", b->name) || + !tg3__json_set_int(out, "byteLength", + (int64_t)(b->byte_length ? b->byte_length : b->data.count))) { + tg3json_value_free(out); + return 0; + } + if (b->uri.data && b->uri.len > 0) { + if (!tg3__serialize_str(out, "uri", b->uri)) { + tg3json_value_free(out); + return 0; + } + } else if (embed && b->data.data && b->data.count > 0) { + size_t enc_len = 0; + char *encoded = tg3__b64_encode(b->data.data, (size_t)b->data.count, &enc_len); + const char prefix[] = "data:application/octet-stream;base64,"; + size_t prefix_len = sizeof(prefix) - 1u; + char *uri; + if (!encoded) { + tg3json_value_free(out); + return 0; + } + uri = (char *)TINYGLTF3_MALLOC(prefix_len + enc_len + 1u); + if (!uri) { + TINYGLTF3_FREE(encoded); + tg3json_value_free(out); + return 0; + } + TINYGLTF3_MEMCPY(uri, prefix, prefix_len); + TINYGLTF3_MEMCPY(uri + prefix_len, encoded, enc_len); + uri[prefix_len + enc_len] = '\0'; + TINYGLTF3_FREE(encoded); + if (!tg3__json_set_string_n(out, "uri", uri, prefix_len + enc_len)) { + TINYGLTF3_FREE(uri); + tg3json_value_free(out); + return 0; + } + TINYGLTF3_FREE(uri); + } + if (!tg3__serialize_extras_ext(out, &b->ext)) { + tg3json_value_free(out); + return 0; + } + return 1; +} + +static int tg3__serialize_buffer_view(const tg3_buffer_view *bv, int wd, tg3json_value *out) { + tg3json_value_init_object(out); + if (!tg3__serialize_str(out, "name", bv->name) || + !tg3__json_set_int(out, "buffer", bv->buffer) || + !tg3__json_set_int(out, "byteLength", (int64_t)bv->byte_length) || + !tg3__serialize_uint64(out, "byteOffset", bv->byte_offset, 0, wd)) { + tg3json_value_free(out); + return 0; + } + if (bv->byte_stride > 0 && !tg3__json_set_int(out, "byteStride", bv->byte_stride)) { + tg3json_value_free(out); + return 0; + } + if (!tg3__serialize_int(out, "target", bv->target, 0, wd) || + !tg3__serialize_extras_ext(out, &bv->ext)) { + tg3json_value_free(out); + return 0; + } + return 1; +} + +static int tg3__serialize_accessor(const tg3_accessor *acc, int wd, tg3json_value *out) { + tg3json_value_init_object(out); + if (!tg3__serialize_str(out, "name", acc->name) || + !tg3__serialize_uint64(out, "byteOffset", acc->byte_offset, 0, wd) || + !tg3__json_set_int(out, "componentType", acc->component_type) || + !tg3__json_set_int(out, "count", (int64_t)acc->count) || + !tg3__json_set_string(out, "type", tg3__accessor_type_to_string(acc->type)) || + !tg3__serialize_bool(out, "normalized", acc->normalized, 0, wd) || + !tg3__serialize_double_array(out, "min", acc->min_values, acc->min_values_count) || + !tg3__serialize_double_array(out, "max", acc->max_values, acc->max_values_count)) { + tg3json_value_free(out); + return 0; + } + if (acc->buffer_view >= 0 && !tg3__json_set_int(out, "bufferView", acc->buffer_view)) { + tg3json_value_free(out); + return 0; + } + if (acc->sparse.is_sparse) { + tg3json_value sparse, indices, values; + tg3json_value_init_object(&sparse); + tg3json_value_init_object(&indices); + tg3json_value_init_object(&values); + if (!tg3__json_set_int(&sparse, "count", acc->sparse.count) || + !tg3__json_set_int(&indices, "bufferView", acc->sparse.indices.buffer_view) || + !tg3__json_set_int(&indices, "componentType", acc->sparse.indices.component_type) || + !tg3__serialize_uint64(&indices, "byteOffset", acc->sparse.indices.byte_offset, 0, wd) || + !tg3__serialize_extras_ext(&indices, &acc->sparse.indices.ext) || + !tg3__json_set_take(&sparse, "indices", &indices) || + !tg3__json_set_int(&values, "bufferView", acc->sparse.values.buffer_view) || + !tg3__serialize_uint64(&values, "byteOffset", acc->sparse.values.byte_offset, 0, wd) || + !tg3__serialize_extras_ext(&values, &acc->sparse.values.ext) || + !tg3__json_set_take(&sparse, "values", &values) || + !tg3__serialize_extras_ext(&sparse, &acc->sparse.ext) || + !tg3__json_set_take(out, "sparse", &sparse)) { + tg3json_value_free(&indices); + tg3json_value_free(&values); + tg3json_value_free(&sparse); + tg3json_value_free(out); + return 0; + } + } + if (!tg3__serialize_extras_ext(out, &acc->ext)) { + tg3json_value_free(out); + return 0; + } + return 1; +} + +static int tg3__serialize_image(const tg3_image *img, int wd, int embed, tg3json_value *out) { + (void)wd; + (void)embed; + tg3json_value_init_object(out); + if (!tg3__serialize_str(out, "name", img->name) || + !tg3__serialize_str(out, "uri", img->uri) || + !tg3__serialize_str(out, "mimeType", img->mime_type) || + !tg3__serialize_extras_ext(out, &img->ext)) { + tg3json_value_free(out); + return 0; + } + if (img->buffer_view >= 0 && !tg3__json_set_int(out, "bufferView", img->buffer_view)) { + tg3json_value_free(out); + return 0; + } + return 1; +} + +static int tg3__serialize_sampler(const tg3_sampler *s, int wd, tg3json_value *out) { + tg3json_value_init_object(out); + if (!tg3__serialize_str(out, "name", s->name) || + !tg3__serialize_int(out, "wrapS", s->wrap_s, TG3_TEXTURE_WRAP_REPEAT, wd) || + !tg3__serialize_int(out, "wrapT", s->wrap_t, TG3_TEXTURE_WRAP_REPEAT, wd) || + !tg3__serialize_extras_ext(out, &s->ext)) { + tg3json_value_free(out); + return 0; + } + if (s->min_filter >= 0 && !tg3__json_set_int(out, "minFilter", s->min_filter)) { + tg3json_value_free(out); + return 0; + } + if (s->mag_filter >= 0 && !tg3__json_set_int(out, "magFilter", s->mag_filter)) { + tg3json_value_free(out); + return 0; + } + return 1; +} + +static int tg3__serialize_texture(const tg3_texture *t, int wd, tg3json_value *out) { + (void)wd; + tg3json_value_init_object(out); + if (!tg3__serialize_str(out, "name", t->name) || + !tg3__serialize_extras_ext(out, &t->ext)) { + tg3json_value_free(out); + return 0; + } + if (t->sampler >= 0 && !tg3__json_set_int(out, "sampler", t->sampler)) { + tg3json_value_free(out); + return 0; + } + if (t->source >= 0 && !tg3__json_set_int(out, "source", t->source)) { + tg3json_value_free(out); + return 0; + } + return 1; +} + +static int tg3__serialize_material(const tg3_material *m, int wd, tg3json_value *out) { + tg3json_value pbr; + int has_pbr = 0; + const tg3_pbr_metallic_roughness *p = &m->pbr_metallic_roughness; + tg3json_value_init_object(out); + tg3json_value_init_object(&pbr); + if (!tg3__serialize_str(out, "name", m->name)) goto fail; + if (p->base_color_factor[0] != 1.0 || p->base_color_factor[1] != 1.0 || + p->base_color_factor[2] != 1.0 || p->base_color_factor[3] != 1.0 || wd) { + if (!tg3__serialize_double_array(&pbr, "baseColorFactor", p->base_color_factor, 4)) goto fail; + has_pbr = 1; + } + if (!tg3__serialize_double(&pbr, "metallicFactor", p->metallic_factor, 1.0, wd)) goto fail; + if (tg3__fabs(p->metallic_factor - 1.0) > 1e-12 || wd) has_pbr = 1; + if (!tg3__serialize_double(&pbr, "roughnessFactor", p->roughness_factor, 1.0, wd)) goto fail; + if (tg3__fabs(p->roughness_factor - 1.0) > 1e-12 || wd) has_pbr = 1; + if (p->base_color_texture.index >= 0) { + if (!tg3__serialize_texture_info(&pbr, "baseColorTexture", &p->base_color_texture, wd)) goto fail; + has_pbr = 1; + } + if (p->metallic_roughness_texture.index >= 0) { + if (!tg3__serialize_texture_info(&pbr, "metallicRoughnessTexture", &p->metallic_roughness_texture, wd)) goto fail; + has_pbr = 1; + } + if (!tg3__serialize_extras_ext(&pbr, &p->ext)) goto fail; + if ((has_pbr || wd) && !tg3__json_set_take(out, "pbrMetallicRoughness", &pbr)) goto fail; + if (!tg3__serialize_normal_texture_info(out, "normalTexture", &m->normal_texture, wd) || + !tg3__serialize_occlusion_texture_info(out, "occlusionTexture", &m->occlusion_texture, wd) || + !tg3__serialize_texture_info(out, "emissiveTexture", &m->emissive_texture, wd)) goto fail; + if ((m->emissive_factor[0] != 0.0 || m->emissive_factor[1] != 0.0 || + m->emissive_factor[2] != 0.0 || wd) && + !tg3__serialize_double_array(out, "emissiveFactor", m->emissive_factor, 3)) goto fail; + if (m->alpha_mode.data && !tg3_str_equals_cstr(m->alpha_mode, "OPAQUE") && + !tg3__serialize_str(out, "alphaMode", m->alpha_mode)) goto fail; + if (!tg3__serialize_double(out, "alphaCutoff", m->alpha_cutoff, 0.5, wd) || + !tg3__serialize_bool(out, "doubleSided", m->double_sided, 0, wd) || + !tg3__serialize_extras_ext(out, &m->ext)) goto fail; + return 1; +fail: + tg3json_value_free(&pbr); + tg3json_value_free(out); + return 0; +} + +static int tg3__serialize_primitive(const tg3_primitive *p, int wd, tg3json_value *out) { + tg3json_value attrs, targets; + uint32_t i; + tg3json_value_init_object(out); + if (p->attributes && p->attributes_count > 0) { + tg3json_value_init_object(&attrs); + for (i = 0; i < p->attributes_count; ++i) { + tg3json_value item; + tg3json_value_init_int(&item, p->attributes[i].value); + if (!tg3json_object_set_take_n(&attrs, + p->attributes[i].key.data ? p->attributes[i].key.data : "", + p->attributes[i].key.data ? p->attributes[i].key.len : 0, + &item)) { + tg3json_value_free(&item); + tg3json_value_free(&attrs); + goto fail; + } + } + if (!tg3__json_set_take(out, "attributes", &attrs)) { + tg3json_value_free(&attrs); + goto fail; + } + } + if (p->indices >= 0 && !tg3__json_set_int(out, "indices", p->indices)) goto fail; + if (p->material >= 0 && !tg3__json_set_int(out, "material", p->material)) goto fail; + if (!tg3__serialize_int(out, "mode", p->mode, TG3_MODE_TRIANGLES, wd)) goto fail; + if (p->targets && p->targets_count > 0) { + uint32_t t; + tg3json_value_init_array(&targets); + for (t = 0; t < p->targets_count; ++t) { + tg3json_value tgt; + uint32_t acount = p->target_attribute_counts ? p->target_attribute_counts[t] : 0; + tg3json_value_init_object(&tgt); + for (i = 0; i < acount; ++i) { + tg3json_value item; + tg3json_value_init_int(&item, p->targets[t][i].value); + if (!tg3json_object_set_take_n(&tgt, + p->targets[t][i].key.data ? p->targets[t][i].key.data : "", + p->targets[t][i].key.data ? p->targets[t][i].key.len : 0, + &item)) { + tg3json_value_free(&item); + tg3json_value_free(&tgt); + tg3json_value_free(&targets); + goto fail; + } + } + if (!tg3__json_push_take(&targets, &tgt)) { + tg3json_value_free(&tgt); + tg3json_value_free(&targets); + goto fail; + } + } + if (!tg3__json_set_take(out, "targets", &targets)) { + tg3json_value_free(&targets); + goto fail; + } + } + if (!tg3__serialize_extras_ext(out, &p->ext)) goto fail; + return 1; +fail: + tg3json_value_free(out); + return 0; +} + +static int tg3__serialize_mesh(const tg3_mesh *m, int wd, tg3json_value *out) { + uint32_t i; + tg3json_value prims; + tg3json_value_init_object(out); + if (!tg3__serialize_str(out, "name", m->name)) goto fail; + if (m->primitives && m->primitives_count > 0) { + tg3json_value_init_array(&prims); + for (i = 0; i < m->primitives_count; ++i) { + tg3json_value prim; + if (!tg3__serialize_primitive(&m->primitives[i], wd, &prim) || + !tg3__json_push_take(&prims, &prim)) { + tg3json_value_free(&prim); + tg3json_value_free(&prims); + goto fail; + } + } + if (!tg3__json_set_take(out, "primitives", &prims)) { + tg3json_value_free(&prims); + goto fail; + } + } + if (!tg3__serialize_double_array(out, "weights", m->weights, m->weights_count) || + !tg3__serialize_extras_ext(out, &m->ext)) goto fail; + return 1; +fail: + tg3json_value_free(out); + return 0; +} + +static int tg3__serialize_node(const tg3_node *n, int wd, tg3json_value *out) { + tg3json_value *exts = NULL; + tg3json_value tmp; + int has_t, has_r, has_s; + tg3json_value_init_object(out); + if (!tg3__serialize_str(out, "name", n->name) || + !tg3__serialize_int_array(out, "children", n->children, n->children_count)) goto fail; + if (n->camera >= 0 && !tg3__json_set_int(out, "camera", n->camera)) goto fail; + if (n->skin >= 0 && !tg3__json_set_int(out, "skin", n->skin)) goto fail; + if (n->mesh >= 0 && !tg3__json_set_int(out, "mesh", n->mesh)) goto fail; + if (n->has_matrix) { + if (!tg3__serialize_double_array(out, "matrix", n->matrix, 16)) goto fail; + } else { + has_t = (n->translation[0] != 0.0 || n->translation[1] != 0.0 || n->translation[2] != 0.0); + has_r = (n->rotation[0] != 0.0 || n->rotation[1] != 0.0 || n->rotation[2] != 0.0 || n->rotation[3] != 1.0); + has_s = (n->scale[0] != 1.0 || n->scale[1] != 1.0 || n->scale[2] != 1.0); + if ((has_t || wd) && !tg3__serialize_double_array(out, "translation", n->translation, 3)) goto fail; + if ((has_r || wd) && !tg3__serialize_double_array(out, "rotation", n->rotation, 4)) goto fail; + if ((has_s || wd) && !tg3__serialize_double_array(out, "scale", n->scale, 3)) goto fail; + } + if (!tg3__serialize_double_array(out, "weights", n->weights, n->weights_count) || + !tg3__serialize_extras_ext(out, &n->ext)) goto fail; + if (n->light >= 0 || n->emitter >= 0 || (n->lods && n->lods_count > 0)) { + if (!tg3__json_ensure_object(out, "extensions", &exts)) goto fail; + if (n->light >= 0) { + tg3json_value_init_object(&tmp); + if (!tg3__json_set_int(&tmp, "light", n->light) || + !tg3__json_set_take(exts, "KHR_lights_punctual", &tmp)) { + tg3json_value_free(&tmp); + goto fail; + } + } + if (n->emitter >= 0) { + tg3json_value_init_object(&tmp); + if (!tg3__json_set_int(&tmp, "emitter", n->emitter) || + !tg3__json_set_take(exts, "KHR_audio", &tmp)) { + tg3json_value_free(&tmp); + goto fail; + } + } + if (n->lods && n->lods_count > 0) { + tg3json_value_init_object(&tmp); + if (!tg3__serialize_int_array(&tmp, "ids", n->lods, n->lods_count) || + !tg3__json_set_take(exts, "MSFT_lod", &tmp)) { + tg3json_value_free(&tmp); + goto fail; + } + } + } + return 1; +fail: + tg3json_value_free(out); + return 0; +} + +static int tg3__serialize_skin(const tg3_skin *s, int wd, tg3json_value *out) { + (void)wd; + tg3json_value_init_object(out); + if (!tg3__serialize_str(out, "name", s->name) || + !tg3__serialize_int_array(out, "joints", s->joints, s->joints_count) || + !tg3__serialize_extras_ext(out, &s->ext)) { + tg3json_value_free(out); + return 0; + } + if (s->inverse_bind_matrices >= 0 && + !tg3__json_set_int(out, "inverseBindMatrices", s->inverse_bind_matrices)) { + tg3json_value_free(out); + return 0; + } + if (s->skeleton >= 0 && !tg3__json_set_int(out, "skeleton", s->skeleton)) { + tg3json_value_free(out); + return 0; + } + return 1; +} + +static int tg3__serialize_animation(const tg3_animation *a, int wd, tg3json_value *out) { + uint32_t i; + tg3json_value channels, samplers; + (void)wd; + tg3json_value_init_object(out); + if (!tg3__serialize_str(out, "name", a->name)) goto fail; + if (a->channels && a->channels_count > 0) { + tg3json_value_init_array(&channels); + for (i = 0; i < a->channels_count; ++i) { + tg3json_value ch, tgt; + tg3json_value_init_object(&ch); + tg3json_value_init_object(&tgt); + if (a->channels[i].target.node >= 0 && + !tg3__json_set_int(&tgt, "node", a->channels[i].target.node)) { + tg3json_value_free(&tgt); + tg3json_value_free(&ch); + tg3json_value_free(&channels); + goto fail; + } + if (!tg3__json_set_int(&ch, "sampler", a->channels[i].sampler) || + !tg3__serialize_str(&tgt, "path", a->channels[i].target.path) || + !tg3__serialize_extras_ext(&tgt, &a->channels[i].target.ext) || + !tg3__json_set_take(&ch, "target", &tgt) || + !tg3__serialize_extras_ext(&ch, &a->channels[i].ext) || + !tg3__json_push_take(&channels, &ch)) { + tg3json_value_free(&tgt); + tg3json_value_free(&ch); + tg3json_value_free(&channels); + goto fail; + } + } + if (!tg3__json_set_take(out, "channels", &channels)) { + tg3json_value_free(&channels); + goto fail; + } + } + if (a->samplers && a->samplers_count > 0) { + tg3json_value_init_array(&samplers); + for (i = 0; i < a->samplers_count; ++i) { + tg3json_value s; + tg3json_value_init_object(&s); + if (!tg3__json_set_int(&s, "input", a->samplers[i].input) || + !tg3__json_set_int(&s, "output", a->samplers[i].output) || + !tg3__serialize_str(&s, "interpolation", a->samplers[i].interpolation) || + !tg3__serialize_extras_ext(&s, &a->samplers[i].ext) || + !tg3__json_push_take(&samplers, &s)) { + tg3json_value_free(&s); + tg3json_value_free(&samplers); + goto fail; + } + } + if (!tg3__json_set_take(out, "samplers", &samplers)) { + tg3json_value_free(&samplers); + goto fail; + } + } + if (!tg3__serialize_extras_ext(out, &a->ext)) goto fail; + return 1; +fail: + tg3json_value_free(out); + return 0; +} + +static int tg3__serialize_camera(const tg3_camera *c, int wd, tg3json_value *out) { + tg3json_value tmp; + (void)wd; + tg3json_value_init_object(out); + if (!tg3__serialize_str(out, "name", c->name) || + !tg3__serialize_str(out, "type", c->type)) goto fail; + if (c->type.data && tg3_str_equals_cstr(c->type, "perspective")) { + tg3json_value_init_object(&tmp); + if ((c->perspective.aspect_ratio > 0.0 && + !tg3__json_set_real(&tmp, "aspectRatio", c->perspective.aspect_ratio)) || + !tg3__json_set_real(&tmp, "yfov", c->perspective.yfov) || + (c->perspective.zfar > 0.0 && + !tg3__json_set_real(&tmp, "zfar", c->perspective.zfar)) || + !tg3__json_set_real(&tmp, "znear", c->perspective.znear) || + !tg3__serialize_extras_ext(&tmp, &c->perspective.ext) || + !tg3__json_set_take(out, "perspective", &tmp)) { + tg3json_value_free(&tmp); + goto fail; + } + } else if (c->type.data && tg3_str_equals_cstr(c->type, "orthographic")) { + tg3json_value_init_object(&tmp); + if (!tg3__json_set_real(&tmp, "xmag", c->orthographic.xmag) || + !tg3__json_set_real(&tmp, "ymag", c->orthographic.ymag) || + !tg3__json_set_real(&tmp, "zfar", c->orthographic.zfar) || + !tg3__json_set_real(&tmp, "znear", c->orthographic.znear) || + !tg3__serialize_extras_ext(&tmp, &c->orthographic.ext) || + !tg3__json_set_take(out, "orthographic", &tmp)) { + tg3json_value_free(&tmp); + goto fail; + } + } + if (!tg3__serialize_extras_ext(out, &c->ext)) goto fail; + return 1; +fail: + tg3json_value_free(out); + return 0; +} + +static int tg3__serialize_scene(const tg3_scene *s, int wd, tg3json_value *out) { + (void)wd; + tg3json_value_init_object(out); + if (!tg3__serialize_str(out, "name", s->name) || + !tg3__serialize_int_array(out, "nodes", s->nodes, s->nodes_count) || + !tg3__serialize_extras_ext(out, &s->ext)) { + tg3json_value_free(out); + return 0; + } + return 1; +} + +static int tg3__serialize_light(const tg3_light *l, int wd, tg3json_value *out) { + tg3json_value spot; + tg3json_value_init_object(out); + if (!tg3__serialize_str(out, "name", l->name) || + !tg3__serialize_str(out, "type", l->type) || + !tg3__serialize_double(out, "intensity", l->intensity, 1.0, wd) || + !tg3__serialize_double(out, "range", l->range, 0.0, wd)) goto fail; + if ((l->color[0] != 1.0 || l->color[1] != 1.0 || l->color[2] != 1.0 || wd) && + !tg3__serialize_double_array(out, "color", l->color, 3)) goto fail; + if (l->type.data && tg3_str_equals_cstr(l->type, "spot")) { + tg3json_value_init_object(&spot); + if (!tg3__serialize_double(&spot, "innerConeAngle", l->spot.inner_cone_angle, 0.0, wd) || + !tg3__serialize_double(&spot, "outerConeAngle", l->spot.outer_cone_angle, 0.7853981634, wd) || + !tg3__serialize_extras_ext(&spot, &l->spot.ext) || + !tg3__json_set_take(out, "spot", &spot)) { + tg3json_value_free(&spot); + goto fail; + } + } + if (!tg3__serialize_extras_ext(out, &l->ext)) goto fail; + return 1; +fail: + tg3json_value_free(out); + return 0; +} + +static int tg3__serialize_model(const tg3_model *model, int wd, + int embed_images, int embed_buffers, + tg3json_value *out) { + tg3json_value asset, arr, item, lights_ext, lights, *exts; + uint32_t i; + tg3json_value_init_object(out); + if (!tg3__serialize_asset(&model->asset, wd, &asset) || + !tg3__json_set_take(out, "asset", &asset)) goto fail; + if (model->default_scene >= 0 && !tg3__json_set_int(out, "scene", model->default_scene)) goto fail; + if (!tg3__serialize_string_array(out, "extensionsUsed", model->extensions_used, model->extensions_used_count) || + !tg3__serialize_string_array(out, "extensionsRequired", model->extensions_required, model->extensions_required_count)) goto fail; + +#define TG3__SERIALIZE_ARRAY_FIELD(json_key, arr_ptr, arr_count, fn, ...) \ + do { \ + if ((arr_ptr) && (arr_count) > 0) { \ + tg3json_value_init_array(&arr); \ + for (i = 0; i < (arr_count); ++i) { \ + tg3json_value_init_null(&item); \ + if (!fn(&(arr_ptr)[i], __VA_ARGS__, &item) || !tg3__json_push_take(&arr, &item)) { \ + tg3json_value_free(&item); \ + tg3json_value_free(&arr); \ + goto fail; \ + } \ + } \ + if (!tg3__json_set_take(out, json_key, &arr)) { \ + tg3json_value_free(&arr); \ + goto fail; \ + } \ + } \ + } while (0) + + TG3__SERIALIZE_ARRAY_FIELD("buffers", model->buffers, model->buffers_count, tg3__serialize_buffer, wd, embed_buffers); + TG3__SERIALIZE_ARRAY_FIELD("bufferViews", model->buffer_views, model->buffer_views_count, tg3__serialize_buffer_view, wd); + TG3__SERIALIZE_ARRAY_FIELD("accessors", model->accessors, model->accessors_count, tg3__serialize_accessor, wd); + TG3__SERIALIZE_ARRAY_FIELD("meshes", model->meshes, model->meshes_count, tg3__serialize_mesh, wd); + TG3__SERIALIZE_ARRAY_FIELD("nodes", model->nodes, model->nodes_count, tg3__serialize_node, wd); + TG3__SERIALIZE_ARRAY_FIELD("materials", model->materials, model->materials_count, tg3__serialize_material, wd); + TG3__SERIALIZE_ARRAY_FIELD("textures", model->textures, model->textures_count, tg3__serialize_texture, wd); + TG3__SERIALIZE_ARRAY_FIELD("samplers", model->samplers, model->samplers_count, tg3__serialize_sampler, wd); + TG3__SERIALIZE_ARRAY_FIELD("images", model->images, model->images_count, tg3__serialize_image, wd, embed_images); + TG3__SERIALIZE_ARRAY_FIELD("skins", model->skins, model->skins_count, tg3__serialize_skin, wd); + TG3__SERIALIZE_ARRAY_FIELD("animations", model->animations, model->animations_count, tg3__serialize_animation, wd); + TG3__SERIALIZE_ARRAY_FIELD("cameras", model->cameras, model->cameras_count, tg3__serialize_camera, wd); + TG3__SERIALIZE_ARRAY_FIELD("scenes", model->scenes, model->scenes_count, tg3__serialize_scene, wd); + +#undef TG3__SERIALIZE_ARRAY_FIELD + + if (model->lights && model->lights_count > 0) { + tg3json_value_init_object(&lights_ext); + tg3json_value_init_array(&lights); + for (i = 0; i < model->lights_count; ++i) { + tg3json_value_init_null(&item); + if (!tg3__serialize_light(&model->lights[i], wd, &item) || + !tg3__json_push_take(&lights, &item)) { + tg3json_value_free(&item); + tg3json_value_free(&lights); + tg3json_value_free(&lights_ext); + goto fail; + } + } + if (!tg3__json_set_take(&lights_ext, "lights", &lights) || + !tg3__json_ensure_object(out, "extensions", &exts) || + !tg3__json_set_take(exts, "KHR_lights_punctual", &lights_ext)) { + tg3json_value_free(&lights); + tg3json_value_free(&lights_ext); + goto fail; + } + } + if (!tg3__serialize_extras_ext(out, &model->ext)) goto fail; + return 1; +fail: + tg3json_value_free(out); + return 0; +} + +TINYGLTF3_API tg3_error_code tg3_write_to_memory(const tg3_model *model, tg3_error_stack *errors, + uint8_t **out_data, uint64_t *out_size, + const tg3_write_options *options) { + tg3_write_options default_opts; + tg3json_value root; + char *json_str; + size_t json_len; + if (out_data) *out_data = NULL; + if (out_size) *out_size = 0; + if (!model || !out_data || !out_size) return TG3_ERR_WRITE_FAILED; + if (!options) { + tg3_write_options_init(&default_opts); + options = &default_opts; + } + if (!tg3__serialize_model(model, options->serialize_defaults, + options->embed_images, options->embed_buffers, &root)) { + tg3__error_push(errors, TG3_SEVERITY_ERROR, TG3_ERR_OUT_OF_MEMORY, + "Failed to serialize model to JSON tree", NULL, -1); + return TG3_ERR_OUT_OF_MEMORY; + } + json_str = options->pretty_print + ? tg3json_stringify_pretty(&root, 2, &json_len) + : tg3json_stringify(&root, &json_len); + tg3json_value_free(&root); + if (!json_str) { + tg3__error_push(errors, TG3_SEVERITY_ERROR, TG3_ERR_OUT_OF_MEMORY, + "Failed to stringify JSON output", NULL, -1); + return TG3_ERR_OUT_OF_MEMORY; + } + if (options->write_binary) { + uint32_t json_padded = ((uint32_t)json_len + 3u) & ~3u; + const uint8_t *bin_data = NULL; + uint64_t bin_len = 0; + uint32_t bin_padded; + uint32_t total; + uint8_t *glb; + if (model->buffers_count > 0 && model->buffers && model->buffers[0].data.data) { + bin_data = model->buffers[0].data.data; + bin_len = model->buffers[0].data.count; + } + bin_padded = ((uint32_t)bin_len + 3u) & ~3u; + total = 12u + 8u + json_padded + ((bin_data && bin_len > 0) ? (8u + bin_padded) : 0u); + glb = (uint8_t *)TINYGLTF3_MALLOC(total); + if (!glb) { + TINYGLTF3_FREE(json_str); + tg3__error_push(errors, TG3_SEVERITY_ERROR, TG3_ERR_OUT_OF_MEMORY, + "OOM allocating GLB output", NULL, -1); + return TG3_ERR_OUT_OF_MEMORY; + } + TINYGLTF3_MEMCPY(glb, "glTF", 4); + { + uint32_t version = 2u; + uint32_t json_type = 0x4E4F534Au; + TINYGLTF3_MEMCPY(glb + 4, &version, 4); + TINYGLTF3_MEMCPY(glb + 8, &total, 4); + TINYGLTF3_MEMCPY(glb + 12, &json_padded, 4); + TINYGLTF3_MEMCPY(glb + 16, &json_type, 4); + TINYGLTF3_MEMCPY(glb + 20, json_str, json_len); + } + while ((uint32_t)json_len < json_padded) { + glb[20u + json_len] = ' '; + ++json_len; + } + if (bin_data && bin_len > 0) { + uint32_t bin_off = 20u + json_padded; + uint32_t bin_type = 0x004E4942u; + uint32_t i; + TINYGLTF3_MEMCPY(glb + bin_off, &bin_padded, 4); + TINYGLTF3_MEMCPY(glb + bin_off + 4u, &bin_type, 4); + TINYGLTF3_MEMCPY(glb + bin_off + 8u, bin_data, (size_t)bin_len); + for (i = (uint32_t)bin_len; i < bin_padded; ++i) glb[bin_off + 8u + i] = 0; + } + TINYGLTF3_FREE(json_str); + *out_data = glb; + *out_size = total; + return TG3_OK; + } else { + uint8_t *data = (uint8_t *)TINYGLTF3_MALLOC(json_len); + if (!data) { + TINYGLTF3_FREE(json_str); + tg3__error_push(errors, TG3_SEVERITY_ERROR, TG3_ERR_OUT_OF_MEMORY, + "OOM allocating JSON output", NULL, -1); + return TG3_ERR_OUT_OF_MEMORY; + } + TINYGLTF3_MEMCPY(data, json_str, json_len); + TINYGLTF3_FREE(json_str); + *out_data = data; + *out_size = (uint64_t)json_len; + return TG3_OK; + } +} + +TINYGLTF3_API tg3_error_code tg3_write_to_file(const tg3_model *model, tg3_error_stack *errors, + const char *filename, uint32_t filename_len, + const tg3_write_options *options) { + tg3_write_options opts; + uint8_t *data = NULL; + uint64_t size = 0; + tg3_error_code err; + int32_t ok; + if (options) opts = *options; + else tg3_write_options_init(&opts); +#if defined(TINYGLTF3_ENABLE_FS) && !defined(TINYGLTF3_NO_STDLIB) + tg3__set_default_fs(&opts.fs); +#endif + if (!opts.fs.write_file) { + tg3__error_push(errors, TG3_SEVERITY_ERROR, TG3_ERR_FS_NOT_AVAILABLE, + "No filesystem write callback", NULL, -1); + return TG3_ERR_FS_NOT_AVAILABLE; + } + err = tg3_write_to_memory(model, errors, &data, &size, &opts); + if (err != TG3_OK) return err; + ok = opts.fs.write_file(filename, filename_len, data, size, opts.fs.user_data); + TINYGLTF3_FREE(data); + if (!ok) { + tg3__error_push(errors, TG3_SEVERITY_ERROR, TG3_ERR_FILE_WRITE, + "Failed to write file", NULL, -1); + return TG3_ERR_FILE_WRITE; + } + return TG3_OK; +} + +TINYGLTF3_API void tg3_write_free(uint8_t *data, const tg3_write_options *options) { + (void)options; + TINYGLTF3_FREE(data); +} + +TINYGLTF3_API tg3_writer *tg3_writer_create(tg3_write_chunk_fn chunk_fn, void *user_data, + const tg3_write_options *options) { + tg3_writer *w = (tg3_writer *)TINYGLTF3_MALLOC(sizeof(tg3_writer)); + if (!w) return NULL; + TINYGLTF3_MEMSET(w, 0, sizeof(*w)); + w->chunk_fn = chunk_fn; + w->user_data = user_data; + if (options) w->options = *options; + else tg3_write_options_init(&w->options); + tg3json_value_init_object(&w->root); + return w; +} + +TINYGLTF3_API tg3_error_code tg3_writer_begin(tg3_writer *w, const tg3_asset *asset) { + tg3json_value asset_json; + if (!w || !asset) return TG3_ERR_WRITE_FAILED; + tg3json_value_init_null(&asset_json); + if (!tg3__serialize_asset(asset, w->options.serialize_defaults, &asset_json) || + !tg3__json_set_take(&w->root, "asset", &asset_json)) { + tg3json_value_free(&asset_json); + return TG3_ERR_OUT_OF_MEMORY; + } + w->begun = 1; + return TG3_OK; +} + +static tg3_error_code tg3__writer_add_item(tg3_writer *w, const char *json_key, const tg3json_value *item) { + tg3json_value *arr = NULL; + if (!w || !w->begun) return TG3_ERR_WRITE_FAILED; + if (!tg3__json_ensure_array(&w->root, json_key, &arr) || + !tg3json_array_append_copy(arr, item)) { + return TG3_ERR_OUT_OF_MEMORY; + } + return TG3_OK; +} + +#define TG3__WRITER_ADD_IMPL(name, Type, json_key, serialize_fn, ...) \ + TINYGLTF3_API tg3_error_code tg3_writer_add_##name(tg3_writer *w, const Type *item) { \ + tg3json_value tmp; \ + if (!item) return TG3_ERR_WRITE_FAILED; \ + if (!serialize_fn(item, w->options.serialize_defaults, __VA_ARGS__, &tmp)) return TG3_ERR_OUT_OF_MEMORY; \ + { tg3_error_code err = tg3__writer_add_item(w, json_key, &tmp); tg3json_value_free(&tmp); return err; } \ + } + +#define TG3__WRITER_ADD_SIMPLE(name, Type, json_key, serialize_fn) \ + TINYGLTF3_API tg3_error_code tg3_writer_add_##name(tg3_writer *w, const Type *item) { \ + tg3json_value tmp; \ + if (!item) return TG3_ERR_WRITE_FAILED; \ + if (!serialize_fn(item, w->options.serialize_defaults, &tmp)) return TG3_ERR_OUT_OF_MEMORY; \ + { tg3_error_code err = tg3__writer_add_item(w, json_key, &tmp); tg3json_value_free(&tmp); return err; } \ + } + +TG3__WRITER_ADD_IMPL(buffer, tg3_buffer, "buffers", tg3__serialize_buffer, w->options.embed_buffers) +TG3__WRITER_ADD_SIMPLE(buffer_view, tg3_buffer_view, "bufferViews", tg3__serialize_buffer_view) +TG3__WRITER_ADD_SIMPLE(accessor, tg3_accessor, "accessors", tg3__serialize_accessor) +TG3__WRITER_ADD_SIMPLE(mesh, tg3_mesh, "meshes", tg3__serialize_mesh) +TG3__WRITER_ADD_SIMPLE(node, tg3_node, "nodes", tg3__serialize_node) +TG3__WRITER_ADD_SIMPLE(material, tg3_material, "materials", tg3__serialize_material) +TG3__WRITER_ADD_SIMPLE(texture, tg3_texture, "textures", tg3__serialize_texture) +TG3__WRITER_ADD_IMPL(image, tg3_image, "images", tg3__serialize_image, w->options.embed_images) +TG3__WRITER_ADD_SIMPLE(sampler, tg3_sampler, "samplers", tg3__serialize_sampler) +TG3__WRITER_ADD_SIMPLE(animation, tg3_animation, "animations", tg3__serialize_animation) +TG3__WRITER_ADD_SIMPLE(skin, tg3_skin, "skins", tg3__serialize_skin) +TG3__WRITER_ADD_SIMPLE(camera, tg3_camera, "cameras", tg3__serialize_camera) +TG3__WRITER_ADD_SIMPLE(scene, tg3_scene, "scenes", tg3__serialize_scene) +TG3__WRITER_ADD_SIMPLE(light, tg3_light, "lights", tg3__serialize_light) + +#undef TG3__WRITER_ADD_IMPL +#undef TG3__WRITER_ADD_SIMPLE + +TINYGLTF3_API tg3_error_code tg3_writer_end(tg3_writer *w) { + char *json_str; + size_t json_len; + int32_t ok; + if (!w || !w->begun || !w->chunk_fn) return TG3_ERR_WRITE_FAILED; + json_str = w->options.pretty_print + ? tg3json_stringify_pretty(&w->root, 2, &json_len) + : tg3json_stringify(&w->root, &json_len); + if (!json_str) return TG3_ERR_OUT_OF_MEMORY; + ok = w->chunk_fn((const uint8_t *)json_str, (uint64_t)json_len, w->user_data); + TINYGLTF3_FREE(json_str); + return ok ? TG3_OK : TG3_ERR_WRITE_FAILED; +} + +TINYGLTF3_API void tg3_writer_destroy(tg3_writer *w) { + if (!w) return; + tg3json_value_free(&w->root); + TINYGLTF3_FREE(w); +} diff --git a/src/tiny_gltf_v3.h b/src/tiny_gltf_v3.h new file mode 100644 index 0000000..6cc1583 --- /dev/null +++ b/src/tiny_gltf_v3.h @@ -0,0 +1,4512 @@ +/* + * tiny_gltf_v3.h - C-first glTF 2.0 loader and writer API (v3) + * + * The MIT License (MIT) + * Copyright (c) 2026 - Present: Syoyo Fujita + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to deal + * in the Software without restriction, including without limitation the rights + * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + * copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in + * all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN + * THE SOFTWARE. + */ + +/* + * Version: v3.0.0-alpha + * + * Ground-up C-centric API rewrite of tinygltf. + * The default runtime implementation lives in tiny_gltf_v3.c. + * + * Key differences from v2: + * - Pure C POD structs (no STL containers in public API) + * - Arena-based memory management (single tg3_model_free() frees all) + * - Filesystem and image decoding OFF by default (opt-in) + * - Structured error reporting via tg3_error_stack + * - Streaming parse/write via callbacks + * - No RTTI, no exceptions required + * - C++20 coroutine facade (optional) + * + * Security considerations (read before processing untrusted glTF): + * + * 1. External URI loading. When TINYGLTF3_ENABLE_FS is defined and no custom + * tg3_fs_callbacks are supplied, the parser opens external buffer/image + * URIs through the libc default fopen(). The parser rejects URIs that + * contain '..' segments, leading '/' or '\\', Windows drive prefixes + * (e.g. "C:"), or NUL bytes — but it does NOT chroot or canonicalize the + * result. Production callers SHOULD provide a tg3_fs_callbacks with a + * read_file callback that confines reads to a known directory (e.g. via + * openat(AT_FDCWD, path, O_NOFOLLOW) plus a realpath() prefix check) when + * the input glTF is attacker-controlled. + * + * 2. Index validation. Many glTF fields are integer indices into model + * arrays (accessor.bufferView, primitive.material, scene.nodes[], etc.). + * With opts.validate_indices = 1 (the default) the parser rejects every + * out-of-range index after the structural parse and returns + * TG3_ERR_INVALID_INDEX. Set opts.validate_indices = 0 only when you + * need to round-trip raw or extension data and have your own validator. + * + * 3. Image decoding. The parser does not decode image bytes by default. + * Set opts.images_as_is = 1 (already the safe default for untrusted + * input) to skip any decoder and store raw bytes only. + * + * 4. Memory budget. The arena is capped at TINYGLTF3_MAX_MEMORY_BYTES + * (1 GB by default; configurable per-parse via tg3_memory_config). + * The parser returns TG3_ERR_OUT_OF_MEMORY rather than overcommitting. + * + * 5. Error message lifetime. Error strings on tg3_error_stack are + * arena-allocated and remain valid until tg3_model_free() is called. + * Read or copy them BEFORE freeing the model. + */ + +#ifndef TINY_GLTF_V3_H_ +#define TINY_GLTF_V3_H_ + +/* ====================================================================== + * Section 2: Configuration Macros + * ====================================================================== */ + +/* Legacy single-translation-unit build mode: define in ONE C or C++ file */ +/* #define TINYGLTF3_IMPLEMENTATION */ + +/* Opt-in features (OFF by default) */ +/* #define TINYGLTF3_ENABLE_FS */ +/* #define TINYGLTF3_ENABLE_STB_IMAGE */ +/* #define TINYGLTF3_ENABLE_STB_IMAGE_WRITE */ + +/* Opt-out */ +/* #define TINYGLTF3_NO_IMAGE_DECODE */ + +/* C++20 coroutines (auto-detected, or force) */ +/* #define TINYGLTF3_ENABLE_COROUTINES */ + +/* SIMD for JSON parsing (forwarded to tinygltf_json.h) */ +/* #define TINYGLTF3_JSON_SIMD_SSE2 */ +/* #define TINYGLTF3_JSON_SIMD_AVX2 */ +/* #define TINYGLTF3_JSON_SIMD_NEON */ + +/* Memory limits */ +#ifndef TINYGLTF3_MAX_MEMORY_BYTES +#define TINYGLTF3_MAX_MEMORY_BYTES (1ULL << 30) /* 1 GB */ +#endif + +#ifndef TINYGLTF3_MAX_NESTING_DEPTH +#define TINYGLTF3_MAX_NESTING_DEPTH 512 +#endif + +#ifndef TINYGLTF3_MAX_STRING_LENGTH +#define TINYGLTF3_MAX_STRING_LENGTH (64 * 1024 * 1024) /* 64 MB */ +#endif + +/* Linkage control */ +#ifndef TINYGLTF3_API +#define TINYGLTF3_API +#endif + +/* Assert override */ +#ifndef TINYGLTF3_ASSERT +#ifndef TINYGLTF3_NO_STDLIB +#include +#define TINYGLTF3_ASSERT(x) assert(x) +#else +#define TINYGLTF3_ASSERT(x) ((void)(x)) +#endif +#endif + +/* ====================================================================== + * Section 3: C Includes + * ====================================================================== */ + +#include +#include +#include +#ifndef TINYGLTF3_NO_STDLIB +#include +#include +#endif + +#ifndef TINYGLTF3_MALLOC +#ifndef TINYGLTF3_NO_STDLIB +#define TINYGLTF3_MALLOC(sz) malloc(sz) +#else +#define TINYGLTF3_MALLOC(sz) NULL +#endif +#endif + +#ifndef TINYGLTF3_REALLOC +#ifndef TINYGLTF3_NO_STDLIB +#define TINYGLTF3_REALLOC(ptr, sz) realloc((ptr), (sz)) +#else +#define TINYGLTF3_REALLOC(ptr, sz) NULL +#endif +#endif + +#ifndef TINYGLTF3_FREE +#ifndef TINYGLTF3_NO_STDLIB +#define TINYGLTF3_FREE(ptr) free(ptr) +#else +#define TINYGLTF3_FREE(ptr) ((void)(ptr)) +#endif +#endif + +/* ====================================================================== + * Section 4: Constants and Enums + * ====================================================================== */ + +#ifdef __cplusplus +extern "C" { +#endif + +/* Primitive modes */ +#define TG3_MODE_POINTS 0 +#define TG3_MODE_LINE 1 +#define TG3_MODE_LINE_LOOP 2 +#define TG3_MODE_LINE_STRIP 3 +#define TG3_MODE_TRIANGLES 4 +#define TG3_MODE_TRIANGLE_STRIP 5 +#define TG3_MODE_TRIANGLE_FAN 6 + +/* Component types */ +#define TG3_COMPONENT_TYPE_BYTE 5120 +#define TG3_COMPONENT_TYPE_UNSIGNED_BYTE 5121 +#define TG3_COMPONENT_TYPE_SHORT 5122 +#define TG3_COMPONENT_TYPE_UNSIGNED_SHORT 5123 +#define TG3_COMPONENT_TYPE_INT 5124 +#define TG3_COMPONENT_TYPE_UNSIGNED_INT 5125 +#define TG3_COMPONENT_TYPE_FLOAT 5126 +#define TG3_COMPONENT_TYPE_DOUBLE 5130 + +/* Accessor types */ +#define TG3_TYPE_VEC2 2 +#define TG3_TYPE_VEC3 3 +#define TG3_TYPE_VEC4 4 +#define TG3_TYPE_MAT2 (32 + 2) +#define TG3_TYPE_MAT3 (32 + 3) +#define TG3_TYPE_MAT4 (32 + 4) +#define TG3_TYPE_SCALAR (64 + 1) +#define TG3_TYPE_VECTOR (64 + 4) +#define TG3_TYPE_MATRIX (64 + 16) + +/* Texture filter */ +#define TG3_TEXTURE_FILTER_NEAREST 9728 +#define TG3_TEXTURE_FILTER_LINEAR 9729 +#define TG3_TEXTURE_FILTER_NEAREST_MIPMAP_NEAREST 9984 +#define TG3_TEXTURE_FILTER_LINEAR_MIPMAP_NEAREST 9985 +#define TG3_TEXTURE_FILTER_NEAREST_MIPMAP_LINEAR 9986 +#define TG3_TEXTURE_FILTER_LINEAR_MIPMAP_LINEAR 9987 + +/* Texture wrap */ +#define TG3_TEXTURE_WRAP_REPEAT 10497 +#define TG3_TEXTURE_WRAP_CLAMP_TO_EDGE 33071 +#define TG3_TEXTURE_WRAP_MIRRORED_REPEAT 33648 + +/* Image format */ +#define TG3_IMAGE_FORMAT_JPEG 0 +#define TG3_IMAGE_FORMAT_PNG 1 +#define TG3_IMAGE_FORMAT_BMP 2 +#define TG3_IMAGE_FORMAT_GIF 3 + +/* Texture format */ +#define TG3_TEXTURE_FORMAT_ALPHA 6406 +#define TG3_TEXTURE_FORMAT_RGB 6407 +#define TG3_TEXTURE_FORMAT_RGBA 6408 +#define TG3_TEXTURE_FORMAT_LUMINANCE 6409 +#define TG3_TEXTURE_FORMAT_LUMINANCE_ALPHA 6410 + +/* Texture target / type */ +#define TG3_TEXTURE_TARGET_TEXTURE2D 3553 +#define TG3_TEXTURE_TYPE_UNSIGNED_BYTE 5121 + +/* Buffer targets */ +#define TG3_TARGET_ARRAY_BUFFER 34962 +#define TG3_TARGET_ELEMENT_ARRAY_BUFFER 34963 + +/* Sentinel for absent index */ +#define TG3_INDEX_NONE (-1) + +/* Section check flags */ +#define TG3_NO_REQUIRE 0x00 +#define TG3_REQUIRE_VERSION 0x01 +#define TG3_REQUIRE_SCENE 0x02 +#define TG3_REQUIRE_SCENES 0x04 +#define TG3_REQUIRE_NODES 0x08 +#define TG3_REQUIRE_ACCESSORS 0x10 +#define TG3_REQUIRE_BUFFERS 0x20 +#define TG3_REQUIRE_BUFFER_VIEWS 0x40 +#define TG3_REQUIRE_ALL 0x7f + +/* Parse strictness */ +typedef enum tg3_strictness { + TG3_PERMISSIVE = 0, + TG3_STRICT = 1 +} tg3_strictness; + +/* ====================================================================== + * Section 5: Foundation Types + * ====================================================================== */ + +typedef struct tg3_str { + const char *data; + uint32_t len; +} tg3_str; + +typedef struct tg3_span_i32 { + const int32_t *data; + uint32_t count; +} tg3_span_i32; + +typedef struct tg3_span_f64 { + const double *data; + uint32_t count; +} tg3_span_f64; + +typedef struct tg3_span_u8 { + const uint8_t *data; + uint64_t count; +} tg3_span_u8; + +typedef struct tg3_str_int_pair { + tg3_str key; + int32_t value; +} tg3_str_int_pair; + +/* ====================================================================== + * Section 6: Allocator Interface + * ====================================================================== */ + +typedef struct tg3_allocator { + void *(*alloc)(size_t size, void *user_data); + void *(*realloc)(void *ptr, size_t old_size, size_t new_size, void *user_data); + void (*free)(void *ptr, size_t size, void *user_data); + void *user_data; +} tg3_allocator; + +/* ====================================================================== + * Section 7: Error Reporting + * ====================================================================== */ + +typedef enum tg3_severity { + TG3_SEVERITY_INFO = 0, + TG3_SEVERITY_WARNING = 1, + TG3_SEVERITY_ERROR = 2 +} tg3_severity; + +typedef enum tg3_error_code { + TG3_OK = 0, + + /* I/O errors: 1-9 */ + TG3_ERR_FILE_NOT_FOUND = 1, + TG3_ERR_FILE_READ = 2, + TG3_ERR_FILE_WRITE = 3, + TG3_ERR_FILE_TOO_LARGE = 4, + + /* JSON errors: 10-19 */ + TG3_ERR_JSON_PARSE = 10, + TG3_ERR_JSON_TYPE_MISMATCH = 11, + TG3_ERR_JSON_MISSING_FIELD = 12, + TG3_ERR_JSON_INVALID_VALUE = 13, + + /* GLB errors: 20-29 */ + TG3_ERR_GLB_INVALID_MAGIC = 20, + TG3_ERR_GLB_INVALID_VERSION = 21, + TG3_ERR_GLB_INVALID_HEADER = 22, + TG3_ERR_GLB_CHUNK_ERROR = 23, + TG3_ERR_GLB_SIZE_MISMATCH = 24, + + /* Schema / validation errors: 30-49 */ + TG3_ERR_MISSING_REQUIRED = 30, + TG3_ERR_INVALID_INDEX = 31, + TG3_ERR_INVALID_TYPE = 32, + TG3_ERR_INVALID_VALUE = 33, + TG3_ERR_INVALID_ACCESSOR = 34, + TG3_ERR_INVALID_BUFFER = 35, + TG3_ERR_INVALID_BUFFER_VIEW = 36, + TG3_ERR_INVALID_IMAGE = 37, + TG3_ERR_INVALID_MATERIAL = 38, + TG3_ERR_INVALID_MESH = 39, + TG3_ERR_INVALID_NODE = 40, + TG3_ERR_INVALID_ANIMATION = 41, + TG3_ERR_INVALID_SKIN = 42, + TG3_ERR_INVALID_CAMERA = 43, + TG3_ERR_INVALID_SCENE = 44, + TG3_ERR_BUFFER_SIZE_MISMATCH = 45, + + /* Resource errors: 50-59 */ + TG3_ERR_OUT_OF_MEMORY = 50, + TG3_ERR_DATA_URI_DECODE = 51, + TG3_ERR_BASE64_DECODE = 52, + TG3_ERR_EXTERNAL_RESOURCE = 53, + TG3_ERR_IMAGE_DECODE = 54, + + /* Callback errors: 60-69 */ + TG3_ERR_CALLBACK_FAILED = 60, + TG3_ERR_FS_NOT_AVAILABLE = 61, + + /* Streaming errors: 70-79 */ + TG3_ERR_STREAM_ABORTED = 70, + + /* Writer errors: 80-89 */ + TG3_ERR_WRITE_FAILED = 80, + TG3_ERR_SERIALIZE_FAILED = 81 +} tg3_error_code; + +typedef struct tg3_error_entry { + tg3_severity severity; + tg3_error_code code; + const char *message; /* Arena-owned, null-terminated */ + const char *json_path; /* e.g. "/meshes/0/primitives/1" or NULL */ + int64_t byte_offset; /* -1 if unknown */ +} tg3_error_entry; + +typedef struct tg3_error_stack { + tg3_error_entry *entries; + uint32_t count; + uint32_t capacity; + int32_t has_error; /* 1 if any entry with severity == ERROR */ +} tg3_error_stack; + +/* Error stack query functions */ +TINYGLTF3_API int32_t tg3_errors_has_error(const tg3_error_stack *es); +TINYGLTF3_API uint32_t tg3_errors_count(const tg3_error_stack *es); +TINYGLTF3_API const tg3_error_entry *tg3_errors_get(const tg3_error_stack *es, + uint32_t index); + +/* ====================================================================== + * Section 8: Generic Value Type (for extras/extensions) + * ====================================================================== */ + +typedef enum tg3_value_type { + TG3_VALUE_NULL = 0, + TG3_VALUE_BOOL = 1, + TG3_VALUE_INT = 2, + TG3_VALUE_REAL = 3, + TG3_VALUE_STRING = 4, + TG3_VALUE_ARRAY = 5, + TG3_VALUE_BINARY = 6, + TG3_VALUE_OBJECT = 7 +} tg3_value_type; + +typedef struct tg3_kv_pair tg3_kv_pair; + +typedef struct tg3_value { + tg3_value_type type; + union { + int32_t bool_val; + int64_t int_val; + double real_val; + }; + tg3_str string_val; + const struct tg3_value *array_data; + uint32_t array_count; + const tg3_kv_pair *object_data; + uint32_t object_count; + tg3_span_u8 binary_val; +} tg3_value; + +struct tg3_kv_pair { + tg3_str key; + tg3_value value; +}; + +typedef struct tg3_extension { + tg3_str name; + tg3_value value; +} tg3_extension; + +typedef struct tg3_extras_ext { + const tg3_value *extras; /* NULL if absent */ + const tg3_extension *extensions; /* Array */ + uint32_t extensions_count; + tg3_str extras_json; /* Raw JSON if store_original_json */ + tg3_str extensions_json; +} tg3_extras_ext; + +/* ====================================================================== + * Section 9: Core POD Structs + * ====================================================================== */ + +/* --- Asset --- */ +typedef struct tg3_asset { + tg3_str version; /* Required, e.g. "2.0" */ + tg3_str generator; + tg3_str min_version; + tg3_str copyright; + tg3_extras_ext ext; +} tg3_asset; + +/* --- Buffer --- */ +typedef struct tg3_buffer { + tg3_str name; + uint64_t byte_length; /* Declared buffer.byteLength */ + tg3_span_u8 data; + tg3_str uri; + tg3_extras_ext ext; +} tg3_buffer; + +/* --- BufferView --- */ +typedef struct tg3_buffer_view { + tg3_str name; + int32_t buffer; /* Index, required */ + uint64_t byte_offset; + uint64_t byte_length; /* Required */ + uint32_t byte_stride; /* 0 = tightly packed */ + int32_t target; /* 0 = unspecified */ + int32_t draco_decoded; + tg3_extras_ext ext; +} tg3_buffer_view; + +/* --- Accessor Sparse --- */ +typedef struct tg3_accessor_sparse_indices { + uint64_t byte_offset; + int32_t buffer_view; /* Required */ + int32_t component_type; /* Required */ + tg3_extras_ext ext; +} tg3_accessor_sparse_indices; + +typedef struct tg3_accessor_sparse_values { + int32_t buffer_view; /* Required */ + uint64_t byte_offset; + tg3_extras_ext ext; +} tg3_accessor_sparse_values; + +typedef struct tg3_accessor_sparse { + int32_t count; /* Required if sparse */ + int32_t is_sparse; /* 0 or 1 */ + tg3_accessor_sparse_indices indices; + tg3_accessor_sparse_values values; + tg3_extras_ext ext; +} tg3_accessor_sparse; + +/* --- Accessor --- */ +typedef struct tg3_accessor { + tg3_str name; + int32_t buffer_view; /* -1 if absent */ + uint64_t byte_offset; + int32_t normalized; /* 0 or 1 */ + int32_t component_type; /* Required */ + uint64_t count; /* Required */ + int32_t type; /* Required: TG3_TYPE_* */ + const double *min_values; + uint32_t min_values_count; + const double *max_values; + uint32_t max_values_count; + tg3_accessor_sparse sparse; + tg3_extras_ext ext; +} tg3_accessor; + +/* --- Image --- */ +typedef struct tg3_image { + tg3_str name; + int32_t width; + int32_t height; + int32_t component; /* Channels */ + int32_t bits; /* Bits per channel */ + int32_t pixel_type; /* Component type */ + tg3_span_u8 image; /* Decoded pixel data (or raw if as_is) */ + int32_t buffer_view; /* -1 if absent */ + tg3_str mime_type; + tg3_str uri; + int32_t as_is; + tg3_extras_ext ext; +} tg3_image; + +/* --- Sampler --- */ +typedef struct tg3_sampler { + tg3_str name; + int32_t min_filter; /* -1 = unspecified */ + int32_t mag_filter; /* -1 = unspecified */ + int32_t wrap_s; /* Default: TG3_TEXTURE_WRAP_REPEAT */ + int32_t wrap_t; /* Default: TG3_TEXTURE_WRAP_REPEAT */ + tg3_extras_ext ext; +} tg3_sampler; + +/* --- Texture --- */ +typedef struct tg3_texture { + tg3_str name; + int32_t sampler; /* -1 if absent */ + int32_t source; /* -1 if absent */ + tg3_extras_ext ext; +} tg3_texture; + +/* --- TextureInfo --- */ +typedef struct tg3_texture_info { + int32_t index; /* -1 if absent */ + int32_t tex_coord; /* Default: 0 */ + tg3_extras_ext ext; +} tg3_texture_info; + +/* --- NormalTextureInfo --- */ +typedef struct tg3_normal_texture_info { + int32_t index; + int32_t tex_coord; + double scale; /* Default: 1.0 */ + tg3_extras_ext ext; +} tg3_normal_texture_info; + +/* --- OcclusionTextureInfo --- */ +typedef struct tg3_occlusion_texture_info { + int32_t index; + int32_t tex_coord; + double strength; /* Default: 1.0 */ + tg3_extras_ext ext; +} tg3_occlusion_texture_info; + +/* --- PBR Metallic Roughness --- */ +typedef struct tg3_pbr_metallic_roughness { + double base_color_factor[4]; /* Default: {1,1,1,1} */ + tg3_texture_info base_color_texture; + double metallic_factor; /* Default: 1.0 */ + double roughness_factor; /* Default: 1.0 */ + tg3_texture_info metallic_roughness_texture; + tg3_extras_ext ext; +} tg3_pbr_metallic_roughness; + +/* --- Material --- */ +typedef struct tg3_material { + tg3_str name; + double emissive_factor[3]; /* Default: {0,0,0} */ + tg3_str alpha_mode; /* "OPAQUE","MASK","BLEND" */ + double alpha_cutoff; /* Default: 0.5 */ + int32_t double_sided; /* 0 or 1 */ + const int32_t *lods; + uint32_t lods_count; + tg3_pbr_metallic_roughness pbr_metallic_roughness; + tg3_normal_texture_info normal_texture; + tg3_occlusion_texture_info occlusion_texture; + tg3_texture_info emissive_texture; + tg3_extras_ext ext; +} tg3_material; + +/* --- Primitive --- */ +typedef struct tg3_primitive { + const tg3_str_int_pair *attributes; + uint32_t attributes_count; + int32_t material; /* -1 if absent */ + int32_t indices; /* -1 if absent */ + int32_t mode; /* -1 = default (TRIANGLES) */ + + /* Morph targets: array of arrays of attribute pairs */ + const tg3_str_int_pair *const *targets; + const uint32_t *target_attribute_counts; + uint32_t targets_count; + + tg3_extras_ext ext; +} tg3_primitive; + +/* --- Mesh --- */ +typedef struct tg3_mesh { + tg3_str name; + const tg3_primitive *primitives; + uint32_t primitives_count; + const double *weights; + uint32_t weights_count; + tg3_extras_ext ext; +} tg3_mesh; + +/* --- Node --- */ +typedef struct tg3_node { + tg3_str name; + int32_t camera; /* -1 if absent */ + int32_t skin; /* -1 if absent */ + int32_t mesh; /* -1 if absent */ + int32_t light; /* -1 if absent (KHR_lights_punctual) */ + int32_t emitter; /* -1 if absent (KHR_audio) */ + + const int32_t *lods; + uint32_t lods_count; + const int32_t *children; + uint32_t children_count; + + double rotation[4]; /* Default: {0,0,0,1} */ + double scale[3]; /* Default: {1,1,1} */ + double translation[3]; /* Default: {0,0,0} */ + double matrix[16]; /* Identity if not set */ + int32_t has_matrix; /* 1 if matrix was specified */ + + const double *weights; + uint32_t weights_count; + + tg3_extras_ext ext; +} tg3_node; + +/* --- Skin --- */ +typedef struct tg3_skin { + tg3_str name; + int32_t inverse_bind_matrices; /* -1 if absent */ + int32_t skeleton; /* -1 if absent */ + const int32_t *joints; + uint32_t joints_count; + tg3_extras_ext ext; +} tg3_skin; + +/* --- Animation --- */ +typedef struct tg3_animation_channel_target { + int32_t node; /* -1 if absent */ + tg3_str path; /* "translation","rotation","scale","weights" */ + tg3_extras_ext ext; +} tg3_animation_channel_target; + +typedef struct tg3_animation_channel { + int32_t sampler; /* Required */ + tg3_animation_channel_target target; + tg3_extras_ext ext; +} tg3_animation_channel; + +typedef struct tg3_animation_sampler { + int32_t input; /* Required */ + int32_t output; /* Required */ + tg3_str interpolation; /* "LINEAR","STEP","CUBICSPLINE" */ + tg3_extras_ext ext; +} tg3_animation_sampler; + +typedef struct tg3_animation { + tg3_str name; + const tg3_animation_channel *channels; + uint32_t channels_count; + const tg3_animation_sampler *samplers; + uint32_t samplers_count; + tg3_extras_ext ext; +} tg3_animation; + +/* --- Camera --- */ +typedef struct tg3_perspective_camera { + double aspect_ratio; + double yfov; + double zfar; /* 0 = infinite */ + double znear; + tg3_extras_ext ext; +} tg3_perspective_camera; + +typedef struct tg3_orthographic_camera { + double xmag; + double ymag; + double zfar; + double znear; + tg3_extras_ext ext; +} tg3_orthographic_camera; + +typedef struct tg3_camera { + tg3_str name; + tg3_str type; /* "perspective" or "orthographic" */ + tg3_perspective_camera perspective; + tg3_orthographic_camera orthographic; + tg3_extras_ext ext; +} tg3_camera; + +/* --- Scene --- */ +typedef struct tg3_scene { + tg3_str name; + const int32_t *nodes; + uint32_t nodes_count; + const int32_t *audio_emitters; + uint32_t audio_emitters_count; + tg3_extras_ext ext; +} tg3_scene; + +/* --- Light (KHR_lights_punctual) --- */ +typedef struct tg3_spot_light { + double inner_cone_angle; /* Default: 0 */ + double outer_cone_angle; /* Default: PI/4 */ + tg3_extras_ext ext; +} tg3_spot_light; + +typedef struct tg3_light { + tg3_str name; + double color[3]; /* Default: {1,1,1} */ + double intensity; /* Default: 1.0 */ + tg3_str type; /* "directional","point","spot" */ + double range; /* Default: 0 (infinite) */ + tg3_spot_light spot; + tg3_extras_ext ext; +} tg3_light; + +/* --- Audio (KHR_audio) --- */ +typedef struct tg3_audio_source { + tg3_str name; + tg3_str uri; + int32_t buffer_view; /* -1 if absent */ + tg3_str mime_type; + tg3_extras_ext ext; +} tg3_audio_source; + +typedef struct tg3_positional_emitter { + double cone_inner_angle; /* Default: 2*PI */ + double cone_outer_angle; /* Default: 2*PI */ + double cone_outer_gain; /* Default: 0 */ + double max_distance; /* Default: 100 */ + double ref_distance; /* Default: 1 */ + double rolloff_factor; /* Default: 1 */ + tg3_extras_ext ext; +} tg3_positional_emitter; + +typedef struct tg3_audio_emitter { + tg3_str name; + double gain; /* Default: 1.0 */ + int32_t loop; /* Default: 0 */ + int32_t playing; /* Default: 0 */ + tg3_str type; /* "positional" or "global" */ + tg3_str distance_model; /* "linear","inverse","exponential" */ + tg3_positional_emitter positional; + int32_t source; /* -1 if absent */ + tg3_extras_ext ext; +} tg3_audio_emitter; + +/* ====================================================================== + * Section 10: Model Container + * ====================================================================== */ + +/* Opaque arena type */ +struct tg3_arena; + +typedef struct tg3_model { + struct tg3_arena *arena_; /* Internal, all memory owned here */ + + const tg3_accessor *accessors; uint32_t accessors_count; + const tg3_animation *animations; uint32_t animations_count; + const tg3_buffer *buffers; uint32_t buffers_count; + const tg3_buffer_view *buffer_views; uint32_t buffer_views_count; + const tg3_material *materials; uint32_t materials_count; + const tg3_mesh *meshes; uint32_t meshes_count; + const tg3_node *nodes; uint32_t nodes_count; + const tg3_texture *textures; uint32_t textures_count; + const tg3_image *images; uint32_t images_count; + const tg3_skin *skins; uint32_t skins_count; + const tg3_sampler *samplers; uint32_t samplers_count; + const tg3_camera *cameras; uint32_t cameras_count; + const tg3_scene *scenes; uint32_t scenes_count; + const tg3_light *lights; uint32_t lights_count; + const tg3_audio_emitter *audio_emitters; uint32_t audio_emitters_count; + const tg3_audio_source *audio_sources; uint32_t audio_sources_count; + + int32_t default_scene; + const tg3_str *extensions_used; uint32_t extensions_used_count; + const tg3_str *extensions_required; uint32_t extensions_required_count; + tg3_asset asset; + tg3_extras_ext ext; +} tg3_model; + +/* ====================================================================== + * Section 11: Callback Typedefs + * ====================================================================== */ + +/* --- Filesystem Callbacks --- */ + +typedef int32_t (*tg3_file_exists_fn)(const char *path, uint32_t path_len, + void *user_data); + +typedef int32_t (*tg3_read_file_fn)(uint8_t **out_data, uint64_t *out_size, + const char *path, uint32_t path_len, + void *user_data); + +typedef void (*tg3_free_file_fn)(uint8_t *data, uint64_t size, + void *user_data); + +typedef int32_t (*tg3_write_file_fn)(const char *path, uint32_t path_len, + const uint8_t *data, uint64_t size, + void *user_data); + +typedef int32_t (*tg3_resolve_path_fn)(char *out_path, uint32_t out_cap, + uint32_t *out_len, + const char *path, uint32_t path_len, + void *user_data); + +typedef int32_t (*tg3_get_file_size_fn)(uint64_t *out_size, + const char *path, uint32_t path_len, + void *user_data); + +typedef struct tg3_fs_callbacks { + tg3_file_exists_fn file_exists; + tg3_read_file_fn read_file; + tg3_free_file_fn free_file; + tg3_write_file_fn write_file; + tg3_resolve_path_fn resolve_path; + tg3_get_file_size_fn get_file_size; + void *user_data; +} tg3_fs_callbacks; + +/* --- Image Callbacks --- */ + +typedef struct tg3_image_request { + const uint8_t *data; + uint64_t data_size; + int32_t image_index; + int32_t req_width; + int32_t req_height; + const char *mime_type; +} tg3_image_request; + +typedef struct tg3_image_result { + uint8_t *pixels; /* Caller must allocate */ + int32_t width; + int32_t height; + int32_t component; + int32_t bits; + int32_t pixel_type; +} tg3_image_result; + +typedef int32_t (*tg3_load_image_fn)(tg3_image_result *result, + const tg3_image_request *request, + void *user_data); + +typedef void (*tg3_free_image_fn)(uint8_t *pixels, void *user_data); + +typedef struct tg3_image_callbacks { + tg3_load_image_fn load_image; + tg3_free_image_fn free_image; + void *user_data; +} tg3_image_callbacks; + +/* --- URI Callbacks --- */ + +typedef int32_t (*tg3_uri_encode_fn)(char *out, uint32_t out_cap, + uint32_t *out_len, + const char *uri, uint32_t uri_len, + const char *obj_type, + void *user_data); + +typedef int32_t (*tg3_uri_decode_fn)(char *out, uint32_t out_cap, + uint32_t *out_len, + const char *uri, uint32_t uri_len, + void *user_data); + +typedef struct tg3_uri_callbacks { + tg3_uri_encode_fn encode; + tg3_uri_decode_fn decode; + void *user_data; +} tg3_uri_callbacks; + +/* --- Streaming Callbacks --- */ + +typedef enum tg3_stream_action { + TG3_STREAM_CONTINUE = 0, + TG3_STREAM_ABORT = 1, + TG3_STREAM_SKIP = 2 +} tg3_stream_action; + +typedef tg3_stream_action (*tg3_on_asset_fn)(const tg3_asset *a, void *ud); +typedef tg3_stream_action (*tg3_on_buffer_fn)(const tg3_buffer *b, int32_t idx, void *ud); +typedef tg3_stream_action (*tg3_on_buffer_view_fn)(const tg3_buffer_view *bv, int32_t idx, void *ud); +typedef tg3_stream_action (*tg3_on_accessor_fn)(const tg3_accessor *a, int32_t idx, void *ud); +typedef tg3_stream_action (*tg3_on_mesh_fn)(const tg3_mesh *m, int32_t idx, void *ud); +typedef tg3_stream_action (*tg3_on_node_fn)(const tg3_node *n, int32_t idx, void *ud); +typedef tg3_stream_action (*tg3_on_material_fn)(const tg3_material *m, int32_t idx, void *ud); +typedef tg3_stream_action (*tg3_on_texture_fn)(const tg3_texture *t, int32_t idx, void *ud); +typedef tg3_stream_action (*tg3_on_image_fn)(const tg3_image *img, int32_t idx, void *ud); +typedef tg3_stream_action (*tg3_on_sampler_fn)(const tg3_sampler *s, int32_t idx, void *ud); +typedef tg3_stream_action (*tg3_on_animation_fn)(const tg3_animation *a, int32_t idx, void *ud); +typedef tg3_stream_action (*tg3_on_skin_fn)(const tg3_skin *s, int32_t idx, void *ud); +typedef tg3_stream_action (*tg3_on_camera_fn)(const tg3_camera *c, int32_t idx, void *ud); +typedef tg3_stream_action (*tg3_on_scene_fn)(const tg3_scene *s, int32_t idx, void *ud); +typedef tg3_stream_action (*tg3_on_light_fn)(const tg3_light *l, int32_t idx, void *ud); + +typedef struct tg3_stream_callbacks { + tg3_on_asset_fn on_asset; + tg3_on_buffer_fn on_buffer; + tg3_on_buffer_view_fn on_buffer_view; + tg3_on_accessor_fn on_accessor; + tg3_on_mesh_fn on_mesh; + tg3_on_node_fn on_node; + tg3_on_material_fn on_material; + tg3_on_texture_fn on_texture; + tg3_on_image_fn on_image; + tg3_on_sampler_fn on_sampler; + tg3_on_animation_fn on_animation; + tg3_on_skin_fn on_skin; + tg3_on_camera_fn on_camera; + tg3_on_scene_fn on_scene; + tg3_on_light_fn on_light; + void *user_data; +} tg3_stream_callbacks; + +/* --- Progress Callback --- */ + +typedef struct tg3_progress_info { + uint64_t bytes_processed; + uint64_t bytes_total; + uint32_t elements_parsed; + const char *current_section; /* e.g. "meshes", "nodes" */ +} tg3_progress_info; + +typedef int32_t (*tg3_progress_fn)(const tg3_progress_info *info, + void *user_data); + +/* --- Write Chunk Callback (for streaming writer) --- */ + +typedef int32_t (*tg3_write_chunk_fn)(const uint8_t *data, uint64_t size, + void *user_data); + +/* ====================================================================== + * Section 12: Options Structs + * ====================================================================== */ + +typedef struct tg3_memory_config { + uint64_t memory_budget; /* 0 = use TINYGLTF3_MAX_MEMORY_BYTES */ + uint64_t max_single_alloc; /* 0 = no limit */ + uint32_t arena_block_size; /* 0 = default (256KB) */ + tg3_allocator allocator; /* All zero = use malloc/free */ +} tg3_memory_config; + +typedef struct tg3_parse_options { + uint32_t required_sections; /* TG3_REQUIRE_* flags */ + tg3_strictness strictness; + tg3_memory_config memory; + + tg3_fs_callbacks fs; + tg3_uri_callbacks uri; + tg3_image_callbacks image; + tg3_stream_callbacks *stream; /* NULL = no streaming */ + tg3_progress_fn progress; + void *progress_user_data; + + int32_t images_as_is; /* 1 = don't decode images */ + int32_t preserve_image_channels; /* 1 = keep original channels */ + int32_t store_original_json; /* 1 = store raw JSON strings */ + int32_t skip_extras_values; /* 1 = skip materializing extras and + * unknown extension value trees */ + int32_t borrow_input_buffers; /* 1 = GLB BIN buffer spans may point + * into caller-owned input data */ + int32_t parse_float32; /* 1 = parse JSON floats as float32 for speed + * (breaks strict double-precision conformance + * but sufficient for glTF data which is + * typically single-precision anyway) */ + int32_t validate_indices; /* 1 = reject out-of-range index fields + * after parse so naive consumers cannot + * dereference attacker-controlled indices. + * Default: 1. Set to 0 to skip (raw mode). */ + uint64_t max_external_file_size; /* 0 = no limit */ +} tg3_parse_options; + +typedef struct tg3_write_options { + int32_t pretty_print; /* 1 = indented JSON */ + int32_t write_binary; /* 1 = GLB format */ + int32_t embed_images; /* 1 = embed as data URIs */ + int32_t embed_buffers; /* 1 = embed as data URIs */ + int32_t serialize_defaults; /* 1 = write default values */ + tg3_fs_callbacks fs; + tg3_uri_callbacks uri; + tg3_memory_config memory; +} tg3_write_options; + +/* ====================================================================== + * Section 13: Parser API + * ====================================================================== */ + +/* Parse JSON glTF from memory */ +TINYGLTF3_API tg3_error_code tg3_parse( + tg3_model *model, tg3_error_stack *errors, + const uint8_t *json_data, uint64_t json_size, + const char *base_dir, uint32_t base_dir_len, + const tg3_parse_options *options); + +/* Parse GLB from memory */ +TINYGLTF3_API tg3_error_code tg3_parse_glb( + tg3_model *model, tg3_error_stack *errors, + const uint8_t *glb_data, uint64_t glb_size, + const char *base_dir, uint32_t base_dir_len, + const tg3_parse_options *options); + +/* Auto-detect format (JSON or GLB) and parse */ +TINYGLTF3_API tg3_error_code tg3_parse_auto( + tg3_model *model, tg3_error_stack *errors, + const uint8_t *data, uint64_t size, + const char *base_dir, uint32_t base_dir_len, + const tg3_parse_options *options); + +/* Parse from file (requires fs callbacks or TINYGLTF3_ENABLE_FS) */ +TINYGLTF3_API tg3_error_code tg3_parse_file( + tg3_model *model, tg3_error_stack *errors, + const char *filename, uint32_t filename_len, + const tg3_parse_options *options); + +/* Free model and all arena memory */ +TINYGLTF3_API void tg3_model_free(tg3_model *model); + +/* Initialize options to defaults */ +TINYGLTF3_API void tg3_parse_options_init(tg3_parse_options *options); +TINYGLTF3_API void tg3_write_options_init(tg3_write_options *options); + +/* Initialize error stack */ +TINYGLTF3_API void tg3_error_stack_init(tg3_error_stack *es); +TINYGLTF3_API void tg3_error_stack_free(tg3_error_stack *es); + +/* ====================================================================== + * Section 14: Writer API + * ====================================================================== */ + +/* Write model to memory buffer */ +TINYGLTF3_API tg3_error_code tg3_write_to_memory( + const tg3_model *model, tg3_error_stack *errors, + uint8_t **out_data, uint64_t *out_size, + const tg3_write_options *options); + +/* Write model to file */ +TINYGLTF3_API tg3_error_code tg3_write_to_file( + const tg3_model *model, tg3_error_stack *errors, + const char *filename, uint32_t filename_len, + const tg3_write_options *options); + +/* Free memory from tg3_write_to_memory */ +TINYGLTF3_API void tg3_write_free(uint8_t *data, const tg3_write_options *options); + +/* --- Streaming Writer --- */ + +typedef struct tg3_writer tg3_writer; + +TINYGLTF3_API tg3_writer *tg3_writer_create( + tg3_write_chunk_fn chunk_fn, void *user_data, + const tg3_write_options *options); + +TINYGLTF3_API tg3_error_code tg3_writer_begin(tg3_writer *w, const tg3_asset *asset); +TINYGLTF3_API tg3_error_code tg3_writer_add_buffer(tg3_writer *w, const tg3_buffer *buf); +TINYGLTF3_API tg3_error_code tg3_writer_add_buffer_view(tg3_writer *w, const tg3_buffer_view *bv); +TINYGLTF3_API tg3_error_code tg3_writer_add_accessor(tg3_writer *w, const tg3_accessor *acc); +TINYGLTF3_API tg3_error_code tg3_writer_add_mesh(tg3_writer *w, const tg3_mesh *mesh); +TINYGLTF3_API tg3_error_code tg3_writer_add_node(tg3_writer *w, const tg3_node *node); +TINYGLTF3_API tg3_error_code tg3_writer_add_material(tg3_writer *w, const tg3_material *mat); +TINYGLTF3_API tg3_error_code tg3_writer_add_texture(tg3_writer *w, const tg3_texture *tex); +TINYGLTF3_API tg3_error_code tg3_writer_add_image(tg3_writer *w, const tg3_image *img); +TINYGLTF3_API tg3_error_code tg3_writer_add_sampler(tg3_writer *w, const tg3_sampler *samp); +TINYGLTF3_API tg3_error_code tg3_writer_add_animation(tg3_writer *w, const tg3_animation *anim); +TINYGLTF3_API tg3_error_code tg3_writer_add_skin(tg3_writer *w, const tg3_skin *skin); +TINYGLTF3_API tg3_error_code tg3_writer_add_camera(tg3_writer *w, const tg3_camera *cam); +TINYGLTF3_API tg3_error_code tg3_writer_add_scene(tg3_writer *w, const tg3_scene *scene); +TINYGLTF3_API tg3_error_code tg3_writer_add_light(tg3_writer *w, const tg3_light *light); +TINYGLTF3_API tg3_error_code tg3_writer_end(tg3_writer *w); +TINYGLTF3_API void tg3_writer_destroy(tg3_writer *w); + +/* ====================================================================== + * Section 15: Utility Functions + * ====================================================================== */ + +/* Get component size in bytes */ +TINYGLTF3_API int32_t tg3_component_size(int32_t component_type); + +/* Get number of components for a type */ +TINYGLTF3_API int32_t tg3_num_components(int32_t type); + +/* Compute byte stride for an accessor */ +TINYGLTF3_API int32_t tg3_accessor_byte_stride(const tg3_accessor *accessor, + const tg3_buffer_view *buffer_view); + +/* Check if a string is a data URI */ +TINYGLTF3_API int32_t tg3_is_data_uri(const char *uri, uint32_t len); + +/* tg3_str helpers */ +TINYGLTF3_API int32_t tg3_str_equals(tg3_str a, tg3_str b); +TINYGLTF3_API int32_t tg3_str_equals_cstr(tg3_str a, const char *b); + +#ifdef __cplusplus +} /* extern "C" */ +#endif + +/* ====================================================================== + * Section 16: C++ Convenience Wrappers + * ====================================================================== */ + +#ifdef __cplusplus +namespace tinygltf3 { + +/* RAII model wrapper */ +class Model { +public: + Model() { memset(&m_, 0, sizeof(m_)); m_.default_scene = -1; } + ~Model() { tg3_model_free(&m_); } + + Model(const Model &) = delete; + Model &operator=(const Model &) = delete; + Model(Model &&o) noexcept : m_(o.m_) { memset(&o.m_, 0, sizeof(o.m_)); } + Model &operator=(Model &&o) noexcept { + if (this != &o) { tg3_model_free(&m_); m_ = o.m_; memset(&o.m_, 0, sizeof(o.m_)); } + return *this; + } + + tg3_model *get() { return &m_; } + const tg3_model *get() const { return &m_; } + tg3_model *operator->() { return &m_; } + const tg3_model *operator->() const { return &m_; } + +private: + tg3_model m_; +}; + +/* RAII error stack wrapper */ +class ErrorStack { +public: + ErrorStack() { tg3_error_stack_init(&es_); } + ~ErrorStack() { tg3_error_stack_free(&es_); } + + ErrorStack(const ErrorStack &) = delete; + ErrorStack &operator=(const ErrorStack &) = delete; + + tg3_error_stack *get() { return &es_; } + const tg3_error_stack *get() const { return &es_; } + + bool has_error() const { return tg3_errors_has_error(&es_) != 0; } + uint32_t count() const { return tg3_errors_count(&es_); } + const tg3_error_entry *entry(uint32_t i) const { return tg3_errors_get(&es_, i); } + +private: + tg3_error_stack es_; +}; + +/* Parse helpers returning error code */ +inline tg3_error_code parse_file(Model &model, ErrorStack &errors, + const char *filename, + const tg3_parse_options *options = nullptr) { + tg3_parse_options opts; + if (!options) { tg3_parse_options_init(&opts); options = &opts; } + return tg3_parse_file(model.get(), errors.get(), filename, + filename ? (uint32_t)strlen(filename) : 0, options); +} + +inline tg3_error_code parse(Model &model, ErrorStack &errors, + const uint8_t *data, uint64_t size, + const char *base_dir = "", + const tg3_parse_options *options = nullptr) { + tg3_parse_options opts; + if (!options) { tg3_parse_options_init(&opts); options = &opts; } + return tg3_parse_auto(model.get(), errors.get(), data, size, + base_dir, base_dir ? (uint32_t)strlen(base_dir) : 0, + options); +} + +} /* namespace tinygltf3 */ +#endif /* __cplusplus */ + +/* ====================================================================== + * Section 17: C++20 Coroutine Facade + * ====================================================================== */ + +#ifdef __cplusplus +#if defined(TINYGLTF3_ENABLE_COROUTINES) || \ + (defined(__cpp_impl_coroutine) && __cpp_impl_coroutine >= 201902L && \ + defined(__cpp_lib_coroutine) && __cpp_lib_coroutine >= 201902L) + +#include + +namespace tinygltf3 { + +struct ParsedElement { + enum Kind { + Asset, Buffer, BufferView, Accessor, Mesh, Node, Material, + Texture, Image, Sampler, Animation, Skin, Camera, Scene, + Light, Done, Error + }; + + Kind kind; + int32_t index; + + union { + const tg3_asset *asset; + const tg3_buffer *buffer; + const tg3_buffer_view *buffer_view; + const tg3_accessor *accessor; + const tg3_mesh *mesh; + const tg3_node *node; + const tg3_material *material; + const tg3_texture *texture; + const tg3_image *image; + const tg3_sampler *sampler; + const tg3_animation *animation; + const tg3_skin *skin; + const tg3_camera *camera; + const tg3_scene *scene; + const tg3_light *light; + const void *ptr; + }; + + tg3_error_code error_code; +}; + +class ParseGenerator { +public: + struct promise_type { + ParsedElement current_; + std::suspend_always initial_suspend() noexcept { return {}; } + std::suspend_always final_suspend() noexcept { return {}; } + ParseGenerator get_return_object() { + return ParseGenerator( + std::coroutine_handle::from_promise(*this)); + } + std::suspend_always yield_value(ParsedElement elem) noexcept { + current_ = elem; + return {}; + } + void return_void() {} + void unhandled_exception() {} + }; + + ParseGenerator() : handle_(nullptr) {} + explicit ParseGenerator(std::coroutine_handle h) : handle_(h) {} + ~ParseGenerator() { if (handle_) handle_.destroy(); } + + ParseGenerator(const ParseGenerator &) = delete; + ParseGenerator &operator=(const ParseGenerator &) = delete; + ParseGenerator(ParseGenerator &&o) noexcept : handle_(o.handle_) { o.handle_ = nullptr; } + ParseGenerator &operator=(ParseGenerator &&o) noexcept { + if (this != &o) { if (handle_) handle_.destroy(); handle_ = o.handle_; o.handle_ = nullptr; } + return *this; + } + + bool next() { + if (!handle_ || handle_.done()) return false; + handle_.resume(); + return !handle_.done(); + } + + const ParsedElement ¤t() const { return handle_.promise().current_; } + bool done() const { return !handle_ || handle_.done(); } + +private: + std::coroutine_handle handle_; +}; + +/* Coroutine parse entry point — declaration only, implemented in TINYGLTF3_IMPLEMENTATION */ +ParseGenerator tg3_parse_coro( + const uint8_t *data, uint64_t size, + const char *base_dir, uint32_t base_dir_len, + tg3_model *model, tg3_error_stack *errors, + const tg3_parse_options *options); + +} /* namespace tinygltf3 */ + +#endif /* coroutines */ +#endif /* __cplusplus */ + +/* ====================================================================== + * Section 18: Implementation + * ====================================================================== */ + +#ifdef TINYGLTF3_IMPLEMENTATION +#define TINYGLTF3_SOURCE_INCLUDED_FROM_HEADER 1 +#include "tiny_gltf_v3.c" +#undef TINYGLTF3_SOURCE_INCLUDED_FROM_HEADER + +#if 0 + +#if !defined(__cplusplus) +#error "TINYGLTF3_IMPLEMENTATION requires a C++ translation unit (compile as .cpp)" +#endif + +/* Include JSON parser */ +#include "tinygltf_json.h" + +#include +#include + +/* Implementation uses C++ features from tinygltf_json.h */ +#include +#include + +/* Forward SIMD macros to tinygltf_json.h */ +#ifdef TINYGLTF3_JSON_SIMD_SSE2 +#ifndef TINYGLTF_JSON_SIMD_SSE2 +#define TINYGLTF_JSON_SIMD_SSE2 +#endif +#endif +#ifdef TINYGLTF3_JSON_SIMD_AVX2 +#ifndef TINYGLTF_JSON_SIMD_AVX2 +#define TINYGLTF_JSON_SIMD_AVX2 +#endif +#endif +#ifdef TINYGLTF3_JSON_SIMD_NEON +#ifndef TINYGLTF_JSON_SIMD_NEON +#define TINYGLTF_JSON_SIMD_NEON +#endif +#endif + +/* ====================================================================== + * Internal: Arena Allocator + * ====================================================================== */ + +#define TG3__ARENA_DEFAULT_BLOCK_SIZE (256u * 1024u) /* 256 KB */ +#define TG3__ARENA_ALIGNMENT 8 + +typedef struct tg3__arena_block { + struct tg3__arena_block *next; + uint8_t *base; + size_t used; + size_t capacity; +} tg3__arena_block; + +struct tg3_arena { + tg3__arena_block *head; + tg3__arena_block *current; + size_t total_allocated; + size_t memory_budget; + size_t block_size; + tg3_allocator alloc; +}; + +static void *tg3__default_alloc(size_t size, void *ud) { + (void)ud; + return malloc(size); +} +static void *tg3__default_realloc(void *ptr, size_t old_size, size_t new_size, void *ud) { + (void)old_size; (void)ud; + return realloc(ptr, new_size); +} +static void tg3__default_free(void *ptr, size_t size, void *ud) { + (void)size; (void)ud; + free(ptr); +} + +static tg3_arena *tg3__arena_create(const tg3_memory_config *config) { + tg3_allocator alloc; + if (config && config->allocator.alloc) { + alloc = config->allocator; + } else { + alloc.alloc = tg3__default_alloc; + alloc.realloc = tg3__default_realloc; + alloc.free = tg3__default_free; + alloc.user_data = NULL; + } + + tg3_arena *arena = (tg3_arena *)alloc.alloc(sizeof(tg3_arena), alloc.user_data); + if (!arena) return NULL; + + memset(arena, 0, sizeof(tg3_arena)); + arena->alloc = alloc; + arena->block_size = (config && config->arena_block_size > 0) + ? config->arena_block_size : TG3__ARENA_DEFAULT_BLOCK_SIZE; + arena->memory_budget = (config && config->memory_budget > 0) + ? (size_t)config->memory_budget : (size_t)TINYGLTF3_MAX_MEMORY_BYTES; + + return arena; +} + +static tg3__arena_block *tg3__arena_new_block(tg3_arena *arena, size_t min_size) { + size_t cap = arena->block_size; + if (cap < min_size) cap = min_size; + + if (arena->total_allocated + sizeof(tg3__arena_block) + cap > arena->memory_budget) { + return NULL; /* OOM */ + } + + uint8_t *raw = (uint8_t *)arena->alloc.alloc( + sizeof(tg3__arena_block) + cap, arena->alloc.user_data); + if (!raw) return NULL; + + tg3__arena_block *block = (tg3__arena_block *)raw; + block->base = raw + sizeof(tg3__arena_block); + block->used = 0; + block->capacity = cap; + block->next = NULL; + + arena->total_allocated += sizeof(tg3__arena_block) + cap; + + if (arena->current) { + arena->current->next = block; + } else { + arena->head = block; + } + arena->current = block; + + return block; +} + +static void *tg3__arena_alloc(tg3_arena *arena, size_t size) { + if (size == 0) return NULL; + + /* Align up */ + size = (size + (TG3__ARENA_ALIGNMENT - 1)) & ~(size_t)(TG3__ARENA_ALIGNMENT - 1); + + tg3__arena_block *block = arena->current; + if (!block || block->used + size > block->capacity) { + block = tg3__arena_new_block(arena, size); + if (!block) return NULL; + } + + void *ptr = block->base + block->used; + block->used += size; + return ptr; +} + +static char *tg3__arena_strdup(tg3_arena *arena, const char *s, size_t len) { + if (!s) return NULL; + /* Allocate len+1 bytes; when len==0 this produces a 1-byte "\0" buffer so + * that empty strings (data!=NULL, len==0) remain distinguishable from + * absent strings (data==NULL, len==0). */ + char *dst = (char *)tg3__arena_alloc(arena, len + 1); + if (!dst) return NULL; + if (len > 0) memcpy(dst, s, len); + dst[len] = '\0'; + return dst; +} + +static tg3_str tg3__arena_str(tg3_arena *arena, const char *s, uint32_t len) { + tg3_str result; + result.data = tg3__arena_strdup(arena, s, len); + result.len = result.data ? len : 0; + return result; +} + +static tg3_str tg3__arena_str_from_std(tg3_arena *arena, const std::string &s) { + return tg3__arena_str(arena, s.c_str(), (uint32_t)s.size()); +} + +static void tg3__arena_destroy(tg3_arena *arena) { + if (!arena) return; + tg3_allocator alloc = arena->alloc; + tg3__arena_block *block = arena->head; + while (block) { + tg3__arena_block *next = block->next; + size_t block_total = sizeof(tg3__arena_block) + block->capacity; + alloc.free(block, block_total, alloc.user_data); + block = next; + } + alloc.free(arena, sizeof(tg3_arena), alloc.user_data); +} + +/* ====================================================================== + * Internal: Error Stack Implementation + * ====================================================================== */ + +static void tg3__error_push(tg3_error_stack *es, tg3_severity sev, + tg3_error_code code, const char *msg, + const char *json_path, int64_t byte_offset) { + if (!es) return; + + if (es->count >= es->capacity) { + uint32_t new_cap = es->capacity ? es->capacity * 2 : 16; + tg3_error_entry *new_entries = (tg3_error_entry *)realloc( + es->entries, new_cap * sizeof(tg3_error_entry)); + if (!new_entries) return; /* Drop error on OOM */ + es->entries = new_entries; + es->capacity = new_cap; + } + + tg3_error_entry *e = &es->entries[es->count++]; + e->severity = sev; + e->code = code; + e->message = msg; /* Caller must ensure lifetime (arena or static) */ + e->json_path = json_path; + e->byte_offset = byte_offset; + + if (sev == TG3_SEVERITY_ERROR) es->has_error = 1; +} + +/* Push an error with a dynamically formatted message allocated from arena */ +static void tg3__error_pushf(tg3_error_stack *es, tg3_arena *arena, + tg3_severity sev, tg3_error_code code, + const char *json_path, const char *fmt, ...) { + if (!es) return; + char buf[1024]; + va_list ap; + va_start(ap, fmt); + int n = vsnprintf(buf, sizeof(buf), fmt, ap); + va_end(ap); + if (n < 0) n = 0; + if ((size_t)n >= sizeof(buf)) n = (int)(sizeof(buf) - 1); + + const char *msg = buf; + if (arena) { + char *dup = tg3__arena_strdup(arena, buf, (size_t)n); + if (dup) msg = dup; + } + tg3__error_push(es, sev, code, msg, json_path, -1); +} + +/* ====================================================================== + * Public: Error Stack API + * ====================================================================== */ + +TINYGLTF3_API int32_t tg3_errors_has_error(const tg3_error_stack *es) { + return es ? es->has_error : 0; +} + +TINYGLTF3_API uint32_t tg3_errors_count(const tg3_error_stack *es) { + return es ? es->count : 0; +} + +TINYGLTF3_API const tg3_error_entry *tg3_errors_get(const tg3_error_stack *es, + uint32_t index) { + if (!es || index >= es->count) return NULL; + return &es->entries[index]; +} + +TINYGLTF3_API void tg3_error_stack_init(tg3_error_stack *es) { + if (!es) return; + memset(es, 0, sizeof(tg3_error_stack)); +} + +TINYGLTF3_API void tg3_error_stack_free(tg3_error_stack *es) { + if (!es) return; + free(es->entries); + memset(es, 0, sizeof(tg3_error_stack)); +} + +/* ====================================================================== + * Public: Options Init + * ====================================================================== */ + +TINYGLTF3_API void tg3_parse_options_init(tg3_parse_options *options) { + if (!options) return; + memset(options, 0, sizeof(tg3_parse_options)); + options->required_sections = TG3_REQUIRE_VERSION; + options->strictness = TG3_PERMISSIVE; +} + +TINYGLTF3_API void tg3_write_options_init(tg3_write_options *options) { + if (!options) return; + memset(options, 0, sizeof(tg3_write_options)); + options->pretty_print = 1; +} + +/* ====================================================================== + * Public: Utility Functions + * ====================================================================== */ + +TINYGLTF3_API int32_t tg3_component_size(int32_t component_type) { + switch (component_type) { + case TG3_COMPONENT_TYPE_BYTE: return 1; + case TG3_COMPONENT_TYPE_UNSIGNED_BYTE: return 1; + case TG3_COMPONENT_TYPE_SHORT: return 2; + case TG3_COMPONENT_TYPE_UNSIGNED_SHORT: return 2; + case TG3_COMPONENT_TYPE_INT: return 4; + case TG3_COMPONENT_TYPE_UNSIGNED_INT: return 4; + case TG3_COMPONENT_TYPE_FLOAT: return 4; + case TG3_COMPONENT_TYPE_DOUBLE: return 8; + default: return -1; + } +} + +TINYGLTF3_API int32_t tg3_num_components(int32_t type) { + switch (type) { + case TG3_TYPE_SCALAR: return 1; + case TG3_TYPE_VEC2: return 2; + case TG3_TYPE_VEC3: return 3; + case TG3_TYPE_VEC4: return 4; + case TG3_TYPE_MAT2: return 4; + case TG3_TYPE_MAT3: return 9; + case TG3_TYPE_MAT4: return 16; + default: return -1; + } +} + +TINYGLTF3_API int32_t tg3_accessor_byte_stride(const tg3_accessor *accessor, + const tg3_buffer_view *bv) { + if (bv && bv->byte_stride > 0) return (int32_t)bv->byte_stride; + int32_t comp = tg3_component_size(accessor->component_type); + int32_t num = tg3_num_components(accessor->type); + if (comp < 0 || num < 0) return -1; + return comp * num; +} + +TINYGLTF3_API int32_t tg3_str_equals(tg3_str a, tg3_str b) { + if (a.len != b.len) return 0; + if (a.len == 0) return 1; + return memcmp(a.data, b.data, a.len) == 0 ? 1 : 0; +} + +TINYGLTF3_API int32_t tg3_str_equals_cstr(tg3_str a, const char *b) { + if (!b) return a.len == 0 ? 1 : 0; + uint32_t blen = (uint32_t)strlen(b); + if (a.len != blen) return 0; + if (a.len == 0) return 1; + return memcmp(a.data, b, a.len) == 0 ? 1 : 0; +} + +/* ====================================================================== + * Internal: Base64 Encode/Decode + * ====================================================================== */ + +static const char tg3__b64_chars[] = + "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/"; + +static int tg3__b64_is_valid(unsigned char c) { + return (c >= 'A' && c <= 'Z') || (c >= 'a' && c <= 'z') || + (c >= '0' && c <= '9') || c == '+' || c == '/' || c == '='; +} + +static int tg3__b64_decode_char(unsigned char c) { + if (c >= 'A' && c <= 'Z') return c - 'A'; + if (c >= 'a' && c <= 'z') return c - 'a' + 26; + if (c >= '0' && c <= '9') return c - '0' + 52; + if (c == '+') return 62; + if (c == '/') return 63; + return -1; +} + +static uint8_t *tg3__b64_decode(const char *input, size_t input_len, + size_t *out_len, tg3_arena *arena) { + if (input_len == 0) { *out_len = 0; return NULL; } + + /* Strip trailing padding */ + size_t pad = 0; + while (input_len > 0 && input[input_len - 1] == '=') { ++pad; --input_len; } + + size_t decoded_len = (input_len * 3) / 4; + uint8_t *out = (uint8_t *)tg3__arena_alloc(arena, decoded_len + 1); + if (!out) { *out_len = 0; return NULL; } + + size_t j = 0; + uint32_t accum = 0; + int bits = 0; + + for (size_t i = 0; i < input_len; ++i) { + int val = tg3__b64_decode_char((unsigned char)input[i]); + if (val < 0) continue; /* skip whitespace/invalid */ + accum = (accum << 6) | (uint32_t)val; + bits += 6; + if (bits >= 8) { + bits -= 8; + out[j++] = (uint8_t)((accum >> bits) & 0xFF); + } + } + + *out_len = j; + return out; +} + +static char *tg3__b64_encode(const uint8_t *input, size_t input_len, + size_t *out_len) { + size_t enc_len = ((input_len + 2) / 3) * 4; + char *out = (char *)malloc(enc_len + 1); + if (!out) { *out_len = 0; return NULL; } + + size_t j = 0; + for (size_t i = 0; i < input_len; i += 3) { + uint32_t a = input[i]; + uint32_t b = (i + 1 < input_len) ? input[i + 1] : 0; + uint32_t c = (i + 2 < input_len) ? input[i + 2] : 0; + uint32_t triple = (a << 16) | (b << 8) | c; + + out[j++] = tg3__b64_chars[(triple >> 18) & 0x3F]; + out[j++] = tg3__b64_chars[(triple >> 12) & 0x3F]; + out[j++] = (i + 1 < input_len) ? tg3__b64_chars[(triple >> 6) & 0x3F] : '='; + out[j++] = (i + 2 < input_len) ? tg3__b64_chars[triple & 0x3F] : '='; + } + out[j] = '\0'; + *out_len = j; + return out; +} + +/* ====================================================================== + * Internal: Data URI Handling + * ====================================================================== */ + +TINYGLTF3_API int32_t tg3_is_data_uri(const char *uri, uint32_t len) { + if (len < 5) return 0; + return (memcmp(uri, "data:", 5) == 0) ? 1 : 0; +} + +typedef struct tg3__data_uri_result { + const char *data_start; + size_t data_len; + char mime_type[64]; +} tg3__data_uri_result; + +static int tg3__parse_data_uri(const char *uri, uint32_t uri_len, + tg3__data_uri_result *result) { + /* Expected format: data:;base64, */ + if (uri_len < 5 || memcmp(uri, "data:", 5) != 0) return 0; + + const char *p = uri + 5; + const char *end = uri + uri_len; + + /* Find semicolon */ + const char *semi = p; + while (semi < end && *semi != ';') ++semi; + if (semi >= end) return 0; + + /* Extract MIME type */ + size_t mime_len = (size_t)(semi - p); + if (mime_len >= sizeof(result->mime_type)) mime_len = sizeof(result->mime_type) - 1; + memcpy(result->mime_type, p, mime_len); + result->mime_type[mime_len] = '\0'; + + /* Skip ";base64," */ + p = semi + 1; + if (end - p < 7 || memcmp(p, "base64,", 7) != 0) return 0; + p += 7; + + result->data_start = p; + result->data_len = (size_t)(end - p); + return 1; +} + +static uint8_t *tg3__decode_data_uri(tg3_arena *arena, const char *uri, + uint32_t uri_len, size_t *out_len, + char *out_mime, size_t out_mime_cap) { + tg3__data_uri_result dr; + if (!tg3__parse_data_uri(uri, uri_len, &dr)) { + *out_len = 0; + return NULL; + } + + if (out_mime && out_mime_cap > 0) { + size_t mlen = strlen(dr.mime_type); + if (mlen >= out_mime_cap) mlen = out_mime_cap - 1; + memcpy(out_mime, dr.mime_type, mlen); + out_mime[mlen] = '\0'; + } + + return tg3__b64_decode(dr.data_start, dr.data_len, out_len, arena); +} + +/* ====================================================================== + * Internal: Parse Context + * ====================================================================== */ + +typedef struct tg3__parse_ctx { + tg3_arena *arena; + tg3_error_stack *errors; + tg3_parse_options opts; + const char *base_dir; + uint32_t base_dir_len; + + /* GLB binary chunk */ + const uint8_t *bin_data; + uint64_t bin_size; + int32_t is_binary; +} tg3__parse_ctx; + +/* ====================================================================== + * Internal: JSON Property Helpers + * ====================================================================== */ + +/* Type alias for JSON */ +typedef tinygltf_json tg3__json; + +static int tg3__json_has(const tg3__json &o, const char *key) { + auto it = o.find(key); + return (it != o.end()) ? 1 : 0; +} + +static int tg3__parse_string(tg3__parse_ctx *ctx, const tg3__json &o, + const char *key, tg3_str *out, + int required, const char *parent) { + auto it = o.find(key); + if (it == o.end()) { + if (required) { + tg3__error_pushf(ctx->errors, ctx->arena, TG3_SEVERITY_ERROR, + TG3_ERR_JSON_MISSING_FIELD, parent, + "Missing required field '%s'", key); + return 0; + } + out->data = NULL; out->len = 0; + return 1; + } + if (!it->is_string()) { + tg3__error_pushf(ctx->errors, ctx->arena, TG3_SEVERITY_ERROR, + TG3_ERR_JSON_TYPE_MISMATCH, parent, + "Field '%s' must be a string", key); + return 0; + } + std::string s = it->get(); + *out = tg3__arena_str_from_std(ctx->arena, s); + return 1; +} + +static int tg3__parse_int(tg3__parse_ctx *ctx, const tg3__json &o, + const char *key, int32_t *out, + int required, const char *parent) { + auto it = o.find(key); + if (it == o.end()) { + if (required) { + tg3__error_pushf(ctx->errors, ctx->arena, TG3_SEVERITY_ERROR, + TG3_ERR_JSON_MISSING_FIELD, parent, + "Missing required field '%s'", key); + return 0; + } + return 1; + } + if (!it->is_number()) { + tg3__error_pushf(ctx->errors, ctx->arena, TG3_SEVERITY_ERROR, + TG3_ERR_JSON_TYPE_MISMATCH, parent, + "Field '%s' must be a number", key); + return 0; + } + if (it->is_number_integer()) { + int64_t v = it->get(); + if (v < (int64_t)INT32_MIN || v > (int64_t)INT32_MAX) { + tg3__error_pushf(ctx->errors, ctx->arena, TG3_SEVERITY_ERROR, + TG3_ERR_JSON_TYPE_MISMATCH, parent, + "Field '%s' value %" PRId64 " is out of range for int32", key, v); + return 0; + } + *out = (int32_t)v; + } else { + double d = it->get(); + if (d < (double)INT32_MIN || d > (double)INT32_MAX) { + tg3__error_pushf(ctx->errors, ctx->arena, TG3_SEVERITY_ERROR, + TG3_ERR_JSON_TYPE_MISMATCH, parent, + "Field '%s' value %f is out of range for int32", key, d); + return 0; + } + *out = (int32_t)d; + } + return 1; +} + +static int tg3__parse_uint64(tg3__parse_ctx *ctx, const tg3__json &o, + const char *key, uint64_t *out, + int required, const char *parent) { + auto it = o.find(key); + if (it == o.end()) { + if (required) { + tg3__error_pushf(ctx->errors, ctx->arena, TG3_SEVERITY_ERROR, + TG3_ERR_JSON_MISSING_FIELD, parent, + "Missing required field '%s'", key); + return 0; + } + return 1; + } + if (!it->is_number()) { + tg3__error_pushf(ctx->errors, ctx->arena, TG3_SEVERITY_ERROR, + TG3_ERR_JSON_TYPE_MISMATCH, parent, + "Field '%s' must be a number", key); + return 0; + } + if (it->is_number_integer()) { + int64_t v = it->get(); + *out = (v >= 0) ? (uint64_t)v : 0; + } else { + *out = (uint64_t)it->get(); + } + return 1; +} + +static int tg3__parse_double(tg3__parse_ctx *ctx, const tg3__json &o, + const char *key, double *out, + int required, const char *parent) { + auto it = o.find(key); + if (it == o.end()) { + if (required) { + tg3__error_pushf(ctx->errors, ctx->arena, TG3_SEVERITY_ERROR, + TG3_ERR_JSON_MISSING_FIELD, parent, + "Missing required field '%s'", key); + return 0; + } + return 1; + } + if (!it->is_number()) { + tg3__error_pushf(ctx->errors, ctx->arena, TG3_SEVERITY_ERROR, + TG3_ERR_JSON_TYPE_MISMATCH, parent, + "Field '%s' must be a number", key); + return 0; + } + *out = it->get(); + return 1; +} + +static int tg3__parse_bool(tg3__parse_ctx *ctx, const tg3__json &o, + const char *key, int32_t *out, + int required, const char *parent) { + auto it = o.find(key); + if (it == o.end()) { + if (required) { + tg3__error_pushf(ctx->errors, ctx->arena, TG3_SEVERITY_ERROR, + TG3_ERR_JSON_MISSING_FIELD, parent, + "Missing required field '%s'", key); + return 0; + } + return 1; + } + if (!it->is_boolean()) { + tg3__error_pushf(ctx->errors, ctx->arena, TG3_SEVERITY_ERROR, + TG3_ERR_JSON_TYPE_MISMATCH, parent, + "Field '%s' must be a boolean", key); + return 0; + } + *out = it->get() ? 1 : 0; + return 1; +} + +static int tg3__parse_number_array(tg3__parse_ctx *ctx, const tg3__json &o, + const char *key, const double **out, + uint32_t *out_count, + int required, const char *parent) { + auto it = o.find(key); + if (it == o.end()) { + if (required) { + tg3__error_pushf(ctx->errors, ctx->arena, TG3_SEVERITY_ERROR, + TG3_ERR_JSON_MISSING_FIELD, parent, + "Missing required field '%s'", key); + return 0; + } + *out = NULL; *out_count = 0; + return 1; + } + if (!it->is_array()) { + tg3__error_pushf(ctx->errors, ctx->arena, TG3_SEVERITY_ERROR, + TG3_ERR_JSON_TYPE_MISMATCH, parent, + "Field '%s' must be an array", key); + return 0; + } + uint32_t count = (uint32_t)it->size(); + if (count == 0) { *out = NULL; *out_count = 0; return 1; } + + double *arr = (double *)tg3__arena_alloc(ctx->arena, count * sizeof(double)); + if (!arr) { + tg3__error_push(ctx->errors, TG3_SEVERITY_ERROR, TG3_ERR_OUT_OF_MEMORY, + "OOM allocating number array", parent, -1); + return 0; + } + uint32_t i = 0; + for (auto eit = it->begin(); eit != it->end(); ++eit, ++i) { + arr[i] = eit->get(); + } + *out = arr; + *out_count = count; + return 1; +} + +static int tg3__parse_int_array(tg3__parse_ctx *ctx, const tg3__json &o, + const char *key, const int32_t **out, + uint32_t *out_count, + int required, const char *parent) { + auto it = o.find(key); + if (it == o.end()) { + if (required) { + tg3__error_pushf(ctx->errors, ctx->arena, TG3_SEVERITY_ERROR, + TG3_ERR_JSON_MISSING_FIELD, parent, + "Missing required field '%s'", key); + return 0; + } + *out = NULL; *out_count = 0; + return 1; + } + if (!it->is_array()) { + tg3__error_pushf(ctx->errors, ctx->arena, TG3_SEVERITY_ERROR, + TG3_ERR_JSON_TYPE_MISMATCH, parent, + "Field '%s' must be an array", key); + return 0; + } + uint32_t count = (uint32_t)it->size(); + if (count == 0) { *out = NULL; *out_count = 0; return 1; } + + int32_t *arr = (int32_t *)tg3__arena_alloc(ctx->arena, count * sizeof(int32_t)); + if (!arr) { + tg3__error_push(ctx->errors, TG3_SEVERITY_ERROR, TG3_ERR_OUT_OF_MEMORY, + "OOM allocating int array", parent, -1); + return 0; + } + uint32_t i = 0; + for (auto eit = it->begin(); eit != it->end(); ++eit, ++i) { + arr[i] = eit->get(); + } + *out = arr; + *out_count = count; + return 1; +} + +static void tg3__parse_number_to_fixed(const tg3__json &o, const char *key, + double *out, uint32_t max_count) { + auto it = o.find(key); + if (it == o.end() || !it->is_array()) return; + uint32_t i = 0; + for (auto eit = it->begin(); eit != it->end() && i < max_count; ++eit, ++i) { + out[i] = eit->get(); + } +} + +/* Parse string array */ +static int tg3__parse_string_array(tg3__parse_ctx *ctx, const tg3__json &o, + const char *key, const tg3_str **out, + uint32_t *out_count, + int required, const char *parent) { + auto it = o.find(key); + if (it == o.end()) { + if (required) { + tg3__error_pushf(ctx->errors, ctx->arena, TG3_SEVERITY_ERROR, + TG3_ERR_JSON_MISSING_FIELD, parent, + "Missing required field '%s'", key); + return 0; + } + *out = NULL; *out_count = 0; + return 1; + } + if (!it->is_array()) return 0; + uint32_t count = (uint32_t)it->size(); + if (count == 0) { *out = NULL; *out_count = 0; return 1; } + + tg3_str *arr = (tg3_str *)tg3__arena_alloc(ctx->arena, count * sizeof(tg3_str)); + if (!arr) return 0; + uint32_t i = 0; + for (auto eit = it->begin(); eit != it->end(); ++eit, ++i) { + std::string s = eit->get(); + arr[i] = tg3__arena_str_from_std(ctx->arena, s); + } + *out = arr; + *out_count = count; + return 1; +} + +/* ====================================================================== + * Internal: Value Conversion (JSON -> tg3_value) + * ====================================================================== */ + +static tg3_value tg3__json_to_value(tg3__parse_ctx *ctx, const tg3__json &j) { + tg3_value v; + memset(&v, 0, sizeof(v)); + + if (j.is_null()) { + v.type = TG3_VALUE_NULL; + } else if (j.is_boolean()) { + v.type = TG3_VALUE_BOOL; + v.bool_val = j.get() ? 1 : 0; + } else if (j.is_number_integer()) { + v.type = TG3_VALUE_INT; + v.int_val = j.get(); + } else if (j.is_number_float()) { + v.type = TG3_VALUE_REAL; + v.real_val = j.get(); + } else if (j.is_string()) { + v.type = TG3_VALUE_STRING; + std::string s = j.get(); + v.string_val = tg3__arena_str_from_std(ctx->arena, s); + } else if (j.is_array()) { + v.type = TG3_VALUE_ARRAY; + uint32_t count = (uint32_t)j.size(); + if (count > 0) { + tg3_value *arr = (tg3_value *)tg3__arena_alloc( + ctx->arena, count * sizeof(tg3_value)); + if (arr) { + uint32_t i = 0; + for (auto it = j.begin(); it != j.end(); ++it, ++i) { + arr[i] = tg3__json_to_value(ctx, *it); + } + v.array_data = arr; + v.array_count = count; + } + } + } else if (j.is_object()) { + v.type = TG3_VALUE_OBJECT; + uint32_t count = (uint32_t)j.size(); + if (count > 0) { + tg3_kv_pair *pairs = (tg3_kv_pair *)tg3__arena_alloc( + ctx->arena, count * sizeof(tg3_kv_pair)); + if (pairs) { + uint32_t i = 0; + for (auto it = j.begin(); it != j.end(); ++it, ++i) { + std::string k = it.key(); + pairs[i].key = tg3__arena_str_from_std(ctx->arena, k); + pairs[i].value = tg3__json_to_value(ctx, *it); + } + v.object_data = pairs; + v.object_count = count; + } + } + } + return v; +} + +/* ====================================================================== + * Internal: Parse Extras and Extensions + * ====================================================================== */ + +static void tg3__init_extras_ext(tg3_extras_ext *ee) { + memset(ee, 0, sizeof(tg3_extras_ext)); +} + +static void tg3__parse_extras_and_extensions(tg3__parse_ctx *ctx, + const tg3__json &o, + tg3_extras_ext *ee) { + /* Extras */ + auto extras_it = o.find("extras"); + if (extras_it != o.end()) { + tg3_value *ev = (tg3_value *)tg3__arena_alloc(ctx->arena, sizeof(tg3_value)); + if (ev) { + *ev = tg3__json_to_value(ctx, *extras_it); + ee->extras = ev; + } + if (ctx->opts.store_original_json) { + std::string raw = extras_it->dump(); + ee->extras_json = tg3__arena_str_from_std(ctx->arena, raw); + } + } + + /* Extensions */ + auto ext_it = o.find("extensions"); + if (ext_it != o.end() && ext_it->is_object()) { + uint32_t count = (uint32_t)ext_it->size(); + if (count > 0) { + tg3_extension *exts = (tg3_extension *)tg3__arena_alloc( + ctx->arena, count * sizeof(tg3_extension)); + if (exts) { + uint32_t i = 0; + for (auto it = ext_it->begin(); it != ext_it->end(); ++it, ++i) { + std::string k = it.key(); + exts[i].name = tg3__arena_str_from_std(ctx->arena, k); + exts[i].value = tg3__json_to_value(ctx, *it); + } + ee->extensions = exts; + ee->extensions_count = count; + } + } + if (ctx->opts.store_original_json) { + std::string raw = ext_it->dump(); + ee->extensions_json = tg3__arena_str_from_std(ctx->arena, raw); + } + } +} + +/* ====================================================================== + * Internal: Init functions for default struct values + * ====================================================================== */ + +static void tg3__init_texture_info(tg3_texture_info *ti) { + memset(ti, 0, sizeof(tg3_texture_info)); + ti->index = -1; + ti->tex_coord = 0; +} + +static void tg3__init_normal_texture_info(tg3_normal_texture_info *ti) { + memset(ti, 0, sizeof(tg3_normal_texture_info)); + ti->index = -1; + ti->tex_coord = 0; + ti->scale = 1.0; +} + +static void tg3__init_occlusion_texture_info(tg3_occlusion_texture_info *ti) { + memset(ti, 0, sizeof(tg3_occlusion_texture_info)); + ti->index = -1; + ti->tex_coord = 0; + ti->strength = 1.0; +} + +static void tg3__init_pbr(tg3_pbr_metallic_roughness *pbr) { + memset(pbr, 0, sizeof(tg3_pbr_metallic_roughness)); + pbr->base_color_factor[0] = 1.0; + pbr->base_color_factor[1] = 1.0; + pbr->base_color_factor[2] = 1.0; + pbr->base_color_factor[3] = 1.0; + pbr->metallic_factor = 1.0; + pbr->roughness_factor = 1.0; + tg3__init_texture_info(&pbr->base_color_texture); + tg3__init_texture_info(&pbr->metallic_roughness_texture); +} + +static void tg3__init_node(tg3_node *n) { + memset(n, 0, sizeof(tg3_node)); + n->camera = -1; + n->skin = -1; + n->mesh = -1; + n->light = -1; + n->emitter = -1; + n->rotation[3] = 1.0; /* w=1 identity quaternion */ + n->scale[0] = 1.0; + n->scale[1] = 1.0; + n->scale[2] = 1.0; + /* Identity matrix */ + n->matrix[0] = 1.0; + n->matrix[5] = 1.0; + n->matrix[10] = 1.0; + n->matrix[15] = 1.0; +} + +/* ====================================================================== + * Internal: Entity Parse Functions + * ====================================================================== */ + +static int tg3__parse_asset(tg3__parse_ctx *ctx, const tg3__json &o, + tg3_asset *asset) { + memset(asset, 0, sizeof(tg3_asset)); + tg3__parse_string(ctx, o, "version", &asset->version, 0, "/asset"); + tg3__parse_string(ctx, o, "generator", &asset->generator, 0, "/asset"); + tg3__parse_string(ctx, o, "minVersion", &asset->min_version, 0, "/asset"); + tg3__parse_string(ctx, o, "copyright", &asset->copyright, 0, "/asset"); + tg3__parse_extras_and_extensions(ctx, o, &asset->ext); + return 1; +} + +static int tg3__parse_texture_info(tg3__parse_ctx *ctx, const tg3__json &o, + const char *key, tg3_texture_info *ti) { + tg3__init_texture_info(ti); + auto it = o.find(key); + if (it == o.end()) return 1; /* Optional */ + if (!it->is_object()) return 0; + tg3__parse_int(ctx, *it, "index", &ti->index, 0, key); + tg3__parse_int(ctx, *it, "texCoord", &ti->tex_coord, 0, key); + tg3__parse_extras_and_extensions(ctx, *it, &ti->ext); + return 1; +} + +static int tg3__parse_normal_texture_info(tg3__parse_ctx *ctx, const tg3__json &o, + const char *key, + tg3_normal_texture_info *ti) { + tg3__init_normal_texture_info(ti); + auto it = o.find(key); + if (it == o.end()) return 1; + if (!it->is_object()) return 0; + tg3__parse_int(ctx, *it, "index", &ti->index, 0, key); + tg3__parse_int(ctx, *it, "texCoord", &ti->tex_coord, 0, key); + tg3__parse_double(ctx, *it, "scale", &ti->scale, 0, key); + tg3__parse_extras_and_extensions(ctx, *it, &ti->ext); + return 1; +} + +static int tg3__parse_occlusion_texture_info(tg3__parse_ctx *ctx, + const tg3__json &o, + const char *key, + tg3_occlusion_texture_info *ti) { + tg3__init_occlusion_texture_info(ti); + auto it = o.find(key); + if (it == o.end()) return 1; + if (!it->is_object()) return 0; + tg3__parse_int(ctx, *it, "index", &ti->index, 0, key); + tg3__parse_int(ctx, *it, "texCoord", &ti->tex_coord, 0, key); + tg3__parse_double(ctx, *it, "strength", &ti->strength, 0, key); + tg3__parse_extras_and_extensions(ctx, *it, &ti->ext); + return 1; +} + +static int tg3__accessor_type_from_string(const char *s, size_t len) { + if (len == 6 && memcmp(s, "SCALAR", 6) == 0) return TG3_TYPE_SCALAR; + if (len == 4 && memcmp(s, "VEC2", 4) == 0) return TG3_TYPE_VEC2; + if (len == 4 && memcmp(s, "VEC3", 4) == 0) return TG3_TYPE_VEC3; + if (len == 4 && memcmp(s, "VEC4", 4) == 0) return TG3_TYPE_VEC4; + if (len == 4 && memcmp(s, "MAT2", 4) == 0) return TG3_TYPE_MAT2; + if (len == 4 && memcmp(s, "MAT3", 4) == 0) return TG3_TYPE_MAT3; + if (len == 4 && memcmp(s, "MAT4", 4) == 0) return TG3_TYPE_MAT4; + return -1; +} + +static const char *tg3__accessor_type_to_string(int type) { + switch (type) { + case TG3_TYPE_SCALAR: return "SCALAR"; + case TG3_TYPE_VEC2: return "VEC2"; + case TG3_TYPE_VEC3: return "VEC3"; + case TG3_TYPE_VEC4: return "VEC4"; + case TG3_TYPE_MAT2: return "MAT2"; + case TG3_TYPE_MAT3: return "MAT3"; + case TG3_TYPE_MAT4: return "MAT4"; + default: return ""; + } +} + +static int tg3__parse_accessor_sparse(tg3__parse_ctx *ctx, const tg3__json &o, + tg3_accessor_sparse *sparse) { + memset(sparse, 0, sizeof(tg3_accessor_sparse)); + sparse->indices.buffer_view = -1; + sparse->values.buffer_view = -1; + + auto it = o.find("sparse"); + if (it == o.end()) return 1; + if (!it->is_object()) return 0; + + sparse->is_sparse = 1; + tg3__parse_int(ctx, *it, "count", &sparse->count, 1, "/sparse"); + + auto idx_it = it->find("indices"); + if (idx_it != it->end() && idx_it->is_object()) { + tg3__parse_int(ctx, *idx_it, "bufferView", + &sparse->indices.buffer_view, 1, "/sparse/indices"); + tg3__parse_int(ctx, *idx_it, "componentType", + &sparse->indices.component_type, 1, "/sparse/indices"); + uint64_t bo = 0; + tg3__parse_uint64(ctx, *idx_it, "byteOffset", &bo, 0, "/sparse/indices"); + sparse->indices.byte_offset = bo; + tg3__parse_extras_and_extensions(ctx, *idx_it, &sparse->indices.ext); + } + + auto val_it = it->find("values"); + if (val_it != it->end() && val_it->is_object()) { + tg3__parse_int(ctx, *val_it, "bufferView", + &sparse->values.buffer_view, 1, "/sparse/values"); + uint64_t bo = 0; + tg3__parse_uint64(ctx, *val_it, "byteOffset", &bo, 0, "/sparse/values"); + sparse->values.byte_offset = bo; + tg3__parse_extras_and_extensions(ctx, *val_it, &sparse->values.ext); + } + + tg3__parse_extras_and_extensions(ctx, *it, &sparse->ext); + return 1; +} + +static int tg3__parse_accessor(tg3__parse_ctx *ctx, const tg3__json &o, + tg3_accessor *acc) { + memset(acc, 0, sizeof(tg3_accessor)); + acc->buffer_view = -1; + acc->component_type = -1; + acc->type = -1; + + tg3__parse_string(ctx, o, "name", &acc->name, 0, "/accessor"); + tg3__parse_int(ctx, o, "bufferView", &acc->buffer_view, 0, "/accessor"); + + uint64_t bo = 0; + tg3__parse_uint64(ctx, o, "byteOffset", &bo, 0, "/accessor"); + acc->byte_offset = bo; + + tg3__parse_bool(ctx, o, "normalized", &acc->normalized, 0, "/accessor"); + tg3__parse_int(ctx, o, "componentType", &acc->component_type, 1, "/accessor"); + + uint64_t cnt = 0; + tg3__parse_uint64(ctx, o, "count", &cnt, 1, "/accessor"); + acc->count = cnt; + + /* Parse type string */ + tg3_str type_str = {0, 0}; + tg3__parse_string(ctx, o, "type", &type_str, 1, "/accessor"); + if (type_str.data) { + acc->type = tg3__accessor_type_from_string(type_str.data, type_str.len); + } + + tg3__parse_number_array(ctx, o, "min", &acc->min_values, &acc->min_values_count, + 0, "/accessor"); + tg3__parse_number_array(ctx, o, "max", &acc->max_values, &acc->max_values_count, + 0, "/accessor"); + + tg3__parse_accessor_sparse(ctx, o, &acc->sparse); + tg3__parse_extras_and_extensions(ctx, o, &acc->ext); + return 1; +} + +static int tg3__load_external_file(tg3__parse_ctx *ctx, uint8_t **out_data, + uint64_t *out_size, const char *uri, + uint32_t uri_len) { + if (!ctx->opts.fs.read_file) { + tg3__error_push(ctx->errors, TG3_SEVERITY_ERROR, TG3_ERR_FS_NOT_AVAILABLE, + "No filesystem callbacks available", NULL, -1); + return 0; + } + + /* Build full path: base_dir + "/" + uri */ + char path_buf[4096]; + uint32_t path_len = 0; + if (ctx->base_dir_len > 0) { + if (ctx->base_dir_len + 1 + uri_len >= sizeof(path_buf)) return 0; + memcpy(path_buf, ctx->base_dir, ctx->base_dir_len); + path_len = ctx->base_dir_len; + if (path_buf[path_len - 1] != '/' && path_buf[path_len - 1] != '\\') { + path_buf[path_len++] = '/'; + } + } + if (path_len + uri_len >= sizeof(path_buf)) return 0; + memcpy(path_buf + path_len, uri, uri_len); + path_len += uri_len; + path_buf[path_len] = '\0'; + + int32_t ok = ctx->opts.fs.read_file(out_data, out_size, path_buf, path_len, + ctx->opts.fs.user_data); + if (!ok) { + tg3__error_pushf(ctx->errors, ctx->arena, TG3_SEVERITY_ERROR, + TG3_ERR_FILE_READ, NULL, "Failed to read file: %s", path_buf); + return 0; + } + return 1; +} + +static int tg3__parse_buffer(tg3__parse_ctx *ctx, const tg3__json &o, + tg3_buffer *buf, int32_t buf_idx) { + memset(buf, 0, sizeof(tg3_buffer)); + tg3__parse_string(ctx, o, "name", &buf->name, 0, "/buffer"); + tg3__parse_string(ctx, o, "uri", &buf->uri, 0, "/buffer"); + + uint64_t byte_length = 0; + tg3__parse_uint64(ctx, o, "byteLength", &byte_length, 1, "/buffer"); + + /* Load buffer data */ + if (ctx->is_binary && buf_idx == 0 && buf->uri.len == 0) { + /* GLB: first buffer uses binary chunk */ + if (!ctx->bin_data || ctx->bin_size < byte_length) { + tg3__error_push(ctx->errors, TG3_SEVERITY_ERROR, + TG3_ERR_BUFFER_SIZE_MISMATCH, + "GLB BIN chunk missing or smaller than buffer.byteLength", + NULL, -1); + return 0; + } + uint8_t *data = (uint8_t *)tg3__arena_alloc(ctx->arena, (size_t)byte_length); + if (!data) { + tg3__error_push(ctx->errors, TG3_SEVERITY_ERROR, + TG3_ERR_OUT_OF_MEMORY, "OOM for buffer data", NULL, -1); + return 0; + } + memcpy(data, ctx->bin_data, (size_t)byte_length); + buf->data.data = data; + buf->data.count = byte_length; + } else if (buf->uri.len > 0) { + if (tg3_is_data_uri(buf->uri.data, buf->uri.len)) { + /* Data URI */ + size_t decoded_len = 0; + char mime[64] = {0}; + uint8_t *decoded = tg3__decode_data_uri(ctx->arena, buf->uri.data, + buf->uri.len, &decoded_len, + mime, sizeof(mime)); + if (!decoded && byte_length > 0) { + tg3__error_push(ctx->errors, TG3_SEVERITY_ERROR, + TG3_ERR_DATA_URI_DECODE, + "Failed to decode buffer data URI", NULL, -1); + return 0; + } + buf->data.data = decoded; + buf->data.count = decoded_len; + } else { + /* External file */ + uint8_t *file_data = NULL; + uint64_t file_size = 0; + if (tg3__load_external_file(ctx, &file_data, &file_size, + buf->uri.data, buf->uri.len)) { + /* Copy into arena */ + uint8_t *data = (uint8_t *)tg3__arena_alloc(ctx->arena, (size_t)file_size); + if (data) { + memcpy(data, file_data, (size_t)file_size); + buf->data.data = data; + buf->data.count = file_size; + } + /* Free file data via callback */ + if (ctx->opts.fs.free_file) { + ctx->opts.fs.free_file(file_data, file_size, + ctx->opts.fs.user_data); + } + } + } + } + + tg3__parse_extras_and_extensions(ctx, o, &buf->ext); + return 1; +} + +static int tg3__parse_buffer_view(tg3__parse_ctx *ctx, const tg3__json &o, + tg3_buffer_view *bv) { + memset(bv, 0, sizeof(tg3_buffer_view)); + bv->buffer = -1; + + tg3__parse_string(ctx, o, "name", &bv->name, 0, "/bufferView"); + tg3__parse_int(ctx, o, "buffer", &bv->buffer, 1, "/bufferView"); + + uint64_t val = 0; + tg3__parse_uint64(ctx, o, "byteOffset", &val, 0, "/bufferView"); + bv->byte_offset = val; + val = 0; + tg3__parse_uint64(ctx, o, "byteLength", &val, 1, "/bufferView"); + bv->byte_length = val; + + int32_t stride = 0; + tg3__parse_int(ctx, o, "byteStride", &stride, 0, "/bufferView"); + bv->byte_stride = (uint32_t)stride; + + tg3__parse_int(ctx, o, "target", &bv->target, 0, "/bufferView"); + tg3__parse_extras_and_extensions(ctx, o, &bv->ext); + return 1; +} + +static int tg3__parse_image(tg3__parse_ctx *ctx, const tg3__json &o, + tg3_image *img, int32_t /*img_idx*/) { + memset(img, 0, sizeof(tg3_image)); + img->width = -1; + img->height = -1; + img->component = -1; + img->bits = -1; + img->pixel_type = -1; + img->buffer_view = -1; + + tg3__parse_string(ctx, o, "name", &img->name, 0, "/image"); + tg3__parse_string(ctx, o, "uri", &img->uri, 0, "/image"); + tg3__parse_string(ctx, o, "mimeType", &img->mime_type, 0, "/image"); + tg3__parse_int(ctx, o, "bufferView", &img->buffer_view, 0, "/image"); + + if (ctx->opts.images_as_is) { + img->as_is = 1; + } + + tg3__parse_extras_and_extensions(ctx, o, &img->ext); + return 1; +} + +static int tg3__parse_sampler(tg3__parse_ctx *ctx, const tg3__json &o, + tg3_sampler *samp) { + memset(samp, 0, sizeof(tg3_sampler)); + samp->min_filter = -1; + samp->mag_filter = -1; + samp->wrap_s = TG3_TEXTURE_WRAP_REPEAT; + samp->wrap_t = TG3_TEXTURE_WRAP_REPEAT; + + tg3__parse_string(ctx, o, "name", &samp->name, 0, "/sampler"); + tg3__parse_int(ctx, o, "minFilter", &samp->min_filter, 0, "/sampler"); + tg3__parse_int(ctx, o, "magFilter", &samp->mag_filter, 0, "/sampler"); + tg3__parse_int(ctx, o, "wrapS", &samp->wrap_s, 0, "/sampler"); + tg3__parse_int(ctx, o, "wrapT", &samp->wrap_t, 0, "/sampler"); + tg3__parse_extras_and_extensions(ctx, o, &samp->ext); + return 1; +} + +static int tg3__parse_texture(tg3__parse_ctx *ctx, const tg3__json &o, + tg3_texture *tex) { + memset(tex, 0, sizeof(tg3_texture)); + tex->sampler = -1; + tex->source = -1; + + tg3__parse_string(ctx, o, "name", &tex->name, 0, "/texture"); + tg3__parse_int(ctx, o, "sampler", &tex->sampler, 0, "/texture"); + tg3__parse_int(ctx, o, "source", &tex->source, 0, "/texture"); + tg3__parse_extras_and_extensions(ctx, o, &tex->ext); + return 1; +} + +static int tg3__parse_material(tg3__parse_ctx *ctx, const tg3__json &o, + tg3_material *mat) { + memset(mat, 0, sizeof(tg3_material)); + tg3__init_pbr(&mat->pbr_metallic_roughness); + tg3__init_normal_texture_info(&mat->normal_texture); + tg3__init_occlusion_texture_info(&mat->occlusion_texture); + tg3__init_texture_info(&mat->emissive_texture); + mat->alpha_cutoff = 0.5; + + tg3__parse_string(ctx, o, "name", &mat->name, 0, "/material"); + + /* Emissive factor */ + tg3__parse_number_to_fixed(o, "emissiveFactor", mat->emissive_factor, 3); + + /* Alpha mode */ + tg3_str alpha_mode = {0, 0}; + tg3__parse_string(ctx, o, "alphaMode", &alpha_mode, 0, "/material"); + if (alpha_mode.len > 0) { + mat->alpha_mode = alpha_mode; + } else { + mat->alpha_mode = tg3__arena_str(ctx->arena, "OPAQUE", 6); + } + + tg3__parse_double(ctx, o, "alphaCutoff", &mat->alpha_cutoff, 0, "/material"); + tg3__parse_bool(ctx, o, "doubleSided", &mat->double_sided, 0, "/material"); + + /* PBR */ + auto pbr_it = o.find("pbrMetallicRoughness"); + if (pbr_it != o.end() && pbr_it->is_object()) { + tg3__parse_number_to_fixed(*pbr_it, "baseColorFactor", + mat->pbr_metallic_roughness.base_color_factor, 4); + tg3__parse_double(ctx, *pbr_it, "metallicFactor", + &mat->pbr_metallic_roughness.metallic_factor, 0, + "/material/pbrMetallicRoughness"); + tg3__parse_double(ctx, *pbr_it, "roughnessFactor", + &mat->pbr_metallic_roughness.roughness_factor, 0, + "/material/pbrMetallicRoughness"); + tg3__parse_texture_info(ctx, *pbr_it, "baseColorTexture", + &mat->pbr_metallic_roughness.base_color_texture); + tg3__parse_texture_info(ctx, *pbr_it, "metallicRoughnessTexture", + &mat->pbr_metallic_roughness.metallic_roughness_texture); + tg3__parse_extras_and_extensions(ctx, *pbr_it, + &mat->pbr_metallic_roughness.ext); + } + + tg3__parse_normal_texture_info(ctx, o, "normalTexture", &mat->normal_texture); + tg3__parse_occlusion_texture_info(ctx, o, "occlusionTexture", + &mat->occlusion_texture); + tg3__parse_texture_info(ctx, o, "emissiveTexture", &mat->emissive_texture); + + /* MSFT_lod */ + auto ext_it = o.find("extensions"); + if (ext_it != o.end() && ext_it->is_object()) { + auto lod_it = ext_it->find("MSFT_lod"); + if (lod_it != ext_it->end() && lod_it->is_object()) { + tg3__parse_int_array(ctx, *lod_it, "ids", + &mat->lods, &mat->lods_count, 0, + "/material/extensions/MSFT_lod"); + } + } + + tg3__parse_extras_and_extensions(ctx, o, &mat->ext); + return 1; +} + +static int tg3__parse_primitive(tg3__parse_ctx *ctx, const tg3__json &o, + tg3_primitive *prim) { + memset(prim, 0, sizeof(tg3_primitive)); + prim->material = -1; + prim->indices = -1; + prim->mode = TG3_MODE_TRIANGLES; + + tg3__parse_int(ctx, o, "material", &prim->material, 0, "/primitive"); + tg3__parse_int(ctx, o, "indices", &prim->indices, 0, "/primitive"); + tg3__parse_int(ctx, o, "mode", &prim->mode, 0, "/primitive"); + + /* Attributes */ + auto attr_it = o.find("attributes"); + if (attr_it != o.end() && attr_it->is_object()) { + uint32_t count = (uint32_t)attr_it->size(); + if (count > 0) { + tg3_str_int_pair *attrs = (tg3_str_int_pair *)tg3__arena_alloc( + ctx->arena, count * sizeof(tg3_str_int_pair)); + if (attrs) { + uint32_t i = 0; + for (auto it = attr_it->begin(); it != attr_it->end(); ++it, ++i) { + std::string k = it.key(); + attrs[i].key = tg3__arena_str_from_std(ctx->arena, k); + attrs[i].value = it->get(); + } + prim->attributes = attrs; + prim->attributes_count = count; + } + } + } + + /* Morph targets */ + auto targets_it = o.find("targets"); + if (targets_it != o.end() && targets_it->is_array()) { + uint32_t tcount = (uint32_t)targets_it->size(); + if (tcount > 0) { + const tg3_str_int_pair **target_arrays = + (const tg3_str_int_pair **)tg3__arena_alloc( + ctx->arena, tcount * sizeof(tg3_str_int_pair *)); + uint32_t *target_counts = (uint32_t *)tg3__arena_alloc( + ctx->arena, tcount * sizeof(uint32_t)); + if (target_arrays && target_counts) { + uint32_t ti = 0; + for (auto tit = targets_it->begin(); tit != targets_it->end(); ++tit, ++ti) { + if (!tit->is_object()) { + target_arrays[ti] = NULL; + target_counts[ti] = 0; + continue; + } + uint32_t acount = (uint32_t)tit->size(); + tg3_str_int_pair *tattrs = (tg3_str_int_pair *)tg3__arena_alloc( + ctx->arena, acount * sizeof(tg3_str_int_pair)); + if (tattrs) { + uint32_t ai = 0; + for (auto ait = tit->begin(); ait != tit->end(); ++ait, ++ai) { + std::string k = ait.key(); + tattrs[ai].key = tg3__arena_str_from_std(ctx->arena, k); + tattrs[ai].value = ait->get(); + } + } + target_arrays[ti] = tattrs; + target_counts[ti] = acount; + } + prim->targets = target_arrays; + prim->target_attribute_counts = target_counts; + prim->targets_count = tcount; + } + } + } + + tg3__parse_extras_and_extensions(ctx, o, &prim->ext); + return 1; +} + +static int tg3__parse_mesh(tg3__parse_ctx *ctx, const tg3__json &o, + tg3_mesh *mesh) { + memset(mesh, 0, sizeof(tg3_mesh)); + tg3__parse_string(ctx, o, "name", &mesh->name, 0, "/mesh"); + + /* Primitives */ + auto prim_it = o.find("primitives"); + if (prim_it != o.end() && prim_it->is_array()) { + uint32_t count = (uint32_t)prim_it->size(); + if (count > 0) { + tg3_primitive *prims = (tg3_primitive *)tg3__arena_alloc( + ctx->arena, count * sizeof(tg3_primitive)); + if (prims) { + uint32_t i = 0; + for (auto it = prim_it->begin(); it != prim_it->end(); ++it, ++i) { + tg3__parse_primitive(ctx, *it, &prims[i]); + } + mesh->primitives = prims; + mesh->primitives_count = count; + } + } + } + + tg3__parse_number_array(ctx, o, "weights", &mesh->weights, + &mesh->weights_count, 0, "/mesh"); + tg3__parse_extras_and_extensions(ctx, o, &mesh->ext); + return 1; +} + +static int tg3__parse_node(tg3__parse_ctx *ctx, const tg3__json &o, + tg3_node *node) { + tg3__init_node(node); + + tg3__parse_string(ctx, o, "name", &node->name, 0, "/node"); + tg3__parse_int(ctx, o, "camera", &node->camera, 0, "/node"); + tg3__parse_int(ctx, o, "skin", &node->skin, 0, "/node"); + tg3__parse_int(ctx, o, "mesh", &node->mesh, 0, "/node"); + + tg3__parse_int_array(ctx, o, "children", &node->children, + &node->children_count, 0, "/node"); + + /* TRS */ + if (tg3__json_has(o, "matrix")) { + tg3__parse_number_to_fixed(o, "matrix", node->matrix, 16); + node->has_matrix = 1; + } + if (tg3__json_has(o, "translation")) { + tg3__parse_number_to_fixed(o, "translation", node->translation, 3); + } + if (tg3__json_has(o, "rotation")) { + tg3__parse_number_to_fixed(o, "rotation", node->rotation, 4); + } + if (tg3__json_has(o, "scale")) { + tg3__parse_number_to_fixed(o, "scale", node->scale, 3); + } + + tg3__parse_number_array(ctx, o, "weights", &node->weights, + &node->weights_count, 0, "/node"); + + /* Extensions: KHR_lights_punctual, KHR_audio, MSFT_lod */ + auto ext_it = o.find("extensions"); + if (ext_it != o.end() && ext_it->is_object()) { + auto khr_lights = ext_it->find("KHR_lights_punctual"); + if (khr_lights != ext_it->end() && khr_lights->is_object()) { + tg3__parse_int(ctx, *khr_lights, "light", &node->light, 0, + "/node/extensions/KHR_lights_punctual"); + } + auto khr_audio = ext_it->find("KHR_audio"); + if (khr_audio != ext_it->end() && khr_audio->is_object()) { + tg3__parse_int(ctx, *khr_audio, "emitter", &node->emitter, 0, + "/node/extensions/KHR_audio"); + } + auto msft_lod = ext_it->find("MSFT_lod"); + if (msft_lod != ext_it->end() && msft_lod->is_object()) { + tg3__parse_int_array(ctx, *msft_lod, "ids", + &node->lods, &node->lods_count, 0, + "/node/extensions/MSFT_lod"); + } + } + + tg3__parse_extras_and_extensions(ctx, o, &node->ext); + return 1; +} + +static int tg3__parse_skin(tg3__parse_ctx *ctx, const tg3__json &o, + tg3_skin *skin) { + memset(skin, 0, sizeof(tg3_skin)); + skin->inverse_bind_matrices = -1; + skin->skeleton = -1; + + tg3__parse_string(ctx, o, "name", &skin->name, 0, "/skin"); + tg3__parse_int(ctx, o, "inverseBindMatrices", &skin->inverse_bind_matrices, + 0, "/skin"); + tg3__parse_int(ctx, o, "skeleton", &skin->skeleton, 0, "/skin"); + tg3__parse_int_array(ctx, o, "joints", &skin->joints, + &skin->joints_count, 1, "/skin"); + tg3__parse_extras_and_extensions(ctx, o, &skin->ext); + return 1; +} + +static int tg3__parse_animation(tg3__parse_ctx *ctx, const tg3__json &o, + tg3_animation *anim) { + memset(anim, 0, sizeof(tg3_animation)); + tg3__parse_string(ctx, o, "name", &anim->name, 0, "/animation"); + + /* Channels */ + auto ch_it = o.find("channels"); + if (ch_it != o.end() && ch_it->is_array()) { + uint32_t count = (uint32_t)ch_it->size(); + if (count > 0) { + tg3_animation_channel *channels = (tg3_animation_channel *)tg3__arena_alloc( + ctx->arena, count * sizeof(tg3_animation_channel)); + if (channels) { + uint32_t i = 0; + for (auto it = ch_it->begin(); it != ch_it->end(); ++it, ++i) { + memset(&channels[i], 0, sizeof(tg3_animation_channel)); + channels[i].sampler = -1; + channels[i].target.node = -1; + + tg3__parse_int(ctx, *it, "sampler", &channels[i].sampler, + 1, "/animation/channel"); + + auto tgt_it = it->find("target"); + if (tgt_it != it->end() && tgt_it->is_object()) { + tg3__parse_int(ctx, *tgt_it, "node", + &channels[i].target.node, 0, + "/animation/channel/target"); + tg3__parse_string(ctx, *tgt_it, "path", + &channels[i].target.path, 1, + "/animation/channel/target"); + tg3__parse_extras_and_extensions(ctx, *tgt_it, + &channels[i].target.ext); + } + tg3__parse_extras_and_extensions(ctx, *it, &channels[i].ext); + } + anim->channels = channels; + anim->channels_count = count; + } + } + } + + /* Samplers */ + auto samp_it = o.find("samplers"); + if (samp_it != o.end() && samp_it->is_array()) { + uint32_t count = (uint32_t)samp_it->size(); + if (count > 0) { + tg3_animation_sampler *samplers = (tg3_animation_sampler *)tg3__arena_alloc( + ctx->arena, count * sizeof(tg3_animation_sampler)); + if (samplers) { + uint32_t i = 0; + for (auto it = samp_it->begin(); it != samp_it->end(); ++it, ++i) { + memset(&samplers[i], 0, sizeof(tg3_animation_sampler)); + samplers[i].input = -1; + samplers[i].output = -1; + + tg3__parse_int(ctx, *it, "input", &samplers[i].input, + 1, "/animation/sampler"); + tg3__parse_int(ctx, *it, "output", &samplers[i].output, + 1, "/animation/sampler"); + + tg3_str interp = {0, 0}; + tg3__parse_string(ctx, *it, "interpolation", &interp, + 0, "/animation/sampler"); + if (interp.len > 0) { + samplers[i].interpolation = interp; + } else { + samplers[i].interpolation = tg3__arena_str(ctx->arena, + "LINEAR", 6); + } + tg3__parse_extras_and_extensions(ctx, *it, &samplers[i].ext); + } + anim->samplers = samplers; + anim->samplers_count = count; + } + } + } + + tg3__parse_extras_and_extensions(ctx, o, &anim->ext); + return 1; +} + +static int tg3__parse_camera(tg3__parse_ctx *ctx, const tg3__json &o, + tg3_camera *cam) { + memset(cam, 0, sizeof(tg3_camera)); + tg3__parse_string(ctx, o, "name", &cam->name, 0, "/camera"); + tg3__parse_string(ctx, o, "type", &cam->type, 1, "/camera"); + + if (cam->type.data && tg3_str_equals_cstr(cam->type, "perspective")) { + auto p_it = o.find("perspective"); + if (p_it != o.end() && p_it->is_object()) { + tg3__parse_double(ctx, *p_it, "aspectRatio", + &cam->perspective.aspect_ratio, 0, "/camera/perspective"); + tg3__parse_double(ctx, *p_it, "yfov", + &cam->perspective.yfov, 1, "/camera/perspective"); + tg3__parse_double(ctx, *p_it, "zfar", + &cam->perspective.zfar, 0, "/camera/perspective"); + tg3__parse_double(ctx, *p_it, "znear", + &cam->perspective.znear, 1, "/camera/perspective"); + tg3__parse_extras_and_extensions(ctx, *p_it, &cam->perspective.ext); + } + } else if (cam->type.data && tg3_str_equals_cstr(cam->type, "orthographic")) { + auto o_it = o.find("orthographic"); + if (o_it != o.end() && o_it->is_object()) { + tg3__parse_double(ctx, *o_it, "xmag", + &cam->orthographic.xmag, 1, "/camera/orthographic"); + tg3__parse_double(ctx, *o_it, "ymag", + &cam->orthographic.ymag, 1, "/camera/orthographic"); + tg3__parse_double(ctx, *o_it, "zfar", + &cam->orthographic.zfar, 1, "/camera/orthographic"); + tg3__parse_double(ctx, *o_it, "znear", + &cam->orthographic.znear, 1, "/camera/orthographic"); + tg3__parse_extras_and_extensions(ctx, *o_it, &cam->orthographic.ext); + } + } + + tg3__parse_extras_and_extensions(ctx, o, &cam->ext); + return 1; +} + +static int tg3__parse_scene(tg3__parse_ctx *ctx, const tg3__json &o, + tg3_scene *scene) { + memset(scene, 0, sizeof(tg3_scene)); + tg3__parse_string(ctx, o, "name", &scene->name, 0, "/scene"); + tg3__parse_int_array(ctx, o, "nodes", &scene->nodes, + &scene->nodes_count, 0, "/scene"); + + /* KHR_audio emitters */ + auto ext_it = o.find("extensions"); + if (ext_it != o.end() && ext_it->is_object()) { + auto audio_it = ext_it->find("KHR_audio"); + if (audio_it != ext_it->end() && audio_it->is_object()) { + tg3__parse_int_array(ctx, *audio_it, "emitters", + &scene->audio_emitters, + &scene->audio_emitters_count, 0, + "/scene/extensions/KHR_audio"); + } + } + + tg3__parse_extras_and_extensions(ctx, o, &scene->ext); + return 1; +} + +static int tg3__parse_light(tg3__parse_ctx *ctx, const tg3__json &o, + tg3_light *light) { + memset(light, 0, sizeof(tg3_light)); + light->color[0] = 1.0; + light->color[1] = 1.0; + light->color[2] = 1.0; + light->intensity = 1.0; + light->spot.outer_cone_angle = 0.7853981634; + + tg3__parse_string(ctx, o, "name", &light->name, 0, "/light"); + tg3__parse_string(ctx, o, "type", &light->type, 1, "/light"); + tg3__parse_double(ctx, o, "intensity", &light->intensity, 0, "/light"); + tg3__parse_double(ctx, o, "range", &light->range, 0, "/light"); + tg3__parse_number_to_fixed(o, "color", light->color, 3); + + auto spot_it = o.find("spot"); + if (spot_it != o.end() && spot_it->is_object()) { + tg3__parse_double(ctx, *spot_it, "innerConeAngle", + &light->spot.inner_cone_angle, 0, "/light/spot"); + tg3__parse_double(ctx, *spot_it, "outerConeAngle", + &light->spot.outer_cone_angle, 0, "/light/spot"); + tg3__parse_extras_and_extensions(ctx, *spot_it, &light->spot.ext); + } + + tg3__parse_extras_and_extensions(ctx, o, &light->ext); + return 1; +} + +static int tg3__parse_audio_source(tg3__parse_ctx *ctx, const tg3__json &o, + tg3_audio_source *src) { + memset(src, 0, sizeof(tg3_audio_source)); + src->buffer_view = -1; + + tg3__parse_string(ctx, o, "name", &src->name, 0, "/audioSource"); + tg3__parse_string(ctx, o, "uri", &src->uri, 0, "/audioSource"); + tg3__parse_int(ctx, o, "bufferView", &src->buffer_view, 0, "/audioSource"); + tg3__parse_string(ctx, o, "mimeType", &src->mime_type, 0, "/audioSource"); + tg3__parse_extras_and_extensions(ctx, o, &src->ext); + return 1; +} + +static int tg3__parse_audio_emitter(tg3__parse_ctx *ctx, const tg3__json &o, + tg3_audio_emitter *emitter) { + memset(emitter, 0, sizeof(tg3_audio_emitter)); + emitter->gain = 1.0; + emitter->source = -1; + emitter->positional.cone_inner_angle = 6.283185307179586; + emitter->positional.cone_outer_angle = 6.283185307179586; + emitter->positional.max_distance = 100.0; + emitter->positional.ref_distance = 1.0; + emitter->positional.rolloff_factor = 1.0; + + tg3__parse_string(ctx, o, "name", &emitter->name, 0, "/audioEmitter"); + tg3__parse_double(ctx, o, "gain", &emitter->gain, 0, "/audioEmitter"); + tg3__parse_bool(ctx, o, "loop", &emitter->loop, 0, "/audioEmitter"); + tg3__parse_bool(ctx, o, "playing", &emitter->playing, 0, "/audioEmitter"); + tg3__parse_string(ctx, o, "type", &emitter->type, 0, "/audioEmitter"); + tg3__parse_string(ctx, o, "distanceModel", &emitter->distance_model, + 0, "/audioEmitter"); + tg3__parse_int(ctx, o, "source", &emitter->source, 0, "/audioEmitter"); + + auto pos_it = o.find("positional"); + if (pos_it != o.end() && pos_it->is_object()) { + tg3__parse_double(ctx, *pos_it, "coneInnerAngle", + &emitter->positional.cone_inner_angle, 0, "/positional"); + tg3__parse_double(ctx, *pos_it, "coneOuterAngle", + &emitter->positional.cone_outer_angle, 0, "/positional"); + tg3__parse_double(ctx, *pos_it, "coneOuterGain", + &emitter->positional.cone_outer_gain, 0, "/positional"); + tg3__parse_double(ctx, *pos_it, "maxDistance", + &emitter->positional.max_distance, 0, "/positional"); + tg3__parse_double(ctx, *pos_it, "refDistance", + &emitter->positional.ref_distance, 0, "/positional"); + tg3__parse_double(ctx, *pos_it, "rolloffFactor", + &emitter->positional.rolloff_factor, 0, "/positional"); + tg3__parse_extras_and_extensions(ctx, *pos_it, &emitter->positional.ext); + } + + tg3__parse_extras_and_extensions(ctx, o, &emitter->ext); + return 1; +} + +/* ====================================================================== + * Internal: Portable variadic-comma helper + * + * TG3__COMMA_VA_ARGS(__VA_ARGS__) expands to , __VA_ARGS__ when the + * argument list is non-empty, and to nothing when it is empty. + * + * - C++20 and later: uses the standard __VA_OPT__(,) token. + * - C++17 and earlier: falls back to the widely-supported GNU/MSVC + * ##__VA_ARGS__ extension. + * ====================================================================== */ +#if __cplusplus >= 202002L +# define TG3__COMMA_VA_ARGS(...) __VA_OPT__(,) __VA_ARGS__ +#else +# define TG3__COMMA_VA_ARGS(...) , ##__VA_ARGS__ +#endif + +/* ====================================================================== + * Internal: Array Parse Macro + * ====================================================================== */ + +#define TG3__PARSE_ARRAY(ctx, json_doc, json_key, Type, model_field, count_field, parse_fn, ...) \ + do { \ + auto _arr_it = (json_doc).find(json_key); \ + if (_arr_it != (json_doc).end() && _arr_it->is_array()) { \ + uint32_t _count = (uint32_t)_arr_it->size(); \ + if (_count > 0) { \ + Type *_items = (Type *)tg3__arena_alloc((ctx)->arena, \ + _count * sizeof(Type)); \ + if (_items) { \ + uint32_t _i = 0; \ + for (auto _it = _arr_it->begin(); _it != _arr_it->end(); ++_it, ++_i) { \ + parse_fn((ctx), *_it, &_items[_i] TG3__COMMA_VA_ARGS(__VA_ARGS__)); \ + } \ + (model_field) = _items; \ + (count_field) = _count; \ + } \ + } \ + } \ + } while (0) + +/* Variant without extra args and with index param */ +#define TG3__PARSE_ARRAY_IDX(ctx, json_doc, json_key, Type, model_field, count_field, parse_fn) \ + do { \ + auto _arr_it = (json_doc).find(json_key); \ + if (_arr_it != (json_doc).end() && _arr_it->is_array()) { \ + uint32_t _count = (uint32_t)_arr_it->size(); \ + if (_count > 0) { \ + Type *_items = (Type *)tg3__arena_alloc((ctx)->arena, \ + _count * sizeof(Type)); \ + if (_items) { \ + uint32_t _i = 0; \ + for (auto _it = _arr_it->begin(); _it != _arr_it->end(); ++_it, ++_i) { \ + if (!_it->is_object()) { \ + tg3__error_pushf((ctx)->errors, (ctx)->arena, \ + TG3_SEVERITY_ERROR, TG3_ERR_JSON_TYPE_MISMATCH, \ + json_key, "Element %u must be an object", _i); \ + continue; \ + } \ + parse_fn((ctx), *_it, &_items[_i], (int32_t)_i); \ + } \ + (model_field) = _items; \ + (count_field) = _count; \ + } \ + } \ + } \ + } while (0) + +/* Simpler variant for entities without index */ +#define TG3__PARSE_ARRAY_SIMPLE(ctx, json_doc, json_key, Type, model_field, count_field, parse_fn) \ + do { \ + auto _arr_it = (json_doc).find(json_key); \ + if (_arr_it != (json_doc).end() && _arr_it->is_array()) { \ + uint32_t _count = (uint32_t)_arr_it->size(); \ + if (_count > 0) { \ + Type *_items = (Type *)tg3__arena_alloc((ctx)->arena, \ + _count * sizeof(Type)); \ + if (_items) { \ + uint32_t _i = 0; \ + for (auto _it = _arr_it->begin(); _it != _arr_it->end(); ++_it, ++_i) { \ + if (!_it->is_object()) { \ + tg3__error_pushf((ctx)->errors, (ctx)->arena, \ + TG3_SEVERITY_ERROR, TG3_ERR_JSON_TYPE_MISMATCH, \ + json_key, "Element %u must be an object", _i); \ + continue; \ + } \ + parse_fn((ctx), *_it, &_items[_i]); \ + } \ + (model_field) = _items; \ + (count_field) = _count; \ + } \ + } \ + } \ + } while (0) + +/* ====================================================================== + * Internal: Main Parse Orchestrator + * ====================================================================== */ + +static tg3_error_code tg3__parse_from_json(tg3__parse_ctx *ctx, + const tg3__json &json_doc, + tg3_model *model) { + /* Asset */ + auto asset_it = json_doc.find("asset"); + if (asset_it != json_doc.end() && asset_it->is_object()) { + tg3__parse_asset(ctx, *asset_it, &model->asset); + } else if (ctx->opts.required_sections & TG3_REQUIRE_VERSION) { + tg3__error_push(ctx->errors, TG3_SEVERITY_ERROR, TG3_ERR_MISSING_REQUIRED, + "Missing required 'asset' property", "/", -1); + return TG3_ERR_MISSING_REQUIRED; + } + + /* Extensions used/required */ + tg3__parse_string_array(ctx, json_doc, "extensionsUsed", + &model->extensions_used, + &model->extensions_used_count, 0, "/"); + tg3__parse_string_array(ctx, json_doc, "extensionsRequired", + &model->extensions_required, + &model->extensions_required_count, 0, "/"); + + /* Default scene */ + model->default_scene = -1; + tg3__parse_int(ctx, json_doc, "scene", &model->default_scene, 0, "/"); + + /* Streaming callback helper macro */ + #define TG3__STREAM_CB(type_name, cb_name, model_arr, model_cnt) \ + if (ctx->opts.stream && ctx->opts.stream->cb_name) { \ + for (uint32_t _si = 0; _si < model_cnt; ++_si) { \ + tg3_stream_action _sa = ctx->opts.stream->cb_name( \ + &model_arr[_si], (int32_t)_si, ctx->opts.stream->user_data); \ + if (_sa == TG3_STREAM_ABORT) return TG3_ERR_STREAM_ABORTED; \ + } \ + } + + /* Parse all entity arrays */ + TG3__PARSE_ARRAY_IDX(ctx, json_doc, "buffers", tg3_buffer, + model->buffers, model->buffers_count, tg3__parse_buffer); + TG3__STREAM_CB(buffer, on_buffer, model->buffers, model->buffers_count); + + TG3__PARSE_ARRAY_SIMPLE(ctx, json_doc, "bufferViews", tg3_buffer_view, + model->buffer_views, model->buffer_views_count, + tg3__parse_buffer_view); + TG3__STREAM_CB(buffer_view, on_buffer_view, model->buffer_views, + model->buffer_views_count); + + TG3__PARSE_ARRAY_SIMPLE(ctx, json_doc, "accessors", tg3_accessor, + model->accessors, model->accessors_count, + tg3__parse_accessor); + TG3__STREAM_CB(accessor, on_accessor, model->accessors, model->accessors_count); + + TG3__PARSE_ARRAY_SIMPLE(ctx, json_doc, "meshes", tg3_mesh, + model->meshes, model->meshes_count, tg3__parse_mesh); + TG3__STREAM_CB(mesh, on_mesh, model->meshes, model->meshes_count); + + TG3__PARSE_ARRAY_SIMPLE(ctx, json_doc, "nodes", tg3_node, + model->nodes, model->nodes_count, tg3__parse_node); + TG3__STREAM_CB(node, on_node, model->nodes, model->nodes_count); + + TG3__PARSE_ARRAY_SIMPLE(ctx, json_doc, "materials", tg3_material, + model->materials, model->materials_count, + tg3__parse_material); + TG3__STREAM_CB(material, on_material, model->materials, model->materials_count); + + TG3__PARSE_ARRAY_SIMPLE(ctx, json_doc, "textures", tg3_texture, + model->textures, model->textures_count, + tg3__parse_texture); + TG3__STREAM_CB(texture, on_texture, model->textures, model->textures_count); + + TG3__PARSE_ARRAY_SIMPLE(ctx, json_doc, "samplers", tg3_sampler, + model->samplers, model->samplers_count, + tg3__parse_sampler); + TG3__STREAM_CB(sampler, on_sampler, model->samplers, model->samplers_count); + + TG3__PARSE_ARRAY_IDX(ctx, json_doc, "images", tg3_image, + model->images, model->images_count, tg3__parse_image); + TG3__STREAM_CB(image, on_image, model->images, model->images_count); + + TG3__PARSE_ARRAY_SIMPLE(ctx, json_doc, "skins", tg3_skin, + model->skins, model->skins_count, tg3__parse_skin); + TG3__STREAM_CB(skin, on_skin, model->skins, model->skins_count); + + TG3__PARSE_ARRAY_SIMPLE(ctx, json_doc, "animations", tg3_animation, + model->animations, model->animations_count, + tg3__parse_animation); + TG3__STREAM_CB(animation, on_animation, model->animations, + model->animations_count); + + TG3__PARSE_ARRAY_SIMPLE(ctx, json_doc, "cameras", tg3_camera, + model->cameras, model->cameras_count, + tg3__parse_camera); + TG3__STREAM_CB(camera, on_camera, model->cameras, model->cameras_count); + + TG3__PARSE_ARRAY_SIMPLE(ctx, json_doc, "scenes", tg3_scene, + model->scenes, model->scenes_count, + tg3__parse_scene); + TG3__STREAM_CB(scene, on_scene, model->scenes, model->scenes_count); + + /* KHR_lights_punctual */ + auto ext_it = json_doc.find("extensions"); + if (ext_it != json_doc.end() && ext_it->is_object()) { + auto lights_ext = ext_it->find("KHR_lights_punctual"); + if (lights_ext != ext_it->end() && lights_ext->is_object()) { + TG3__PARSE_ARRAY_SIMPLE(ctx, *lights_ext, "lights", tg3_light, + model->lights, model->lights_count, + tg3__parse_light); + TG3__STREAM_CB(light, on_light, model->lights, model->lights_count); + } + + /* KHR_audio */ + auto audio_ext = ext_it->find("KHR_audio"); + if (audio_ext != ext_it->end() && audio_ext->is_object()) { + TG3__PARSE_ARRAY_SIMPLE(ctx, *audio_ext, "sources", tg3_audio_source, + model->audio_sources, model->audio_sources_count, + tg3__parse_audio_source); + TG3__PARSE_ARRAY_SIMPLE(ctx, *audio_ext, "emitters", tg3_audio_emitter, + model->audio_emitters, model->audio_emitters_count, + tg3__parse_audio_emitter); + } + } + + /* Root extras/extensions */ + tg3__parse_extras_and_extensions(ctx, json_doc, &model->ext); + + #undef TG3__STREAM_CB + + return ctx->errors->has_error ? TG3_ERR_JSON_PARSE : TG3_OK; +} + +/* ====================================================================== + * Internal: GLB Parsing + * ====================================================================== */ + +static tg3_error_code tg3__parse_glb_header(const uint8_t *data, uint64_t size, + const uint8_t **json_out, + uint64_t *json_size_out, + const uint8_t **bin_out, + uint64_t *bin_size_out, + tg3_error_stack *errors) { + *json_out = NULL; *json_size_out = 0; + *bin_out = NULL; *bin_size_out = 0; + + if (size < 12) { + tg3__error_push(errors, TG3_SEVERITY_ERROR, TG3_ERR_GLB_INVALID_HEADER, + "GLB data too small for header", NULL, -1); + return TG3_ERR_GLB_INVALID_HEADER; + } + + /* Check magic: 'glTF' */ + if (data[0] != 'g' || data[1] != 'l' || data[2] != 'T' || data[3] != 'F') { + tg3__error_push(errors, TG3_SEVERITY_ERROR, TG3_ERR_GLB_INVALID_MAGIC, + "Invalid GLB magic bytes", NULL, -1); + return TG3_ERR_GLB_INVALID_MAGIC; + } + + /* Version */ + uint32_t version; + memcpy(&version, data + 4, 4); + if (version != 2) { + tg3__error_push(errors, TG3_SEVERITY_ERROR, TG3_ERR_GLB_INVALID_VERSION, + "Unsupported GLB version (expected 2)", NULL, -1); + return TG3_ERR_GLB_INVALID_VERSION; + } + + /* Total length */ + uint32_t total_length; + memcpy(&total_length, data + 8, 4); + if ((uint64_t)total_length > size) { + tg3__error_push(errors, TG3_SEVERITY_ERROR, TG3_ERR_GLB_SIZE_MISMATCH, + "GLB total length exceeds data size", NULL, -1); + return TG3_ERR_GLB_SIZE_MISMATCH; + } + + if (total_length < 20) { + tg3__error_push(errors, TG3_SEVERITY_ERROR, TG3_ERR_GLB_INVALID_HEADER, + "GLB too small for JSON chunk header", NULL, -1); + return TG3_ERR_GLB_INVALID_HEADER; + } + + /* Chunk 0: JSON */ + uint32_t chunk0_length, chunk0_type; + memcpy(&chunk0_length, data + 12, 4); + memcpy(&chunk0_type, data + 16, 4); + + if (chunk0_type != 0x4E4F534A) { /* 'JSON' in LE */ + tg3__error_push(errors, TG3_SEVERITY_ERROR, TG3_ERR_GLB_CHUNK_ERROR, + "First GLB chunk is not JSON", NULL, -1); + return TG3_ERR_GLB_CHUNK_ERROR; + } + + if (20 + (uint64_t)chunk0_length > total_length) { + tg3__error_push(errors, TG3_SEVERITY_ERROR, TG3_ERR_GLB_CHUNK_ERROR, + "JSON chunk length exceeds GLB size", NULL, -1); + return TG3_ERR_GLB_CHUNK_ERROR; + } + + *json_out = data + 20; + *json_size_out = chunk0_length; + + /* Chunk 1: BIN (optional) */ + uint64_t bin_offset = 20 + (uint64_t)chunk0_length; + /* Align to 4 bytes */ + bin_offset = (bin_offset + 3) & ~(uint64_t)3; + + if (bin_offset + 8 <= total_length) { + uint32_t chunk1_length, chunk1_type; + memcpy(&chunk1_length, data + bin_offset, 4); + memcpy(&chunk1_type, data + bin_offset + 4, 4); + + if (chunk1_type == 0x004E4942) { /* 'BIN\0' in LE */ + if (bin_offset + 8 + chunk1_length <= total_length) { + *bin_out = data + bin_offset + 8; + *bin_size_out = chunk1_length; + } + } + } + + return TG3_OK; +} + +/* ====================================================================== + * Optional: Default FS Callbacks + * ====================================================================== */ + +#ifdef TINYGLTF3_ENABLE_FS + +static int32_t tg3__fs_file_exists(const char *path, uint32_t path_len, + void *ud) { + (void)ud; (void)path_len; + FILE *f = fopen(path, "rb"); + if (f) { fclose(f); return 1; } + return 0; +} + +static int32_t tg3__fs_read_file(uint8_t **out_data, uint64_t *out_size, + const char *path, uint32_t path_len, + void *ud) { + (void)ud; (void)path_len; + FILE *f = fopen(path, "rb"); + if (!f) return 0; + + fseek(f, 0, SEEK_END); + long sz = ftell(f); + fseek(f, 0, SEEK_SET); + if (sz < 0) { fclose(f); return 0; } + + uint8_t *data = (uint8_t *)malloc((size_t)sz); + if (!data) { fclose(f); return 0; } + + size_t read = fread(data, 1, (size_t)sz, f); + fclose(f); + + if ((long)read != sz) { free(data); return 0; } + + *out_data = data; + *out_size = (uint64_t)sz; + return 1; +} + +static void tg3__fs_free_file(uint8_t *data, uint64_t size, void *ud) { + (void)size; (void)ud; + free(data); +} + +static int32_t tg3__fs_write_file(const char *path, uint32_t path_len, + const uint8_t *data, uint64_t size, + void *ud) { + (void)ud; (void)path_len; + FILE *f = fopen(path, "wb"); + if (!f) return 0; + size_t written = fwrite(data, 1, (size_t)size, f); + fclose(f); + return (written == (size_t)size) ? 1 : 0; +} + +static void tg3__set_default_fs(tg3_fs_callbacks *fs) { + if (!fs->read_file) fs->read_file = tg3__fs_read_file; + if (!fs->free_file) fs->free_file = tg3__fs_free_file; + if (!fs->file_exists) fs->file_exists = tg3__fs_file_exists; + if (!fs->write_file) fs->write_file = tg3__fs_write_file; +} + +#endif /* TINYGLTF3_ENABLE_FS */ + +/* ====================================================================== + * Internal: Model Init Helper + * ====================================================================== */ + +static void tg3__model_init(tg3_model *model) { + memset(model, 0, sizeof(tg3_model)); + model->default_scene = -1; +} + +/* ====================================================================== + * Public: Parser API Implementation + * ====================================================================== */ + +TINYGLTF3_API tg3_error_code tg3_parse( + tg3_model *model, tg3_error_stack *errors, + const uint8_t *json_data, uint64_t json_size, + const char *base_dir, uint32_t base_dir_len, + const tg3_parse_options *options) { + + tg3_parse_options default_opts; + if (!options) { + tg3_parse_options_init(&default_opts); + options = &default_opts; + } + + tg3__model_init(model); + + tg3_arena *arena = tg3__arena_create(&options->memory); + if (!arena) { + tg3__error_push(errors, TG3_SEVERITY_ERROR, TG3_ERR_OUT_OF_MEMORY, + "Failed to create arena", NULL, -1); + return TG3_ERR_OUT_OF_MEMORY; + } + model->arena_ = arena; + + /* Parse JSON */ + tg3__json json_doc = options->parse_float32 + ? tg3__json::parse_float32( + (const char *)json_data, (const char *)json_data + json_size) + : tg3__json::parse( + (const char *)json_data, (const char *)json_data + json_size, + nullptr, false); + + if (json_doc.is_null()) { + tg3__error_push(errors, TG3_SEVERITY_ERROR, TG3_ERR_JSON_PARSE, + "Failed to parse JSON", NULL, -1); + return TG3_ERR_JSON_PARSE; + } + + if (!json_doc.is_object()) { + tg3__error_push(errors, TG3_SEVERITY_ERROR, TG3_ERR_JSON_PARSE, + "JSON root must be an object", NULL, -1); + return TG3_ERR_JSON_PARSE; + } + + tg3__parse_ctx ctx; + memset(&ctx, 0, sizeof(ctx)); + ctx.arena = arena; + ctx.errors = errors; + ctx.opts = *options; + ctx.base_dir = base_dir; + ctx.base_dir_len = base_dir_len; + ctx.is_binary = 0; + +#ifdef TINYGLTF3_ENABLE_FS + tg3__set_default_fs(&ctx.opts.fs); +#endif + + return tg3__parse_from_json(&ctx, json_doc, model); +} + +TINYGLTF3_API tg3_error_code tg3_parse_glb( + tg3_model *model, tg3_error_stack *errors, + const uint8_t *glb_data, uint64_t glb_size, + const char *base_dir, uint32_t base_dir_len, + const tg3_parse_options *options) { + + const uint8_t *json_chunk = NULL; + uint64_t json_chunk_size = 0; + const uint8_t *bin_chunk = NULL; + uint64_t bin_chunk_size = 0; + + tg3_error_code err = tg3__parse_glb_header(glb_data, glb_size, + &json_chunk, &json_chunk_size, + &bin_chunk, &bin_chunk_size, + errors); + if (err != TG3_OK) return err; + + tg3_parse_options default_opts; + if (!options) { + tg3_parse_options_init(&default_opts); + options = &default_opts; + } + + tg3__model_init(model); + + tg3_arena *arena = tg3__arena_create(&options->memory); + if (!arena) { + tg3__error_push(errors, TG3_SEVERITY_ERROR, TG3_ERR_OUT_OF_MEMORY, + "Failed to create arena", NULL, -1); + return TG3_ERR_OUT_OF_MEMORY; + } + model->arena_ = arena; + + /* Parse JSON chunk */ + tg3__json json_doc = options->parse_float32 + ? tg3__json::parse_float32( + (const char *)json_chunk, (const char *)json_chunk + json_chunk_size) + : tg3__json::parse( + (const char *)json_chunk, (const char *)json_chunk + json_chunk_size, + nullptr, false); + + if (json_doc.is_null() || !json_doc.is_object()) { + tg3__error_push(errors, TG3_SEVERITY_ERROR, TG3_ERR_JSON_PARSE, + "Failed to parse GLB JSON chunk", NULL, -1); + return TG3_ERR_JSON_PARSE; + } + + tg3__parse_ctx ctx; + memset(&ctx, 0, sizeof(ctx)); + ctx.arena = arena; + ctx.errors = errors; + ctx.opts = *options; + ctx.base_dir = base_dir; + ctx.base_dir_len = base_dir_len; + ctx.is_binary = 1; + ctx.bin_data = bin_chunk; + ctx.bin_size = bin_chunk_size; + +#ifdef TINYGLTF3_ENABLE_FS + tg3__set_default_fs(&ctx.opts.fs); +#endif + + return tg3__parse_from_json(&ctx, json_doc, model); +} + +TINYGLTF3_API tg3_error_code tg3_parse_auto( + tg3_model *model, tg3_error_stack *errors, + const uint8_t *data, uint64_t size, + const char *base_dir, uint32_t base_dir_len, + const tg3_parse_options *options) { + + /* Check for GLB magic */ + if (size >= 4 && data[0] == 'g' && data[1] == 'l' && + data[2] == 'T' && data[3] == 'F') { + return tg3_parse_glb(model, errors, data, size, + base_dir, base_dir_len, options); + } + return tg3_parse(model, errors, data, size, + base_dir, base_dir_len, options); +} + +TINYGLTF3_API tg3_error_code tg3_parse_file( + tg3_model *model, tg3_error_stack *errors, + const char *filename, uint32_t filename_len, + const tg3_parse_options *options) { + + tg3_parse_options opts; + if (options) { + opts = *options; + } else { + tg3_parse_options_init(&opts); + } + +#ifdef TINYGLTF3_ENABLE_FS + tg3__set_default_fs(&opts.fs); +#endif + + if (!opts.fs.read_file) { + tg3__error_push(errors, TG3_SEVERITY_ERROR, TG3_ERR_FS_NOT_AVAILABLE, + "No filesystem callbacks. Define TINYGLTF3_ENABLE_FS " + "or provide fs callbacks.", NULL, -1); + return TG3_ERR_FS_NOT_AVAILABLE; + } + + /* Read file */ + uint8_t *file_data = NULL; + uint64_t file_size = 0; + int32_t ok = opts.fs.read_file(&file_data, &file_size, filename, + filename_len, opts.fs.user_data); + if (!ok || !file_data) { + tg3__error_push(errors, TG3_SEVERITY_ERROR, TG3_ERR_FILE_NOT_FOUND, + "Failed to read file", NULL, -1); + return TG3_ERR_FILE_NOT_FOUND; + } + + /* Extract base directory */ + char base_dir_buf[4096] = {0}; + uint32_t base_dir_len = 0; + if (filename && filename_len > 0) { + /* Find last separator */ + const char *last_sep = NULL; + for (uint32_t i = 0; i < filename_len; ++i) { + if (filename[i] == '/' || filename[i] == '\\') { + last_sep = filename + i; + } + } + if (last_sep) { + base_dir_len = (uint32_t)(last_sep - filename); + if (base_dir_len >= sizeof(base_dir_buf)) + base_dir_len = (uint32_t)(sizeof(base_dir_buf) - 1); + memcpy(base_dir_buf, filename, base_dir_len); + base_dir_buf[base_dir_len] = '\0'; + } + } + + tg3_error_code result = tg3_parse_auto(model, errors, file_data, file_size, + base_dir_buf, base_dir_len, &opts); + + /* Free file data */ + if (opts.fs.free_file) { + opts.fs.free_file(file_data, file_size, opts.fs.user_data); + } + + return result; +} + +TINYGLTF3_API void tg3_model_free(tg3_model *model) { + if (!model) return; + if (model->arena_) { + tg3__arena_destroy(model->arena_); + } + memset(model, 0, sizeof(tg3_model)); + model->default_scene = -1; +} + +/* ====================================================================== + * Internal: JSON Serialization Helpers + * ====================================================================== */ + +static void tg3__serialize_str(tg3__json &o, const char *key, tg3_str s) { + if (s.data && s.len > 0) { + o[key] = std::string(s.data, s.len); + } +} + +static void tg3__serialize_int(tg3__json &o, const char *key, int32_t val, + int32_t default_val, int write_defaults) { + if (val != default_val || write_defaults) { + o[key] = val; + } +} + +static void tg3__serialize_uint64(tg3__json &o, const char *key, uint64_t val, + uint64_t default_val, int write_defaults) { + if (val != default_val || write_defaults) { + o[key] = (int64_t)val; + } +} + +static void tg3__serialize_double(tg3__json &o, const char *key, double val, + double default_val, int write_defaults) { + if (fabs(val - default_val) > 1e-12 || write_defaults) { + o[key] = val; + } +} + +static void tg3__serialize_bool(tg3__json &o, const char *key, int32_t val, + int32_t default_val, int write_defaults) { + if (val != default_val || write_defaults) { + o[key] = (val != 0); + } +} + +static void tg3__serialize_double_array(tg3__json &o, const char *key, + const double *arr, uint32_t count) { + if (!arr || count == 0) return; + tg3__json jarr; + jarr.set_array(); + for (uint32_t i = 0; i < count; ++i) { + jarr.push_back(tg3__json(arr[i])); + } + o[key] = static_cast(jarr); +} + +static void tg3__serialize_int_array(tg3__json &o, const char *key, + const int32_t *arr, uint32_t count) { + if (!arr || count == 0) return; + tg3__json jarr; + jarr.set_array(); + for (uint32_t i = 0; i < count; ++i) { + jarr.push_back(tg3__json(arr[i])); + } + o[key] = static_cast(jarr); +} + +static void tg3__serialize_string_array(tg3__json &o, const char *key, + const tg3_str *arr, uint32_t count) { + if (!arr || count == 0) return; + tg3__json jarr; + jarr.set_array(); + for (uint32_t i = 0; i < count; ++i) { + if (arr[i].data) { + jarr.push_back(tg3__json(std::string(arr[i].data, arr[i].len))); + } + } + o[key] = static_cast(jarr); +} + +static tg3__json tg3__value_to_json(const tg3_value *v) { + if (!v) return tg3__json(); + switch (v->type) { + case TG3_VALUE_NULL: return tg3__json(); + case TG3_VALUE_BOOL: return tg3__json(v->bool_val != 0); + case TG3_VALUE_INT: return tg3__json(v->int_val); + case TG3_VALUE_REAL: return tg3__json(v->real_val); + case TG3_VALUE_STRING: + return tg3__json(std::string(v->string_val.data ? v->string_val.data : "", + v->string_val.len)); + case TG3_VALUE_ARRAY: { + tg3__json arr; + arr.set_array(); + for (uint32_t i = 0; i < v->array_count; ++i) { + arr.push_back(tg3__value_to_json(&v->array_data[i])); + } + return arr; + } + case TG3_VALUE_OBJECT: { + tg3__json obj = tg3__json::object(); + for (uint32_t i = 0; i < v->object_count; ++i) { + std::string k(v->object_data[i].key.data ? v->object_data[i].key.data : "", + v->object_data[i].key.len); + obj[k.c_str()] = tg3__value_to_json(&v->object_data[i].value); + } + return obj; + } + default: return tg3__json(); + } +} + +static void tg3__serialize_extras_ext(tg3__json &o, const tg3_extras_ext *ee) { + if (!ee) return; + if (ee->extras) { + o["extras"] = tg3__value_to_json(ee->extras); + } + if (ee->extensions && ee->extensions_count > 0) { + tg3__json exts = tg3__json::object(); + for (uint32_t i = 0; i < ee->extensions_count; ++i) { + std::string name(ee->extensions[i].name.data ? ee->extensions[i].name.data : "", + ee->extensions[i].name.len); + exts[name.c_str()] = tg3__value_to_json(&ee->extensions[i].value); + } + o["extensions"] = static_cast(exts); + } +} + +/* ====================================================================== + * Internal: Entity Serialize Functions + * ====================================================================== */ + +static void tg3__serialize_texture_info(tg3__json &parent, const char *key, + const tg3_texture_info *ti, int wd) { + if (ti->index < 0) return; + tg3__json o = tg3__json::object(); + o["index"] = ti->index; + tg3__serialize_int(o, "texCoord", ti->tex_coord, 0, wd); + tg3__serialize_extras_ext(o, &ti->ext); + parent[key] = static_cast(o); +} + +static void tg3__serialize_normal_texture_info(tg3__json &parent, const char *key, + const tg3_normal_texture_info *ti, + int wd) { + if (ti->index < 0) return; + tg3__json o = tg3__json::object(); + o["index"] = ti->index; + tg3__serialize_int(o, "texCoord", ti->tex_coord, 0, wd); + tg3__serialize_double(o, "scale", ti->scale, 1.0, wd); + tg3__serialize_extras_ext(o, &ti->ext); + parent[key] = static_cast(o); +} + +static void tg3__serialize_occlusion_texture_info(tg3__json &parent, const char *key, + const tg3_occlusion_texture_info *ti, + int wd) { + if (ti->index < 0) return; + tg3__json o = tg3__json::object(); + o["index"] = ti->index; + tg3__serialize_int(o, "texCoord", ti->tex_coord, 0, wd); + tg3__serialize_double(o, "strength", ti->strength, 1.0, wd); + tg3__serialize_extras_ext(o, &ti->ext); + parent[key] = static_cast(o); +} + +static tg3__json tg3__serialize_asset(const tg3_asset *a, int wd) { + (void)wd; + tg3__json o = tg3__json::object(); + tg3__serialize_str(o, "version", a->version); + tg3__serialize_str(o, "generator", a->generator); + tg3__serialize_str(o, "minVersion", a->min_version); + tg3__serialize_str(o, "copyright", a->copyright); + tg3__serialize_extras_ext(o, &a->ext); + return o; +} + +static tg3__json tg3__serialize_buffer(const tg3_buffer *b, int wd, + int embed) { + (void)wd; + tg3__json o = tg3__json::object(); + tg3__serialize_str(o, "name", b->name); + o["byteLength"] = (int64_t)b->data.count; + + if (b->uri.data && b->uri.len > 0) { + tg3__serialize_str(o, "uri", b->uri); + } else if (embed && b->data.data && b->data.count > 0) { + /* Encode as data URI */ + size_t enc_len = 0; + char *encoded = tg3__b64_encode(b->data.data, (size_t)b->data.count, + &enc_len); + if (encoded) { + std::string uri = "data:application/octet-stream;base64,"; + uri.append(encoded, enc_len); + o["uri"] = uri; + free(encoded); + } + } + + tg3__serialize_extras_ext(o, &b->ext); + return o; +} + +static tg3__json tg3__serialize_buffer_view(const tg3_buffer_view *bv, int wd) { + tg3__json o = tg3__json::object(); + tg3__serialize_str(o, "name", bv->name); + o["buffer"] = bv->buffer; + o["byteLength"] = (int64_t)bv->byte_length; + tg3__serialize_uint64(o, "byteOffset", bv->byte_offset, 0, wd); + if (bv->byte_stride > 0) o["byteStride"] = (int)bv->byte_stride; + tg3__serialize_int(o, "target", bv->target, 0, wd); + tg3__serialize_extras_ext(o, &bv->ext); + return o; +} + +static tg3__json tg3__serialize_accessor(const tg3_accessor *acc, int wd) { + tg3__json o = tg3__json::object(); + tg3__serialize_str(o, "name", acc->name); + if (acc->buffer_view >= 0) o["bufferView"] = acc->buffer_view; + tg3__serialize_uint64(o, "byteOffset", acc->byte_offset, 0, wd); + o["componentType"] = acc->component_type; + o["count"] = (int64_t)acc->count; + o["type"] = tg3__accessor_type_to_string(acc->type); + tg3__serialize_bool(o, "normalized", acc->normalized, 0, wd); + + tg3__serialize_double_array(o, "min", acc->min_values, acc->min_values_count); + tg3__serialize_double_array(o, "max", acc->max_values, acc->max_values_count); + + if (acc->sparse.is_sparse) { + tg3__json sparse = tg3__json::object(); + sparse["count"] = acc->sparse.count; + + tg3__json indices = tg3__json::object(); + indices["bufferView"] = acc->sparse.indices.buffer_view; + indices["componentType"] = acc->sparse.indices.component_type; + tg3__serialize_uint64(indices, "byteOffset", + acc->sparse.indices.byte_offset, 0, wd); + tg3__serialize_extras_ext(indices, &acc->sparse.indices.ext); + sparse["indices"] = static_cast(indices); + + tg3__json values = tg3__json::object(); + values["bufferView"] = acc->sparse.values.buffer_view; + tg3__serialize_uint64(values, "byteOffset", + acc->sparse.values.byte_offset, 0, wd); + tg3__serialize_extras_ext(values, &acc->sparse.values.ext); + sparse["values"] = static_cast(values); + + tg3__serialize_extras_ext(sparse, &acc->sparse.ext); + o["sparse"] = static_cast(sparse); + } + + tg3__serialize_extras_ext(o, &acc->ext); + return o; +} + +static tg3__json tg3__serialize_image(const tg3_image *img, int wd, int embed) { + (void)wd; (void)embed; + tg3__json o = tg3__json::object(); + tg3__serialize_str(o, "name", img->name); + tg3__serialize_str(o, "uri", img->uri); + tg3__serialize_str(o, "mimeType", img->mime_type); + if (img->buffer_view >= 0) o["bufferView"] = img->buffer_view; + tg3__serialize_extras_ext(o, &img->ext); + return o; +} + +static tg3__json tg3__serialize_sampler(const tg3_sampler *s, int wd) { + tg3__json o = tg3__json::object(); + tg3__serialize_str(o, "name", s->name); + if (s->min_filter >= 0) o["minFilter"] = s->min_filter; + if (s->mag_filter >= 0) o["magFilter"] = s->mag_filter; + tg3__serialize_int(o, "wrapS", s->wrap_s, TG3_TEXTURE_WRAP_REPEAT, wd); + tg3__serialize_int(o, "wrapT", s->wrap_t, TG3_TEXTURE_WRAP_REPEAT, wd); + tg3__serialize_extras_ext(o, &s->ext); + return o; +} + +static tg3__json tg3__serialize_texture(const tg3_texture *t, int wd) { + (void)wd; + tg3__json o = tg3__json::object(); + tg3__serialize_str(o, "name", t->name); + if (t->sampler >= 0) o["sampler"] = t->sampler; + if (t->source >= 0) o["source"] = t->source; + tg3__serialize_extras_ext(o, &t->ext); + return o; +} + +static tg3__json tg3__serialize_material(const tg3_material *m, int wd) { + tg3__json o = tg3__json::object(); + tg3__serialize_str(o, "name", m->name); + + /* PBR */ + tg3__json pbr = tg3__json::object(); + int has_pbr = 0; + + const tg3_pbr_metallic_roughness *p = &m->pbr_metallic_roughness; + if (p->base_color_factor[0] != 1.0 || p->base_color_factor[1] != 1.0 || + p->base_color_factor[2] != 1.0 || p->base_color_factor[3] != 1.0 || wd) { + tg3__serialize_double_array(pbr, "baseColorFactor", + p->base_color_factor, 4); + has_pbr = 1; + } + tg3__serialize_double(pbr, "metallicFactor", p->metallic_factor, 1.0, wd); + if (fabs(p->metallic_factor - 1.0) > 1e-12 || wd) has_pbr = 1; + tg3__serialize_double(pbr, "roughnessFactor", p->roughness_factor, 1.0, wd); + if (fabs(p->roughness_factor - 1.0) > 1e-12 || wd) has_pbr = 1; + + if (p->base_color_texture.index >= 0) { + tg3__serialize_texture_info(pbr, "baseColorTexture", + &p->base_color_texture, wd); + has_pbr = 1; + } + if (p->metallic_roughness_texture.index >= 0) { + tg3__serialize_texture_info(pbr, "metallicRoughnessTexture", + &p->metallic_roughness_texture, wd); + has_pbr = 1; + } + tg3__serialize_extras_ext(pbr, &p->ext); + if (has_pbr || wd) { + o["pbrMetallicRoughness"] = static_cast(pbr); + } + + tg3__serialize_normal_texture_info(o, "normalTexture", &m->normal_texture, wd); + tg3__serialize_occlusion_texture_info(o, "occlusionTexture", + &m->occlusion_texture, wd); + tg3__serialize_texture_info(o, "emissiveTexture", &m->emissive_texture, wd); + + if (m->emissive_factor[0] != 0.0 || m->emissive_factor[1] != 0.0 || + m->emissive_factor[2] != 0.0 || wd) { + tg3__serialize_double_array(o, "emissiveFactor", m->emissive_factor, 3); + } + + if (m->alpha_mode.data && !tg3_str_equals_cstr(m->alpha_mode, "OPAQUE")) { + tg3__serialize_str(o, "alphaMode", m->alpha_mode); + } + tg3__serialize_double(o, "alphaCutoff", m->alpha_cutoff, 0.5, wd); + tg3__serialize_bool(o, "doubleSided", m->double_sided, 0, wd); + + tg3__serialize_extras_ext(o, &m->ext); + return o; +} + +static tg3__json tg3__serialize_primitive(const tg3_primitive *p, int wd) { + tg3__json o = tg3__json::object(); + + /* Attributes */ + if (p->attributes && p->attributes_count > 0) { + tg3__json attrs = tg3__json::object(); + for (uint32_t i = 0; i < p->attributes_count; ++i) { + std::string k(p->attributes[i].key.data ? p->attributes[i].key.data : "", + p->attributes[i].key.len); + attrs[k.c_str()] = p->attributes[i].value; + } + o["attributes"] = static_cast(attrs); + } + + if (p->indices >= 0) o["indices"] = p->indices; + if (p->material >= 0) o["material"] = p->material; + tg3__serialize_int(o, "mode", p->mode, TG3_MODE_TRIANGLES, wd); + + /* Morph targets */ + if (p->targets && p->targets_count > 0) { + tg3__json targets; + targets.set_array(); + for (uint32_t t = 0; t < p->targets_count; ++t) { + tg3__json tgt = tg3__json::object(); + uint32_t acount = p->target_attribute_counts ? + p->target_attribute_counts[t] : 0; + const tg3_str_int_pair *tattrs = p->targets[t]; + for (uint32_t a = 0; a < acount; ++a) { + std::string k(tattrs[a].key.data ? tattrs[a].key.data : "", + tattrs[a].key.len); + tgt[k.c_str()] = tattrs[a].value; + } + targets.push_back(static_cast(tgt)); + } + o["targets"] = static_cast(targets); + } + + tg3__serialize_extras_ext(o, &p->ext); + return o; +} + +static tg3__json tg3__serialize_mesh(const tg3_mesh *m, int wd) { + tg3__json o = tg3__json::object(); + tg3__serialize_str(o, "name", m->name); + + if (m->primitives && m->primitives_count > 0) { + tg3__json prims; + prims.set_array(); + for (uint32_t i = 0; i < m->primitives_count; ++i) { + prims.push_back(tg3__serialize_primitive(&m->primitives[i], wd)); + } + o["primitives"] = static_cast(prims); + } + + tg3__serialize_double_array(o, "weights", m->weights, m->weights_count); + tg3__serialize_extras_ext(o, &m->ext); + return o; +} + +static tg3__json tg3__serialize_node(const tg3_node *n, int wd) { + tg3__json o = tg3__json::object(); + tg3__serialize_str(o, "name", n->name); + + if (n->camera >= 0) o["camera"] = n->camera; + if (n->skin >= 0) o["skin"] = n->skin; + if (n->mesh >= 0) o["mesh"] = n->mesh; + + tg3__serialize_int_array(o, "children", n->children, n->children_count); + + if (n->has_matrix) { + tg3__serialize_double_array(o, "matrix", n->matrix, 16); + } else { + int has_t = (n->translation[0] != 0.0 || n->translation[1] != 0.0 || + n->translation[2] != 0.0); + int has_r = (n->rotation[0] != 0.0 || n->rotation[1] != 0.0 || + n->rotation[2] != 0.0 || n->rotation[3] != 1.0); + int has_s = (n->scale[0] != 1.0 || n->scale[1] != 1.0 || + n->scale[2] != 1.0); + + if (has_t || wd) tg3__serialize_double_array(o, "translation", n->translation, 3); + if (has_r || wd) tg3__serialize_double_array(o, "rotation", n->rotation, 4); + if (has_s || wd) tg3__serialize_double_array(o, "scale", n->scale, 3); + } + + tg3__serialize_double_array(o, "weights", n->weights, n->weights_count); + + /* Extensions for lights / audio / lod */ + int has_ext = (n->light >= 0 || n->emitter >= 0 || + (n->lods && n->lods_count > 0)); + if (has_ext) { + /* Check if extensions already set by extras_ext */ + auto existing = o.find("extensions"); + tg3__json exts = (existing != o.end()) ? + tg3__json(*existing) : tg3__json::object(); + + if (n->light >= 0) { + tg3__json lp = tg3__json::object(); + lp["light"] = n->light; + exts["KHR_lights_punctual"] = static_cast(lp); + } + if (n->emitter >= 0) { + tg3__json ae = tg3__json::object(); + ae["emitter"] = n->emitter; + exts["KHR_audio"] = static_cast(ae); + } + if (n->lods && n->lods_count > 0) { + tg3__json lod = tg3__json::object(); + tg3__serialize_int_array(lod, "ids", n->lods, n->lods_count); + exts["MSFT_lod"] = static_cast(lod); + } + o["extensions"] = static_cast(exts); + } + + tg3__serialize_extras_ext(o, &n->ext); + return o; +} + +static tg3__json tg3__serialize_skin(const tg3_skin *s, int wd) { + (void)wd; + tg3__json o = tg3__json::object(); + tg3__serialize_str(o, "name", s->name); + if (s->inverse_bind_matrices >= 0) o["inverseBindMatrices"] = s->inverse_bind_matrices; + if (s->skeleton >= 0) o["skeleton"] = s->skeleton; + tg3__serialize_int_array(o, "joints", s->joints, s->joints_count); + tg3__serialize_extras_ext(o, &s->ext); + return o; +} + +static tg3__json tg3__serialize_animation(const tg3_animation *a, int wd) { + (void)wd; + tg3__json o = tg3__json::object(); + tg3__serialize_str(o, "name", a->name); + + if (a->channels && a->channels_count > 0) { + tg3__json channels; + channels.set_array(); + for (uint32_t i = 0; i < a->channels_count; ++i) { + tg3__json ch = tg3__json::object(); + ch["sampler"] = a->channels[i].sampler; + tg3__json tgt = tg3__json::object(); + if (a->channels[i].target.node >= 0) + tgt["node"] = a->channels[i].target.node; + tg3__serialize_str(tgt, "path", a->channels[i].target.path); + tg3__serialize_extras_ext(tgt, &a->channels[i].target.ext); + ch["target"] = static_cast(tgt); + tg3__serialize_extras_ext(ch, &a->channels[i].ext); + channels.push_back(static_cast(ch)); + } + o["channels"] = static_cast(channels); + } + + if (a->samplers && a->samplers_count > 0) { + tg3__json samplers; + samplers.set_array(); + for (uint32_t i = 0; i < a->samplers_count; ++i) { + tg3__json s = tg3__json::object(); + s["input"] = a->samplers[i].input; + s["output"] = a->samplers[i].output; + tg3__serialize_str(s, "interpolation", a->samplers[i].interpolation); + tg3__serialize_extras_ext(s, &a->samplers[i].ext); + samplers.push_back(static_cast(s)); + } + o["samplers"] = static_cast(samplers); + } + + tg3__serialize_extras_ext(o, &a->ext); + return o; +} + +static tg3__json tg3__serialize_camera(const tg3_camera *c, int wd) { + (void)wd; + tg3__json o = tg3__json::object(); + tg3__serialize_str(o, "name", c->name); + tg3__serialize_str(o, "type", c->type); + + if (c->type.data && tg3_str_equals_cstr(c->type, "perspective")) { + tg3__json p = tg3__json::object(); + if (c->perspective.aspect_ratio > 0) + p["aspectRatio"] = c->perspective.aspect_ratio; + p["yfov"] = c->perspective.yfov; + if (c->perspective.zfar > 0) p["zfar"] = c->perspective.zfar; + p["znear"] = c->perspective.znear; + tg3__serialize_extras_ext(p, &c->perspective.ext); + o["perspective"] = static_cast(p); + } else if (c->type.data && tg3_str_equals_cstr(c->type, "orthographic")) { + tg3__json orth = tg3__json::object(); + orth["xmag"] = c->orthographic.xmag; + orth["ymag"] = c->orthographic.ymag; + orth["zfar"] = c->orthographic.zfar; + orth["znear"] = c->orthographic.znear; + tg3__serialize_extras_ext(orth, &c->orthographic.ext); + o["orthographic"] = static_cast(orth); + } + + tg3__serialize_extras_ext(o, &c->ext); + return o; +} + +static tg3__json tg3__serialize_scene(const tg3_scene *s, int wd) { + (void)wd; + tg3__json o = tg3__json::object(); + tg3__serialize_str(o, "name", s->name); + tg3__serialize_int_array(o, "nodes", s->nodes, s->nodes_count); + tg3__serialize_extras_ext(o, &s->ext); + return o; +} + +static tg3__json tg3__serialize_light(const tg3_light *l, int wd) { + tg3__json o = tg3__json::object(); + tg3__serialize_str(o, "name", l->name); + tg3__serialize_str(o, "type", l->type); + tg3__serialize_double(o, "intensity", l->intensity, 1.0, wd); + tg3__serialize_double(o, "range", l->range, 0.0, wd); + + if (l->color[0] != 1.0 || l->color[1] != 1.0 || l->color[2] != 1.0 || wd) { + tg3__serialize_double_array(o, "color", l->color, 3); + } + + if (l->type.data && tg3_str_equals_cstr(l->type, "spot")) { + tg3__json spot = tg3__json::object(); + tg3__serialize_double(spot, "innerConeAngle", l->spot.inner_cone_angle, 0.0, wd); + tg3__serialize_double(spot, "outerConeAngle", l->spot.outer_cone_angle, + 0.7853981634, wd); + tg3__serialize_extras_ext(spot, &l->spot.ext); + o["spot"] = static_cast(spot); + } + + tg3__serialize_extras_ext(o, &l->ext); + return o; +} + +/* ====================================================================== + * Internal: Main Model Serializer + * ====================================================================== */ + +static tg3__json tg3__serialize_model(const tg3_model *model, int wd, + int embed_images, int embed_buffers) { + tg3__json root = tg3__json::object(); + + /* Asset */ + root["asset"] = tg3__serialize_asset(&model->asset, wd); + + /* Default scene */ + if (model->default_scene >= 0) { + root["scene"] = model->default_scene; + } + + /* Extensions used/required */ + tg3__serialize_string_array(root, "extensionsUsed", + model->extensions_used, + model->extensions_used_count); + tg3__serialize_string_array(root, "extensionsRequired", + model->extensions_required, + model->extensions_required_count); + + /* Entity arrays */ + #define TG3__SERIALIZE_ARRAY(key, arr, cnt, fn, ...) \ + if ((arr) && (cnt) > 0) { \ + tg3__json jarr; jarr.set_array(); \ + for (uint32_t _i = 0; _i < (cnt); ++_i) { \ + jarr.push_back(fn(&(arr)[_i] TG3__COMMA_VA_ARGS(__VA_ARGS__))); \ + } \ + root[key] = static_cast(jarr); \ + } + + TG3__SERIALIZE_ARRAY("buffers", model->buffers, model->buffers_count, + tg3__serialize_buffer, wd, embed_buffers); + TG3__SERIALIZE_ARRAY("bufferViews", model->buffer_views, + model->buffer_views_count, tg3__serialize_buffer_view, wd); + TG3__SERIALIZE_ARRAY("accessors", model->accessors, model->accessors_count, + tg3__serialize_accessor, wd); + TG3__SERIALIZE_ARRAY("meshes", model->meshes, model->meshes_count, + tg3__serialize_mesh, wd); + TG3__SERIALIZE_ARRAY("nodes", model->nodes, model->nodes_count, + tg3__serialize_node, wd); + TG3__SERIALIZE_ARRAY("materials", model->materials, model->materials_count, + tg3__serialize_material, wd); + TG3__SERIALIZE_ARRAY("textures", model->textures, model->textures_count, + tg3__serialize_texture, wd); + TG3__SERIALIZE_ARRAY("samplers", model->samplers, model->samplers_count, + tg3__serialize_sampler, wd); + TG3__SERIALIZE_ARRAY("images", model->images, model->images_count, + tg3__serialize_image, wd, embed_images); + TG3__SERIALIZE_ARRAY("skins", model->skins, model->skins_count, + tg3__serialize_skin, wd); + TG3__SERIALIZE_ARRAY("animations", model->animations, model->animations_count, + tg3__serialize_animation, wd); + TG3__SERIALIZE_ARRAY("cameras", model->cameras, model->cameras_count, + tg3__serialize_camera, wd); + TG3__SERIALIZE_ARRAY("scenes", model->scenes, model->scenes_count, + tg3__serialize_scene, wd); + + /* KHR_lights_punctual */ + if (model->lights && model->lights_count > 0) { + tg3__json lights_ext = tg3__json::object(); + tg3__json lights; + lights.set_array(); + for (uint32_t i = 0; i < model->lights_count; ++i) { + lights.push_back(tg3__serialize_light(&model->lights[i], wd)); + } + lights_ext["lights"] = static_cast(lights); + + auto ext_it = root.find("extensions"); + tg3__json exts = (ext_it != root.end()) ? + tg3__json(*ext_it) : tg3__json::object(); + exts["KHR_lights_punctual"] = static_cast(lights_ext); + root["extensions"] = static_cast(exts); + } + + /* Root extras/extensions */ + tg3__serialize_extras_ext(root, &model->ext); + + #undef TG3__SERIALIZE_ARRAY + return root; +} + +/* ====================================================================== + * Public: Writer API Implementation + * ====================================================================== */ + +TINYGLTF3_API tg3_error_code tg3_write_to_memory( + const tg3_model *model, tg3_error_stack *errors, + uint8_t **out_data, uint64_t *out_size, + const tg3_write_options *options) { + + tg3_write_options default_opts; + if (!options) { + tg3_write_options_init(&default_opts); + options = &default_opts; + } + + int wd = options->serialize_defaults; + tg3__json root = tg3__serialize_model(model, wd, + options->embed_images, + options->embed_buffers); + + int indent = options->pretty_print ? 2 : -1; + std::string json_str = root.dump(indent); + + if (options->write_binary) { + /* GLB format */ + uint32_t json_len = (uint32_t)json_str.size(); + /* Pad JSON to 4-byte alignment with spaces */ + uint32_t json_padded = (json_len + 3) & ~3u; + + /* Collect binary buffer data */ + const uint8_t *bin_data = NULL; + uint64_t bin_len = 0; + if (model->buffers_count > 0 && model->buffers[0].data.data) { + bin_data = model->buffers[0].data.data; + bin_len = model->buffers[0].data.count; + } + uint32_t bin_padded = ((uint32_t)bin_len + 3) & ~3u; + + uint32_t total = 12; /* Header */ + total += 8 + json_padded; /* JSON chunk */ + if (bin_data && bin_len > 0) { + total += 8 + bin_padded; /* BIN chunk */ + } + + uint8_t *glb = (uint8_t *)malloc(total); + if (!glb) { + tg3__error_push(errors, TG3_SEVERITY_ERROR, TG3_ERR_OUT_OF_MEMORY, + "OOM allocating GLB output", NULL, -1); + return TG3_ERR_OUT_OF_MEMORY; + } + + /* Header */ + memcpy(glb, "glTF", 4); + uint32_t version = 2; + memcpy(glb + 4, &version, 4); + memcpy(glb + 8, &total, 4); + + /* JSON chunk */ + memcpy(glb + 12, &json_padded, 4); + uint32_t json_type = 0x4E4F534A; + memcpy(glb + 16, &json_type, 4); + memcpy(glb + 20, json_str.c_str(), json_len); + /* Pad with spaces */ + for (uint32_t i = json_len; i < json_padded; ++i) { + glb[20 + i] = ' '; + } + + /* BIN chunk */ + if (bin_data && bin_len > 0) { + uint32_t bin_off = 20 + json_padded; + memcpy(glb + bin_off, &bin_padded, 4); + uint32_t bin_type = 0x004E4942; + memcpy(glb + bin_off + 4, &bin_type, 4); + memcpy(glb + bin_off + 8, bin_data, (size_t)bin_len); + /* Pad with zeros */ + for (uint32_t i = (uint32_t)bin_len; i < bin_padded; ++i) { + glb[bin_off + 8 + i] = 0; + } + } + + *out_data = glb; + *out_size = total; + } else { + /* JSON format */ + uint64_t sz = json_str.size(); + uint8_t *data = (uint8_t *)malloc((size_t)sz); + if (!data) { + tg3__error_push(errors, TG3_SEVERITY_ERROR, TG3_ERR_OUT_OF_MEMORY, + "OOM allocating JSON output", NULL, -1); + return TG3_ERR_OUT_OF_MEMORY; + } + memcpy(data, json_str.c_str(), (size_t)sz); + *out_data = data; + *out_size = sz; + } + + return TG3_OK; +} + +TINYGLTF3_API tg3_error_code tg3_write_to_file( + const tg3_model *model, tg3_error_stack *errors, + const char *filename, uint32_t filename_len, + const tg3_write_options *options) { + + tg3_write_options opts; + if (options) { + opts = *options; + } else { + tg3_write_options_init(&opts); + } + +#ifdef TINYGLTF3_ENABLE_FS + tg3__set_default_fs(&opts.fs); +#endif + + if (!opts.fs.write_file) { + tg3__error_push(errors, TG3_SEVERITY_ERROR, TG3_ERR_FS_NOT_AVAILABLE, + "No filesystem write callback", NULL, -1); + return TG3_ERR_FS_NOT_AVAILABLE; + } + + uint8_t *data = NULL; + uint64_t size = 0; + tg3_error_code err = tg3_write_to_memory(model, errors, &data, &size, &opts); + if (err != TG3_OK) return err; + + int32_t ok = opts.fs.write_file(filename, filename_len, data, size, + opts.fs.user_data); + free(data); + + if (!ok) { + tg3__error_push(errors, TG3_SEVERITY_ERROR, TG3_ERR_FILE_WRITE, + "Failed to write file", NULL, -1); + return TG3_ERR_FILE_WRITE; + } + + return TG3_OK; +} + +TINYGLTF3_API void tg3_write_free(uint8_t *data, const tg3_write_options *options) { + (void)options; + free(data); +} + +/* ====================================================================== + * Streaming Writer (stub implementation) + * ====================================================================== */ + +struct tg3_writer { + tg3_write_chunk_fn chunk_fn; + void *user_data; + tg3_write_options options; + tg3__json root; + int begun; +}; + +TINYGLTF3_API tg3_writer *tg3_writer_create( + tg3_write_chunk_fn chunk_fn, void *user_data, + const tg3_write_options *options) { + tg3_writer *w = new (std::nothrow) tg3_writer(); + if (!w) return NULL; + w->chunk_fn = chunk_fn; + w->user_data = user_data; + if (options) w->options = *options; + else tg3_write_options_init(&w->options); + w->root = tg3__json::object(); + return w; +} + +TINYGLTF3_API tg3_error_code tg3_writer_begin(tg3_writer *w, const tg3_asset *asset) { + if (!w) return TG3_ERR_WRITE_FAILED; + w->root["asset"] = tg3__serialize_asset(asset, w->options.serialize_defaults); + w->begun = 1; + return TG3_OK; +} + +#define TG3__WRITER_ADD_IMPL(name, Type, json_key, serialize_fn, ...) \ + TINYGLTF3_API tg3_error_code tg3_writer_add_##name(tg3_writer *w, const Type *item) { \ + if (!w || !w->begun) return TG3_ERR_WRITE_FAILED; \ + auto it = w->root.find(json_key); \ + if (it == w->root.end()) { \ + tg3__json arr; arr.set_array(); \ + w->root[json_key] = static_cast(arr); \ + } \ + w->root[json_key].push_back( \ + serialize_fn(item, w->options.serialize_defaults TG3__COMMA_VA_ARGS(__VA_ARGS__))); \ + return TG3_OK; \ + } + +#define TG3__WRITER_ADD_SIMPLE(name, Type, json_key, serialize_fn) \ + TINYGLTF3_API tg3_error_code tg3_writer_add_##name(tg3_writer *w, const Type *item) { \ + if (!w || !w->begun) return TG3_ERR_WRITE_FAILED; \ + auto it = w->root.find(json_key); \ + if (it == w->root.end()) { \ + tg3__json arr; arr.set_array(); \ + w->root[json_key] = static_cast(arr); \ + } \ + w->root[json_key].push_back( \ + serialize_fn(item, w->options.serialize_defaults)); \ + return TG3_OK; \ + } + +TG3__WRITER_ADD_IMPL(buffer, tg3_buffer, "buffers", tg3__serialize_buffer, + w->options.embed_buffers) +TG3__WRITER_ADD_SIMPLE(buffer_view, tg3_buffer_view, "bufferViews", + tg3__serialize_buffer_view) +TG3__WRITER_ADD_SIMPLE(accessor, tg3_accessor, "accessors", tg3__serialize_accessor) +TG3__WRITER_ADD_SIMPLE(mesh, tg3_mesh, "meshes", tg3__serialize_mesh) +TG3__WRITER_ADD_SIMPLE(node, tg3_node, "nodes", tg3__serialize_node) +TG3__WRITER_ADD_SIMPLE(material, tg3_material, "materials", tg3__serialize_material) +TG3__WRITER_ADD_SIMPLE(texture, tg3_texture, "textures", tg3__serialize_texture) +TG3__WRITER_ADD_IMPL(image, tg3_image, "images", tg3__serialize_image, + w->options.embed_images) +TG3__WRITER_ADD_SIMPLE(sampler, tg3_sampler, "samplers", tg3__serialize_sampler) +TG3__WRITER_ADD_SIMPLE(animation, tg3_animation, "animations", tg3__serialize_animation) +TG3__WRITER_ADD_SIMPLE(skin, tg3_skin, "skins", tg3__serialize_skin) +TG3__WRITER_ADD_SIMPLE(camera, tg3_camera, "cameras", tg3__serialize_camera) +TG3__WRITER_ADD_SIMPLE(scene, tg3_scene, "scenes", tg3__serialize_scene) +TG3__WRITER_ADD_SIMPLE(light, tg3_light, "lights", tg3__serialize_light) + +#undef TG3__WRITER_ADD_IMPL +#undef TG3__WRITER_ADD_SIMPLE + +TINYGLTF3_API tg3_error_code tg3_writer_end(tg3_writer *w) { + if (!w || !w->begun || !w->chunk_fn) return TG3_ERR_WRITE_FAILED; + + int indent = w->options.pretty_print ? 2 : -1; + std::string json_str = w->root.dump(indent); + + int32_t ok = w->chunk_fn((const uint8_t *)json_str.c_str(), + json_str.size(), w->user_data); + return ok ? TG3_OK : TG3_ERR_WRITE_FAILED; +} + +TINYGLTF3_API void tg3_writer_destroy(tg3_writer *w) { + delete w; +} + +#endif /* legacy header-only v3 implementation */ +#endif /* TINYGLTF3_IMPLEMENTATION */ + +#endif /* TINY_GLTF_V3_H_ */ diff --git a/src/tinygltf_json_c.h b/src/tinygltf_json_c.h new file mode 100644 index 0000000..83e8e65 --- /dev/null +++ b/src/tinygltf_json_c.h @@ -0,0 +1,1743 @@ +#ifndef TINYGLTF_JSON_C_H_ +#define TINYGLTF_JSON_C_H_ + +/* + * Floating-point conversion attribution: + * + * - JSON number parsing in this C11 port is based on fast_float. + * Upstream: https://github.com/fastfloat/fast_float + * Copyright (c) 2021 The fast_float authors. + * License: Apache License 2.0, MIT License, or Boost Software License 1.0. + * + * - JSON number serialization in this C11 port is based on Dragonbox-style + * shortest round-trippable binary floating-point to decimal conversion. + * Upstream: https://github.com/jk-jeon/dragonbox + * Copyright 2020-2024 Junekey Jeon. + * License: Apache License 2.0 with LLVM Exceptions, or Boost Software + * License 1.0. + */ + +#include +#include + +#ifdef __cplusplus +extern "C" { +#endif + +typedef enum tg3json_type { + TG3JSON_NULL = 0, + TG3JSON_BOOL = 1, + TG3JSON_INT = 2, + TG3JSON_REAL = 3, + TG3JSON_STRING = 4, + TG3JSON_ARRAY = 5, + TG3JSON_OBJECT = 6 +} tg3json_type; + +typedef struct tg3json_value tg3json_value; + +typedef struct tg3json_string { + char *ptr; + size_t len; +} tg3json_string; + +typedef struct tg3json_array { + tg3json_value *items; + size_t count; +} tg3json_array; + +typedef struct tg3json_object_entry { + char *key; + size_t key_len; + tg3json_value *value; +} tg3json_object_entry; + +typedef struct tg3json_object { + tg3json_object_entry *items; + size_t count; +} tg3json_object; + +struct tg3json_value { + tg3json_type type; + union { + int boolean; + int64_t integer; + double real; + tg3json_string string; + tg3json_array array; + tg3json_object object; + } u; +}; + +int tg3json_parse_n(const char *data, size_t len, size_t depth_limit, + tg3json_value *out_value, const char **out_error_pos); +int tg3json_parse(const char *begin, const char *end, size_t depth_limit, + tg3json_value *out_value, const char **out_error_pos); +typedef struct tg3json_parse_options { + size_t depth_limit; /* 0 = default */ + size_t memory_budget; /* 0 = unlimited */ + size_t max_single_alloc; /* 0 = unlimited */ + size_t max_string_length; /* 0 = unlimited */ + int parse_float32; /* 1 = round JSON reals to float */ +} tg3json_parse_options; +int tg3json_parse_n_opts(const char *data, size_t len, + const tg3json_parse_options *options, + tg3json_value *out_value, + const char **out_error_pos); +void tg3json_value_free(tg3json_value *value); +void tg3json_value_init_null(tg3json_value *value); +void tg3json_value_init_bool(tg3json_value *value, int boolean_value); +void tg3json_value_init_int(tg3json_value *value, int64_t integer_value); +void tg3json_value_init_real(tg3json_value *value, double real_value); +int tg3json_value_init_string_n(tg3json_value *value, const char *str, size_t len); +int tg3json_value_init_string(tg3json_value *value, const char *str); +void tg3json_value_init_array(tg3json_value *value); +void tg3json_value_init_object(tg3json_value *value); +int tg3json_value_copy(tg3json_value *dst, const tg3json_value *src); + +const tg3json_value *tg3json_object_get(const tg3json_value *object, + const char *key); +const tg3json_value *tg3json_object_get_n(const tg3json_value *object, + const char *key, size_t key_len); +tg3json_value *tg3json_object_get_mut(tg3json_value *object, const char *key); +tg3json_value *tg3json_object_get_mut_n(tg3json_value *object, + const char *key, size_t key_len); +const tg3json_object_entry *tg3json_object_at(const tg3json_value *object, + size_t index); +size_t tg3json_object_size(const tg3json_value *object); +int tg3json_object_set_take_n(tg3json_value *object, const char *key, size_t key_len, + tg3json_value *value); +int tg3json_object_set_take(tg3json_value *object, const char *key, + tg3json_value *value); +int tg3json_object_set_copy_n(tg3json_value *object, const char *key, size_t key_len, + const tg3json_value *value); +int tg3json_object_set_copy(tg3json_value *object, const char *key, + const tg3json_value *value); +const tg3json_value *tg3json_array_get(const tg3json_value *array, size_t index); +size_t tg3json_array_size(const tg3json_value *array); +int tg3json_array_append_take(tg3json_value *array, tg3json_value *value); +int tg3json_array_append_copy(tg3json_value *array, const tg3json_value *value); +char *tg3json_stringify(const tg3json_value *value, size_t *out_len); +char *tg3json_stringify_pretty(const tg3json_value *value, int indent, size_t *out_len); + +#ifdef __cplusplus +} /* extern "C" */ +#endif + +#ifdef TINYGLTF_JSON_C_IMPLEMENTATION + +#ifndef TINYGLTF_JSON_NO_STDLIB + #include + #include + #include + #include +#if defined(_MSC_VER) || (defined(LDBL_MANT_DIG) && LDBL_MANT_DIG <= 53) +#define TG3JSON_USE_STDLIB_FPCONV 1 +#endif +#endif +#ifndef TG3JSON_USE_STDLIB_FPCONV +#define TG3JSON_USE_STDLIB_FPCONV 0 +#endif + +#ifdef TINYGLTF_JSON_NO_STDLIB +static void *tg3json__memcpy_fallback(void *dst, const void *src, size_t sz) { + unsigned char *d = (unsigned char *)dst; + const unsigned char *s = (const unsigned char *)src; + while (sz--) *d++ = *s++; + return dst; +} + +static void *tg3json__memset_fallback(void *dst, int val, size_t sz) { + unsigned char *d = (unsigned char *)dst; + while (sz--) *d++ = (unsigned char)val; + return dst; +} + +static int tg3json__memcmp_fallback(const void *a, const void *b, size_t sz) { + const unsigned char *pa = (const unsigned char *)a; + const unsigned char *pb = (const unsigned char *)b; + while (sz--) { + if (*pa != *pb) return (int)*pa - (int)*pb; + ++pa; + ++pb; + } + return 0; +} + +static size_t tg3json__strlen_fallback(const char *str) { + const char *p = str; + while (*p) ++p; + return (size_t)(p - str); +} + +#endif + +#ifndef TINYGLTF_JSON_MALLOC +#ifdef TINYGLTF_JSON_NO_STDLIB +#define TINYGLTF_JSON_MALLOC(sz) NULL +#else +#define TINYGLTF_JSON_MALLOC(sz) malloc(sz) +#endif +#endif +#ifndef TINYGLTF_JSON_REALLOC +#ifdef TINYGLTF_JSON_NO_STDLIB +#define TINYGLTF_JSON_REALLOC(ptr, sz) NULL +#else +#define TINYGLTF_JSON_REALLOC(ptr, sz) realloc(ptr, sz) +#endif +#endif +#ifndef TINYGLTF_JSON_FREE +#ifdef TINYGLTF_JSON_NO_STDLIB +#define TINYGLTF_JSON_FREE(ptr) ((void)(ptr)) +#else +#define TINYGLTF_JSON_FREE(ptr) free(ptr) +#endif +#endif + +#ifndef TINYGLTF_JSON_MEMCPY +#ifdef TINYGLTF_JSON_NO_STDLIB +#define TINYGLTF_JSON_MEMCPY(dst, src, sz) tg3json__memcpy_fallback((dst), (src), (sz)) +#else +#define TINYGLTF_JSON_MEMCPY(dst, src, sz) memcpy(dst, src, sz) +#endif +#endif +#ifndef TINYGLTF_JSON_MEMSET +#ifdef TINYGLTF_JSON_NO_STDLIB +#define TINYGLTF_JSON_MEMSET(dst, val, sz) tg3json__memset_fallback((dst), (val), (sz)) +#else +#define TINYGLTF_JSON_MEMSET(dst, val, sz) memset(dst, val, sz) +#endif +#endif +#ifndef TINYGLTF_JSON_MEMCMP +#ifdef TINYGLTF_JSON_NO_STDLIB +#define TINYGLTF_JSON_MEMCMP(a, b, sz) tg3json__memcmp_fallback((a), (b), (sz)) +#else +#define TINYGLTF_JSON_MEMCMP(a, b, sz) memcmp(a, b, sz) +#endif +#endif +#ifndef TINYGLTF_JSON_STRLEN +#ifdef TINYGLTF_JSON_NO_STDLIB +#define TINYGLTF_JSON_STRLEN(str) tg3json__strlen_fallback((str)) +#else +#define TINYGLTF_JSON_STRLEN(str) strlen(str) +#endif +#endif + +static size_t tg3json__itoa(int64_t value, char *buf) { + char *p = buf; + uint64_t val; + char tmp[24]; + int i = 0; + if (value < 0) { + *p++ = '-'; + val = (value == -9223372036854775807LL - 1) ? 9223372036854775808ULL : (uint64_t)(-value); + } else { + val = (uint64_t)value; + } + if (val == 0) { + *p++ = '0'; + *p = '\0'; + return (size_t)(p - buf); + } + while (val > 0) { + tmp[i++] = (char)('0' + (val % 10)); + val /= 10; + } + while (i > 0) { + *p++ = tmp[--i]; + } + *p = '\0'; + return (size_t)(p - buf); +} + +#if !TG3JSON_USE_STDLIB_FPCONV +static size_t tg3json__utoa(uint64_t value, char *buf) { + char tmp[32]; + size_t n = 0; + size_t i = 0; + if (value == 0) { + buf[0] = '0'; + buf[1] = '\0'; + return 1; + } + while (value > 0) { + tmp[n++] = (char)('0' + (value % 10u)); + value /= 10u; + } + while (n > 0) buf[i++] = tmp[--n]; + buf[i] = '\0'; + return i; +} +#endif /* !TG3JSON_USE_STDLIB_FPCONV */ + +static uint64_t tg3json__double_bits(double v) { + uint64_t bits = 0; + TINYGLTF_JSON_MEMCPY(&bits, &v, sizeof(bits)); + return bits; +} + +static int tg3json__is_nan_bits(uint64_t bits) { + return ((bits & 0x7ff0000000000000ULL) == 0x7ff0000000000000ULL) && + ((bits & 0x000fffffffffffffULL) != 0); +} + +static int tg3json__is_inf_bits(uint64_t bits) { + return (bits & 0x7fffffffffffffffULL) == 0x7ff0000000000000ULL; +} + +#if !TG3JSON_USE_STDLIB_FPCONV +static double tg3json__double_from_bits(uint64_t bits) { + double v = 0.0; + TINYGLTF_JSON_MEMCPY(&v, &bits, sizeof(v)); + return v; +} + +static long double tg3json__pow10_ld(int exp10) { + long double v = 1.0L; + if (exp10 < 0) { + exp10 = -exp10; + while (exp10 >= 16) { + v *= 1.0e-16L; + exp10 -= 16; + } + while (exp10-- > 0) v *= 0.1L; + } else { + while (exp10 >= 16) { + v *= 1.0e16L; + exp10 -= 16; + } + while (exp10-- > 0) v *= 10.0L; + } + return v; +} +#endif + +static int tg3json__parse_f64_c(const char *start, const char *end, double *out) { +#if TG3JSON_USE_STDLIB_FPCONV + size_t len = (size_t)(end - start); + char stack_buf[128]; + char *buf = stack_buf; + char *parse_end = NULL; + double v; + if (len + 1 > sizeof(stack_buf)) { + buf = (char *)TINYGLTF_JSON_MALLOC(len + 1); + if (!buf) return 0; + } + if (len > 0) TINYGLTF_JSON_MEMCPY(buf, start, len); + buf[len] = '\0'; + v = strtod(buf, &parse_end); + if (parse_end != buf + len || tg3json__is_inf_bits(tg3json__double_bits(v))) { + if (buf != stack_buf) TINYGLTF_JSON_FREE(buf); + return 0; + } + if (buf != stack_buf) TINYGLTF_JSON_FREE(buf); + *out = v; + return 1; +#else + const char *p = start; + int neg = 0; + int saw_digit = 0; + int nonzero_seen = 0; + int exp10 = 0; + uint64_t sig = 0; + int sig_digits = 0; + long double extra = 0.0L; + int extra_digits = 0; + int exp_sign = 1; + int exp_lit = 0; + long double v; + + if (p < end && *p == '-') { + neg = 1; + ++p; + } + if (p >= end) return 0; + if (*p == '0') { + saw_digit = 1; + ++p; + } else if (*p >= '1' && *p <= '9') { + do { + int d = *p - '0'; + saw_digit = 1; + nonzero_seen = 1; + if (sig_digits < 19) { + sig = sig * 10u + (uint64_t)d; + ++sig_digits; + } else if (extra_digits < 64) { + extra = extra * 10.0L + (long double)d; + ++extra_digits; + } else { + ++exp10; + } + ++p; + } while (p < end && *p >= '0' && *p <= '9'); + } else { + return 0; + } + if (p < end && *p == '.') { + ++p; + if (p >= end || *p < '0' || *p > '9') return 0; + do { + int d = *p - '0'; + saw_digit = 1; + if (d != 0 || nonzero_seen) { + nonzero_seen = nonzero_seen || (d != 0); + if (sig_digits < 19) { + sig = sig * 10u + (uint64_t)d; + ++sig_digits; + --exp10; + } else if (extra_digits < 64) { + extra = extra * 10.0L + (long double)d; + ++extra_digits; + --exp10; + } else { + --exp10; + } + } else { + --exp10; + } + ++p; + } while (p < end && *p >= '0' && *p <= '9'); + } + if (!saw_digit) return 0; + if (p < end && (*p == 'e' || *p == 'E')) { + ++p; + if (p < end && (*p == '+' || *p == '-')) { + exp_sign = (*p == '-') ? -1 : 1; + ++p; + } + if (p >= end || *p < '0' || *p > '9') return 0; + while (p < end && *p >= '0' && *p <= '9') { + if (exp_lit < 10000) exp_lit = exp_lit * 10 + (*p - '0'); + ++p; + } + exp10 += exp_sign * exp_lit; + } + if (p != end) return 0; + if (!nonzero_seen || sig_digits == 0) { + *out = neg ? tg3json__double_from_bits(0x8000000000000000ULL) : 0.0; + return 1; + } + if (exp10 > 309) return 0; + if (exp10 < -4000) { + *out = neg ? tg3json__double_from_bits(0x8000000000000000ULL) : 0.0; + return 1; + } + v = (long double)sig; + if (extra_digits > 0) { + v = v * tg3json__pow10_ld(extra_digits) + extra; + } + if (exp10 != 0) v *= tg3json__pow10_ld(exp10); + if (neg) v = -v; + *out = (double)v; + if (tg3json__is_inf_bits(tg3json__double_bits(*out))) return 0; + return 1; +#endif +} + +#if !TG3JSON_USE_STDLIB_FPCONV +static char *tg3json__write_exp(char *p, int exp10) { + char tmp[16]; + size_t n; + *p++ = 'e'; + if (exp10 < 0) { + *p++ = '-'; + exp10 = -exp10; + } + n = tg3json__utoa((uint64_t)exp10, tmp); + TINYGLTF_JSON_MEMCPY(p, tmp, n); + return p + n; +} + +static char *tg3json__format_decimal_digits(char *out, const char *digits, + int ndigits, int dec_exp, + int negative) { + char *p = out; + int i; + int output_exp = dec_exp + ndigits - 1; + if (negative) *p++ = '-'; + if (output_exp < -4 || output_exp >= 16) { + *p++ = digits[0]; + if (ndigits > 1) { + *p++ = '.'; + for (i = 1; i < ndigits; ++i) *p++ = digits[i]; + } + return tg3json__write_exp(p, output_exp); + } + if (dec_exp >= 0) { + for (i = 0; i < ndigits; ++i) *p++ = digits[i]; + for (i = 0; i < dec_exp; ++i) *p++ = '0'; + return p; + } + if (dec_exp + ndigits > 0) { + int int_digits = dec_exp + ndigits; + for (i = 0; i < int_digits; ++i) *p++ = digits[i]; + *p++ = '.'; + for (; i < ndigits; ++i) *p++ = digits[i]; + return p; + } + *p++ = '0'; + *p++ = '.'; + for (i = 0; i < -(dec_exp + ndigits); ++i) *p++ = '0'; + for (i = 0; i < ndigits; ++i) *p++ = digits[i]; + return p; +} +#endif /* !TG3JSON_USE_STDLIB_FPCONV */ + +static int tg3json__same_f64(double a, double b) { + return tg3json__double_bits(a) == tg3json__double_bits(b); +} + +#if TG3JSON_USE_STDLIB_FPCONV +static void tg3json__normalize_exponent(char *s) { + char *e = s; + char *dst; + int neg = 0; + while (*e && *e != 'e' && *e != 'E') ++e; + if (!*e) return; + *e++ = 'e'; + dst = e; + if (*e == '+' || *e == '-') { + neg = (*e == '-'); + ++e; + } + while (*e == '0') ++e; + if (neg) *dst++ = '-'; + if (!*e) { + *dst++ = '0'; + } else { + while (*e) *dst++ = *e++; + } + *dst = '\0'; +} + +static void tg3json__expand_short_plain_decimal(char *s) { + char *p = s; + char *e; + char digits[32]; + char out[96]; + int negative = 0; + int ndigits = 0; + int int_digits = 0; + int exp10 = 0; + int new_point; + int i; + char *q = out; + + if (*p == '-') { + negative = 1; + ++p; + } + e = p; + while (*e && *e != 'e') ++e; + if (!*e) return; + for (; p < e; ++p) { + if (*p == '.') { + int_digits = ndigits; + } else { + if (ndigits < (int)(sizeof(digits) - 1)) digits[ndigits++] = *p; + } + } + if (int_digits == 0) int_digits = ndigits; + ++e; + if (*e == '-') { + int sign = -1; + ++e; + while (*e >= '0' && *e <= '9') exp10 = exp10 * 10 + (*e++ - '0'); + exp10 *= sign; + } else { + while (*e >= '0' && *e <= '9') exp10 = exp10 * 10 + (*e++ - '0'); + } + if (exp10 < -4 || exp10 >= 16) return; + + new_point = int_digits + exp10; + if (negative) *q++ = '-'; + if (new_point <= 0) { + *q++ = '0'; + *q++ = '.'; + for (i = 0; i < -new_point; ++i) *q++ = '0'; + for (i = 0; i < ndigits; ++i) *q++ = digits[i]; + } else if (new_point >= ndigits) { + for (i = 0; i < ndigits; ++i) *q++ = digits[i]; + for (i = ndigits; i < new_point; ++i) *q++ = '0'; + } else { + for (i = 0; i < new_point; ++i) *q++ = digits[i]; + *q++ = '.'; + for (; i < ndigits; ++i) *q++ = digits[i]; + } + *q = '\0'; + if (q > out) { + char *dot = out; + while (*dot && *dot != '.') ++dot; + if (*dot == '.') { + char *end = q - 1; + while (end > dot && *end == '0') *end-- = '\0'; + if (end == dot) *end = '\0'; + } + } + TINYGLTF_JSON_MEMCPY(s, out, (size_t)(TINYGLTF_JSON_STRLEN(out) + 1)); +} +#endif + +static char *tg3json__dtoa_c(double value, char *buf) { + uint64_t bits = tg3json__double_bits(value); + int negative = (int)(bits >> 63); + uint64_t abits = bits & 0x7fffffffffffffffULL; +#if !TG3JSON_USE_STDLIB_FPCONV + long double x; + int dec_e = 0; + char digits[24]; + int ndigits = 17; + int i; + char best[80]; + size_t best_len; +#endif + + if (tg3json__is_nan_bits(bits)) { + TINYGLTF_JSON_MEMCPY(buf, "nan", 3); + return buf + 3; + } + if (tg3json__is_inf_bits(bits)) { + if (negative) { + TINYGLTF_JSON_MEMCPY(buf, "-inf", 4); + return buf + 4; + } + TINYGLTF_JSON_MEMCPY(buf, "inf", 3); + return buf + 3; + } + if (abits == 0) { + *buf++ = '0'; + return buf; + } + if (bits == 0x3ff0000000000000ULL) { + *buf++ = '1'; + return buf; + } + if (bits == 0xbff0000000000000ULL) { + *buf++ = '-'; + *buf++ = '1'; + return buf; + } + +#if TG3JSON_USE_STDLIB_FPCONV + { + int precision; + char candidate[96]; + char shortest[96]; + shortest[0] = '\0'; + for (precision = 1; precision <= 17; ++precision) { + char fmt[8]; + double parsed = 0.0; + int n; + n = snprintf(fmt, sizeof(fmt), "%%.%dg", precision); + if (n <= 0 || n >= (int)sizeof(fmt)) continue; + n = snprintf(candidate, sizeof(candidate), fmt, value); + if (n <= 0 || n >= (int)sizeof(candidate)) continue; + tg3json__normalize_exponent(candidate); + tg3json__expand_short_plain_decimal(candidate); + if (tg3json__parse_f64_c(candidate, candidate + TINYGLTF_JSON_STRLEN(candidate), &parsed) && + tg3json__same_f64(parsed, value)) { + TINYGLTF_JSON_MEMCPY(shortest, candidate, TINYGLTF_JSON_STRLEN(candidate) + 1); + break; + } + } + if (!shortest[0]) { + int n = snprintf(shortest, sizeof(shortest), "%.17g", value); + if (n <= 0 || n >= (int)sizeof(shortest)) return buf; + tg3json__normalize_exponent(shortest); + tg3json__expand_short_plain_decimal(shortest); + } + TINYGLTF_JSON_MEMCPY(buf, shortest, TINYGLTF_JSON_STRLEN(shortest)); + return buf + TINYGLTF_JSON_STRLEN(shortest); + } +#else + + x = negative ? -(long double)value : (long double)value; + while (x >= 1.0e16L) { + x *= 1.0e-16L; + dec_e += 16; + } + while (x >= 10.0L) { + x *= 0.1L; + ++dec_e; + } + while (x < 1.0L) { + x *= 10.0L; + --dec_e; + } + for (i = 0; i < 18; ++i) { + int d = (int)x; + if (d < 0) d = 0; + if (d > 9) d = 9; + digits[i] = (char)('0' + d); + x = (x - (long double)d) * 10.0L; + } + if (digits[17] >= '5') { + int carry = 1; + for (i = 16; i >= 0 && carry; --i) { + if (digits[i] == '9') { + digits[i] = '0'; + } else { + digits[i]++; + carry = 0; + } + } + if (carry) { + digits[0] = '1'; + for (i = 1; i < 17; ++i) digits[i] = '0'; + ++dec_e; + } + } + while (ndigits > 1 && digits[ndigits - 1] == '0') --ndigits; + + { + char *end = tg3json__format_decimal_digits(best, digits, ndigits, + dec_e - ndigits + 1, + negative); + *end = '\0'; + best_len = (size_t)(end - best); + } + for (i = ndigits - 1; i >= 1; --i) { + char candidate[80]; + char *end; + double parsed = 0.0; + end = tg3json__format_decimal_digits(candidate, digits, i, + dec_e - i + 1, negative); + *end = '\0'; + if (tg3json__parse_f64_c(candidate, end, &parsed) && + tg3json__same_f64(parsed, value)) { + TINYGLTF_JSON_MEMCPY(best, candidate, (size_t)(end - candidate) + 1); + best_len = (size_t)(end - candidate); + } else { + break; + } + } + TINYGLTF_JSON_MEMCPY(buf, best, best_len); + return buf + best_len; +#endif +} + +typedef struct tg3json__parser { + const char *cur; + const char *end; + const char *error; + size_t depth_limit; + size_t memory_budget; + size_t max_single_alloc; + size_t max_string_length; + size_t allocated; + int parse_float32; +} tg3json__parser; + +typedef struct tg3json__buffer { + tg3json__parser *parser; + char *data; + size_t len; + size_t cap; +} tg3json__buffer; + +static void tg3json__init_value(tg3json_value *value) { + if (!value) return; + TINYGLTF_JSON_MEMSET(value, 0, sizeof(*value)); + value->type = TG3JSON_NULL; +} + +static char *tg3json__strndup_local(const char *src, size_t len) { + char *dst = (char *)TINYGLTF_JSON_MALLOC(len + 1); + if (!dst) return NULL; + if (len > 0) TINYGLTF_JSON_MEMCPY(dst, src, len); + dst[len] = '\0'; + return dst; +} + +static void *tg3json__parser_alloc(tg3json__parser *parser, size_t size) { + void *ptr; + if (!parser) return TINYGLTF_JSON_MALLOC(size); + if (parser->max_single_alloc && size > parser->max_single_alloc) return NULL; + if (parser->memory_budget && + (size > parser->memory_budget || parser->allocated > parser->memory_budget - size)) { + return NULL; + } + ptr = TINYGLTF_JSON_MALLOC(size); + if (!ptr) return NULL; + parser->allocated += size; + return ptr; +} + +static int tg3json__reserve_bytes(void **ptr, size_t elem_size, + size_t needed, size_t *capacity) { + void *new_ptr; + size_t new_cap; + + if (needed <= *capacity) return 1; + new_cap = (*capacity > 0) ? *capacity : 8; + while (new_cap < needed) { + if (new_cap > ((size_t)-1) / 2) { + new_cap = needed; + break; + } + new_cap *= 2; + } + + if (elem_size != 0 && new_cap > ((size_t)-1) / elem_size) return 0; + new_ptr = TINYGLTF_JSON_REALLOC(*ptr, elem_size * new_cap); + if (!new_ptr) return 0; + *ptr = new_ptr; + *capacity = new_cap; + return 1; +} + +static int tg3json__reserve_bytes_parser(tg3json__parser *parser, void **ptr, + size_t elem_size, size_t needed, + size_t *capacity) { + void *new_ptr; + size_t new_cap; + size_t old_bytes; + size_t new_bytes; + + if (needed <= *capacity) return 1; + new_cap = (*capacity > 0) ? *capacity : 8; + while (new_cap < needed) { + if (new_cap > ((size_t)-1) / 2) { + new_cap = needed; + break; + } + new_cap *= 2; + } + + if (elem_size != 0 && new_cap > ((size_t)-1) / elem_size) return 0; + old_bytes = elem_size * (*capacity); + new_bytes = elem_size * new_cap; + if (parser) { + size_t delta = (new_bytes > old_bytes) ? (new_bytes - old_bytes) : 0; + if (parser->max_single_alloc && new_bytes > parser->max_single_alloc) return 0; + if (parser->memory_budget && delta > 0 && + (delta > parser->memory_budget || + parser->allocated > parser->memory_budget - delta)) { + return 0; + } + } + new_ptr = TINYGLTF_JSON_REALLOC(*ptr, new_bytes); + if (!new_ptr) return 0; + if (parser && new_bytes > old_bytes) parser->allocated += new_bytes - old_bytes; + *ptr = new_ptr; + *capacity = new_cap; + return 1; +} + +static const char *tg3json__skip_ws(const char *p, const char *end) { + while (p < end) { + unsigned char c = (unsigned char)*p; + if (c != ' ' && c != '\n' && c != '\r' && c != '\t') break; + ++p; + } + return p; +} + +static void tg3json__set_error(tg3json__parser *parser, const char *pos) { + if (!parser->error) parser->error = pos; +} + +static int tg3json__buf_append(tg3json__buffer *buf, const char *src, size_t len) { + if (len == 0) return 1; + if (!tg3json__reserve_bytes_parser(buf->parser, (void **)&buf->data, 1, + buf->len + len + 1, &buf->cap)) { + return 0; + } + TINYGLTF_JSON_MEMCPY(buf->data + buf->len, src, len); + buf->len += len; + buf->data[buf->len] = '\0'; + return 1; +} + +static int tg3json__buf_putc(tg3json__buffer *buf, char c) { + if (!tg3json__reserve_bytes_parser(buf->parser, (void **)&buf->data, 1, + buf->len + 2, &buf->cap)) { + return 0; + } + buf->data[buf->len++] = c; + buf->data[buf->len] = '\0'; + return 1; +} + +static int tg3json__hex4(const char *p, uint32_t *out) { + uint32_t value = 0; + size_t i; + for (i = 0; i < 4; ++i) { + unsigned char c = (unsigned char)p[i]; + value <<= 4; + if (c >= '0' && c <= '9') value |= (uint32_t)(c - '0'); + else if (c >= 'a' && c <= 'f') value |= (uint32_t)(10 + c - 'a'); + else if (c >= 'A' && c <= 'F') value |= (uint32_t)(10 + c - 'A'); + else return 0; + } + *out = value; + return 1; +} + +static int tg3json__append_utf8(tg3json__buffer *buf, uint32_t cp) { + char tmp[4]; + size_t len = 0; + if (cp <= 0x7Fu) { + tmp[len++] = (char)cp; + } else if (cp <= 0x7FFu) { + tmp[len++] = (char)(0xC0u | ((cp >> 6) & 0x1Fu)); + tmp[len++] = (char)(0x80u | (cp & 0x3Fu)); + } else if (cp <= 0xFFFFu) { + tmp[len++] = (char)(0xE0u | ((cp >> 12) & 0x0Fu)); + tmp[len++] = (char)(0x80u | ((cp >> 6) & 0x3Fu)); + tmp[len++] = (char)(0x80u | (cp & 0x3Fu)); + } else if (cp <= 0x10FFFFu) { + tmp[len++] = (char)(0xF0u | ((cp >> 18) & 0x07u)); + tmp[len++] = (char)(0x80u | ((cp >> 12) & 0x3Fu)); + tmp[len++] = (char)(0x80u | ((cp >> 6) & 0x3Fu)); + tmp[len++] = (char)(0x80u | (cp & 0x3Fu)); + } else { + return 0; + } + return tg3json__buf_append(buf, tmp, len); +} + +static int tg3json__parse_string_raw(tg3json__parser *parser, + char **out_str, size_t *out_len) { + tg3json__buffer buf; + const char *start; + TINYGLTF_JSON_MEMSET(&buf, 0, sizeof(buf)); + buf.parser = parser; + + if (parser->cur >= parser->end || *parser->cur != '"') { + tg3json__set_error(parser, parser->cur); + return 0; + } + + ++parser->cur; + start = parser->cur; + while (parser->cur < parser->end) { + unsigned char c = (unsigned char)*parser->cur; + if (c == '"') { + size_t final_len = buf.len + (size_t)(parser->cur - start); + if (parser->max_string_length && final_len > parser->max_string_length) goto oom; + if (!tg3json__buf_append(&buf, start, (size_t)(parser->cur - start))) goto oom; + ++parser->cur; + *out_str = buf.data; + *out_len = buf.len; + return 1; + } + if (c == '\\') { + uint32_t codepoint; + size_t pending_len = (size_t)(parser->cur - start); + if (parser->max_string_length && buf.len + pending_len > parser->max_string_length) goto oom; + if (!tg3json__buf_append(&buf, start, (size_t)(parser->cur - start))) goto oom; + ++parser->cur; + if (parser->cur >= parser->end) break; + switch (*parser->cur) { + case '"': if (!tg3json__buf_putc(&buf, '"')) goto oom; break; + case '\\': if (!tg3json__buf_putc(&buf, '\\')) goto oom; break; + case '/': if (!tg3json__buf_putc(&buf, '/')) goto oom; break; + case 'b': if (!tg3json__buf_putc(&buf, '\b')) goto oom; break; + case 'f': if (!tg3json__buf_putc(&buf, '\f')) goto oom; break; + case 'n': if (!tg3json__buf_putc(&buf, '\n')) goto oom; break; + case 'r': if (!tg3json__buf_putc(&buf, '\r')) goto oom; break; + case 't': if (!tg3json__buf_putc(&buf, '\t')) goto oom; break; + case 'u': { + if ((size_t)(parser->end - parser->cur) < 5) break; + if (!tg3json__hex4(parser->cur + 1, &codepoint)) break; + parser->cur += 4; + if (codepoint >= 0xD800u && codepoint <= 0xDBFFu) { + uint32_t low; + if ((size_t)(parser->end - parser->cur) < 7 || parser->cur[1] != '\\' || parser->cur[2] != 'u') break; + if (!tg3json__hex4(parser->cur + 3, &low)) break; + if (low < 0xDC00u || low > 0xDFFFu) break; + codepoint = 0x10000u + (((codepoint - 0xD800u) << 10) | (low - 0xDC00u)); + parser->cur += 6; + } else if (codepoint >= 0xDC00u && codepoint <= 0xDFFFu) { + break; + } + if (!tg3json__append_utf8(&buf, codepoint)) goto oom; + break; + } + default: + tg3json__set_error(parser, parser->cur); + TINYGLTF_JSON_FREE(buf.data); + return 0; + } + ++parser->cur; + start = parser->cur; + continue; + } + if (c < 0x20u) break; + ++parser->cur; + } + + tg3json__set_error(parser, parser->cur); + TINYGLTF_JSON_FREE(buf.data); + return 0; + +oom: + tg3json__set_error(parser, parser->cur); + TINYGLTF_JSON_FREE(buf.data); + return 0; +} + +static int tg3json__parse_value(tg3json__parser *parser, size_t depth, + tg3json_value *out_value); + +static int tg3json__parse_int64_span(const char *start, const char *end, + int64_t *out) { + const char *p = start; + uint64_t value = 0; + uint64_t limit = (uint64_t)INT64_MAX; + int neg = 0; + if (p < end && *p == '-') { + neg = 1; + limit += 1u; + ++p; + } + if (p >= end) return 0; + while (p < end) { + unsigned digit = (unsigned)(*p - '0'); + if (digit > 9u) return 0; + if (value > (limit - digit) / 10u) return 0; + value = value * 10u + (uint64_t)digit; + ++p; + } + if (neg) { + if (value == ((uint64_t)INT64_MAX + 1u)) { + *out = INT64_MIN; + } else { + *out = -(int64_t)value; + } + } else { + *out = (int64_t)value; + } + return 1; +} + +static int tg3json__parse_array(tg3json__parser *parser, size_t depth, + tg3json_value *out_value) { + tg3json_value *items = NULL; + size_t count = 0; + size_t cap = 0; + + ++parser->cur; + parser->cur = tg3json__skip_ws(parser->cur, parser->end); + if (parser->cur < parser->end && *parser->cur == ']') { + ++parser->cur; + out_value->type = TG3JSON_ARRAY; + out_value->u.array.items = NULL; + out_value->u.array.count = 0; + return 1; + } + + while (parser->cur < parser->end) { + tg3json_value value; + tg3json__init_value(&value); + if (!tg3json__reserve_bytes_parser(parser, (void **)&items, + sizeof(*items), count + 1, &cap)) goto oom; + if (!tg3json__parse_value(parser, depth + 1, &value)) goto fail; + items[count++] = value; + parser->cur = tg3json__skip_ws(parser->cur, parser->end); + if (parser->cur >= parser->end) break; + if (*parser->cur == ',') { + ++parser->cur; + parser->cur = tg3json__skip_ws(parser->cur, parser->end); + continue; + } + if (*parser->cur == ']') { + ++parser->cur; + out_value->type = TG3JSON_ARRAY; + out_value->u.array.items = items; + out_value->u.array.count = count; + return 1; + } + break; + } + +fail: + while (count > 0) { + --count; + tg3json_value_free(&items[count]); + } + TINYGLTF_JSON_FREE(items); + tg3json__set_error(parser, parser->cur); + return 0; + +oom: + while (count > 0) { + --count; + tg3json_value_free(&items[count]); + } + TINYGLTF_JSON_FREE(items); + tg3json__set_error(parser, parser->cur); + return 0; +} + +static int tg3json__parse_object(tg3json__parser *parser, size_t depth, + tg3json_value *out_value) { + tg3json_object_entry *items = NULL; + size_t count = 0; + size_t cap = 0; + + ++parser->cur; + parser->cur = tg3json__skip_ws(parser->cur, parser->end); + if (parser->cur < parser->end && *parser->cur == '}') { + ++parser->cur; + out_value->type = TG3JSON_OBJECT; + out_value->u.object.items = NULL; + out_value->u.object.count = 0; + return 1; + } + + while (parser->cur < parser->end) { + char *key = NULL; + size_t key_len = 0; + tg3json_value value; + tg3json__init_value(&value); + if (!tg3json__parse_string_raw(parser, &key, &key_len)) goto fail; + parser->cur = tg3json__skip_ws(parser->cur, parser->end); + if (parser->cur >= parser->end || *parser->cur != ':') { + TINYGLTF_JSON_FREE(key); + goto fail; + } + ++parser->cur; + parser->cur = tg3json__skip_ws(parser->cur, parser->end); + if (!tg3json__parse_value(parser, depth + 1, &value)) { + TINYGLTF_JSON_FREE(key); + goto fail; + } + if (!tg3json__reserve_bytes_parser(parser, (void **)&items, + sizeof(*items), count + 1, &cap)) { + TINYGLTF_JSON_FREE(key); + tg3json_value_free(&value); + goto oom; + } + items[count].key = key; + items[count].key_len = key_len; + items[count].value = (tg3json_value *)tg3json__parser_alloc(parser, sizeof(tg3json_value)); + if (!items[count].value) { + TINYGLTF_JSON_FREE(key); + tg3json_value_free(&value); + goto oom; + } + *items[count].value = value; + ++count; + parser->cur = tg3json__skip_ws(parser->cur, parser->end); + if (parser->cur >= parser->end) break; + if (*parser->cur == ',') { + ++parser->cur; + parser->cur = tg3json__skip_ws(parser->cur, parser->end); + continue; + } + if (*parser->cur == '}') { + ++parser->cur; + out_value->type = TG3JSON_OBJECT; + out_value->u.object.items = items; + out_value->u.object.count = count; + return 1; + } + break; + } + +fail: + while (count > 0) { + --count; + TINYGLTF_JSON_FREE(items[count].key); + if (items[count].value) { + tg3json_value_free(items[count].value); + TINYGLTF_JSON_FREE(items[count].value); + } + } + TINYGLTF_JSON_FREE(items); + tg3json__set_error(parser, parser->cur); + return 0; + +oom: + while (count > 0) { + --count; + TINYGLTF_JSON_FREE(items[count].key); + if (items[count].value) { + tg3json_value_free(items[count].value); + TINYGLTF_JSON_FREE(items[count].value); + } + } + TINYGLTF_JSON_FREE(items); + tg3json__set_error(parser, parser->cur); + return 0; +} + +static int tg3json__parse_number(tg3json__parser *parser, tg3json_value *out_value) { + const char *start = parser->cur; + const char *p = parser->cur; + int is_real = 0; + + if (*p == '-') ++p; + if (p >= parser->end) goto fail; + if (*p == '0') { + ++p; + } else if (*p >= '1' && *p <= '9') { + do { ++p; } while (p < parser->end && *p >= '0' && *p <= '9'); + } else { + goto fail; + } + if (p < parser->end && *p == '.') { + is_real = 1; + ++p; + if (p >= parser->end || *p < '0' || *p > '9') goto fail; + do { ++p; } while (p < parser->end && *p >= '0' && *p <= '9'); + } + if (p < parser->end && (*p == 'e' || *p == 'E')) { + is_real = 1; + ++p; + if (p < parser->end && (*p == '+' || *p == '-')) ++p; + if (p >= parser->end || *p < '0' || *p > '9') goto fail; + do { ++p; } while (p < parser->end && *p >= '0' && *p <= '9'); + } + + if (!is_real) { + int64_t v; + if (tg3json__parse_int64_span(start, p, &v)) { + out_value->type = TG3JSON_INT; + out_value->u.integer = v; + parser->cur = p; + return 1; + } + is_real = 1; + } + + { + if (!tg3json__parse_f64_c(start, p, &out_value->u.real)) goto fail; + if (parser->parse_float32) out_value->u.real = (double)(float)out_value->u.real; + out_value->type = TG3JSON_REAL; + parser->cur = p; + return 1; + } + +fail: + tg3json__set_error(parser, parser->cur); + return 0; +} + +static int tg3json__parse_value(tg3json__parser *parser, size_t depth, + tg3json_value *out_value) { + if (parser->depth_limit && depth > parser->depth_limit) { + tg3json__set_error(parser, parser->cur); + return 0; + } + + parser->cur = tg3json__skip_ws(parser->cur, parser->end); + if (parser->cur >= parser->end) { + tg3json__set_error(parser, parser->cur); + return 0; + } + + switch (*parser->cur) { + case '[': + return tg3json__parse_array(parser, depth, out_value); + case '{': + return tg3json__parse_object(parser, depth, out_value); + case '"': { + char *str = NULL; + size_t len = 0; + if (!tg3json__parse_string_raw(parser, &str, &len)) return 0; + out_value->type = TG3JSON_STRING; + out_value->u.string.ptr = str; + out_value->u.string.len = len; + return 1; + } + case 'n': + if ((size_t)(parser->end - parser->cur) >= 4 && TINYGLTF_JSON_MEMCMP(parser->cur, "null", 4) == 0) { + out_value->type = TG3JSON_NULL; + parser->cur += 4; + return 1; + } + break; + case 't': + if ((size_t)(parser->end - parser->cur) >= 4 && TINYGLTF_JSON_MEMCMP(parser->cur, "true", 4) == 0) { + out_value->type = TG3JSON_BOOL; + out_value->u.boolean = 1; + parser->cur += 4; + return 1; + } + break; + case 'f': + if ((size_t)(parser->end - parser->cur) >= 5 && TINYGLTF_JSON_MEMCMP(parser->cur, "false", 5) == 0) { + out_value->type = TG3JSON_BOOL; + out_value->u.boolean = 0; + parser->cur += 5; + return 1; + } + break; + default: + return tg3json__parse_number(parser, out_value); + } + + tg3json__set_error(parser, parser->cur); + return 0; +} + +int tg3json_parse_n_opts(const char *data, size_t len, + const tg3json_parse_options *options, + tg3json_value *out_value, + const char **out_error_pos) { + tg3json__parser parser; + int ok; + + if (out_error_pos) *out_error_pos = NULL; + if (!out_value) return 0; + tg3json__init_value(out_value); + if (!data) return 0; + + parser.cur = data; + parser.end = data + len; + parser.error = NULL; + parser.depth_limit = options ? (options->depth_limit ? options->depth_limit : 256) : 256; + parser.memory_budget = options ? options->memory_budget : 0; + parser.max_single_alloc = options ? options->max_single_alloc : 0; + parser.max_string_length = options ? options->max_string_length : 0; + parser.allocated = 0; + parser.parse_float32 = options ? options->parse_float32 : 0; + + parser.cur = tg3json__skip_ws(parser.cur, parser.end); + if (parser.cur >= parser.end) { + if (out_error_pos) *out_error_pos = data; + return 0; + } + + ok = tg3json__parse_value(&parser, 0, out_value); + if (!ok) { + if (out_error_pos) *out_error_pos = parser.error ? parser.error : parser.cur; + tg3json_value_free(out_value); + return 0; + } + + parser.cur = tg3json__skip_ws(parser.cur, parser.end); + if (parser.cur != parser.end) { + if (out_error_pos) *out_error_pos = parser.cur; + tg3json_value_free(out_value); + return 0; + } + + return 1; +} + +int tg3json_parse_n(const char *data, size_t len, size_t depth_limit, + tg3json_value *out_value, const char **out_error_pos) { + tg3json_parse_options options; + TINYGLTF_JSON_MEMSET(&options, 0, sizeof(options)); + options.depth_limit = depth_limit; + return tg3json_parse_n_opts(data, len, &options, out_value, out_error_pos); +} + +int tg3json_parse(const char *begin, const char *end, size_t depth_limit, + tg3json_value *out_value, const char **out_error_pos) { + if (!begin || !end || end < begin) { + if (out_error_pos) *out_error_pos = begin; + return 0; + } + return tg3json_parse_n(begin, (size_t)(end - begin), depth_limit, + out_value, out_error_pos); +} + +void tg3json_value_free(tg3json_value *value) { + size_t i; + if (!value) return; + switch (value->type) { + case TG3JSON_STRING: + TINYGLTF_JSON_FREE(value->u.string.ptr); + break; + case TG3JSON_ARRAY: + for (i = 0; i < value->u.array.count; ++i) { + tg3json_value_free(&value->u.array.items[i]); + } + TINYGLTF_JSON_FREE(value->u.array.items); + break; + case TG3JSON_OBJECT: + for (i = 0; i < value->u.object.count; ++i) { + TINYGLTF_JSON_FREE(value->u.object.items[i].key); + if (value->u.object.items[i].value) { + tg3json_value_free(value->u.object.items[i].value); + TINYGLTF_JSON_FREE(value->u.object.items[i].value); + } + } + TINYGLTF_JSON_FREE(value->u.object.items); + break; + case TG3JSON_NULL: + case TG3JSON_BOOL: + case TG3JSON_INT: + case TG3JSON_REAL: + /* Scalar variants own no heap memory. */ + break; + } + tg3json__init_value(value); +} + +void tg3json_value_init_null(tg3json_value *value) { + tg3json__init_value(value); +} + +void tg3json_value_init_bool(tg3json_value *value, int boolean_value) { + tg3json__init_value(value); + value->type = TG3JSON_BOOL; + value->u.boolean = boolean_value ? 1 : 0; +} + +void tg3json_value_init_int(tg3json_value *value, int64_t integer_value) { + tg3json__init_value(value); + value->type = TG3JSON_INT; + value->u.integer = integer_value; +} + +void tg3json_value_init_real(tg3json_value *value, double real_value) { + tg3json__init_value(value); + value->type = TG3JSON_REAL; + value->u.real = real_value; +} + +int tg3json_value_init_string_n(tg3json_value *value, const char *str, size_t len) { + tg3json__init_value(value); + value->type = TG3JSON_STRING; + value->u.string.ptr = tg3json__strndup_local(str ? str : "", str ? len : 0); + if (!value->u.string.ptr) { + tg3json__init_value(value); + return 0; + } + value->u.string.len = str ? len : 0; + return 1; +} + +int tg3json_value_init_string(tg3json_value *value, const char *str) { + return tg3json_value_init_string_n(value, str, str ? TINYGLTF_JSON_STRLEN(str) : 0); +} + +void tg3json_value_init_array(tg3json_value *value) { + tg3json__init_value(value); + value->type = TG3JSON_ARRAY; +} + +void tg3json_value_init_object(tg3json_value *value) { + tg3json__init_value(value); + value->type = TG3JSON_OBJECT; +} + +int tg3json_value_copy(tg3json_value *dst, const tg3json_value *src) { + size_t i; + tg3json__init_value(dst); + if (!src) return 1; + switch (src->type) { + case TG3JSON_NULL: + return 1; + case TG3JSON_BOOL: + tg3json_value_init_bool(dst, src->u.boolean); + return 1; + case TG3JSON_INT: + tg3json_value_init_int(dst, src->u.integer); + return 1; + case TG3JSON_REAL: + tg3json_value_init_real(dst, src->u.real); + return 1; + case TG3JSON_STRING: + return tg3json_value_init_string_n(dst, src->u.string.ptr, src->u.string.len); + case TG3JSON_ARRAY: + tg3json_value_init_array(dst); + for (i = 0; i < src->u.array.count; ++i) { + if (!tg3json_array_append_copy(dst, &src->u.array.items[i])) { + tg3json_value_free(dst); + return 0; + } + } + return 1; + case TG3JSON_OBJECT: + tg3json_value_init_object(dst); + for (i = 0; i < src->u.object.count; ++i) { + if (!tg3json_object_set_copy_n(dst, src->u.object.items[i].key, + src->u.object.items[i].key_len, + src->u.object.items[i].value)) { + tg3json_value_free(dst); + return 0; + } + } + return 1; + } + return 0; /* unreachable: all enum cases handled above. */ +} + +const tg3json_value *tg3json_object_get_n(const tg3json_value *object, + const char *key, size_t key_len) { + size_t i; + if (!object || object->type != TG3JSON_OBJECT) return NULL; + for (i = 0; i < object->u.object.count; ++i) { + const tg3json_object_entry *entry = &object->u.object.items[i]; + if (entry->key_len == key_len && TINYGLTF_JSON_MEMCMP(entry->key, key, key_len) == 0) { + return entry->value; + } + } + return NULL; +} + +const tg3json_value *tg3json_object_get(const tg3json_value *object, + const char *key) { + if (!key) return NULL; + return tg3json_object_get_n(object, key, TINYGLTF_JSON_STRLEN(key)); +} + +tg3json_value *tg3json_object_get_mut_n(tg3json_value *object, + const char *key, size_t key_len) { + size_t i; + if (!object || object->type != TG3JSON_OBJECT) return NULL; + for (i = 0; i < object->u.object.count; ++i) { + tg3json_object_entry *entry = &object->u.object.items[i]; + if (entry->key_len == key_len && TINYGLTF_JSON_MEMCMP(entry->key, key, key_len) == 0) { + return entry->value; + } + } + return NULL; +} + +tg3json_value *tg3json_object_get_mut(tg3json_value *object, const char *key) { + if (!key) return NULL; + return tg3json_object_get_mut_n(object, key, TINYGLTF_JSON_STRLEN(key)); +} + +const tg3json_object_entry *tg3json_object_at(const tg3json_value *object, + size_t index) { + if (!object || object->type != TG3JSON_OBJECT || index >= object->u.object.count) { + return NULL; + } + return &object->u.object.items[index]; +} + +size_t tg3json_object_size(const tg3json_value *object) { + if (!object || object->type != TG3JSON_OBJECT) return 0; + return object->u.object.count; +} + +int tg3json_object_set_take_n(tg3json_value *object, const char *key, size_t key_len, + tg3json_value *value) { + tg3json_value *existing; + tg3json_object_entry *entry; + size_t cap; + if (!object || object->type != TG3JSON_OBJECT || !value || !key) return 0; + existing = tg3json_object_get_mut_n(object, key, key_len); + if (existing) { + tg3json_value_free(existing); + *existing = *value; + tg3json__init_value(value); + return 1; + } + cap = object->u.object.count; + if (!tg3json__reserve_bytes((void **)&object->u.object.items, sizeof(*object->u.object.items), + object->u.object.count + 1, &cap)) { + return 0; + } + entry = &object->u.object.items[object->u.object.count]; + entry->key = tg3json__strndup_local(key, key_len); + if (!entry->key) return 0; + entry->key_len = key_len; + entry->value = (tg3json_value *)TINYGLTF_JSON_MALLOC(sizeof(tg3json_value)); + if (!entry->value) { + TINYGLTF_JSON_FREE(entry->key); + entry->key = NULL; + entry->key_len = 0; + return 0; + } + *entry->value = *value; + tg3json__init_value(value); + object->u.object.count += 1; + return 1; +} + +int tg3json_object_set_take(tg3json_value *object, const char *key, + tg3json_value *value) { + if (!key) return 0; + return tg3json_object_set_take_n(object, key, TINYGLTF_JSON_STRLEN(key), value); +} + +int tg3json_object_set_copy_n(tg3json_value *object, const char *key, size_t key_len, + const tg3json_value *value) { + tg3json_value copy; + tg3json__init_value(©); + if (!tg3json_value_copy(©, value)) return 0; + if (!tg3json_object_set_take_n(object, key, key_len, ©)) { + tg3json_value_free(©); + return 0; + } + return 1; +} + +int tg3json_object_set_copy(tg3json_value *object, const char *key, + const tg3json_value *value) { + if (!key) return 0; + return tg3json_object_set_copy_n(object, key, TINYGLTF_JSON_STRLEN(key), value); +} + +const tg3json_value *tg3json_array_get(const tg3json_value *array, size_t index) { + if (!array || array->type != TG3JSON_ARRAY || index >= array->u.array.count) { + return NULL; + } + return &array->u.array.items[index]; +} + +size_t tg3json_array_size(const tg3json_value *array) { + if (!array || array->type != TG3JSON_ARRAY) return 0; + return array->u.array.count; +} + +int tg3json_array_append_take(tg3json_value *array, tg3json_value *value) { + size_t cap; + if (!array || array->type != TG3JSON_ARRAY || !value) return 0; + cap = array->u.array.count; + if (!tg3json__reserve_bytes((void **)&array->u.array.items, sizeof(*array->u.array.items), + array->u.array.count + 1, &cap)) { + return 0; + } + array->u.array.items[array->u.array.count++] = *value; + tg3json__init_value(value); + return 1; +} + +int tg3json_array_append_copy(tg3json_value *array, const tg3json_value *value) { + tg3json_value copy; + tg3json__init_value(©); + if (!tg3json_value_copy(©, value)) return 0; + if (!tg3json_array_append_take(array, ©)) { + tg3json_value_free(©); + return 0; + } + return 1; +} + +static int tg3json__indent(tg3json__buffer *buf, int indent, int depth) { + int i; + if (indent <= 0) return 1; + if (!tg3json__buf_putc(buf, '\n')) return 0; + for (i = 0; i < indent * depth; ++i) { + if (!tg3json__buf_putc(buf, ' ')) return 0; + } + return 1; +} + +static int tg3json__stringify_value_ex(tg3json__buffer *buf, const tg3json_value *value, + int indent, int depth) { + size_t i; + char numbuf[64]; + switch (value->type) { + case TG3JSON_NULL: + return tg3json__buf_append(buf, "null", 4); + case TG3JSON_BOOL: + return value->u.boolean ? tg3json__buf_append(buf, "true", 4) + : tg3json__buf_append(buf, "false", 5); + case TG3JSON_INT: + tg3json__itoa(value->u.integer, numbuf); + return tg3json__buf_append(buf, numbuf, TINYGLTF_JSON_STRLEN(numbuf)); + case TG3JSON_REAL: + { + char *end = tg3json__dtoa_c(value->u.real, numbuf); + *end = '\0'; + const char *b = numbuf; + if (*b == '-') ++b; + if (*b == 'n' || *b == 'N' || *b == 'i' || *b == 'I') { + return tg3json__buf_append(buf, "null", 4); + } + } + return tg3json__buf_append(buf, numbuf, TINYGLTF_JSON_STRLEN(numbuf)); + case TG3JSON_STRING: + if (!tg3json__buf_putc(buf, '"')) return 0; + for (i = 0; i < value->u.string.len; ++i) { + unsigned char c = (unsigned char)value->u.string.ptr[i]; + switch (c) { + case '"': if (!tg3json__buf_append(buf, "\\\"", 2)) return 0; break; + case '\\': if (!tg3json__buf_append(buf, "\\\\", 2)) return 0; break; + case '\b': if (!tg3json__buf_append(buf, "\\b", 2)) return 0; break; + case '\f': if (!tg3json__buf_append(buf, "\\f", 2)) return 0; break; + case '\n': if (!tg3json__buf_append(buf, "\\n", 2)) return 0; break; + case '\r': if (!tg3json__buf_append(buf, "\\r", 2)) return 0; break; + case '\t': if (!tg3json__buf_append(buf, "\\t", 2)) return 0; break; + default: + if (c < 0x20u) { + numbuf[0] = '\\'; + numbuf[1] = 'u'; + numbuf[2] = '0'; + numbuf[3] = '0'; + numbuf[4] = "0123456789abcdef"[(c >> 4) & 0xf]; + numbuf[5] = "0123456789abcdef"[c & 0xf]; + numbuf[6] = '\0'; + if (!tg3json__buf_append(buf, numbuf, 6)) return 0; + } else { + if (!tg3json__buf_putc(buf, (char)c)) return 0; + } + break; + } + } + return tg3json__buf_putc(buf, '"'); + case TG3JSON_ARRAY: + if (!tg3json__buf_putc(buf, '[')) return 0; + for (i = 0; i < value->u.array.count; ++i) { + if (i > 0 && !tg3json__buf_putc(buf, ',')) return 0; + if (indent > 0 && !tg3json__indent(buf, indent, depth + 1)) return 0; + if (!tg3json__stringify_value_ex(buf, &value->u.array.items[i], indent, depth + 1)) return 0; + } + if (indent > 0 && value->u.array.count > 0 && !tg3json__indent(buf, indent, depth)) return 0; + return tg3json__buf_putc(buf, ']'); + case TG3JSON_OBJECT: + if (!tg3json__buf_putc(buf, '{')) return 0; + for (i = 0; i < value->u.object.count; ++i) { + tg3json_value key_value; + if (i > 0 && !tg3json__buf_putc(buf, ',')) return 0; + if (indent > 0 && !tg3json__indent(buf, indent, depth + 1)) return 0; + tg3json__init_value(&key_value); + key_value.type = TG3JSON_STRING; + key_value.u.string.ptr = value->u.object.items[i].key; + key_value.u.string.len = value->u.object.items[i].key_len; + if (!tg3json__stringify_value_ex(buf, &key_value, indent, depth + 1)) return 0; + if (!tg3json__buf_putc(buf, ':')) return 0; + if (indent > 0 && !tg3json__buf_putc(buf, ' ')) return 0; + if (!tg3json__stringify_value_ex(buf, value->u.object.items[i].value, indent, depth + 1)) return 0; + } + if (indent > 0 && value->u.object.count > 0 && !tg3json__indent(buf, indent, depth)) return 0; + return tg3json__buf_putc(buf, '}'); + } + return 0; /* unreachable: all enum cases handled above. */ +} + +char *tg3json_stringify(const tg3json_value *value, size_t *out_len) { + tg3json__buffer buf; + TINYGLTF_JSON_MEMSET(&buf, 0, sizeof(buf)); + if (!value || !tg3json__stringify_value_ex(&buf, value, -1, 0)) { + TINYGLTF_JSON_FREE(buf.data); + if (out_len) *out_len = 0; + return NULL; + } + if (!buf.data) { + buf.data = (char *)TINYGLTF_JSON_MALLOC(1); + if (!buf.data) { + if (out_len) *out_len = 0; + return NULL; + } + buf.data[0] = '\0'; + } + if (out_len) *out_len = buf.len; + return buf.data; +} + +char *tg3json_stringify_pretty(const tg3json_value *value, int indent, size_t *out_len) { + tg3json__buffer buf; + TINYGLTF_JSON_MEMSET(&buf, 0, sizeof(buf)); + if (!value || !tg3json__stringify_value_ex(&buf, value, indent, 0)) { + TINYGLTF_JSON_FREE(buf.data); + if (out_len) *out_len = 0; + return NULL; + } + if (!buf.data) { + buf.data = (char *)TINYGLTF_JSON_MALLOC(1); + if (!buf.data) { + if (out_len) *out_len = 0; + return NULL; + } + buf.data[0] = '\0'; + } + if (out_len) *out_len = buf.len; + return buf.data; +} + +#endif /* TINYGLTF_JSON_C_IMPLEMENTATION */ +#endif /* TINYGLTF_JSON_C_H_ */