diff options
| author | Gabriel Schneider <[email protected]> | 2026-11-16 18:04:21 -0300 |
|---|---|---|
| committer | Gabriel Schneider <[email protected]> | 2026-11-16 18:04:21 -0300 |
| commit | e77b01d4b5504cea08a3f88cf8502897d868a1d3 (patch) | |
| tree | c8e643d234dd26d920cbc563bfa7f740febf1fc7 | |
| parent | d3074636fff0fbcd5fd9b71c0c3b1c1f5c0c1285 (diff) | |
| download | sketchbook-e77b01d4b5504cea08a3f88cf8502897d868a1d3.tar.gz sketchbook-e77b01d4b5504cea08a3f88cf8502897d868a1d3.zip | |
Add glTF scene rendering, resource setup and 9P controls
| -rw-r--r-- | README.md | 192 | ||||
| -rw-r--r-- | build.zig | 90 | ||||
| -rw-r--r-- | build.zig.zon | 1 | ||||
| -rw-r--r-- | src/abi.zig | 24 | ||||
| -rw-r--r-- | src/gltf.zig | 156 | ||||
| -rw-r--r-- | src/gltf_generate.zig | 112 | ||||
| -rw-r--r-- | src/gltf_render/basic.frag | 10 | ||||
| -rw-r--r-- | src/gltf_render/basic.vert | 16 | ||||
| -rw-r--r-- | src/gltf_render/math.zig | 67 | ||||
| -rw-r--r-- | src/gltf_render/root.zig | 164 | ||||
| -rw-r--r-- | src/gltf_render/types.zig | 13 | ||||
| -rw-r--r-- | src/gltf_render/web.zig | 2 | ||||
| -rw-r--r-- | src/gltf_scene.zig | 416 | ||||
| -rw-r--r-- | src/gpu/Executor.zig (renamed from src/host/gpu.zig) | 157 | ||||
| -rw-r--r-- | src/gpu/scene.zig | 263 | ||||
| -rw-r--r-- | src/host/Host.zig | 177 | ||||
| -rw-r--r-- | src/host/control.zig | 368 | ||||
| -rw-r--r-- | src/host/gfx.zig | 9 | ||||
| -rw-r--r-- | src/host/root.zig | 5 | ||||
| -rw-r--r-- | src/sketch/root.zig | 60 | ||||
| -rw-r--r-- | src/sketch/web.zig | 15 | ||||
| -rw-r--r-- | tools/gltf_bindings.zig | 14 | ||||
| -rw-r--r-- | vendor/README.md | 3 | ||||
| -rw-r--r-- | vendor/cgltf.c | 2 | ||||
| -rw-r--r-- | vendor/cgltf.h | 7240 | ||||
| -rw-r--r-- | web/host.js | 15 |
26 files changed, 9525 insertions, 66 deletions
@@ -32,7 +32,8 @@ An app is an ordinary module. Every declaration is optional: | `State` | Saved to a file, snapshotted, replayed: what `update` changes. No pointers and no host handles (compile errors). | | `Session` | This process: survives reloads, never saved. Caches, image and buffer handles, playback cursors. | | `Store` | On disk, at the same address in every run: survives reloads and restarts. Big data that is not replayed (a recording, a document). May point into itself; no host handles. | -| `init(state, host)` | Setup for brand-new state, after the declared defaults | +| `init(state, host)` | Seed brand-new state, after the declared defaults | +| `setup(session, init) !void` | Initialize resources once per fresh Session, including startup with restored State | | `update(state, input)` | **Deterministic**: the host replays recorded input through it | | `draw(state, session, store, frame)` | Pictures and sound, as commands; may change Session and Store | | `command(state, session, store, console, line) !bool` | Console lines the host does not know | @@ -44,6 +45,22 @@ Functions take the parameters they name, matched by type and in any order: `State` and `Input`; asking for more is a compile error, since a replay could not reproduce it. +`setup` receives `*sk.Init` with `host`, `session`, and `store` allocators; +it may also request Session, Store, or Host directly. It gets no State, Input, +or Frame. Load assets and create/upload GPU buffers there, then use those +resources in `draw`. `try init.host.writeBuffer(buffer, offset, bytes)` submits +a copy immediately; the source bytes may be released when it returns. WebGPU +uploads require four-byte-aligned offsets and sizes. + +Resource setup runs after Session defaults, once on startup even when State was +restored from disk, and again if a reload changes Session's layout. Compatible +reloads and ordinary state resets preserve the Session and do not rerun setup. +The browser invokes it during its initial setup too. A hook may return `void` or +`!void`; uncaught errors are logged and disable app callbacks, while the native +host console and 9P controls remain available. Restart after fixing a failed setup. +Use a Session error field and handle the error inside setup when the app needs +to display an initialization failure. `zig build test-setup` checks this lifecycle. + Memory comes by lifetime, one allocator each: | Allocator | Lifetime | Released | @@ -828,6 +845,10 @@ Add `.sketchbook = .{ .path = "..." }` to your `build.zig.zon`. decoded, multisampling is 4× at most, and mixing runs on the main thread (a ScriptProcessor), so a busy page can crackle. +The reusable GPU executor and the pardes integration are described in +[docs/pardes-rendering.md](docs/pardes-rendering.md), including the remaining +renderer migration work and the optional addon boundary. + ## Designs - [Regions in source](docs/regions-in-source.md): editing layout from the @@ -907,3 +928,172 @@ initialize Sketchbook so the build shares one host/client module. ASCII text caches coverage independently of animated ink. The pinned SDL Vulkan patch keeps memory relocation disabled and lets small transfer buffers share allocations, avoiding hundreds of dedicated allocation frees during presentation. + +## glTF / GLB assets + +The optional `gltf` module wraps the vendored C99 `cgltf` loader. It loads scene +hierarchies, mesh accessors, materials, cameras, animation tracks and arbitrary +`extras` metadata without depending on the window or renderer. Import it into a +native executable or sketch with `.imports = &.{.{ .name = "gltf", .module = sb.modules.gltf }}`. +It currently requires libc; it is not wired into the freestanding browser host. + +```zig +const gltf = @import("gltf"); +const document = try gltf.Document.parse(bytes); +defer document.deinit(); +try document.loadBuffers(null); // embedded GLB / data-URI buffers, no file reads +const node = document.findNode("CAM_StreetTour") orelse return error.MissingCamera; +const json = gltf.extrasJson(&node.extras) orelse return error.MissingMetadata; +// Parse json with std.json using the application's own metadata schema. +``` + +Keep `bytes` alive until `deinit`: GLB buffers may borrow it. Parsing validates +structure and uses cgltf's C allocator, released by `deinit`. `loadBuffers` +validates again with loaded data. Only passing a non-null, zero-terminated glTF +source path enables relative external buffer-file reads; use that for trusted +assets. Images and compressed geometry still need their own decoders. + +`document.data` and `gltf.c` expose cgltf directly; `gltf.readFloats(accessor, +index, out)` adds bounds/component checks and supports strided, normalized and +sparse accessors. The raw animation channels remain available to the caller; +this module does not create GPU resources or implement an animation player. +Run `zig build test-gltf` for focused loader tests; they are also part of +`zig build test`. + +### Generated scene bindings + +`sb.addGltf` runs a native host executable in a separate build step, then supplies +its generated `.zig` file as a module. The glTF file is a tracked build input; +changing it regenerates the bindings before compiling their consumers. + +```zig +// build.zig: add this import to the consuming module's .imports. +.{ .name = "street_scene", .module = sb.addGltf(b.path("street.glb")) } +``` + +```zig +const scene = @import("street_scene"); +const camera = scene.nodes.CAM_StreetTour; +comptime { + if (!@import("std").mem.eql(u8, camera.extras.drat_role, "camera")) + @compileError("expected a camera role"); +} +// camera.index locates the node; @TypeOf(camera.extras) exposes metadata fields. +``` + +The generated `nodes`, `animations`, `cameras`, `meshes`, and `materials` +namespaces expose named entries with indices and typed `extras`; nodes also +include optional camera and mesh indices. Labels with spaces use Zig's quoted +identifier syntax, e.g. `scene.nodes.@"Camera - At the corner"`. Unnamed entries +are omitted; duplicate labels within one namespace fail generation. JSON objects +become struct values, arrays become tuples, and strings/numbers retain explicit +Zig types. Comptime can reflect on these types or assert expected values; it never +parses the asset. Missing referenced labels/fields and incompatible types fail +compilation; application assertions define which metadata values must match. + +The module contains no libc dependency. `source_path` is the build input filename; +`source_sha256` lets runtime consumers +reject a replaced asset before using generated indices. Code generation reads +metadata, not external buffers; geometry and animation sample checks still use +the runtime loader. The game repo's `scripts/check_scene.zig` demonstrates both. + +### Local 9P controls + +Native hosts accept `--9p /absolute/path/game.sock`. The opt-in Unix socket uses +cloud9, is owner-only (`0600`), refuses existing paths, and is removed on clean +exit. Four clients can connect; requests run between frames on the host thread. +The build uses the sibling `../cloud9` checkout. + +```sh +./zig-out/bin/drat-meout --9p /tmp/drat.sock +printf 'scene street\nget scene\n' | 9p -a unix!/tmp/drat.sock write ctl +9p -a unix!/tmp/drat.sock read log +printf 'screenshot\n' | 9p -a unix!/tmp/drat.sock write ctl +9p -a unix!/tmp/drat.sock read status +# Once screenshot_pending is false and screenshot_generation has advanced: +9p -a unix!/tmp/drat.sock read screen.png > /tmp/street.png +printf 'quit\n' | 9p -a unix!/tmp/drat.sock write ctl +``` + +`ctl` accepts complete console command lines (up to 4096 bytes per write), +including game commands and host `set`, `get`, `pause`, `step`, `seek`, and `quit`. +Errors return as 9P errors. `log` exposes the console's latest five lines; +`status` reports canvas size, playback mode, GPU availability and capture state. +`screenshot` captures the next rendered canvas as PNG; `screen.png` opens fail +while capture is pending or failed. Each successful open pins its own snapshot, +so a later capture cannot change a partially read image. Screenshots include +visible overlays. `zig build test-control` checks the control boundary and +snapshot lifetime; the same tests belong to the full host suite. + +With `--profile-gpu`, `profile` reports tab-separated `label`, `count`, `mean_ms`, +and `worst_ms`, plus a `# frames N` line. `profile-reset` written to `ctl` resets +counters and the frame denominator without discarding label allocations. Warm up +first, reset, then wait for the desired number of frames before reading. These +measure CPU wall time from GPU command recording through submission and fence +wait, including synchronization overhead; they are not hardware GPU timestamps. +Both operations return `ProfilingDisabled` when profiling is off. + +### Imperative glTF drawing + +Add an import with `.module = sb.addGltfRenderer()` (e.g. named `gltf_render`). +Its `Model` copies a GLB's meshes and animation tracks into the caller's session +arena. The cgltf document is released after loading; geometry uploads once to +host-owned GPU buffers. Opaque primitives in each mesh are batched into one draw +with per-vertex material colors. Only transforms and draw commands change each frame. + +```zig +const render = @import("gltf_render"); +const street_scene = @import("street_scene"); +pub const Session = struct { model: render.Model = undefined, image: sk.Image = .none }; + +pub fn setup(ss: *Session, init: *sk.Init) !void { + // Filename + hash come from the generated bindings. Parses and uploads once. + ss.model = try render.Model.load(init, street_scene); + ss.image = init.host.newImage(960, 600); +} + +pub fn draw(s: *const State, ss: *Session, f: *sk.Frame) void { + renderFrame(s, ss, f) catch |err| f.host.print("scene: {t}", .{err}); +} +fn renderFrame(s: *const State, ss: *Session, f: *sk.Frame) !void { + try ss.model.scene.sample(street_scene.animations.CAM_StreetTour.index, s.time); + const camera = try render.sceneCamera(&ss.model.scene, street_scene.nodes.CAM_StreetTour.index); + var view = render.View.init(f, ss.image, 960, 600, camera); + try view.scene(&ss.model); + // Or: try view.mesh(&ss.model, street_scene.meshes.MyMesh.index, transform); + // Or: try view.triangles(&geometry, transform, color); // upload in setup first + view.end(); + f.image(ss.image, .{ .x = 0, .y = 0, .w = 960, .h = 600 }, .{}); +} +``` + +`model.scene.nodes[index].world` is a column-major transform; `meshes[index]` +exposes indexed vertices, normals and material colors. Animation sampling is +allocation-free, supports STEP, LINEAR (slerp for rotations), and CUBICSPLINE TRS, +and clamps to the clip range; the application decides how to loop. The separate +CPU API is `gltf.Scene.init(allocator, document)`, `sample`, `reset`, and `deinit`. +It copies loaded data, so the document can be destroyed after initialization. + +`render.sceneCamera(scene, node_index)` derives perspective or orthographic +projection and view from the sampled camera node. Alternatively pass a plain +`render.Camera` with your own eye/target to `View.init`. `Model.init` remains +available for CPU loading, and `Geometry.upload(host)` uploads custom triangles +explicitly during setup. No resource loading happens inside `View.scene/mesh`. + +This initial renderer uses opaque material base colors, directional light and a +depth buffer. It has no texture sampling, alpha blending, shadows, skinning or +morph animation. Unsupported mesh/animation features fail loading explicitly; +material textures are ignored. The renderer currently supports native hosts; +`render.supported` is false in the browser replacement module. GPU handles are +released by the host on session reset; call `model.release(host)` to release them +earlier. Vertex storage layout and shader uniform layout are checked at comptime; +GLSL uniform declarations are generated from the Zig types. + +`profile` also includes `p95_ms` and `p99_ms`: nearest-rank percentiles of the +latest 2048 measured commands per label. Mean and worst cover every command since +reset. `profile-trace` exposes those retained samples as CSV (`label,sample,ns`), +ordered oldest to newest within each label; sample numbers start at 1 after +reset. Each open pins the trace even if profiling continues or counters reset. +The render path writes a fixed ring; sorting and CSV generation happen only on +inspection. A trace snapshot is limited to 256 KiB and fails if it exceeds that +limit. Capture it with `9p -a unix!/tmp/drat.sock read profile-trace > trace.csv`. @@ -30,8 +30,25 @@ pub fn build(b: *Build) void { const target = b.standardTargetOptions(.{}); const optimize = b.standardOptimizeOption(.{}); + const gltf = gltfModule(b, target, optimize); + b.modules.put(b.graph.arena, "gltf", gltf) catch @panic("OOM"); + const gltf_generator = b.addExecutable(.{ + .name = "gltf-bindings", + .root_module = b.createModule(.{ + .root_source_file = b.path("tools/gltf_bindings.zig"), + .target = b.graph.host, + .optimize = .ReleaseSafe, + .imports = &.{.{ .name = "gltf", .module = gltfModule(b, b.graph.host, .ReleaseSafe) }}, + }), + }); + b.installArtifact(gltf_generator); + // Target-free: they compile for whatever imports them, native or wasm. const abi = b.addModule("abi", .{ .root_source_file = b.path("src/abi.zig") }); + const gpu = b.addModule("gpu", .{ .root_source_file = b.path("src/gpu/Executor.zig"), .imports = &.{.{ .name = "abi", .module = abi }} }); + _ = b.addModule("gpu_scene", .{ .root_source_file = b.path("src/gpu/scene.zig"), .imports = &.{.{ .name = "abi", .module = abi }} }); + // Embedders provide their existing SDL translation and device. + if (b.option(bool, "gpu-only", "export GPU modules without building the sketch host") orelse false) return; // Geometry and noise, shared by the sketch library and `vector`. const math = b.addModule("math", .{ .root_source_file = b.path("src/math/root.zig") }); const sketch_imports: []const Build.Module.Import = &.{ .{ .name = "abi", .module = abi }, .{ .name = "math", .module = math } }; @@ -51,14 +68,21 @@ pub fn build(b: *Build) void { tracy.link_libcpp = true; } const c = cModule(b, target, optimize); + gpu.addImport("c", c); // No optimize mode of its own: the host's Zig code builds in the mode // of the executable it is part of (`script_optimize` makes use of it). + const cloud9 = b.dependency("cloud9", .{ .target = target, .optimize = optimize }).module("cloud9"); const host = b.addModule("host", .{ .root_source_file = b.path("src/host/root.zig"), .target = target, - .imports = &.{ .{ .name = "abi", .module = abi }, .{ .name = "c", .module = c }, .{ .name = "tracy", .module = tracy } }, + .imports = &.{ .{ .name = "abi", .module = abi }, .{ .name = "c", .module = c }, .{ .name = "gpu", .module = gpu }, .{ .name = "tracy", .module = tracy }, .{ .name = "cloud9", .module = cloud9 } }, }); + b.step("test-control", "Test 9P control validation and screenshot snapshots").dependOn(&b.addRunArtifact(b.addTest(.{ .root_module = host, .filters = &.{ "control writes", "9P reads" } })).step); + + const setup_tests = b.step("test-setup", "Test resource setup lifecycle and arguments"); + for ([_]*Build.Module{ host, b.createModule(.{ .root_source_file = b.path("src/sketch/root.zig"), .target = target, .optimize = optimize, .imports = sketch_imports }) }) |module| setup_tests.dependOn(&b.addRunArtifact(b.addTest(.{ .root_module = module, .filters = &.{"setup"} })).step); + const host_exe = b.addExecutable(.{ .name = "sketchbook", .root_module = b.createModule(.{ @@ -81,7 +105,7 @@ pub fn build(b: *Build) void { }); b.installArtifact(probe); - var sb: Sketchbook = .{ .b = b, .target = target, .optimize = optimize, .modules = .{ .abi = abi, .sketch = sketch, .host = host, .tracy = tracy, .vector = undefined, .scope = undefined, .anim = undefined }, .host_exe = host_exe, .probe_exe = probe, .web = b.path("web"), .glsl = b.path("src/glsl.zig"), .tools = b.path("tools"), .anim_dir = b.path("src/anim"), .script_optimize = optimize, .shared = .create(b) }; + var sb: Sketchbook = .{ .b = b, .target = target, .optimize = optimize, .modules = .{ .abi = abi, .sketch = sketch, .host = host, .tracy = tracy, .vector = undefined, .scope = undefined, .anim = undefined, .gltf = gltf }, .host_exe = host_exe, .probe_exe = probe, .gltf_generator = gltf_generator, .web = b.path("web"), .glsl = b.path("src/glsl.zig"), .tools = b.path("tools"), .anim_dir = b.path("src/anim"), .gltf_render_dir = b.path("src/gltf_render"), .script_optimize = optimize, .shared = .create(b) }; // Vector graphics: built with the same shader step apps use. Both forms // of its shaders are exported, so apps' web builds can swap them too. @@ -129,6 +153,11 @@ pub fn build(b: *Build) void { sb.modules.scope = b.addModule("scope", .{ .root_source_file = b.path("src/scope/root.zig"), .imports = scope_imports }); const test_step = b.step("test", "Run unit tests and the reload end-to-end test"); + const gltf_tests = b.addRunArtifact(b.addTest(.{ .root_module = gltf })); + b.step("test-gltf", "Test glTF parsing, extras and accessor reads").dependOn(&gltf_tests.step); + test_step.dependOn(&gltf_tests.step); + const scene_tests = b.createModule(.{ .root_source_file = b.path("src/gpu/scene.zig"), .target = target, .optimize = optimize, .imports = &.{.{ .name = "abi", .module = abi }} }); + test_step.dependOn(&b.addRunArtifact(b.addTest(.{ .root_module = scene_tests })).step); for ([_]*Build.Module{ b.createModule(.{ .root_source_file = b.path("src/vector/root.zig"), .target = target, .optimize = optimize, .imports = vector_imports }), b.createModule(.{ .root_source_file = b.path("src/scope/root.zig"), .target = target, .optimize = optimize, .imports = scope_imports }), @@ -137,7 +166,7 @@ pub fn build(b: *Build) void { b.createModule(.{ .root_source_file = b.path("src/abi.zig"), .target = target, .optimize = optimize }), b.createModule(.{ .root_source_file = b.path("src/sketch/root.zig"), .target = target, .optimize = optimize, .imports = sketch_imports }), b.createModule(.{ .root_source_file = b.path("src/math/root.zig"), .target = target, .optimize = optimize }), - b.createModule(.{ .root_source_file = b.path("src/host/root.zig"), .target = target, .optimize = optimize, .imports = &.{ .{ .name = "abi", .module = abi }, .{ .name = "c", .module = c }, .{ .name = "tracy", .module = tracy } } }), + b.createModule(.{ .root_source_file = b.path("src/host/root.zig"), .target = target, .optimize = optimize, .imports = &.{ .{ .name = "abi", .module = abi }, .{ .name = "c", .module = c }, .{ .name = "gpu", .module = gpu }, .{ .name = "tracy", .module = tracy }, .{ .name = "cloud9", .module = cloud9 } } }), }) |module| test_step.dependOn(&b.addRunArtifact(b.addTest(.{ .root_module = module })).step); // The noise tests again on wasm32 as the web builds it, under Node's @@ -264,7 +293,8 @@ pub fn build(b: *Build) void { exported.addArg("--define"); exported.addPrefixedDirectoryArg("b=", export_b.addExport(export_b.addExecutable(), export_options).frames); test_step.dependOn(&exported.step); - const raw = b.addSystemCommand(&.{ "sh", "-c", + const raw = b.addSystemCommand(&.{ + "sh", "-c", \\set -e \\test "$("$0" --state "$1" --export - --fps 30 --size 320x180 | wc -c)" = $((320 * 180 * 4 * 8)) \\command -v ffmpeg >/dev/null && command -v ffprobe >/dev/null || exit 0 @@ -300,6 +330,21 @@ pub fn build(b: *Build) void { test_step.dependOn(&replay.step); } +fn gltfModule(b: *Build, target: Build.ResolvedTarget, optimize: std.builtin.OptimizeMode) *Build.Module { + const translator: translate_c.Translator = .init(b.dependency("translate_c", .{}), .{ + .c_source_file = b.path("vendor/cgltf.h"), + .target = target, + .optimize = optimize, + }); + translator.mod.addCSourceFile(.{ .file = b.path("vendor/cgltf.c"), .flags = &.{"-std=c99"} }); + return b.createModule(.{ + .root_source_file = b.path("src/gltf.zig"), + .target = target, + .optimize = optimize, + .imports = &.{.{ .name = "cgltf_c", .module = translator.mod }}, + }); +} + fn cModule(b: *Build, target: Build.ResolvedTarget, optimize: std.builtin.OptimizeMode) *Build.Module { const sdl_dep = b.dependency("sdl", .{ .target = target, .optimize = optimize }); const sdl = sdl_dep.artifact("SDL3"); @@ -452,13 +497,15 @@ pub fn init(b: *Build, options: Options) Sketchbook { .b = b, .target = options.target, .optimize = options.optimize, - .modules = .{ .abi = dep.module("abi"), .sketch = dep.module("sketch"), .host = dep.module("host"), .tracy = dep.module("tracy"), .vector = dep.module("vector"), .scope = dep.module("scope"), .anim = dep.module("anim") }, + .modules = .{ .abi = dep.module("abi"), .sketch = dep.module("sketch"), .host = dep.module("host"), .tracy = dep.module("tracy"), .vector = dep.module("vector"), .scope = dep.module("scope"), .anim = dep.module("anim"), .gltf = dep.module("gltf") }, .host_exe = dep.artifact("sketchbook"), .probe_exe = dep.artifact("sketchbook-probe"), + .gltf_generator = dep.artifact("gltf-bindings"), .web = dep.path("web"), .glsl = dep.path("src/glsl.zig"), .tools = dep.path("tools"), .anim_dir = dep.path("src/anim"), + .gltf_render_dir = dep.path("src/gltf_render"), .script_optimize = options.script_optimize orelse options.optimize, .shared = shared, }; @@ -497,7 +544,8 @@ pub const Sketchbook = struct { /// `vector`: SVG, cubic geometry, and CPU and GPU renderers. `scope`: /// waveform, spectrogram, spectrum and oscilloscope views of a sound. /// `anim`: manim-style scenes as code (see `addScene`). - modules: struct { abi: *Build.Module, sketch: *Build.Module, host: *Build.Module, tracy: *Build.Module, vector: *Build.Module, scope: *Build.Module, anim: *Build.Module }, + /// `gltf`: native glTF/GLB documents, accessors and extras through cgltf. + modules: struct { abi: *Build.Module, sketch: *Build.Module, host: *Build.Module, tracy: *Build.Module, vector: *Build.Module, scope: *Build.Module, anim: *Build.Module, gltf: *Build.Module }, /// The generic host: loads and hot-reloads a sketch library. host_exe: *Build.Step.Compile, /// Prints any sketch's state file. @@ -516,6 +564,34 @@ pub const Sketchbook = struct { script_optimize: std.builtin.OptimizeMode, shared: *Shared, + /// Host executable; stays native even when the consumer is cross-compiled. + gltf_generator: *Build.Step.Compile, + gltf_render_dir: Build.LazyPath, + + /// Opaque native glTF rendering, with shader layouts generated from Zig types. + pub fn addGltfRenderer(sb: Sketchbook) *Build.Module { + const b = sb.b; + const types = b.createModule(.{ .root_source_file = sb.gltf_render_dir.path(b, "types.zig") }); + const shaders = sb.addShaders(.{ .layouts = .{ .module = types, .types = &.{"Transform"} }, .sources = &.{ + sb.gltf_render_dir.path(b, "basic.vert"), sb.gltf_render_dir.path(b, "basic.frag"), + } }); + const module = b.createModule(.{ .root_source_file = sb.gltf_render_dir.path(b, "root.zig"), .imports = &.{ + .{ .name = "sketch", .module = sb.modules.sketch }, .{ .name = "gltf", .module = sb.modules.gltf }, + .{ .name = "types", .module = types }, .{ .name = "shaders", .module = shaders.module }, + } }); + sb.shared.web_twins.put(b.graph.arena, module, b.createModule(.{ .root_source_file = sb.gltf_render_dir.path(b, "web.zig") })) catch @panic("OOM"); + return module; + } + + /// A cached generator run writes Zig source first; consumers compile it next. + /// Exact glTF labels become declarations; duplicate labels fail generation. + pub fn addGltf(sb: Sketchbook, source: Build.LazyPath) *Build.Module { + const run = sb.b.addRunArtifact(sb.gltf_generator); + run.addFileArg(source); + const generated = run.addOutputFileArg("gltf_bindings.zig"); + return sb.b.createModule(.{ .root_source_file = generated }); + } + pub const GlslLayouts = struct { run: *Build.Step.Run, /// `<Name>.glsl` for each type: pass it to `addGlslc` as an include. @@ -1481,6 +1557,8 @@ pub const App = struct { /// whose display name would be "generated". fn fileName(path: Build.LazyPath) []const u8 { return switch (path) { + .dependency => |d| std.fs.path.basename(d.sub_path), + .relative => |r| std.fs.path.basename(r.sub_path), .generated => |g| if (g.sub_path.len > 0) std.fs.path.basename(g.sub_path) else path.getDisplayName(), else => std.fs.path.basename(path.getDisplayName()), }; diff --git a/build.zig.zon b/build.zig.zon index ff49d2b..f48b70a 100644 --- a/build.zig.zon +++ b/build.zig.zon @@ -2,6 +2,7 @@ .name = .sketchbook, .version = "0.1.0", .dependencies = .{ + .cloud9 = .{ .path = "../cloud9" }, .sdl = .{ .url = "git+https://github.com/castholm/SDL.git#88f45bb1621c4373dd3633280ca01446b3eb8b11", .hash = "sdl-0.6.1-dev+3.4.18-SDL--pegqAGHW2CzWPJalwfjV_8Q5qdmSjk3uPRTsFUE", diff --git a/src/abi.zig b/src/abi.zig index 77a737d..2eed3a7 100644 --- a/src/abi.zig +++ b/src/abi.zig @@ -464,6 +464,8 @@ pub const gpu = struct { primitive: enum { triangle_list, triangle_strip, line_list, line_strip } = .triangle_list, blend: Blend = .premultiplied, write_color: bool = true, + depth_test: ?Compare = null, + depth_write: bool = false, /// Stencil test and update, per triangle facing. Needs a pass with /// a stencil buffer. stencil: ?struct { front: StencilFace, back: StencilFace } = null, @@ -527,6 +529,8 @@ pub const gpu = struct { primitive: @FieldType(Pipeline, "primitive") = .triangle_list, blend: Blend = .premultiplied, write_color: bool = true, + depth_test: ?Compare = null, + depth_write: bool = false, stencil: @FieldType(Pipeline, "stencil") = null, }) Pipeline { return .{ @@ -537,6 +541,8 @@ pub const gpu = struct { .primitive = p.primitive, .blend = p.blend, .write_color = p.write_color, + .depth_test = p.depth_test, + .depth_write = p.depth_write, .stencil = p.stencil, }; } @@ -564,11 +570,20 @@ pub const gpu = struct { /// 1, 2, 4 or 8. More than one renders multisampled and resolves. samples: u8 = 1, stencil: bool = false, + /// Clears depth to 1 each pass; pipelines choose comparison and writes. + depth: bool = false, /// Premultiplied; null keeps the image's previous contents. clear: ?[4]f32 = .{ 0, 0, 0, 0 }, pipelines: []const Pipeline, draws: []const Draw, }; + + /// A fullscreen triangle sampling one completed pass at fragment binding 0. + pub const PostProcess = struct { + vertex: Shader, + fragment: Shader, + fragment_uniforms: []const u8 = &.{}, + }; }; /// Host services. Handles and loaded data outlive reloads. @@ -593,6 +608,8 @@ pub const Host = struct { /// A GPU buffer of `size` bytes, zeroed; `.none` without a GPU. newBuffer: *const fn (*anyopaque, u32) Buffer, freeBuffer: *const fn (*anyopaque, Buffer) void, + /// Submits a copy now; source bytes may be released on return. + writeBuffer: *const fn (*anyopaque, Buffer, u32, []const u8) anyerror!void, /// Zero while unknown. imageSize: *const fn (*anyopaque, Image) [2]u32, /// What `Command.text` gives the bytes at a scale: the width they @@ -642,6 +659,10 @@ pub const Host = struct { pub fn freeBuffer(h: Host, buffer: Buffer) void { h.vtable.freeBuffer(h.ctx, buffer); } + /// Upload immediately, including during session setup. + pub fn writeBuffer(h: Host, buffer: Buffer, offset: u32, bytes: []const u8) !void { + try h.vtable.writeBuffer(h.ctx, buffer, offset, bytes); + } pub fn imageSize(h: Host, image: Image) [2]u32 { return h.vtable.imageSize(h.ctx, image); } @@ -766,6 +787,8 @@ pub const Sketch = struct { defaults: *const fn (Memory, [*]u8) callconv(.c) void, /// Setup for brand new state, after its defaults. init: *const fn (*const Context, [*]u8) callconv(.c) void, + /// Resource setup once per fresh Session; receives no State pointer. + setup: *const fn (*const Context) callconv(.c) bool, /// Deterministic: new state from state and input, nothing else. update: *const fn (*const Context, [*]u8) callconv(.c) void, /// Presentation: reads state, may change session and store, appends @@ -778,6 +801,7 @@ pub const Sketch = struct { .info = "sketch_info", .defaults = "sketch_defaults", .init = "sketch_init", + .setup = "sketch_setup", .update = "sketch_update", .draw = "sketch_draw", .command = "sketch_command", diff --git a/src/gltf.zig b/src/gltf.zig new file mode 100644 index 0000000..2d4ca47 --- /dev/null +++ b/src/gltf.zig @@ -0,0 +1,156 @@ +//! glTF/GLB documents backed by cgltf. Native/libc module; no renderer required. +//! The input bytes must outlive Document: GLB buffers can point into them. +//! C allocations are released by deinit; raw cgltf data stays available in `data`. +const std = @import("std"); +pub const c = @import("cgltf_c"); +pub const scene = @import("gltf_scene.zig"); +pub const Scene = scene.Scene; +/// Build-time code generation, not comptime glTF parsing. +pub const generate = @import("gltf_generate.zig").generate; + +test { + _ = @import("gltf_generate.zig"); + _ = scene; +} + +pub const Error = error{ + DataTooShort, + UnknownFormat, + InvalidJson, + InvalidGltf, + InvalidOptions, + FileNotFound, + IoError, + OutOfMemory, + LegacyGltf, + InvalidAccessor, + MissingBuffer, +}; + +fn check(result: c.cgltf_result) Error!void { + return switch (result) { + c.cgltf_result_success => {}, + c.cgltf_result_data_too_short => error.DataTooShort, + c.cgltf_result_unknown_format => error.UnknownFormat, + c.cgltf_result_invalid_json => error.InvalidJson, + c.cgltf_result_invalid_gltf => error.InvalidGltf, + c.cgltf_result_invalid_options => error.InvalidOptions, + c.cgltf_result_file_not_found => error.FileNotFound, + c.cgltf_result_io_error => error.IoError, + c.cgltf_result_out_of_memory => error.OutOfMemory, + c.cgltf_result_legacy_gltf => error.LegacyGltf, + else => error.InvalidGltf, + }; +} + +pub const Document = struct { + data: *c.cgltf_data, + + /// Parses and validates structure. Does not perform filesystem I/O. + pub fn parse(bytes: []const u8) Error!Document { + const options = std.mem.zeroes(c.cgltf_options); + var data: ?*c.cgltf_data = null; + try check(c.cgltf_parse(&options, bytes.ptr, bytes.len, &data)); + const doc: Document = .{ .data = data.? }; + errdefer doc.deinit(); + try check(c.cgltf_validate(doc.data)); + return doc; + } + + pub fn deinit(self: Document) void { + c.cgltf_free(self.data); + } + + /// Binds GLB/data-URI buffers. A non-null source path also permits external + /// buffer files, resolved relative to that glTF file; only pass trusted paths. + /// Images and compressed geometry are not decoded by this module. + pub fn loadBuffers(self: Document, source_path: ?[:0]const u8) Error!void { + const options = std.mem.zeroes(c.cgltf_options); + try check(c.cgltf_load_buffers(&options, self.data, if (source_path) |p| p.ptr else null)); + try check(c.cgltf_validate(self.data)); + } + + pub fn nodes(self: Document) []c.cgltf_node { + return if (self.data.nodes_count == 0) &.{} else self.data.nodes[0..self.data.nodes_count]; + } + + pub fn findNode(self: Document, name: []const u8) ?*c.cgltf_node { + for (self.nodes()) |*node| { + if (node.name != null and std.mem.eql(u8, std.mem.span(node.name), name)) return node; + } + return null; + } +}; + +/// Borrowed JSON, ready for std.json.parseFromSlice with the caller's schema. +pub fn extrasJson(extras: *const c.cgltf_extras) ?[]const u8 { + return if (extras.data != null) std.mem.span(extras.data) else null; +} + +/// Read one element after loadBuffers; handles strides, normalization and sparse +/// accessors. Bounds and component count are checked before entering C. +pub fn readFloats(accessor: [*c]const c.cgltf_accessor, index: usize, out: []f32) Error!void { + if (accessor == null or index >= accessor.*.count or out.len == 0 or out.len != c.cgltf_num_components(accessor.*.type)) return error.InvalidAccessor; + if (accessor.*.is_sparse != 0 and + (c.cgltf_buffer_view_data(accessor.*.sparse.indices_buffer_view) == null or + c.cgltf_buffer_view_data(accessor.*.sparse.values_buffer_view) == null)) return error.MissingBuffer; + if (c.cgltf_accessor_read_float(accessor, index, out.ptr, out.len) == 0) return error.MissingBuffer; +} + +test "node names and arbitrary typed extras survive parsing" { + const bytes = + \\{"asset":{"version":"2.0"},"nodes":[{"name":"Target","extras":{"role":"look_at_target","id":"target","future":1}}]} + ; + const doc = try Document.parse(bytes); + defer doc.deinit(); + try doc.loadBuffers(null); + const node = doc.findNode("Target").?; + const meta = try std.json.parseFromSlice(struct { role: []const u8, id: []const u8 }, std.testing.allocator, extrasJson(&node.extras).?, .{ .ignore_unknown_fields = true }); + defer meta.deinit(); + try std.testing.expectEqualStrings("look_at_target", meta.value.role); + try std.testing.expectEqualStrings("target", meta.value.id); + try std.testing.expect(doc.findNode("missing") == null); + try std.testing.expect(extrasJson(&std.mem.zeroes(c.cgltf_extras)) == null); +} + +test "embedded buffers and accessor bounds" { + const bytes = + \\{"asset":{"version":"2.0"},"buffers":[{"byteLength":4,"uri":"data:application/octet-stream;base64,AACAPw=="}],"bufferViews":[{"buffer":0,"byteLength":4}],"accessors":[{"bufferView":0,"componentType":5126,"count":1,"type":"SCALAR"}]} + ; + const doc = try Document.parse(bytes); + defer doc.deinit(); + const accessor = &doc.data.accessors[0]; + var value: [1]f32 = undefined; + try std.testing.expectError(error.MissingBuffer, readFloats(accessor, 0, &value)); + try doc.loadBuffers(null); + try readFloats(accessor, 0, &value); + try std.testing.expectEqual(@as(f32, 1), value[0]); + try std.testing.expectError(error.InvalidAccessor, readFloats(accessor, 1, &value)); + var wrong: [3]f32 = undefined; + try std.testing.expectError(error.InvalidAccessor, readFloats(accessor, 0, &wrong)); +} + +test "malformed and truncated input fails" { + try std.testing.expectError(error.DataTooShort, Document.parse("glTF")); + try std.testing.expectError(error.InvalidJson, Document.parse("{\"asset\": invalid json}")); + const invalid = + \\{"asset":{"version":"2.0"},"buffers":[{"byteLength":4}],"bufferViews":[{"buffer":0,"byteLength":16}],"accessors":[{"bufferView":0,"componentType":5126,"count":4,"type":"SCALAR"}]} + ; + try std.testing.expectError(error.DataTooShort, Document.parse(invalid)); +} + +test "sparse values need loaded buffers and preserve zero base elements" { + const bytes = + \\{"asset":{"version":"2.0"},"buffers":[{"byteLength":16,"uri":"data:application/octet-stream;base64,AQAAAAAAgD8AAABAAABAQA=="}],"bufferViews":[{"buffer":0,"byteLength":1},{"buffer":0,"byteOffset":4,"byteLength":12}],"accessors":[{"componentType":5126,"count":2,"type":"VEC3","sparse":{"count":1,"indices":{"bufferView":0,"componentType":5121},"values":{"bufferView":1}}}]} + ; + const doc = try Document.parse(bytes); + defer doc.deinit(); + const accessor = &doc.data.accessors[0]; + var out: [3]f32 = undefined; + try std.testing.expectError(error.MissingBuffer, readFloats(accessor, 1, &out)); + try doc.loadBuffers(null); + try readFloats(accessor, 0, &out); + try std.testing.expectEqualSlices(f32, &.{ 0, 0, 0 }, &out); + try readFloats(accessor, 1, &out); + try std.testing.expectEqualSlices(f32, &.{ 1, 2, 3 }, &out); +} diff --git a/src/gltf_generate.zig b/src/gltf_generate.zig new file mode 100644 index 0000000..a1d1449 --- /dev/null +++ b/src/gltf_generate.zig @@ -0,0 +1,112 @@ +//! Runs before compilation: glTF labels/extras become ordinary Zig constants. +const std = @import("std"); +const gltf = @import("gltf.zig"); + +pub fn generate(allocator: std.mem.Allocator, bytes: []const u8, source_path: []const u8) ![]u8 { + const doc = try gltf.Document.parse(bytes); + defer doc.deinit(); + var out: std.ArrayList(u8) = .empty; + defer out.deinit(allocator); + try out.appendSlice(allocator, "// Generated from glTF; do not edit.\n"); + try out.print(allocator, "pub const source_path: []const u8 = \"{f}\";\n", .{std.zig.fmtString(source_path)}); + var hash: [32]u8 = undefined; + std.crypto.hash.sha2.Sha256.hash(bytes, &hash, .{}); + try out.appendSlice(allocator, "pub const source_sha256: [32]u8 = .{"); + for (hash) |byte| try out.print(allocator, "{d},", .{byte}); + try out.appendSlice(allocator, "};\n"); + try labels(allocator, &out, "nodes", doc.nodes(), doc.data); + try labels(allocator, &out, "animations", if (doc.data.animations_count == 0) &.{} else doc.data.animations[0..doc.data.animations_count], doc.data); + try labels(allocator, &out, "cameras", if (doc.data.cameras_count == 0) &.{} else doc.data.cameras[0..doc.data.cameras_count], doc.data); + try labels(allocator, &out, "meshes", if (doc.data.meshes_count == 0) &.{} else doc.data.meshes[0..doc.data.meshes_count], doc.data); + try labels(allocator, &out, "materials", if (doc.data.materials_count == 0) &.{} else doc.data.materials[0..doc.data.materials_count], doc.data); + const source = try allocator.allocSentinel(u8, out.items.len, 0); + defer allocator.free(source); + @memcpy(source, out.items); + var ast = try std.zig.Ast.parse(allocator, source, .{}); + defer ast.deinit(allocator); + if (ast.errors.len != 0) return error.InvalidGeneratedZig; + return ast.renderAlloc(allocator); +} + +fn labels(a: std.mem.Allocator, out: *std.ArrayList(u8), category: []const u8, items: anytype, data: *const gltf.c.cgltf_data) !void { + var names: std.StringHashMapUnmanaged(void) = .empty; + defer names.deinit(a); + try out.print(a, "pub const {s} = struct {{\n", .{category}); + for (items, 0..) |item, index| { + if (item.name == null) continue; + const name = item.name[0..gltf.c.cgltf_decode_string(item.name)]; + if (name.len == 0) continue; + const entry = try names.getOrPut(a, name); + if (entry.found_existing) return error.DuplicateLabel; + try out.print(a, "pub const {f} = .{{ .index = @as(usize, {d}), .extras = ", .{ std.zig.fmtId(name), index }); + if (gltf.extrasJson(&item.extras)) |json| { + const parsed = try std.json.parseFromSlice(std.json.Value, a, json, .{}); + defer parsed.deinit(); + try value(a, out, parsed.value); + } else try out.appendSlice(a, ".{}"); + if (@TypeOf(item) == gltf.c.cgltf_node) { + try out.appendSlice(a, ", .camera = @as(?usize, "); + if (item.camera != null) { + try out.print(a, "{d}", .{gltf.c.cgltf_camera_index(data, item.camera)}); + } else try out.appendSlice(a, "null"); + try out.appendSlice(a, "), .mesh = @as(?usize, "); + if (item.mesh != null) { + try out.print(a, "{d}", .{gltf.c.cgltf_mesh_index(data, item.mesh)}); + } else try out.appendSlice(a, "null"); + try out.appendSlice(a, ")"); + } + try out.appendSlice(a, " };\n"); + } + try out.appendSlice(a, "};\n"); +} + +fn value(a: std.mem.Allocator, out: *std.ArrayList(u8), json: std.json.Value) std.mem.Allocator.Error!void { + switch (json) { + .null => try out.appendSlice(a, "null"), + .bool => |v| try out.appendSlice(a, if (v) "true" else "false"), + .integer => |v| try out.print(a, "@as(i64, {d})", .{v}), + .float => |v| try out.print(a, "@as(f64, {e})", .{v}), + .number_string => |v| try out.appendSlice(a, v), + .string => |v| try out.print(a, "@as([]const u8, \"{f}\")", .{std.zig.fmtString(v)}), + .array => |array| { + try out.appendSlice(a, ".{"); + for (array.items) |item| { + try value(a, out, item); + try out.appendSlice(a, ","); + } + try out.appendSlice(a, "}"); + }, + .object => |object| { + try out.appendSlice(a, ".{"); + for (object.keys(), object.values()) |key, item| { + try out.print(a, ".{f} = ", .{std.zig.fmtId(key)}); + try value(a, out, item); + try out.appendSlice(a, ","); + } + try out.appendSlice(a, "}"); + }, + } +} + +test "generated labels and nested metadata escape as valid Zig" { + const source = try generate(std.testing.allocator, + \\{"asset":{"version":"2.0"},"nodes":[{"name":"a\"b","extras":{"type":"look\nat","nested":{"enabled":true},"points":[1,2.5,-0.0,null]}},{"name":"while"},{"extras":{}}],"animations":[]} + , "fixtures/a\"b.glb"); + defer std.testing.allocator.free(source); + const terminated = try std.testing.allocator.allocSentinel(u8, source.len, 0); + @memcpy(terminated, source); + defer std.testing.allocator.free(terminated); + var ast = try std.zig.Ast.parse(std.testing.allocator, terminated, .{}); + defer ast.deinit(std.testing.allocator); + try std.testing.expectEqual(@as(usize, 0), ast.errors.len); + try std.testing.expect(std.mem.indexOf(u8, source, "pub const source_path: []const u8 = \"fixtures/a\\\"b.glb\";") != null); + try std.testing.expect(std.mem.indexOf(u8, source, "pub const @\"a\\\"b\"") != null); + try std.testing.expect(std.mem.indexOf(u8, source, "pub const @\"while\"") != null); + try std.testing.expect(std.mem.indexOf(u8, source, ".index = @as(usize, 1)") != null); +} + +test "duplicate labels cannot silently choose an object" { + try std.testing.expectError(error.DuplicateLabel, generate(std.testing.allocator, + \\{"asset":{"version":"2.0"},"nodes":[{"name":"Camera"},{"name":"Camera"}]} + , "fixtures/duplicate.glb")); +} diff --git a/src/gltf_render/basic.frag b/src/gltf_render/basic.frag new file mode 100644 index 0000000..73209ea --- /dev/null +++ b/src/gltf_render/basic.frag @@ -0,0 +1,10 @@ +#version 450 +layout(location = 0) in vec3 world_normal; +layout(location = 1) in vec4 color; +layout(location = 0) out vec4 out_color; +void main() { + vec3 normal = normalize(world_normal); + if (!gl_FrontFacing) normal = -normal; + float light = 0.42 + 0.58 * max(dot(normal, normalize(vec3(-0.45, 0.85, 0.3))), 0.0); + out_color = vec4(pow(max(color.rgb * light, vec3(0.0)), vec3(1.0 / 2.2)), 1.0); +} diff --git a/src/gltf_render/basic.vert b/src/gltf_render/basic.vert new file mode 100644 index 0000000..3239a38 --- /dev/null +++ b/src/gltf_render/basic.vert @@ -0,0 +1,16 @@ +#version 450 +#extension GL_GOOGLE_include_directive : require +layout(std430, set = 0, binding = 0) readonly buffer Vertices { float data[]; }; +#include "Transform.glsl" +layout(location = 0) out vec3 world_normal; +layout(location = 1) out vec4 color; +void main() { + uint offset = uint(gl_VertexIndex) * 10; + vec3 position = vec3(data[offset], data[offset+1], data[offset+2]); + vec3 normal = vec3(data[offset+3], data[offset+4], data[offset+5]); + mat4 model = mat4(transform.model[0], transform.model[1], transform.model[2], transform.model[3]); + mat4 vp = mat4(transform.view_projection[0], transform.view_projection[1], transform.view_projection[2], transform.view_projection[3]); + gl_Position = vp * model * vec4(position, 1.0); + world_normal = transpose(inverse(mat3(model))) * normal; + color = transform.color * vec4(data[offset+6], data[offset+7], data[offset+8], data[offset+9]); +} diff --git a/src/gltf_render/math.zig b/src/gltf_render/math.zig new file mode 100644 index 0000000..6279ce4 --- /dev/null +++ b/src/gltf_render/math.zig @@ -0,0 +1,67 @@ +const std = @import("std"); +pub const Mat4 = [16]f32; +pub const identity: Mat4 = .{ 1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1 }; +pub fn multiply(a: Mat4, b: Mat4) Mat4 { + var out: Mat4 = @splat(0); + for (0..4) |col| for (0..4) |row| { + for (0..4) |k| out[col * 4 + row] += a[k * 4 + row] * b[col * 4 + k]; + }; + return out; +} +fn sub(a: [3]f32, b: [3]f32) [3]f32 { + return .{ a[0] - b[0], a[1] - b[1], a[2] - b[2] }; +} +fn dot(a: [3]f32, b: [3]f32) f32 { + return a[0] * b[0] + a[1] * b[1] + a[2] * b[2]; +} +fn cross(a: [3]f32, b: [3]f32) [3]f32 { + return .{ a[1] * b[2] - a[2] * b[1], a[2] * b[0] - a[0] * b[2], a[0] * b[1] - a[1] * b[0] }; +} +fn unit(a: [3]f32) [3]f32 { + const n = @sqrt(dot(a, a)); + return .{ a[0] / n, a[1] / n, a[2] / n }; +} +pub const Camera = struct { + eye: [3]f32, + target: [3]f32, + up: [3]f32 = .{ 0, 1, 0 }, + fov: f32 = std.math.pi / 3.0, + near: f32 = 0.1, + far: f32 = 300, + aspect_ratio: ?f32 = null, + orthographic: ?struct { xmag: f32, ymag: f32 } = null, + /// Right-handed, column-major; depth range 0..1, camera forward -Z. + pub fn matrix(c: Camera, aspect: f32) Mat4 { + const z = unit(sub(c.eye, c.target)); + const x = unit(cross(c.up, z)); + const y = cross(z, x); + const view: Mat4 = .{ x[0], y[0], z[0], 0, x[1], y[1], z[1], 0, x[2], y[2], z[2], 0, -dot(x, c.eye), -dot(y, c.eye), -dot(z, c.eye), 1 }; + const scale = 1 / @tan(c.fov / 2); + const d = c.near - c.far; + const projection: Mat4 = if (c.orthographic) |o| + .{ 1 / o.xmag, 0, 0, 0, 0, 1 / o.ymag, 0, 0, 0, 0, 1 / d, 0, 0, 0, c.near / d, 1 } + else if (std.math.isInf(c.far)) + .{ scale / (c.aspect_ratio orelse aspect), 0, 0, 0, 0, scale, 0, 0, 0, 0, -1, -1, 0, 0, -c.near, 0 } + else + .{ scale / (c.aspect_ratio orelse aspect), 0, 0, 0, 0, scale, 0, 0, 0, 0, c.far / d, -1, 0, 0, c.near * c.far / d, 0 }; + return multiply(projection, view); + } +}; +test "perspective maps near and far to zero and one" { + const camera: Camera = .{ .eye = .{ 0, 0, 0 }, .target = .{ 0, 0, -1 } }; + const m = camera.matrix(1); + try std.testing.expectApproxEqAbs(@as(f32, 0), (m[10] * -camera.near + m[14]) / camera.near, 0.00001); + try std.testing.expectApproxEqAbs(@as(f32, 1), (m[10] * -camera.far + m[14]) / camera.far, 0.00001); +} + +test "orthographic and infinite perspective keep valid depth" { + var camera: Camera = .{ .eye = .{ 0, 0, 0 }, .target = .{ 0, 0, -1 }, .orthographic = .{ .xmag = 2, .ymag = 3 } }; + const ortho = camera.matrix(1); + try std.testing.expectApproxEqAbs(@as(f32, 0), ortho[10] * -camera.near + ortho[14], 0.00001); + try std.testing.expectApproxEqAbs(@as(f32, 1), ortho[10] * -camera.far + ortho[14], 0.00001); + camera.orthographic = null; + camera.far = std.math.inf(f32); + const infinite = camera.matrix(1); + for (infinite) |v| try std.testing.expect(std.math.isFinite(v)); + try std.testing.expectApproxEqAbs(@as(f32, 0), (infinite[10] * -camera.near + infinite[14]) / camera.near, 0.00001); +} diff --git a/src/gltf_render/root.zig b/src/gltf_render/root.zig new file mode 100644 index 0000000..6bf8673 --- /dev/null +++ b/src/gltf_render/root.zig @@ -0,0 +1,164 @@ +//! Basic opaque glTF drawing. Geometry uploads once; each frame submits transforms. +//! shortcut: base colors only; add texture/alpha handling when the assets need it. +const std = @import("std"); +const sk = @import("sketch"); +const gltf = @import("gltf"); +const shaders = @import("shaders"); +const types = @import("types"); +pub const math = @import("math.zig"); +pub const Camera = math.Camera; +pub const Vertex = types.Vertex; +pub const supported = true; +const gpu = sk.abi.gpu; + +/// Camera projection plus the sampled node transform; no Blender constraint solver. +pub fn sceneCamera(scene: *const gltf.Scene, node_index: usize) !Camera { + if (node_index >= scene.nodes.len) return error.InvalidCameraNode; + const node = scene.nodes[node_index]; + const index = node.camera orelse return error.NodeHasNoCamera; + const m = node.world; + var camera: Camera = .{ + .eye = .{ m[12], m[13], m[14] }, + .target = .{ m[12] - m[8], m[13] - m[9], m[14] - m[10] }, + .up = .{ m[4], m[5], m[6] }, + }; + switch (scene.cameras[index]) { + .perspective => |p| { + camera.fov = p.yfov; + camera.near = p.znear; + camera.far = p.zfar orelse std.math.inf(f32); + camera.aspect_ratio = p.aspect_ratio; + }, + .orthographic => |o| { + camera.orthographic = .{ .xmag = o.xmag, .ymag = o.ymag }; + camera.near = o.znear; + camera.far = o.zfar; + }, + } + return camera; +} + +pub const Geometry = struct { + vertices: []const Vertex, + buffer: sk.abi.Buffer = .none, + pub fn upload(g: *Geometry, host: sk.Host) !void { + if (g.buffer != .none) return; + const bytes = std.mem.sliceAsBytes(g.vertices); + if (bytes.len == 0 or bytes.len > std.math.maxInt(u32)) return error.InvalidGeometrySize; + g.buffer = host.newBuffer(@intCast(bytes.len)); + if (g.buffer == .none) return error.GpuBufferCreationFailed; + errdefer g.release(host); + try host.writeBuffer(g.buffer, 0, bytes); + } + pub fn release(g: *Geometry, host: sk.Host) void { + if (g.buffer != .none) host.freeBuffer(g.buffer); + g.buffer = .none; + } +}; + +pub const Model = struct { + scene: gltf.Scene, + geometry: []Geometry, + /// Read the generated asset filename, validate its binding hash, and upload once. + pub fn load(setup: *sk.Init, comptime asset: type) !Model { + const bytes = setup.host.readFile(asset.source_path); + var hash: [32]u8 = undefined; + std.crypto.hash.sha2.Sha256.hash(bytes, &hash, .{}); + if (!std.mem.eql(u8, &hash, &asset.source_sha256)) return error.SceneChangedRebuildBindings; + var model = try Model.init(setup.session, bytes); + errdefer model.release(setup.host); + for (model.geometry) |*g| try g.upload(setup.host); + return model; + } + /// Allocate in the sketch's Session arena; GPU handles share its host lifetime. + pub fn init(arena: std.mem.Allocator, bytes: []const u8) !Model { + const doc = try gltf.Document.parse(bytes); + defer doc.deinit(); + try doc.loadBuffers(null); + var scene = try gltf.Scene.init(arena, doc); + errdefer scene.deinit(); + const geometry = try arena.alloc(Geometry, scene.meshes.len); + for (scene.meshes, geometry) |mesh, *g| { + var count: usize = 0; + for (mesh.primitives) |primitive| count = try std.math.add(usize, count, primitive.indices.len); + const vertices = try arena.alloc(Vertex, count); + var offset: usize = 0; + // Opaque materials share one pipeline: carry color per vertex to batch a mesh. + for (mesh.primitives) |primitive| { + for (primitive.indices) |index| { + const source = primitive.vertices[index]; + vertices[offset] = .{ .position = source.position, .normal = source.normal, .color = primitive.color }; + offset += 1; + } + } + g.* = .{ .vertices = vertices }; + } + return .{ .scene = scene, .geometry = geometry }; + } + pub fn release(m: *Model, host: sk.Host) void { + for (m.geometry) |*g| g.release(host); + } +}; + +/// Imperative frame builder: add a whole scene, individual meshes, or geometry. +pub const View = struct { + frame: *sk.Frame, + image: sk.Image, + width: u32, + height: u32, + vp: math.Mat4, + draws: std.ArrayList(gpu.Draw) = .empty, + background: [4]f32 = .{ 0.54, 0.72, 0.83, 1 }, + + pub fn init(f: *sk.Frame, image: sk.Image, width: u32, height: u32, camera: Camera) View { + return .{ .frame = f, .image = image, .width = width, .height = height, .vp = camera.matrix(@as(f32, @floatFromInt(width)) / @as(f32, @floatFromInt(height))) }; + } + pub fn scene(v: *View, model: *Model) !void { + for (model.scene.nodes) |node| if (node.visible) { + if (node.mesh) |index| try v.mesh(model, index, node.world); + }; + } + pub fn mesh(v: *View, model: *Model, index: usize, transform: math.Mat4) !void { + if (index >= model.geometry.len) return error.InvalidMesh; + try v.triangles(&model.geometry[index], transform, .{ 1, 1, 1, 1 }); + } + pub fn triangles(v: *View, geometry: *Geometry, transform: math.Mat4, color: [4]f32) !void { + if (geometry.buffer == .none) return error.GeometryNotUploaded; + try v.draws.append(v.frame.scratch, .{ + .pipeline = 0, + .vertex_count = @intCast(geometry.vertices.len), + .vertex_storage = v.frame.keep(sk.abi.Buffer, &.{geometry.buffer}), + .vertex_uniforms = gpu.uniform(v.frame.scratch, types.Transform{ + .model = @bitCast(transform), + .view_projection = @bitCast(v.vp), + .color = color, + }), + }); + } + pub fn end(v: *View) void { + v.frame.gpu(.{ + .label = "gltf scene", + .image = v.image, + .width = v.width, + .height = v.height, + .depth = true, + .clear = v.background, + .pipelines = &.{pipeline}, + .draws = v.draws.items, + }); + } +}; +const pipeline: gpu.Pipeline = .{ + .vertex = .{ .code = shaders.basic_vert, .uniform_buffers = 1, .storage_buffers = 1 }, + .fragment = .{ .code = shaders.basic_frag }, + .stride = 0, + .attributes = &.{}, + .blend = .none, + .depth_test = .less, + .depth_write = true, +}; +comptime { + // std430 scalar storage is ten contiguous floats, with no vec3 padding. + if (@sizeOf(Vertex) != 40 or @offsetOf(Vertex, "normal") != 12 or @offsetOf(Vertex, "color") != 24) @compileError("unexpected glTF vertex layout"); + gpu.assertStd140(types.Transform); +} diff --git a/src/gltf_render/types.zig b/src/gltf_render/types.zig new file mode 100644 index 0000000..29b784f --- /dev/null +++ b/src/gltf_render/types.zig @@ -0,0 +1,13 @@ +//! These types generate the GLSL vertex and uniform declarations. +pub const Vertex = extern struct { + position: [3]f32, + normal: [3]f32, + color: [4]f32 = .{ 1, 1, 1, 1 }, + pub const glsl = .vertex; +}; +pub const Transform = extern struct { + model: [4][4]f32, + view_projection: [4][4]f32, + color: [4]f32, + pub const glsl = .{ .uniform = .{ .set = 1, .instance = "transform" } }; +}; diff --git a/src/gltf_render/web.zig b/src/gltf_render/web.zig new file mode 100644 index 0000000..f8dc252 --- /dev/null +++ b/src/gltf_render/web.zig @@ -0,0 +1,2 @@ +//! The cgltf loader currently requires libc; the existing 2D web game still works. +pub const supported = false; diff --git a/src/gltf_scene.zig b/src/gltf_scene.zig new file mode 100644 index 0000000..0b8ef03 --- /dev/null +++ b/src/gltf_scene.zig @@ -0,0 +1,416 @@ +//! CPU mesh data and sampled node transforms. No renderer or GPU ownership. +const std = @import("std"); +const gltf = @import("gltf.zig"); +const c = gltf.c; + +pub const Vertex = extern struct { position: [3]f32, normal: [3]f32 }; +pub const Primitive = struct { + vertices: []Vertex, + indices: []u32, + color: [4]f32 = .{ 1, 1, 1, 1 }, + double_sided: bool = false, +}; +pub const Mesh = struct { primitives: []Primitive }; +pub const Camera = union(enum) { + perspective: struct { yfov: f32, znear: f32, zfar: ?f32, aspect_ratio: ?f32 }, + orthographic: struct { xmag: f32, ymag: f32, znear: f32, zfar: f32 }, +}; +pub const Node = struct { + mesh: ?usize, + camera: ?usize = null, + parent: ?usize, + world: [16]f32 = undefined, + visible: bool, +}; +const Track = struct { + node: usize, + path: c.cgltf_animation_path_type, + interpolation: c.cgltf_interpolation_type, + times: []f32, + values: [][4]f32, +}; +const Animation = struct { tracks: []Track, duration: f32 }; + +pub const Scene = struct { + arena: std.heap.ArenaAllocator, + meshes: []Mesh, + cameras: []Camera, + nodes: []Node, + animations: []Animation, + base: []c.cgltf_node, + pose: []c.cgltf_node, + + /// Copies geometry and tracks from a document whose buffers are loaded. + /// The document can be released after this returns. Indices match glTF. + pub fn init(allocator: std.mem.Allocator, document: gltf.Document) !Scene { + var arena = std.heap.ArenaAllocator.init(allocator); + errdefer arena.deinit(); + const a = arena.allocator(); + const data = document.data; + const meshes = try a.alloc(Mesh, data.meshes_count); + for (meshes, 0..) |*mesh, i| { + const source = data.meshes[i]; + mesh.primitives = try a.alloc(Primitive, source.primitives_count); + for (mesh.primitives, 0..) |*primitive, j| primitive.* = try readPrimitive(a, @ptrCast(&source.primitives[j])); + } + const cameras = try a.alloc(Camera, data.cameras_count); + for (cameras, 0..) |*camera, i| { + const source = data.cameras[i]; + camera.* = switch (source.type) { + c.cgltf_camera_type_perspective => blk: { + const p = source.data.perspective; + try finite(&.{ p.yfov, p.znear }); + if (p.yfov <= 0 or p.yfov >= std.math.pi or p.znear <= 0) return error.InvalidCamera; + if (p.has_zfar != 0 and (!std.math.isFinite(p.zfar) or p.zfar <= p.znear)) return error.InvalidCamera; + if (p.has_aspect_ratio != 0 and (!std.math.isFinite(p.aspect_ratio) or p.aspect_ratio <= 0)) return error.InvalidCamera; + break :blk .{ .perspective = .{ + .yfov = p.yfov, + .znear = p.znear, + .zfar = if (p.has_zfar != 0) p.zfar else null, + .aspect_ratio = if (p.has_aspect_ratio != 0) p.aspect_ratio else null, + } }; + }, + c.cgltf_camera_type_orthographic => blk: { + const o = source.data.orthographic; + try finite(&.{ o.xmag, o.ymag, o.znear, o.zfar }); + if (o.xmag == 0 or o.ymag == 0 or o.znear < 0 or o.zfar <= o.znear) return error.InvalidCamera; + break :blk .{ .orthographic = .{ .xmag = o.xmag, .ymag = o.ymag, .znear = o.znear, .zfar = o.zfar } }; + }, + else => return error.UnsupportedCamera, + }; + } + const nodes = try a.alloc(Node, data.nodes_count); + const base = try a.dupe(c.cgltf_node, document.nodes()); + for (nodes, base) |*node, source| { + if (source.skin != null) return error.UnsupportedSkin; + if (source.has_mesh_gpu_instancing != 0) return error.UnsupportedInstancing; + node.* = .{ + .mesh = if (source.mesh != null) c.cgltf_mesh_index(data, source.mesh) else null, + .camera = if (source.camera != null) c.cgltf_camera_index(data, source.camera) else null, + .parent = if (source.parent != null) c.cgltf_node_index(data, source.parent) else null, + .visible = data.scene == null, + }; + } + // A glTF scene selects roots; other scene nodes stay addressable but hidden. + if (data.scene != null) for (nodes, 0..) |*node, i| { + var root = i; + var depth: usize = 0; + while (nodes[root].parent) |parent| { + root = parent; + depth += 1; + if (depth > nodes.len) return error.InvalidHierarchy; + } + const selected = data.scene.*; + for (0..selected.nodes_count) |j| { + if (root == c.cgltf_node_index(data, selected.nodes[j])) node.visible = true; + } + }; + const animations = try a.alloc(Animation, data.animations_count); + for (animations, 0..) |*animation, i| { + const source = data.animations[i]; + animation.* = .{ .tracks = try a.alloc(Track, source.channels_count), .duration = 0 }; + for (animation.tracks, 0..) |*track, j| { + const channel = source.channels[j]; + if (channel.target_node == null) return error.UnsupportedAnimationTarget; + const node = c.cgltf_node_index(data, channel.target_node); + if (base[node].has_matrix != 0) return error.AnimatedMatrix; + const components: usize = switch (channel.target_path) { + c.cgltf_animation_path_type_translation, c.cgltf_animation_path_type_scale => 3, + c.cgltf_animation_path_type_rotation => 4, + else => return error.UnsupportedAnimationTarget, + }; + const sampler = channel.sampler.*; + const multiplier: usize = switch (sampler.interpolation) { + c.cgltf_interpolation_type_linear, c.cgltf_interpolation_type_step => 1, + c.cgltf_interpolation_type_cubic_spline => 3, + else => return error.UnsupportedInterpolation, + }; + if (sampler.input.*.count == 0 or sampler.output.*.count != try std.math.mul(usize, sampler.input.*.count, multiplier)) return error.InvalidAnimation; + track.* = .{ .node = node, .path = channel.target_path, .interpolation = sampler.interpolation, .times = try a.alloc(f32, sampler.input.*.count), .values = try a.alloc([4]f32, sampler.output.*.count) }; + for (track.times, 0..) |*time, k| { + try gltf.readFloats(sampler.input, k, @as(*[1]f32, @ptrCast(time))); + if (!std.math.isFinite(time.*) or time.* < 0 or (k > 0 and time.* <= track.times[k - 1])) return error.InvalidAnimation; + } + for (track.values, 0..) |*value, k| { + value.* = .{ 0, 0, 0, 0 }; + try gltf.readFloats(sampler.output, k, value[0..components]); + try finite(value); + } + animation.duration = @max(animation.duration, track.times[track.times.len - 1]); + } + } + var scene: Scene = .{ .arena = arena, .meshes = meshes, .cameras = cameras, .nodes = nodes, .animations = animations, .base = base, .pose = try a.dupe(c.cgltf_node, base) }; + try scene.updateWorld(); + return scene; + } + + pub fn deinit(self: *Scene) void { + self.arena.deinit(); + self.* = undefined; + } + + pub fn duration(self: *const Scene, animation: usize) !f32 { + if (animation >= self.animations.len) return error.InvalidAnimationIndex; + return self.animations[animation].duration; + } + + /// Samples seconds, clamped to each track's range. Looping belongs to callers. + pub fn sample(self: *Scene, animation: usize, seconds: f32) !void { + if (animation >= self.animations.len) return error.InvalidAnimationIndex; + if (!std.math.isFinite(seconds)) return error.InvalidAnimationTime; + @memcpy(self.pose, self.base); + for (self.animations[animation].tracks) |track| { + const value = try sampleTrack(track, seconds); + const node = &self.pose[track.node]; + switch (track.path) { + c.cgltf_animation_path_type_translation => node.translation = value[0..3].*, + c.cgltf_animation_path_type_rotation => node.rotation = value, + c.cgltf_animation_path_type_scale => node.scale = value[0..3].*, + else => unreachable, + } + } + try self.updateWorld(); + } + + pub fn reset(self: *Scene) !void { + @memcpy(self.pose, self.base); + try self.updateWorld(); + } + + fn updateWorld(self: *Scene) !void { + for (self.nodes, self.pose) |*node, *pose| { + c.cgltf_node_transform_local(pose, &node.world); + var ancestor = node.parent; + var depth: usize = 0; + while (ancestor) |index| { + var parent: [16]f32 = undefined; + c.cgltf_node_transform_local(&self.pose[index], &parent); + node.world = multiply(parent, node.world); + ancestor = self.nodes[index].parent; + depth += 1; + if (depth > self.nodes.len) return error.InvalidHierarchy; + } + try finite(&node.world); + } + } +}; + +fn readPrimitive(a: std.mem.Allocator, primitive: *const c.cgltf_primitive) !Primitive { + if (primitive.type != c.cgltf_primitive_type_triangles) return error.UnsupportedPrimitive; + if (primitive.targets_count != 0) return error.UnsupportedMorphTargets; + if (primitive.has_draco_mesh_compression != 0) return error.UnsupportedCompression; + var positions: [*c]c.cgltf_accessor = null; + var normals: [*c]c.cgltf_accessor = null; + for (0..primitive.attributes_count) |i| { + const attr = primitive.attributes[i]; + if (attr.type == c.cgltf_attribute_type_position) positions = attr.data; + if (attr.type == c.cgltf_attribute_type_normal) normals = attr.data; + } + if (positions == null or positions.*.count == 0 or positions.*.count > std.math.maxInt(u32)) return error.InvalidPositions; + if (normals != null and normals.*.count != positions.*.count) return error.InvalidNormals; + var out: Primitive = .{ .vertices = try a.alloc(Vertex, positions.*.count), .indices = try a.alloc(u32, if (primitive.indices != null) primitive.indices.*.count else positions.*.count) }; + if (out.indices.len % 3 != 0) return error.InvalidTriangles; + for (out.vertices, 0..) |*vertex, i| { + try gltf.readFloats(positions, i, &vertex.position); + try finite(&vertex.position); + vertex.normal = .{ 0, 0, 0 }; + if (normals != null) { + try gltf.readFloats(normals, i, &vertex.normal); + try finite(&vertex.normal); + } + } + if (primitive.indices != null) { + const accessor = primitive.indices; + if (accessor.*.type != c.cgltf_type_scalar or (accessor.*.component_type != c.cgltf_component_type_r_8u and accessor.*.component_type != c.cgltf_component_type_r_16u and accessor.*.component_type != c.cgltf_component_type_r_32u)) return error.InvalidIndices; + // cgltf's uint reader handles sparse indices without lossy f32 conversion. + if (accessor.*.is_sparse != 0 and (c.cgltf_buffer_view_data(accessor.*.sparse.indices_buffer_view) == null or c.cgltf_buffer_view_data(accessor.*.sparse.values_buffer_view) == null)) return error.MissingBuffer; + for (out.indices, 0..) |*index, i| { + if (c.cgltf_accessor_read_uint(accessor, i, @ptrCast(index), 1) == 0) return error.MissingBuffer; + if (index.* >= out.vertices.len) return error.InvalidIndices; + } + } else { + for (out.indices, 0..) |*index, i| index.* = @intCast(i); + } + // With no authored normals, split triangles to preserve flat faces. + if (normals == null) { + const expanded = try a.alloc(Vertex, out.indices.len); + var i: usize = 0; + while (i < out.indices.len) : (i += 3) { + const p = out.vertices[out.indices[i]].position; + const q = out.vertices[out.indices[i + 1]].position; + const r = out.vertices[out.indices[i + 2]].position; + const u = [3]f32{ q[0] - p[0], q[1] - p[1], q[2] - p[2] }; + const v = [3]f32{ r[0] - p[0], r[1] - p[1], r[2] - p[2] }; + var normal = [3]f32{ u[1] * v[2] - u[2] * v[1], u[2] * v[0] - u[0] * v[2], u[0] * v[1] - u[1] * v[0] }; + const length = @sqrt(normal[0] * normal[0] + normal[1] * normal[1] + normal[2] * normal[2]); + if (length > 0) for (&normal) |*n| { + n.* /= length; + }; + for (0..3) |j| { + expanded[i + j] = .{ .position = out.vertices[out.indices[i + j]].position, .normal = normal }; + out.indices[i + j] = @intCast(i + j); + } + } + out.vertices = expanded; + } + if (primitive.material != null) { + out.color = primitive.material.*.pbr_metallic_roughness.base_color_factor; + out.double_sided = primitive.material.*.double_sided != 0; + try finite(&out.color); + } + return out; +} + +fn finite(values: []const f32) !void { + for (values) |v| if (!std.math.isFinite(v)) return error.NonFiniteValue; +} + +/// Column-major multiplication, compatible with glTF and shader mat4 values. +pub fn multiply(a: [16]f32, b: [16]f32) [16]f32 { + var out: [16]f32 = undefined; + for (0..4) |col| for (0..4) |row| { + var value: f32 = 0; + for (0..4) |k| value += a[k * 4 + row] * b[col * 4 + k]; + out[col * 4 + row] = value; + }; + return out; +} + +fn sampleTrack(track: Track, seconds: f32) ![4]f32 { + const cubic = track.interpolation == c.cgltf_interpolation_type_cubic_spline; + const stride: usize = if (cubic) 3 else 1; + const offset: usize = if (cubic) 1 else 0; + var lo: usize = 0; + var hi = track.times.len; + while (lo < hi) { + const mid = lo + (hi - lo) / 2; + if (track.times[mid] <= seconds) lo = mid + 1 else hi = mid; + } + const first = lo -| 1; + const last = @min(first + 1, track.times.len - 1); + var result = track.values[first * stride + offset]; + const rotation = track.path == c.cgltf_animation_path_type_rotation; + if (seconds > track.times[first] and first != last and track.interpolation != c.cgltf_interpolation_type_step) { + const dt = track.times[last] - track.times[first]; + const t = (seconds - track.times[first]) / dt; + var next = track.values[last * stride + offset]; + if (cubic) { + const t2 = t * t; + const t3 = t2 * t; + const a = track.values[first * stride + 2]; + const b = track.values[last * stride]; + for (&result, 0..) |*v, i| v.* = (2 * t3 - 3 * t2 + 1) * v.* + (t3 - 2 * t2 + t) * dt * a[i] + (-2 * t3 + 3 * t2) * next[i] + (t3 - t2) * dt * b[i]; + } else if (rotation) { + result = try normalizeQuaternion(result); + next = try normalizeQuaternion(next); + var dot: f32 = 0; + for (result, next) |a, b| dot += a * b; + if (dot < 0) { + dot = -dot; + for (&next) |*v| v.* = -v.*; + } + dot = std.math.clamp(dot, 0, 1); + const angle = std.math.acos(dot); + const denominator = @sin(angle); + const a = if (dot > 0.9995) 1 - t else @sin((1 - t) * angle) / denominator; + const b = if (dot > 0.9995) t else @sin(t * angle) / denominator; + for (&result, next) |*v, n| v.* = a * v.* + b * n; + } else { + for (&result, next) |*v, n| v.* += (n - v.*) * t; + } + } + try finite(&result); + return if (rotation) normalizeQuaternion(result) else result; +} + +fn normalizeQuaternion(q: [4]f32) ![4]f32 { + var length: f32 = 0; + for (q) |v| length += v * v; + if (!std.math.isFinite(length) or length < 1e-12) return error.InvalidQuaternion; + var out = q; + for (&out) |*v| v.* /= @sqrt(length); + return out; +} + +test "animation interpolation clamps, steps, slerps shortest path, and scales cubic tangents by time" { + var times = [_]f32{ 0, 2 }; + var values = [_][4]f32{ .{ 0, 0, 0, 0 }, .{ 2, 4, 6, 0 } }; + var track: Track = .{ .node = 0, .path = c.cgltf_animation_path_type_translation, .interpolation = c.cgltf_interpolation_type_linear, .times = ×, .values = &values }; + try std.testing.expectEqualSlices(f32, &.{ 1, 2, 3, 0 }, &(try sampleTrack(track, 1))); + try std.testing.expectEqualSlices(f32, &values[0], &(try sampleTrack(track, -1))); + try std.testing.expectEqualSlices(f32, &values[1], &(try sampleTrack(track, 9))); + track.interpolation = c.cgltf_interpolation_type_step; + try std.testing.expectEqualSlices(f32, &values[0], &(try sampleTrack(track, 1))); + track.path = c.cgltf_animation_path_type_rotation; + track.interpolation = c.cgltf_interpolation_type_linear; + values = .{ .{ 0, 0, 0, 1 }, .{ 0, 0, -0.70710678, -0.70710678 } }; + const q = try sampleTrack(track, 1); + try std.testing.expectApproxEqAbs(@as(f32, 0.38268343), q[2], 0.00001); + try std.testing.expectApproxEqAbs(@as(f32, 0.92387953), q[3], 0.00001); + var cubic = [_][4]f32{ .{ 0, 0, 0, 0 }, .{ 0, 0, 0, 0 }, .{ 2, 0, 0, 0 }, .{ 0, 0, 0, 0 }, .{ 0, 0, 0, 0 }, .{ 0, 0, 0, 0 } }; + track.path = c.cgltf_animation_path_type_translation; + track.interpolation = c.cgltf_interpolation_type_cubic_spline; + track.values = &cubic; + try std.testing.expectApproxEqAbs(@as(f32, 0.5), (try sampleTrack(track, 1))[0], 0.00001); +} + +test "scene copies hierarchy and restricts visibility to selected scene" { + const doc = try gltf.Document.parse( + \\{"asset":{"version":"2.0"},"scene":0,"scenes":[{"nodes":[1]}],"nodes":[{"translation":[0,2,0]},{"translation":[3,0,0],"children":[2]},{"translation":[0,4,0]}]} + ); + defer doc.deinit(); + var scene = try Scene.init(std.testing.allocator, doc); + defer scene.deinit(); + try std.testing.expect(!scene.nodes[0].visible); + try std.testing.expect(scene.nodes[2].visible); + try std.testing.expectEqual(@as(f32, 3), scene.nodes[2].world[12]); + try std.testing.expectEqual(@as(f32, 4), scene.nodes[2].world[13]); + try std.testing.expectError(error.InvalidAnimationIndex, scene.sample(0, 0)); +} + +test "indexed mesh flat normals, material and decoded animation survive document release" { + const doc = try gltf.Document.parse( + \\{"asset":{"version":"2.0"},"buffers":[{"byteLength":72,"uri":"data:application/octet-stream;base64,AAAAAAAAAAAAAAAAAACAPwAAAAAAAAAAAAAAAAAAgD8AAAAAAgABAAAAAAAAAABAAAAAAAAAAAAAAAAAAACAQAAAAAAAAAAA"}],"bufferViews":[{"buffer":0,"byteOffset":0,"byteLength":36},{"buffer":0,"byteOffset":36,"byteLength":3},{"buffer":0,"byteOffset":40,"byteLength":8},{"buffer":0,"byteOffset":48,"byteLength":24}],"accessors":[{"bufferView":0,"componentType":5126,"count":3,"type":"VEC3","min":[0,0,0],"max":[1,1,0]},{"bufferView":1,"componentType":5121,"count":3,"type":"SCALAR"},{"bufferView":2,"componentType":5126,"count":2,"type":"SCALAR","min":[0],"max":[2]},{"bufferView":3,"componentType":5126,"count":2,"type":"VEC3"}],"materials":[{"pbrMetallicRoughness":{"baseColorFactor":[0.2,0.4,0.6,1]},"doubleSided":true}],"meshes":[{"primitives":[{"attributes":{"POSITION":0},"indices":1,"material":0}]}],"nodes":[{"translation":[0,3,0],"children":[1]},{"mesh":0}],"animations":[{"samplers":[{"input":2,"output":3}],"channels":[{"sampler":0,"target":{"node":1,"path":"translation"}}]}]} + ); + var scene = blk: { + defer doc.deinit(); + try doc.loadBuffers(null); + break :blk try Scene.init(std.testing.allocator, doc); + }; + defer scene.deinit(); + const primitive = scene.meshes[0].primitives[0]; + try std.testing.expectEqualSlices(f32, &.{ 0, 1, 0 }, &primitive.vertices[0].position); + try std.testing.expectEqualSlices(f32, &.{ 0, 0, 1 }, &primitive.vertices[0].normal); + try std.testing.expectEqualSlices(u32, &.{ 0, 1, 2 }, primitive.indices); + try std.testing.expectApproxEqAbs(@as(f32, 0.4), primitive.color[1], 0.00001); + try std.testing.expect(primitive.double_sided); + try std.testing.expectEqual(@as(f32, 2), try scene.duration(0)); + try scene.sample(0, 1); + try std.testing.expectEqual(@as(f32, 2), scene.nodes[1].world[12]); + try std.testing.expectEqual(@as(f32, 3), scene.nodes[1].world[13]); + try scene.sample(0, 0); + try std.testing.expectEqual(@as(f32, 0), scene.nodes[1].world[12]); + try std.testing.expectError(error.InvalidAnimationTime, scene.sample(0, std.math.nan(f32))); +} + +test "perspective and orthographic cameras survive document release" { + const doc = try gltf.Document.parse( + \\{"asset":{"version":"2.0"},"cameras":[{"type":"perspective","perspective":{"yfov":0.8,"znear":0.1}},{"type":"perspective","perspective":{"yfov":1,"znear":1,"zfar":100,"aspectRatio":1.5}},{"type":"orthographic","orthographic":{"xmag":8,"ymag":6,"znear":0,"zfar":50}}],"nodes":[{"camera":0},{"camera":1},{"camera":2}]} + ); + var scene = blk: { + defer doc.deinit(); + break :blk try Scene.init(std.testing.allocator, doc); + }; + defer scene.deinit(); + const infinite = scene.cameras[scene.nodes[0].camera.?].perspective; + try std.testing.expectEqual(@as(f32, 0.8), infinite.yfov); + try std.testing.expect(infinite.zfar == null and infinite.aspect_ratio == null); + const perspective = scene.cameras[scene.nodes[1].camera.?].perspective; + try std.testing.expectEqual(@as(f32, 100), perspective.zfar.?); + try std.testing.expectEqual(@as(f32, 1.5), perspective.aspect_ratio.?); + const orthographic = scene.cameras[scene.nodes[2].camera.?].orthographic; + try std.testing.expectEqual(@as(f32, 8), orthographic.xmag); + try std.testing.expectEqual(@as(f32, 6), orthographic.ymag); + try std.testing.expectEqual(@as(f32, 0), orthographic.znear); + try std.testing.expectEqual(@as(f32, 50), orthographic.zfar); +} diff --git a/src/host/gpu.zig b/src/gpu/Executor.zig index 94b2e39..412d0ed 100644 --- a/src/host/gpu.zig +++ b/src/gpu/Executor.zig @@ -6,7 +6,6 @@ const Gpu = @This(); const std = @import("std"); const c = @import("c"); const abi = @import("abi"); -const gfx = @import("gfx.zig"); pub const color_format = c.SDL_GPU_TEXTUREFORMAT_R8G8B8A8_UNORM; /// Frames an unused shader or pipeline survives. @@ -29,6 +28,7 @@ vertices: ?*c.SDL_GPUBuffer = null, vertex_capacity: u32 = 0, upload: ?*c.SDL_GPUTransferBuffer = null, upload_capacity: u32 = 0, +post_sampler: ?*c.SDL_GPUSampler = null, frame: u64 = 0, /// Set by `--profile-gpu`: every command is timed alone (see `Profile`). profile: ?Profile = null, @@ -39,14 +39,45 @@ spare: std.ArrayList(Transfer) = .empty, const Transfer = struct { buffer: *c.SDL_GPUTransferBuffer, size: u32 }; const Download = struct { key: u32, size: u32, transfer: Transfer, fence: *c.SDL_GPUFence }; -/// GPU time per labelled command. Each command starts on an idle GPU and is -/// waited for, so its time is its own: the total of a frame is what the -/// GPU spends on it, though the waiting makes the frame itself slower. +/// CPU wall time per labelled GPU command, from recording through fence wait. +/// Includes submission and synchronization overhead; not hardware GPU timestamps. pub const Profile = struct { entries: std.StringArrayHashMapUnmanaged(Entry) = .empty, arena: std.heap.ArenaAllocator, + start_frame: u64 = 0, - const Entry = struct { count: u64 = 0, total: u64 = 0, worst: u64 = 0 }; + pub const Entry = struct { + count: u64 = 0, + total: u64 = 0, + worst: u64 = 0, + samples: [2048]u64 = undefined, + + pub fn add(entry: *Entry, ns: u64) void { + entry.samples[@intCast(entry.count % entry.samples.len)] = ns; + entry.count += 1; + entry.total += ns; + entry.worst = @max(entry.worst, ns); + } + + pub fn retained(entry: *const Entry) usize { + return @intCast(@min(entry.count, entry.samples.len)); + } + + pub fn sample(entry: *const Entry, index: usize) u64 { + std.debug.assert(index < entry.retained()); + return entry.samples[@intCast((entry.count - entry.retained() + index) % entry.samples.len)]; + } + + /// Called by inspection only; the render path just writes the ring. + pub fn percentiles(entry: *const Entry) [2]u64 { + const n = entry.retained(); + if (n == 0) return .{ 0, 0 }; + var scratch: [2048]u64 = undefined; + @memcpy(scratch[0..n], entry.samples[0..n]); + std.mem.sortUnstable(u64, scratch[0..n], {}, std.sort.asc(u64)); + return .{ scratch[(n * 95 + 99) / 100 - 1], scratch[(n * 99 + 99) / 100 - 1] }; + } + }; pub fn init(gpa: std.mem.Allocator) Profile { return .{ .arena = .init(gpa) }; @@ -63,19 +94,18 @@ pub const Profile = struct { entry.key_ptr.* = a.dupe(u8, label) catch "?"; entry.value_ptr.* = .{}; } - entry.value_ptr.count += 1; - entry.value_ptr.total += ns; - entry.value_ptr.worst = @max(entry.value_ptr.worst, ns); + entry.value_ptr.add(ns); } - pub fn report(p: *Profile, frames: u64) void { + pub fn report(p: *Profile, total_frames: u64) void { + const frames = total_frames -| p.start_frame; std.debug.print("gpu time over {d} frames (ms)\n{s: <24} {s: >7} {s: >9} {s: >9} {s: >11}\n", .{ frames, "command", "count", "mean", "worst", "per frame" }); var sum: u64 = 0; var it = p.entries.iterator(); while (it.next()) |e| { - const v = e.value_ptr.*; + const v = e.value_ptr; sum += v.total; - std.debug.print("{s: <24} {d: >7} {d: >9.3} {d: >9.3} {d: >11.3}\n", .{ e.key_ptr.*, v.count, ms(v.total) / @as(f64, @floatFromInt(v.count)), ms(v.worst), ms(v.total) / @as(f64, @floatFromInt(@max(frames, 1))) }); + std.debug.print("{s: <24} {d: >7} {d: >9.3} {d: >9.3} {d: >11.3}\n", .{ e.key_ptr.*, v.count, ms(v.total) / @as(f64, @floatFromInt(@max(v.count, 1))), ms(v.worst), ms(v.total) / @as(f64, @floatFromInt(@max(frames, 1))) }); } std.debug.print("{s: <24} {s: >7} {s: >9} {s: >9} {d: >11.3}\n", .{ "all", "", "", "", ms(sum) / @as(f64, @floatFromInt(@max(frames, 1))) }); } @@ -88,10 +118,10 @@ pub const Profile = struct { /// Submits `cmd`; when profiling, waits for it and books its time from /// `start` (taken on an idle GPU, before recording) under `label`. fn submit(g: *Gpu, cmd: *c.SDL_GPUCommandBuffer, label: []const u8, start: u64) !void { - const p = &(g.profile orelse { + const p = if (g.profile) |*profile| profile else { if (!c.SDL_SubmitGPUCommandBuffer(cmd)) return error.GpuSubmit; return; - }); + }; const fence = c.SDL_SubmitGPUCommandBufferAndAcquireFence(cmd) orelse return error.GpuSubmit; defer c.SDL_ReleaseGPUFence(g.device, fence); _ = c.SDL_WaitForGPUFences(g.device, true, &fence, 1); @@ -136,7 +166,7 @@ pub fn init(gpa: std.mem.Allocator, device: *c.SDL_GPUDevice) Gpu { }; } -pub fn deinit(g: *Gpu, images: *gfx.Images) void { +pub fn deinit(g: *Gpu) void { if (g.profile) |*p| { p.report(g.frame); p.deinit(); @@ -158,9 +188,10 @@ pub fn deinit(g: *Gpu, images: *gfx.Images) void { g.spare.deinit(g.gpa); if (g.staging) |b| c.SDL_ReleaseGPUTransferBuffer(g.device, b); var targets = g.targets.iterator(); - while (targets.next()) |entry| g.releaseTarget(images, entry.key_ptr.*, entry.value_ptr.*); + while (targets.next()) |entry| g.releaseTarget(entry.value_ptr.*); if (g.vertices) |b| c.SDL_ReleaseGPUBuffer(g.device, b); if (g.upload) |b| c.SDL_ReleaseGPUTransferBuffer(g.device, b); + if (g.post_sampler) |s| c.SDL_ReleaseGPUSampler(g.device, s); g.shaders.deinit(g.gpa); g.pipelines.deinit(g.gpa); g.kernels.deinit(g.gpa); @@ -187,22 +218,63 @@ pub fn endFrame(g: *Gpu) void { } } -pub fn run(g: *Gpu, images: *gfx.Images, pass: abi.gpu.Pass) !void { +pub fn run(g: *Gpu, pass: abi.gpu.Pass) !void { + const start = g.startTiming(); + const cmd = c.SDL_AcquireGPUCommandBuffer(g.device) orelse return error.GpuCommandBuffer; + errdefer _ = c.SDL_CancelGPUCommandBuffer(cmd); + try g.record(cmd, pass); + try g.submit(cmd, if (pass.label.len > 0) pass.label else "pass", start); +} + +/// Records into the caller's command buffer; the caller submits it. +/// Uploads cycle their buffers, allowing several passes in one frame. +pub fn record(g: *Gpu, cmd: *c.SDL_GPUCommandBuffer, pass: abi.gpu.Pass) !void { + return g.recordWithInput(cmd, pass, null); +} + +/// A second pass on the same command buffer; input and output must differ. +pub fn postProcess(g: *Gpu, cmd: *c.SDL_GPUCommandBuffer, source: abi.Image, target: abi.Image, post: abi.gpu.PostProcess) !void { + if (source == target) return error.FeedbackLoop; + const input = g.output(source) orelse return error.MissingImage; + try g.recordWithInput(cmd, .{ + .image = target, + .width = input.width, + .height = input.height, + .pipelines = &.{.{ .vertex = post.vertex, .fragment = post.fragment, .stride = 0, .attributes = &.{}, .blend = .none }}, + .draws = &.{.{ .pipeline = 0, .vertex_count = 3, .fragment_uniforms = post.fragment_uniforms }}, + }, input.texture); +} + +fn recordWithInput(g: *Gpu, cmd: *c.SDL_GPUCommandBuffer, pass: abi.gpu.Pass, input: ?*c.SDL_GPUTexture) !void { if (pass.width == 0 or pass.height == 0 or pass.draws.len == 0 and pass.clear == null) return; + if (input != null and g.post_sampler == null) { + g.post_sampler = c.SDL_CreateGPUSampler(g.device, &std.mem.zeroInit(c.SDL_GPUSamplerCreateInfo, .{ + .min_filter = c.SDL_GPU_FILTER_NEAREST, + .mag_filter = c.SDL_GPU_FILTER_NEAREST, + .address_mode_u = c.SDL_GPU_SAMPLERADDRESSMODE_CLAMP_TO_EDGE, + .address_mode_v = c.SDL_GPU_SAMPLERADDRESSMODE_CLAMP_TO_EDGE, + })) orelse return error.GpuSampler; + } const samples = g.supportedSamples(pass.samples); - const t = try g.renderTarget(images, pass.image, pass.width, pass.height, samples, pass.stencil); + const t = try g.renderTarget(pass.image, pass.width, pass.height, samples, pass.stencil or pass.depth); // Each pipeline is looked up on first use in the pass, not per draw: // the lookup hashes the shaders' code. Outer null: not looked up yet; // inner null: it failed (warned once). const built = try g.gpa.alloc(??*c.SDL_GPUGraphicsPipeline, pass.pipelines.len); defer g.gpa.free(built); @memset(built, null); + // Compile before recording: a refused shader leaves the caller's + // command buffer usable and the fallback picture visible. + for (pass.draws) |d| { + if (d.pipeline >= pass.pipelines.len) return error.BadPipeline; + const p = pass.pipelines[d.pipeline]; + if ((p.depth_test != null or p.depth_write) and !pass.depth) return error.MissingDepthAttachment; + if (built[d.pipeline] == null) built[d.pipeline] = try g.pipeline(pass.pipelines[d.pipeline], samples, pass.stencil or pass.depth, @intFromBool(input != null)); + } - const start = g.startTiming(); // Every draw's vertices go up in one copy. var total: u32 = 0; for (pass.draws) |d| total += @intCast(std.mem.alignForward(usize, d.vertices.len, 4)); - const cmd = c.SDL_AcquireGPUCommandBuffer(g.device) orelse return error.GpuCommandBuffer; if (total > 0) { try g.reserve(total); const mapped: [*]u8 = @ptrCast(c.SDL_MapGPUTransferBuffer(g.device, g.upload, true) orelse return error.GpuMap); @@ -238,15 +310,17 @@ pub fn run(g: *Gpu, images: *gfx.Images, pass: abi.gpu.Pass) !void { } t.fresh = false; var depth: c.SDL_GPUDepthStencilTargetInfo = std.mem.zeroes(c.SDL_GPUDepthStencilTargetInfo); - if (pass.stencil) { + if (pass.stencil or pass.depth) { depth.texture = t.stencil; - depth.load_op = c.SDL_GPU_LOADOP_DONT_CARE; + depth.load_op = if (pass.depth) c.SDL_GPU_LOADOP_CLEAR else c.SDL_GPU_LOADOP_DONT_CARE; + depth.clear_depth = 1; depth.store_op = c.SDL_GPU_STOREOP_DONT_CARE; depth.stencil_load_op = c.SDL_GPU_LOADOP_CLEAR; depth.stencil_store_op = c.SDL_GPU_STOREOP_DONT_CARE; depth.clear_stencil = 0; } - const rp = c.SDL_BeginGPURenderPass(cmd, &color, 1, if (pass.stencil) &depth else null) orelse return error.GpuRenderPass; + const rp = c.SDL_BeginGPURenderPass(cmd, &color, 1, if (pass.stencil or pass.depth) &depth else null) orelse return error.GpuRenderPass; + if (input) |texture_| c.SDL_BindGPUFragmentSamplers(rp, 0, &.{ .texture = texture_, .sampler = g.post_sampler.? }, 1); var bound: ?*c.SDL_GPUGraphicsPipeline = null; // State already set in this pass, so draws that repeat it skip the call. var vertex_uniforms: ?[]const u8 = null; @@ -258,10 +332,6 @@ pub fn run(g: *Gpu, images: *gfx.Images, pass: abi.gpu.Pass) !void { defer offset += @intCast(std.mem.alignForward(usize, d.vertices.len, 4)); if (d.pipeline >= pass.pipelines.len or d.vertex_count == 0) continue; const slot = &built[d.pipeline]; - if (slot.* == null) slot.* = g.pipeline(pass.pipelines[d.pipeline], samples, pass.stencil) catch |err| blk: { - std.log.warn("gpu pipeline {d}: {t} ({s})", .{ d.pipeline, err, c.SDL_GetError() }); - break :blk @as(?*c.SDL_GPUGraphicsPipeline, null); - }; const chosen = slot.*.? orelse continue; if (bound != chosen) { c.SDL_BindGPUGraphicsPipeline(rp, chosen); @@ -303,7 +373,6 @@ pub fn run(g: *Gpu, images: *gfx.Images, pass: abi.gpu.Pass) !void { c.SDL_DrawGPUPrimitives(rp, d.vertex_count, 1, first, 0); } c.SDL_EndGPURenderPass(rp); - try g.submit(cmd, if (pass.label.len > 0) pass.label else "pass", start); } /// Runs one dispatch in a compute pass of its own. @@ -486,17 +555,16 @@ fn sampleCount(s: u8) c.SDL_GPUSampleCount { } /// The image's render target, (re)created to fit the pass. -fn renderTarget(g: *Gpu, images: *gfx.Images, image: abi.Image, w: u32, h: u32, samples: u8, stencil: bool) !*Target { +fn renderTarget(g: *Gpu, image: abi.Image, w: u32, h: u32, samples: u8, stencil: bool) !*Target { var entry = try g.targets.getOrPut(g.gpa, image); if (entry.found_existing and (entry.value_ptr.width != w or entry.value_ptr.height != h)) { - g.releaseTarget(images, image, entry.value_ptr.*); + g.releaseTarget(entry.value_ptr.*); entry.found_existing = false; } if (!entry.found_existing) { errdefer _ = g.targets.remove(image); const resolved = try g.texture(w, h, color_format, c.SDL_GPU_TEXTUREUSAGE_COLOR_TARGET | c.SDL_GPU_TEXTUREUSAGE_SAMPLER, 1); errdefer c.SDL_ReleaseGPUTexture(g.device, resolved); - try images.wrap(image, resolved, w, h); entry.value_ptr.* = .{ .width = w, .height = h, .texture = resolved }; } const t = entry.value_ptr; @@ -514,17 +582,16 @@ fn renderTarget(g: *Gpu, images: *gfx.Images, image: abi.Image, w: u32, h: u32, return t; } -fn releaseTarget(g: *Gpu, images: *gfx.Images, image: abi.Image, t: Target) void { - images.unwrap(image); +fn releaseTarget(g: *Gpu, t: Target) void { c.SDL_ReleaseGPUTexture(g.device, t.texture); if (t.msaa) |m| c.SDL_ReleaseGPUTexture(g.device, m); if (t.stencil) |s| c.SDL_ReleaseGPUTexture(g.device, s); } /// Forgets an image's target, when the image itself is freed. -pub fn forget(g: *Gpu, images: *gfx.Images, image: abi.Image) void { +pub fn forget(g: *Gpu, image: abi.Image) void { const t = g.targets.fetchRemove(image) orelse return; - g.releaseTarget(images, image, t.value); + g.releaseTarget(t.value); } fn texture(g: *Gpu, w: u32, h: u32, format: c.SDL_GPUTextureFormat, usage: c.SDL_GPUTextureUsageFlags, samples: u8) !*c.SDL_GPUTexture { @@ -555,11 +622,12 @@ fn reserve(g: *Gpu, bytes: u32) !void { } } -fn shader(g: *Gpu, s: abi.gpu.Shader, stage: c.SDL_GPUShaderStage) !struct { *c.SDL_GPUShader, u64 } { +fn shader(g: *Gpu, s: abi.gpu.Shader, stage: c.SDL_GPUShaderStage, samplers: u32) !struct { *c.SDL_GPUShader, u64 } { var h = std.hash.Wyhash.init(stage); h.update(s.code); h.update(std.mem.asBytes(&s.uniform_buffers)); h.update(std.mem.asBytes(&s.storage_buffers)); + h.update(std.mem.asBytes(&samplers)); const key = h.final(); const entry = try g.shaders.getOrPut(g.gpa, key); if (!entry.found_existing) { @@ -570,7 +638,7 @@ fn shader(g: *Gpu, s: abi.gpu.Shader, stage: c.SDL_GPUShaderStage) !struct { *c. .entrypoint = "main", .format = c.SDL_GPU_SHADERFORMAT_SPIRV, .stage = stage, - .num_samplers = 0, + .num_samplers = samplers, .num_storage_textures = 0, .num_storage_buffers = s.storage_buffers, .num_uniform_buffers = s.uniform_buffers, @@ -581,12 +649,12 @@ fn shader(g: *Gpu, s: abi.gpu.Shader, stage: c.SDL_GPUShaderStage) !struct { *c. return .{ entry.value_ptr.object, key }; } -fn pipeline(g: *Gpu, p: abi.gpu.Pipeline, samples: u8, stencil: bool) !*c.SDL_GPUGraphicsPipeline { - const vertex, const vertex_key = try g.shader(p.vertex, c.SDL_GPU_SHADERSTAGE_VERTEX); - const fragment, const fragment_key = try g.shader(p.fragment, c.SDL_GPU_SHADERSTAGE_FRAGMENT); +fn pipeline(g: *Gpu, p: abi.gpu.Pipeline, samples: u8, stencil: bool, samplers: u32) !*c.SDL_GPUGraphicsPipeline { + const vertex, const vertex_key = try g.shader(p.vertex, c.SDL_GPU_SHADERSTAGE_VERTEX, 0); + const fragment, const fragment_key = try g.shader(p.fragment, c.SDL_GPU_SHADERSTAGE_FRAGMENT, samplers); // Field by field: no padding bytes in the key. var h = std.hash.Wyhash.init(vertex_key ^ (fragment_key *% 31)); - inline for (.{ p.stride, @backingInt(p.primitive), @backingInt(p.blend), @intFromBool(p.write_color), samples, @intFromBool(stencil) }) |v| h.update(std.mem.asBytes(&@as(u32, v))); + inline for (.{ p.stride, @backingInt(p.primitive), @backingInt(p.blend), @intFromBool(p.write_color), @intFromBool(p.depth_write), if (p.depth_test) |compare| @as(u32, @backingInt(compare)) + 1 else @as(u32, 0), samples, @intFromBool(stencil) }) |v| h.update(std.mem.asBytes(&@as(u32, v))); for (p.attributes) |a| inline for (.{ a.location, @backingInt(a.format), a.offset }) |v| h.update(std.mem.asBytes(&@as(u32, v))); if (p.stencil) |st| inline for (.{ st.front, st.back }) |face| inline for (.{ @backingInt(face.compare), @backingInt(face.pass), @backingInt(face.fail) }) |v| h.update(std.mem.asBytes(&@as(u32, v))); const key = h.final(); @@ -620,6 +688,9 @@ fn pipeline(g: *Gpu, p: abi.gpu.Pipeline, samples: u8, stencil: bool) !*c.SDL_GP blend.color_write_mask = if (p.write_color) c.SDL_GPU_COLORCOMPONENT_R | c.SDL_GPU_COLORCOMPONENT_G | c.SDL_GPU_COLORCOMPONENT_B | c.SDL_GPU_COLORCOMPONENT_A else 0; const target_description: c.SDL_GPUColorTargetDescription = .{ .format = color_format, .blend_state = blend }; var depth_stencil: c.SDL_GPUDepthStencilState = std.mem.zeroes(c.SDL_GPUDepthStencilState); + depth_stencil.enable_depth_test = p.depth_test != null or p.depth_write; + depth_stencil.enable_depth_write = p.depth_write; + depth_stencil.compare_op = @as(u32, @backingInt(p.depth_test orelse .always)) + 1; if (p.stencil) |st| { depth_stencil.enable_stencil_test = true; depth_stencil.compare_mask = 0xff; @@ -667,3 +738,9 @@ fn stencilFace(face: abi.gpu.StencilFace) c.SDL_GPUStencilOpState { .depth_fail_op = c.SDL_GPU_STENCILOP_KEEP, }; } + +/// Borrowed until resize, forget, or deinit. The executor owns the texture. +pub fn output(g: *Gpu, image: abi.Image) ?struct { texture: *c.SDL_GPUTexture, width: u32, height: u32 } { + const t = g.targets.get(image) orelse return null; + return .{ .texture = t.texture, .width = t.width, .height = t.height }; +} diff --git a/src/gpu/scene.zig b/src/gpu/scene.zig new file mode 100644 index 0000000..e5ff3d0 --- /dev/null +++ b/src/gpu/scene.zig @@ -0,0 +1,263 @@ +//! Optional, self-contained GPU frames for embedders and remote views. +//! Version 1: "SGPU", u32 version, then Pass fields in declaration order. +//! Version 2 appends one fullscreen PostProcess sampling that pass's output. +//! Version 3 adds depth fields and an optional PostProcess after the pass. +//! Integers/enums/f32 are little endian; slices have a u32 count, optionals +//! and bools a byte (0 or 1). No pointers, native padding, or device handles. +//! Storage buffers are not part of this version: each frame stands alone. +const std = @import("std"); +pub const abi = @import("abi"); +pub const max_bytes = 4 << 20; +pub const Frame = struct { pass: abi.gpu.Pass, post: ?abi.gpu.PostProcess = null }; + +pub fn encode(w: *std.Io.Writer, pass: abi.gpu.Pass) !void { + try validate(pass); + try w.writeAll("SGPU"); + const version: u32 = if (pass.depth) 3 else 1; + try w.writeInt(u32, version, .little); + try put(w, pass, version); + if (version == 3) try put(w, @as(?abi.gpu.PostProcess, null), version); +} + +pub fn encodePostProcess(w: *std.Io.Writer, pass: abi.gpu.Pass, post: abi.gpu.PostProcess) !void { + try validate(pass); + try validatePostProcess(post); + try w.writeAll("SGPU"); + const version: u32 = if (pass.depth) 3 else 2; + try w.writeInt(u32, version, .little); + try put(w, pass, version); + if (version == 3) try put(w, @as(?abi.gpu.PostProcess, post), version) else try put(w, post, version); +} + +/// Allocations belong to the caller's frame arena. Never run unvalidated +/// wire data through a driver; this checks lengths, layouts and indices. +pub fn decode(arena: std.mem.Allocator, bytes: []const u8) !abi.gpu.Pass { + const frame = try decodeFrame(arena, bytes); + if (frame.post != null) return error.BadScene; + return frame.pass; +} + +pub fn decodeFrame(arena: std.mem.Allocator, bytes: []const u8) !Frame { + if (bytes.len > max_bytes) return error.SceneTooLarge; + var r: std.Io.Reader = .fixed(bytes); + if (!std.mem.eql(u8, try r.take(4), "SGPU")) return error.BadScene; + const version = try r.takeInt(u32, .little); + if (version < 1 or version > 3) return error.BadScene; + var budget: usize = max_bytes * 4; + const pass = try get(abi.gpu.Pass, arena, &r, &budget, version); + const post: ?abi.gpu.PostProcess = if (version == 3) try get(?abi.gpu.PostProcess, arena, &r, &budget, version) else if (version == 2) try get(abi.gpu.PostProcess, arena, &r, &budget, version) else null; + if (r.end != r.seek) return error.BadScene; + try validate(pass); + if (post) |p| try validatePostProcess(p); + return .{ .pass = pass, .post = post }; +} + +fn depthField(comptime T: type, comptime name: []const u8) bool { + return (T == abi.gpu.Pass and std.mem.eql(u8, name, "depth")) or + (T == abi.gpu.Pipeline and (std.mem.eql(u8, name, "depth_test") or std.mem.eql(u8, name, "depth_write"))); +} + +fn put(w: *std.Io.Writer, value: anytype, version: u32) anyerror!void { + const T = @TypeOf(value); + switch (@typeInfo(T)) { + .int => try w.writeInt(T, value, .little), + .float => try w.writeInt(u32, @bitCast(value), .little), + .bool => try w.writeByte(@intFromBool(value)), + .@"enum" => try w.writeInt(u32, @intCast(@backingInt(value)), .little), + .optional => { + try w.writeByte(@intFromBool(value != null)); + if (value) |v| try put(w, v, version); + }, + .array => for (value) |v| try put(w, v, version), + .pointer => { + try w.writeInt(u32, @intCast(value.len), .little); + for (value) |v| try put(w, v, version); + }, + .@"struct" => |s| inline for (s.field_names) |name| { + if (version >= 3 or !depthField(T, name)) try put(w, @field(value, name), version); + }, + else => @compileError("unsupported scene field"), + } +} + +fn get(comptime T: type, a: std.mem.Allocator, r: *std.Io.Reader, budget: *usize, version: u32) anyerror!T { + switch (@typeInfo(T)) { + .int => return r.takeInt(T, .little), + .float => return @bitCast(try r.takeInt(u32, .little)), + .bool => return switch (try r.takeByte()) { + 0 => false, + 1 => true, + else => error.BadScene, + }, + .@"enum" => |e| { + const n = try r.takeInt(u32, .little); + inline for (e.field_names, e.field_values) |name, value| if (n == value) return @field(T, name); + return error.BadScene; + }, + .optional => |o| return switch (try r.takeByte()) { + 0 => null, + 1 => try get(o.child, a, r, budget, version), + else => error.BadScene, + }, + .array => |ar| { + var out: T = undefined; + for (&out) |*v| v.* = try get(ar.child, a, r, budget, version); + return out; + }, + .pointer => |p| { + const n = try r.takeInt(u32, .little); + const size = std.math.mul(usize, n, @sizeOf(p.child)) catch return error.SceneTooLarge; + if (size > budget.* or n > max_bytes) return error.SceneTooLarge; + budget.* -= size; + // SPIR-V must be word aligned, including after a wire decode. + const out = try a.alignedAlloc(p.child, .fromByteUnits(@max(4, @alignOf(p.child))), n); + for (out) |*v| v.* = try get(p.child, a, r, budget, version); + return out; + }, + .@"struct" => |s| { + var out: T = undefined; + inline for (s.field_names, s.field_types) |name, F| { + @field(out, name) = if (version < 3 and comptime depthField(T, name)) std.mem.zeroes(F) else try get(F, a, r, budget, version); + } + return out; + }, + else => @compileError("unsupported scene field"), + } +} + +fn shader(s: abi.gpu.Shader) !void { + if (s.code.len < 20 or s.code.len % 4 != 0 or std.mem.readInt(u32, s.code[0..4], .little) != 0x07230203 or s.uniform_buffers > 1 or s.storage_buffers != 0) return error.BadShader; +} + +pub fn validatePostProcess(p: abi.gpu.PostProcess) !void { + try shader(p.vertex); + try shader(p.fragment); + if (p.vertex.uniform_buffers != 0 or p.fragment_uniforms.len > 16384 or + (p.fragment_uniforms.len > 0) != (p.fragment.uniform_buffers == 1)) return error.BadScene; +} + +pub fn validate(p: abi.gpu.Pass) !void { + if (p.image != .none or p.width == 0 or p.height == 0 or p.width > 4096 or p.height > 4096 or p.pipelines.len > 64 or p.draws.len > 4096 or (p.samples != 1 and p.samples != 2 and p.samples != 4 and p.samples != 8)) return error.BadScene; + // Self-contained frames must not depend on an earlier view's contents. + const clear = p.clear orelse return error.BadScene; + for (clear) |v| if (!std.math.isFinite(v)) return error.BadScene; + for (p.pipelines) |pipe| { + if ((pipe.depth_test != null or pipe.depth_write) and !p.depth) return error.BadScene; + try shader(pipe.vertex); + try shader(pipe.fragment); + if (pipe.attributes.len > 16 or pipe.stride > 4096) return error.BadScene; + var locations: u32 = 0; + for (pipe.attributes) |attr| { + const size: u32 = switch (attr.format) { + .float, .ubyte4_norm => 4, + .float2 => 8, + .float3 => 12, + .float4 => 16, + }; + if (attr.location >= 16 or attr.offset > pipe.stride or size > pipe.stride - attr.offset) return error.BadScene; + const bit = @as(u32, 1) << @intCast(attr.location); + if (locations & bit != 0) return error.BadScene; + locations |= bit; + } + } + var total: usize = 0; + for (p.draws) |d| { + if (d.pipeline >= p.pipelines.len or d.vertex_count > 1 << 20 or d.vertex_storage.len != 0 or d.fragment_storage.len != 0) return error.BadScene; + const pipe = p.pipelines[d.pipeline]; + if (pipe.attributes.len != 0 and @as(u64, pipe.stride) * d.vertex_count > d.vertices.len) return error.BadScene; + if (d.vertex_uniforms.len > 16384 or d.fragment_uniforms.len > 16384 or (d.vertex_uniforms.len > 0) != (pipe.vertex.uniform_buffers == 1) or (d.fragment_uniforms.len > 0) != (pipe.fragment.uniform_buffers == 1)) return error.BadScene; + total += d.vertices.len; + if (total > max_bytes) return error.SceneTooLarge; + if (d.scissor) |r| inline for (.{ r.x, r.y, r.w, r.h }) |v| if (!std.math.isFinite(v) or v < 0 or v > 4096) return error.BadScene; + } +} + +test "GPU scene roundtrip, truncated and oversized inputs are refused" { + const shader_bytes = std.mem.asBytes(&[_]u32{ 0x07230203, 0, 0, 0, 0 }); + const pipelines = [_]abi.gpu.Pipeline{.{ .vertex = .{ .code = shader_bytes }, .fragment = .{ .code = shader_bytes }, .stride = 0, .attributes = &.{} }}; + const pass: abi.gpu.Pass = .{ .image = .none, .width = 32, .height = 24, .pipelines = &pipelines, .draws = &.{.{ .pipeline = 0, .vertex_count = 3 }} }; + var out: std.Io.Writer.Allocating = .init(std.testing.allocator); + defer out.deinit(); + try encode(&out.writer, pass); + var arena: std.heap.ArenaAllocator = .init(std.testing.allocator); + defer arena.deinit(); + const decoded = try decode(arena.allocator(), out.written()); + try std.testing.expectEqual(32, decoded.width); + try std.testing.expectEqual(3, decoded.draws[0].vertex_count); + for (0..out.written().len) |i| { + _ = decode(arena.allocator(), out.written()[0..i]) catch continue; + return error.AcceptedTruncatedScene; + } + var bad = pass; + bad.width = 4097; + try std.testing.expectError(error.BadScene, validate(bad)); + var draw = pass.draws[0]; + draw.pipeline = 1; + bad = pass; + bad.draws = &.{draw}; + try std.testing.expectError(error.BadScene, validate(bad)); +} + +test "GPU postprocess keeps v1 readable and validates the complete second pass" { + const code = std.mem.asBytes(&[_]u32{ 0x07230203, 0, 0, 0, 0 }); + const pipelines = [_]abi.gpu.Pipeline{.{ .vertex = .{ .code = code }, .fragment = .{ .code = code }, .stride = 0, .attributes = &.{} }}; + const pass: abi.gpu.Pass = .{ .image = .none, .width = 32, .height = 24, .pipelines = &pipelines, .draws = &.{.{ .pipeline = 0, .vertex_count = 3 }} }; + const post: abi.gpu.PostProcess = .{ .vertex = .{ .code = code }, .fragment = .{ .code = code } }; + var out: std.Io.Writer.Allocating = .init(std.testing.allocator); + defer out.deinit(); + var arena: std.heap.ArenaAllocator = .init(std.testing.allocator); + defer arena.deinit(); + try encode(&out.writer, pass); + try std.testing.expect((try decodeFrame(arena.allocator(), out.written())).post == null); + out.clearRetainingCapacity(); + try encodePostProcess(&out.writer, pass, post); + const frame = try decodeFrame(arena.allocator(), out.written()); + try std.testing.expectEqual(32, frame.pass.width); + try std.testing.expectEqualSlices(u8, code, frame.post.?.fragment.code); + for (0..out.written().len) |i| { + _ = decodeFrame(arena.allocator(), out.written()[0..i]) catch continue; + return error.AcceptedTruncatedScene; + } + var bad = post; + bad.vertex.uniform_buffers = 1; + try std.testing.expectError(error.BadScene, validatePostProcess(bad)); + bad = post; + bad.fragment.uniform_buffers = 1; + try std.testing.expectError(error.BadScene, validatePostProcess(bad)); + bad = post; + bad.fragment.storage_buffers = 1; + try std.testing.expectError(error.BadShader, validatePostProcess(bad)); + out.written()[4] = 4; + try std.testing.expectError(error.BadScene, decodeFrame(arena.allocator(), out.written())); +} + +test "depth uses v3 and requires an attachment; legacy frames keep depth disabled" { + const code = std.mem.asBytes(&[_]u32{ 0x07230203, 0, 0, 0, 0 }); + var pipelines = [_]abi.gpu.Pipeline{.{ .vertex = .{ .code = code }, .fragment = .{ .code = code }, .stride = 0, .attributes = &.{}, .depth_test = .less, .depth_write = true }}; + var pass: abi.gpu.Pass = .{ .image = .none, .width = 32, .height = 24, .pipelines = &pipelines, .draws = &.{.{ .pipeline = 0, .vertex_count = 3 }} }; + try std.testing.expectError(error.BadScene, validate(pass)); + pass.depth = true; + var out: std.Io.Writer.Allocating = .init(std.testing.allocator); + defer out.deinit(); + var arena: std.heap.ArenaAllocator = .init(std.testing.allocator); + defer arena.deinit(); + try encode(&out.writer, pass); + try std.testing.expectEqual(3, out.written()[4]); + const decoded = try decode(arena.allocator(), out.written()); + try std.testing.expect(decoded.depth); + try std.testing.expectEqual(abi.gpu.Compare.less, decoded.pipelines[0].depth_test.?); + try std.testing.expect(decoded.pipelines[0].depth_write); + const post: abi.gpu.PostProcess = .{ .vertex = .{ .code = code }, .fragment = .{ .code = code } }; + out.clearRetainingCapacity(); + try encodePostProcess(&out.writer, pass, post); + const frame = try decodeFrame(arena.allocator(), out.written()); + try std.testing.expect(frame.post != null and frame.pass.depth); + pass.depth = false; + pipelines[0].depth_test = null; + pipelines[0].depth_write = false; + out.clearRetainingCapacity(); + try encode(&out.writer, pass); + try std.testing.expectEqual(1, out.written()[4]); + const legacy = try decode(arena.allocator(), out.written()); + try std.testing.expect(!legacy.depth and legacy.pipelines[0].depth_test == null and !legacy.pipelines[0].depth_write); +} diff --git a/src/host/Host.zig b/src/host/Host.zig index 008d143..02a88c7 100644 --- a/src/host/Host.zig +++ b/src/host/Host.zig @@ -12,15 +12,18 @@ const Timeline = playback.Timeline; const mapRecordings = playback.mapRecordings; const gfx = @import("gfx.zig"); const sound = @import("audio.zig"); -const Gpu = @import("gpu.zig"); +const Gpu = @import("gpu"); const overlay = @import("overlay.zig"); const Console = @import("Console.zig"); +const Control = @import("control.zig").Control; const Library = @import("library.zig").Library; const Watch = @import("library.zig").Watch; pub const Options = struct { /// A hot-reloaded sketch library. Unused when a sketch is linked in. library: ?[]const u8 = null, + /// Local 9P control socket, opt-in. + ninep: ?[]const u8 = null, /// State file; recordings go next to it with an `.inputs` suffix. state: []const u8 = "sketch.state", /// Offscreen video, silent audio, no vsync: for scripts and CI. @@ -59,6 +62,8 @@ painter: gfx.Painter, audio: sound.Audio, state: memory.StateFile, session: memory.Session, +/// A failed resource setup disables app callbacks while keeping host controls alive. +session_ready: bool = false, store: memory.StoreFile, /// Images and buffers the sketch made (`newImage`, `decodeImage`, /// `newBuffer`): Session holds their handles, so they go when it resets. @@ -98,6 +103,7 @@ screenshot: ?[:0]const u8 = null, /// Frames exported so far (`Options.export_to`). exported: u64 = 0, dialog: Dialog = .{}, +control: ?*Control = null, pub fn init(self: *Host, gpa: std.mem.Allocator, io: std.Io, environ: *const std.process.Environ.Map, options: Options, linked: ?abi.Sketch) !void { if (options.headless) { @@ -200,12 +206,13 @@ pub fn init(self: *Host, gpa: std.mem.Allocator, io: std.Io, environ: *const std } pub fn deinit(self: *Host) void { + if (self.control) |control| control.deinit(); self.dialog.deinit(); if (self.watch) |w| w.deinit(); self.audio.deinit(); - if (self.passes) |*g| g.deinit(&self.images); self.painter.deinit(); self.images.deinit(); + if (self.passes) |*g| g.deinit(); if (self.pointer_cursor) |cursor| c.SDL_DestroyCursor(cursor); if (self.offscreen) |texture| c.SDL_DestroyTexture(texture); c.SDL_DestroyRenderer(self.renderer); @@ -233,7 +240,9 @@ pub fn deinit(self: *Host) void { /// The interactive loop. An export runs it on a clock of its own, frame k /// at k/fps seconds (from 1 s, as scripts do), whatever the wall clock says. pub fn run(self: *Host) !void { + if (self.options.ninep) |path| self.control = try Control.init(self.gpa, path); while (!self.quit) { + if (self.control) |control| control.poll(self); try self.poll(); try self.frame(if (self.options.export_to == null) c.SDL_GetTicksNS() else std.time.ns_per_s + self.exported * std.time.ns_per_s / self.options.fps); } @@ -278,6 +287,7 @@ pub fn frame(self: *Host, now: u64) !void { /// Feeds whole frames to the sketch's deterministic `update`, one call per /// frame (events up to and including a tick), live or replayed alike. pub fn update(self: *Host, events: []const abi.Event) void { + if (!self.session_ready) return; var frames = playback.frames(events); while (frames.next()) |one| { // Input follows the events actually fed, frame by frame. @@ -353,7 +363,7 @@ fn draw(self: *Host, now: u64) !void { self.input.downloads = if (self.passes) |*g| try g.collect(arena) else &.{}; self.input.frame += 1; const ctx = self.context(); - self.sketch.draw(&ctx, self.live().ptr); + if (self.session_ready) self.sketch.draw(&ctx, self.live().ptr); _ = c.SDL_SetRenderTarget(self.renderer, self.offscreen); _ = c.SDL_SetRenderClipRect(self.renderer, null); @@ -375,7 +385,7 @@ fn draw(self: *Host, now: u64) !void { .voice => |voice| self.audio.declare(voice), .audio => |a| self.audio.push(a.key, a.samples, a.clear), .quit => self.quit = true, - .gpu => |pass| if (self.passes) |*g| g.run(&self.images, pass) catch |err| self.print("gpu pass: {t} ({s})", .{ err, c.SDL_GetError() }), + .gpu => |pass| if (self.passes) |*g| self.runGpu(g, pass) catch |err| self.print("gpu pass: {t} ({s})", .{ err, c.SDL_GetError() }), .upload => |u| if (self.passes) |*g| g.write(u.buffer, u.offset, u.bytes) catch |err| self.print("gpu upload: {t} ({s})", .{ err, c.SDL_GetError() }), .compute => |d| if (self.passes) |*g| g.compute(d) catch |err| self.print("gpu compute: {t} ({s})", .{ err, c.SDL_GetError() }), .microphone => self.audio.listen(), @@ -400,13 +410,14 @@ fn draw(self: *Host, now: u64) !void { self.painter.end(); self.applyCursor(); - if (self.screenshot != null or self.options.export_to != null) { + if (self.screenshot != null or self.options.export_to != null or (self.control != null and self.control.?.capture_pending)) { const surface = c.SDL_RenderReadPixels(self.renderer, null) orelse return sdlError("SDL_RenderReadPixels"); defer c.SDL_DestroySurface(surface); if (self.screenshot) |path| { self.screenshot = null; if (!c.SDL_SavePNG(surface, path.ptr)) return sdlError("SDL_SavePNG"); } + if (self.control) |control| if (control.capture_pending) control.capture(surface); if (self.options.export_to) |to| try self.exportFrame(surface, to); } if (!self.options.headless) if (self.offscreen) |canvas| { @@ -573,6 +584,10 @@ fn movesState(line: []const u8) bool { /// Offers a line to the sketch. pub fn forward(self: *Host, _: *Console, line: []const u8, now: u64) abi.Outcome { + if (!self.session_ready) { + self.print("session setup failed; restart after fixing the resource error", .{}); + return .failed; + } self.input.now = now; const ctx = self.context(); return self.sketch.command(&ctx, self.live().ptr, &line); @@ -626,6 +641,11 @@ fn adopt(self: *Host, sketch: abi.Sketch) !void { .migrated => |m| self.print("state layout changed: kept {d} fields, reset {d} to defaults", .{ m.kept, m.reset }), } if (!self.state.used(0)) self.resetState(); + if (session_reset) { + const ctx = self.context(); + self.session_ready = self.sketch.setup(&ctx); + if (!self.session_ready) self.console.visible = true; + } if (session_reset and self.reloads > 0) self.print("session layout changed: session reset", .{}); switch (stored) { .unchanged, .created => {}, @@ -636,7 +656,8 @@ fn adopt(self: *Host, sketch: abi.Sketch) !void { /// Frees what the old Session made: its handles are gone with it. fn releaseMade(self: *Host) void { for (self.made.images.items) |image| { - if (self.passes) |*g| g.forget(&self.images, image); + self.images.unwrap(image); + if (self.passes) |*g| g.forget(image); self.images.free(image); } if (self.passes) |*g| for (self.made.buffers.items) |buffer| g.freeBuffer(buffer); @@ -800,6 +821,7 @@ const api: abi.Host.VTable = .{ .gpu = apiGpu, .newBuffer = apiNewBuffer, .freeBuffer = apiFreeBuffer, + .writeBuffer = apiWriteBuffer, .imageSize = apiImageSize, .textSize = apiTextSize, .loadSound = apiLoadSound, @@ -830,7 +852,8 @@ fn apiNewImage(ctx: *anyopaque, w: u32, h: u32) abi.Image { fn apiFreeImage(ctx: *anyopaque, image: abi.Image) void { const self = hostOf(ctx); forget(&self.made.images, image); - if (self.passes) |*g| g.forget(&self.images, image); + self.images.unwrap(image); + if (self.passes) |*g| g.forget(image); self.images.free(image); } fn apiGpu(ctx: *anyopaque) bool { @@ -838,12 +861,17 @@ fn apiGpu(ctx: *anyopaque) bool { } fn apiNewBuffer(ctx: *anyopaque, size: u32) abi.Buffer { const self = hostOf(ctx); - const g = &(self.passes orelse return .none); + const g = if (self.passes) |*passes| passes else return .none; return self.remember(.buffers, g.newBuffer(size) catch |err| blk: { self.print("gpu buffer: {t} ({s})", .{ err, c.SDL_GetError() }); break :blk .none; }); } +fn apiWriteBuffer(ctx: *anyopaque, buffer: abi.Buffer, offset: u32, bytes: []const u8) !void { + const self = hostOf(ctx); + const gpu = if (self.passes) |*passes| passes else return error.GpuUnavailable; + try gpu.write(buffer, offset, bytes); +} fn apiFreeBuffer(ctx: *anyopaque, buffer: abi.Buffer) void { const self = hostOf(ctx); forget(&self.made.buffers, buffer); @@ -879,3 +907,136 @@ fn apiClock(_: *anyopaque) u64 { fn apiEnv(ctx: *anyopaque, name: []const u8) ?[]const u8 { return hostOf(ctx).environ.get(name); } + +fn runGpu(self: *Host, g: *Gpu, pass: abi.gpu.Pass) !void { + const before = g.output(pass.image); + const changed = if (before) |t| t.width != pass.width or t.height != pass.height else true; + if (changed) self.images.unwrap(pass.image); + try g.run(pass); + if (g.output(pass.image)) |t| try self.images.wrap(pass.image, t.texture, t.width, t.height); +} + +test "session setup runs for restored state and layout reset, not same-layout reload or state reset" { + const Fixture = struct { + const State = extern struct { value: u32 = 1 }; + const Session1 = extern struct { ready: u32 = 0 }; + const Session2 = extern struct { ready: u32 = 0, extra: u32 = 0 }; + const Store = struct {}; + var setup_calls: usize = 0; + var init_calls: usize = 0; + var fail_setup = false; + const description: abi.Info = .{ .abi = abi.hash, .name = "setup-test", .width = 1, .height = 1, .state = abi.layout.of(State, .state), .session = abi.layout.of(Session1, .session), .store = abi.layout.of(Store, .store) }; + const changed: abi.Info = blk: { + var value = description; + value.session = abi.layout.of(Session2, .session); + break :blk value; + }; + fn info() callconv(.c) *const abi.Info { + return &description; + } + fn info2() callconv(.c) *const abi.Info { + return &changed; + } + fn defaults(kind: abi.Memory, ptr: [*]u8) callconv(.c) void { + switch (kind) { + .state => @as(*State, @ptrCast(@alignCast(ptr))).* = .{}, + .session => @as(*Session1, @ptrCast(@alignCast(ptr))).* = .{}, + .store => {}, + } + } + fn defaults2(kind: abi.Memory, ptr: [*]u8) callconv(.c) void { + if (kind == .session) @as(*Session2, @ptrCast(@alignCast(ptr))).* = .{} else defaults(kind, ptr); + } + fn init(_: *const abi.Context, _: [*]u8) callconv(.c) void { + init_calls += 1; + } + fn setup(ctx: *const abi.Context) callconv(.c) bool { + setup_calls += 1; + @as(*u32, @ptrCast(@alignCast(ctx.session_root))).* += 1; + return !fail_setup; + } + fn update(_: *const abi.Context, _: [*]u8) callconv(.c) void {} + fn draw(_: *const abi.Context, _: [*]const u8) callconv(.c) void {} + fn command(_: *const abi.Context, _: [*]u8, _: *const []const u8) callconv(.c) abi.Outcome { + return .unknown; + } + const sketch: abi.Sketch = .{ .info = info, .defaults = defaults, .init = @This().init, .setup = setup, .update = @This().update, .draw = @This().draw, .command = command }; + }; + Fixture.setup_calls = 0; + Fixture.init_calls = 0; + Fixture.fail_setup = false; + const a = std.testing.allocator; + var tmp = std.testing.tmpDir(.{}); + defer tmp.cleanup(); + var state_buf: [std.fs.max_path_bytes]u8 = undefined; + var store_buf: [std.fs.max_path_bytes]u8 = undefined; + const state_path = try std.mem.print(&state_buf, ".zig-cache/tmp/{s}/setup.state", .{&tmp.sub_path}); + const store_path = try std.mem.print(&store_buf, ".zig-cache/tmp/{s}/setup.store", .{&tmp.sub_path}); + { + var state = try memory.StateFile.open(a, state_path); + defer state.close(); + _ = try state.adopt(a, Fixture.description.state, Fixture.defaults); + @as(*Fixture.State, @ptrCast(state.slot(0).ptr)).value = 77; + state.markUsed(0, true); + } + // Exercise adoption with real persisted memory, without opening SDL devices. + var host: Host = undefined; + host.gpa = a; + host.state = try memory.StateFile.open(a, state_path); + defer host.state.close(); + host.store = try memory.StoreFile.open(a, store_path, false); + defer host.store.close(); + host.session = .init(a); + defer host.session.deinit(a); + host.info_arena = .init(a); + defer host.info_arena.deinit(); + host.frame_arena = .init(a); + defer host.frame_arena.deinit(); + host.options = .{ .headless = true }; + host.console = .{}; + host.reloads = 0; + host.made = .{}; + host.passes = null; + host.input = .{}; + host.commands = .empty; + try host.adopt(Fixture.sketch); + try std.testing.expectEqual(@as(u32, 77), @as(*Fixture.State, @ptrCast(@alignCast(host.live().ptr))).value); + try std.testing.expectEqual(@as(usize, 0), Fixture.init_calls); + try std.testing.expectEqual(@as(usize, 1), Fixture.setup_calls); + const session_ptr = host.session.bytes.ptr; + try host.adopt(Fixture.sketch); + try std.testing.expectEqual(session_ptr, host.session.bytes.ptr); + try std.testing.expectEqual(@as(usize, 1), Fixture.setup_calls); + host.resetState(); + try std.testing.expectEqual(@as(usize, 1), Fixture.init_calls); + try std.testing.expectEqual(@as(usize, 1), Fixture.setup_calls); + var changed = Fixture.sketch; + changed.info = Fixture.info2; + changed.defaults = Fixture.defaults2; + try host.adopt(changed); + try std.testing.expectEqual(@as(usize, 2), Fixture.setup_calls); + try std.testing.expectEqual(@as(u32, 1), @as(*Fixture.Session2, @ptrCast(host.session.bytes.ptr)).ready); + try std.testing.expect(host.session_ready); + Fixture.fail_setup = true; + defer Fixture.fail_setup = false; + try host.adopt(Fixture.sketch); + try std.testing.expect(!host.session_ready); + try std.testing.expect(host.console.visible); + try std.testing.expectEqual(abi.Outcome.failed, host.forward(&host.console, "anything", 0)); + try host.adopt(Fixture.sketch); + try std.testing.expect(!host.session_ready); // A compatible reload cannot bless partial resources. + try std.testing.expectEqual(@as(usize, 3), Fixture.setup_calls); +} + +test "setup writeBuffer propagates unavailable, unknown and out-of-bounds upload errors" { + const a = std.testing.allocator; + var host: Host = undefined; + host.passes = null; + const client: abi.Host = .{ .ctx = &host, .vtable = &api }; + try std.testing.expectError(error.GpuUnavailable, client.writeBuffer(.none, 0, "data")); + host.passes = .{ .gpa = a, .device = undefined, .stencil_format = undefined }; + defer host.passes.?.buffers.deinit(a); + try std.testing.expectError(error.UnknownBuffer, client.writeBuffer(.none, 0, "data")); + try host.passes.?.buffers.append(a, .{ .buffer = undefined, .size = 4 }); + try std.testing.expectError(error.UploadOutOfBounds, client.writeBuffer(@fromBackingInt(@intCast(1)), 2, "data")); +} diff --git a/src/host/control.zig b/src/host/control.zig new file mode 100644 index 0000000..58b41b3 --- /dev/null +++ b/src/host/control.zig @@ -0,0 +1,368 @@ +//! Local 9P controls, serviced on the frame thread: no SDL or state races. +const std = @import("std"); +const c9 = @import("cloud9"); +const c = @import("c"); +const Host = @import("Host.zig"); +const fs = c9.fs; +const transport = c9.transport; +const Backend = struct { + pub const Req = fs.Req; + pub const Reply = fs.Reply; +}; +const Server = fs.Server(Backend, .{ .fid_capacity = 32, .slot_capacity = 4 }); +const msize = 16384; +const names = [_][]const u8{ "/", "ctl", "status", "log", "screen.png", "profile", "profile-trace" }; + +const Connection = struct { + fd: c_int = -1, + server: Server = undefined, + input: [msize]u8 = undefined, + output: [msize * 2]u8 = undefined, + incoming: [msize]u8 = undefined, + used: usize = 0, + snapshots: [32]?[]u8 = @splat(null), + + fn close(self: *Connection, a: std.mem.Allocator) void { + if (self.fd < 0) return; + transport.close(self.fd); + for (&self.snapshots) |*snapshot| if (snapshot.*) |bytes| { + a.free(bytes); + snapshot.* = null; + }; + self.fd = -1; + } +}; + +pub const Control = struct { + allocator: std.mem.Allocator, + path: [:0]u8, + listener: c_int, + connections: [4]Connection = @splat(.{}), + png: []u8 = &.{}, + capture_pending: bool = false, + generation: u64 = 0, + capture_error: ?anyerror = null, + + pub fn init(a: std.mem.Allocator, path: []const u8) !*Control { + const self = try a.create(Control); + errdefer a.destroy(self); + const z = try a.dupeSentinel(u8, path, 0); + errdefer a.free(z); + // Refuse an existing path; never unlink another process's socket. + const fd = try transport.listenFd(.{ .unix = z }, 4); + errdefer { + transport.close(fd); + _ = std.c.unlink(z); + } + if (std.c.chmod(z, 0o600) != 0) return error.SocketPermissions; + self.* = .{ .allocator = a, .path = z, .listener = fd }; + return self; + } + + pub fn deinit(self: *Control) void { + for (&self.connections) |*conn| conn.close(self.allocator); + transport.close(self.listener); + _ = std.c.unlink(self.path); + self.allocator.free(self.path); + self.allocator.free(self.png); + self.allocator.destroy(self); + } + + pub fn poll(self: *Control, host: *Host) void { + if (transport.acceptFd(self.listener, false) catch null) |fd| { + var accepted = false; + for (&self.connections) |*conn| if (conn.fd < 0) { + conn.fd = fd; + conn.used = 0; + conn.server = .init(.{ .in = &conn.input, .out = &conn.output, .root = 1 }); + accepted = true; + break; + }; + if (!accepted) transport.close(fd); + } + for (&self.connections) |*conn| { + if (conn.fd < 0) continue; + self.service(host, conn) catch conn.close(self.allocator); + } + } + + fn service(self: *Control, host: *Host, conn: *Connection) !void { + // Bound work per frame, including clients which continually write. + for (0..32) |_| { + var progressed = false; + if (conn.used != 0) { + const consumed = conn.server.push(conn.incoming[0..conn.used]); + std.mem.copyForwards(u8, &conn.incoming, conn.incoming[consumed..conn.used]); + conn.used -= consumed; + progressed = consumed != 0; + } + while (conn.server.next()) |req| self.answer(host, conn, req); + if (conn.server.protocol.dead) return error.Closed; + if (conn.server.output().len > 0) { + if (try transport.write(conn.fd, conn.server.output())) |n| { + if (n == 0) return error.Closed; + conn.server.wrote(n); + progressed = true; + } + } + if (conn.used < conn.incoming.len) { + if (try transport.read(conn.fd, conn.incoming[conn.used..])) |n| { + if (n == 0) return error.Closed; + conn.used += n; + progressed = true; + } + } + if (!progressed) break; + } + } + + fn answer(self: *Control, host: *Host, conn: *Connection, req: fs.Req) void { + var reply: fs.Reply = .{ .tag = req.tag }; + var buffer: [msize]u8 = undefined; + const bytes = self.respond(host, conn, req, &reply, &buffer) catch |err| blk: { + reply = .{ .tag = req.tag, .status = .err, .errno = fs.E.INVAL, .ename = @errorName(err) }; + break :blk &.{}; + }; + conn.server.reply(&reply, bytes); + } + + fn respond(self: *Control, host: *Host, conn: *Connection, req: fs.Req, reply: *fs.Reply, buffer: []u8) ![]const u8 { + if (req.node < 1 or req.node > names.len) return error.UnknownFile; + switch (req.op) { + .lookup => { + if (req.node != 1) return error.NotDirectory; + for (names[1..], 2..) |name, node| if (std.mem.eql(u8, name, req.data)) { + reply.attr = self.attr(node); + return &.{}; + }; + return error.UnknownFile; + }, + .getattr => reply.attr = self.attr(req.node), + .open => { + if (req.node == 5 or req.node == 7) { + if (req.node == 5) { + if (self.capture_pending) return error.CapturePending; + if (self.capture_error) |err| return err; + if (self.png.len == 0) return error.CaptureScreenshotFirst; + } + for (&conn.snapshots, 1..) |*slot, handle| if (slot.* == null) { + slot.* = if (req.node == 5) try self.allocator.dupe(u8, self.png) else try self.trace(host); + reply.handle = @intCast(handle); + return &.{}; + }; + return error.TooManySnapshots; + } + }, + .release => if (req.opened and req.handle > 0 and req.handle <= conn.snapshots.len) { + const slot = &conn.snapshots[req.handle - 1]; + if (slot.*) |bytes| self.allocator.free(bytes); + slot.* = null; + }, + .readdir => { + if (req.node != 1) return error.NotDirectory; + var used: usize = 0; + for (names[1..], 0..) |name, index| { + if (index < req.off) continue; + std.mem.writeInt(u64, buffer[used..][0..8], index + 2, .little); + buffer[used + 8] = 0; + buffer[used + 9] = @intCast(name.len); + @memcpy(buffer[used + 10 ..][0..name.len], name); + used += 10 + name.len; + } + return buffer[0..used]; + }, + .read => { + var writer: std.Io.Writer = .fixed(buffer); + const bytes: []const u8 = switch (req.node) { + 2 => "Write one console command per line. screenshot captures the next frame.\n", + 3 => blk: { + try writer.print("name {s}\nsize {d} {d}\nmode {t}\ngpu {s}\nscreenshot_pending {}\nscreenshot_generation {d}\nscreenshot_error {s}\n", .{ host.name, host.canvas[0], host.canvas[1], host.timeline.mode, if (host.gpu != null) "yes" else "no", self.capture_pending, self.generation, if (self.capture_error) |err| @errorName(err) else "none" }); + break :blk writer.buffered(); + }, + 4 => blk: { + for (host.console.lines) |line| { + try writer.writeAll(line.bytes[0..line.len]); + try writer.writeByte('\n'); + } + break :blk writer.buffered(); + }, + 5, 7 => if (req.handle > 0 and req.handle <= conn.snapshots.len) conn.snapshots[req.handle - 1] orelse return error.InvalidHandle else return error.InvalidHandle, + 6 => blk: { + const gpu = if (host.passes) |*gpu| gpu else return error.ProfilingDisabled; + const profile = if (gpu.profile) |*profile| profile else return error.ProfilingDisabled; + try writer.print("# CPU wall milliseconds including GPU submission and fence wait; not hardware timestamps\n# frames {d}\nlabel\tcount\tmean_ms\tworst_ms\tp95_ms\tp99_ms\n", .{gpu.frame - profile.start_frame}); + var entries = profile.entries.iterator(); + while (entries.next()) |entry| { + const value = entry.value_ptr; + const percentiles = value.percentiles(); + const count: f64 = @floatFromInt(@max(value.count, 1)); + try writer.print("{s}\t{d}\t{d:.6}\t{d:.6}\t{d:.6}\t{d:.6}\n", .{ entry.key_ptr.*, value.count, @as(f64, @floatFromInt(value.total)) / count / std.time.ns_per_ms, @as(f64, @floatFromInt(value.worst)) / std.time.ns_per_ms, @as(f64, @floatFromInt(percentiles[0])) / std.time.ns_per_ms, @as(f64, @floatFromInt(percentiles[1])) / std.time.ns_per_ms }); + } + break :blk writer.buffered(); + }, + else => return error.NotFile, + }; + return window(bytes, req.off, req.size); + }, + .write => { + if (req.node != 2) return error.ReadOnly; + if (req.data.len > 4096 or std.mem.indexOfScalar(u8, req.data, 0) != null) return error.InvalidCommand; + var lines = std.mem.tokenizeScalar(u8, req.data, '\n'); + while (lines.next()) |raw| { + const line = std.mem.trim(u8, raw, " \t\r"); + if (std.mem.eql(u8, line, "screenshot")) { + self.capture_pending = true; + self.capture_error = null; + } else if (std.mem.eql(u8, line, "profile-reset")) { + const gpu = if (host.passes) |*gpu| gpu else return error.ProfilingDisabled; + const profile = if (gpu.profile) |*profile| profile else return error.ProfilingDisabled; + for (profile.entries.values()) |*entry| entry.* = .{}; + profile.start_frame = gpu.frame; + } else try host.runLine(line, c.SDL_GetTicksNS()); + } + reply.written = @intCast(req.data.len); + }, + .setattr => { + if (req.node != 2 or !req.truncate) return error.ReadOnly; + reply.attr = self.attr(req.node); + }, + } + return &.{}; + } + + fn trace(self: *Control, host: *Host) ![]u8 { + const gpu = if (host.passes) |*gpu| gpu else return error.ProfilingDisabled; + const profile = if (gpu.profile) |*profile| profile else return error.ProfilingDisabled; + const buffer = try self.allocator.alloc(u8, 256 << 10); + defer self.allocator.free(buffer); + var writer: std.Io.Writer = .fixed(buffer); + try writer.writeAll("label,sample,ns\n"); + var entries = profile.entries.iterator(); + while (entries.next()) |entry| { + const value = entry.value_ptr; + for (0..value.retained()) |i| { + try writer.writeByte('"'); + for (entry.key_ptr.*) |ch| { + if (ch == '"') try writer.writeByte('"'); + try writer.writeByte(ch); + } + try writer.print("\",{d},{d}\n", .{ value.count - value.retained() + i + 1, value.sample(i) }); + } + } + return self.allocator.dupe(u8, writer.buffered()); + } + + fn attr(self: *Control, node: u64) fs.Attr { + return .{ .name = names[@intCast(node - 1)], .node = node, .dir = node == 1, .mode = if (node == 1) 0o700 else if (node == 2) 0o600 else 0o400, .size = if (node == 5) self.png.len else 0, .version = if (node == 5) @truncate(self.generation) else 0 }; + } + + pub fn capture(self: *Control, surface: *c.SDL_Surface) void { + self.capture_pending = false; + self.save(surface) catch |err| { + self.capture_error = err; + }; + } + + fn save(self: *Control, surface: *c.SDL_Surface) !void { + const stream = c.SDL_IOFromDynamicMem() orelse return error.CaptureStream; + defer _ = c.SDL_CloseIO(stream); + if (!c.SDL_SavePNG_IO(surface, stream, false)) return error.EncodePng; + const size = c.SDL_GetIOSize(stream); + if (size <= 0) return error.EncodePng; + const pointer = c.SDL_GetPointerProperty(c.SDL_GetIOProperties(stream), c.SDL_PROP_IOSTREAM_DYNAMIC_MEMORY_POINTER, null) orelse return error.EncodePng; + const png = try self.allocator.dupe(u8, @as([*]const u8, @ptrCast(pointer))[0..@intCast(size)]); + self.allocator.free(self.png); + self.png = png; + self.generation += 1; + } +}; + +fn window(bytes: []const u8, offset: u64, count: u32) []const u8 { + if (offset >= bytes.len) return &.{}; + const start: usize = @intCast(offset); + return bytes[start..][0..@min(count, bytes.len - start)]; +} + +test "9P reads respect offsets, counts and EOF" { + try std.testing.expectEqualStrings("cd", window("abcdef", 2, 2)); + try std.testing.expectEqualStrings("ef", window("abcdef", 4, 200)); + try std.testing.expectEqualStrings("", window("abcdef", std.math.maxInt(u64), 10)); +} + +test "control writes validate and screenshot opens pin an immutable snapshot" { + const a = std.testing.allocator; + var control: Control = .{ .allocator = a, .path = undefined, .listener = -1 }; + var host: Host = undefined; // These backend operations do not access the host. + var conn: Connection = .{}; + var reply: fs.Reply = .{ .tag = 1 }; + var buf: [256]u8 = undefined; + _ = try control.respond(&host, &conn, .{ .tag = 1, .op = .setattr, .node = 2, .truncate = true }, &reply, &buf); + try std.testing.expectError(error.ReadOnly, control.respond(&host, &conn, .{ .tag = 1, .op = .write, .node = 3, .data = "screenshot" }, &reply, &buf)); + try std.testing.expectError(error.InvalidCommand, control.respond(&host, &conn, .{ .tag = 1, .op = .write, .node = 2, .data = "screenshot\x00" }, &reply, &buf)); + _ = try control.respond(&host, &conn, .{ .tag = 1, .op = .write, .node = 2, .data = "screenshot\n" }, &reply, &buf); + try std.testing.expect(control.capture_pending); + try std.testing.expectError(error.CapturePending, control.respond(&host, &conn, .{ .tag = 1, .op = .open, .node = 5 }, &reply, &buf)); + control.capture_pending = false; + control.png = try a.dupe(u8, "first image"); + _ = try control.respond(&host, &conn, .{ .tag = 1, .op = .open, .node = 5 }, &reply, &buf); + const handle = reply.handle; + a.free(control.png); + control.png = try a.dupe(u8, "second image"); + defer a.free(control.png); + const bytes = try control.respond(&host, &conn, .{ .tag = 1, .op = .read, .node = 5, .handle = handle, .size = 100 }, &reply, &buf); + try std.testing.expectEqualStrings("first image", bytes); + _ = try control.respond(&host, &conn, .{ .tag = 1, .op = .release, .node = 5, .handle = handle, .opened = true }, &reply, &buf); + try std.testing.expect(conn.snapshots[handle - 1] == null); +} + +test "control writes reset profiling counters while retaining labels" { + const a = std.testing.allocator; + var control: Control = .{ .allocator = a, .path = undefined, .listener = -1 }; + var host: Host = undefined; + host.passes = null; + var conn: Connection = .{}; + var reply: fs.Reply = .{ .tag = 1 }; + var buf: [512]u8 = undefined; + const reset: fs.Req = .{ .tag = 1, .op = .write, .node = 2, .data = "profile-reset\n" }; + try std.testing.expectError(error.ProfilingDisabled, control.respond(&host, &conn, reset, &reply, &buf)); + host.passes = @as(@import("gpu"), undefined); + const gpu = &host.passes.?; + gpu.profile = .init(a); + defer gpu.profile.?.deinit(); + const profile = &gpu.profile.?; + try profile.entries.put(profile.arena.allocator(), "scene", .{}); + profile.entries.values()[0].add(400_000); + profile.entries.values()[0].add(600_000); + gpu.frame = 420; + const read: fs.Req = .{ .tag = 1, .op = .read, .node = 6, .size = buf.len }; + const before = try control.respond(&host, &conn, read, &reply, &buf); + try std.testing.expect(std.mem.indexOf(u8, before, "scene\t2\t0.500000\t0.600000") != null); + _ = try control.respond(&host, &conn, .{ .tag = 1, .op = .open, .node = 7 }, &reply, &buf); + const trace_handle = reply.handle; + _ = try control.respond(&host, &conn, reset, &reply, &buf); + const trace = try control.respond(&host, &conn, .{ .tag = 1, .op = .read, .node = 7, .handle = trace_handle, .size = 100 }, &reply, &buf); + try std.testing.expectEqualStrings("label,sample,ns\n\"scene\",1,400000\n\"scene\",2,600000\n", trace); + _ = try control.respond(&host, &conn, .{ .tag = 1, .op = .release, .node = 7, .handle = trace_handle, .opened = true }, &reply, &buf); + try std.testing.expect(conn.snapshots[trace_handle - 1] == null); + try std.testing.expectEqual(@as(usize, 1), profile.entries.count()); + try std.testing.expectEqual(@as(u64, 0), profile.entries.values()[0].total); + try std.testing.expectEqual(@as(u64, 420), profile.start_frame); + const after = try control.respond(&host, &conn, read, &reply, &buf); + try std.testing.expect(std.mem.indexOf(u8, after, "# frames 0") != null); + try std.testing.expect(std.mem.indexOf(u8, after, "scene\t0\t0.000000\t0.000000") != null); +} + +test "control writes profiling ring retains latest samples and nearest rank percentiles" { + var entry: @import("gpu").Profile.Entry = .{}; + for (1..4100) |ns| entry.add(ns); + try std.testing.expectEqual(@as(u64, 4099), entry.count); + try std.testing.expectEqual(@as(usize, 2048), entry.retained()); + try std.testing.expectEqual(@as(u64, 2052), entry.sample(0)); + try std.testing.expectEqual(@as(u64, 4099), entry.sample(2047)); + try std.testing.expectEqual([2]u64{ 3997, 4079 }, entry.percentiles()); + entry = .{}; + try std.testing.expectEqual(@as(usize, 0), entry.retained()); + try std.testing.expectEqual([2]u64{ 0, 0 }, entry.percentiles()); + entry.add(20); + try std.testing.expectEqual([2]u64{ 20, 20 }, entry.percentiles()); +} diff --git a/src/host/gfx.zig b/src/host/gfx.zig index a7ebd05..fef58c3 100644 --- a/src/host/gfx.zig +++ b/src/host/gfx.zig @@ -12,6 +12,7 @@ pub const Images = struct { const Entry = struct { texture: ?*c.SDL_Texture = null, + gpu_texture: ?*anyopaque = null, w: u32 = 0, h: u32 = 0, /// Holds premultiplied colour: a target drawn into, a GPU pass's @@ -79,6 +80,7 @@ pub const Images = struct { /// Makes `image` show a GPU render target (GPU renderer only). pub fn wrap(self: *Images, image: abi.Image, gpu_texture: *anyopaque, w: u32, h: u32) !void { const entry = self.get(image) orelse return error.UnknownImage; + if (entry.gpu_texture == gpu_texture) return; const props = c.SDL_CreateProperties(); defer c.SDL_DestroyProperties(props); _ = c.SDL_SetPointerProperty(props, c.SDL_PROP_TEXTURE_CREATE_GPU_TEXTURE_POINTER, gpu_texture); @@ -89,7 +91,7 @@ pub const Images = struct { // Rendered output: smooth scaling, and already premultiplied. _ = c.SDL_SetTextureScaleMode(texture, c.SDL_SCALEMODE_LINEAR); entry.release(); - entry.* = .{ .texture = texture, .w = w, .h = h, .premultiplied = true, .smooth = true }; + entry.* = .{ .texture = texture, .w = w, .h = h, .premultiplied = true, .smooth = true, .gpu_texture = gpu_texture }; } /// Stops showing a wrapped render target, before the target goes away. @@ -97,6 +99,7 @@ pub const Images = struct { const entry = self.get(image) orelse return; if (entry.texture) |t| c.SDL_DestroyTexture(t); entry.texture = null; + entry.gpu_texture = null; } pub fn free(self: *Images, image: abi.Image) void { @@ -591,7 +594,7 @@ fn fcolor(color: abi.Color) c.SDL_FColor { /// Native shaped text on Linux, using a 13px monospace face at scale 1. /// Other targets retain SDL's built-in 8x8 fallback. Coordinates are line-box tops. pub fn drawText(renderer: *c.SDL_Renderer, x: f32, y: f32, scale: f32, bytes: []const u8, color: abi.Color, face: abi.Face, raster: f32) void { - if (@import("builtin").os.tag == .linux and c.sk_text_draw_scaled(renderer, @intFromEnum(face), x, y, scale, raster, bytes.ptr, bytes.len, color.r, color.g, color.b, color.a)) return; + if (@import("builtin").os.tag == .linux and c.sk_text_draw_scaled(renderer, @backingInt(face), x, y, scale, raster, bytes.ptr, bytes.len, color.r, color.g, color.b, color.a)) return; var buf: [1024]u8 = undefined; const len = @min(std.mem.indexOfScalar(u8, bytes, 0) orelse bytes.len, buf.len - 1); @memcpy(buf[0..len], bytes[0..len]); @@ -623,7 +626,7 @@ pub fn drawText(renderer: *c.SDL_Renderer, x: f32, y: f32, scale: f32, bytes: [] /// its line, in canvas units (`Host.textSize`). pub fn textSize(renderer: *c.SDL_Renderer, scale: f32, bytes: []const u8, face: abi.Face) [2]f32 { var size: [2]f32 = .{ 0, 0 }; - if (@import("builtin").os.tag == .linux and c.sk_text_measure_face(renderer, @intFromEnum(face), scale, bytes.ptr, bytes.len, &size[0], &size[1])) return size; + if (@import("builtin").os.tag == .linux and c.sk_text_measure_face(renderer, @backingInt(face), scale, bytes.ptr, bytes.len, &size[0], &size[1])) return size; // The debug font's 8 px cells. const s = @max(scale, 1); return .{ @as(f32, @floatFromInt(bytes.len)) * 8 * s, 8 * s }; diff --git a/src/host/root.zig b/src/host/root.zig index d01a63f..c9cdde6 100644 --- a/src/host/root.zig +++ b/src/host/root.zig @@ -39,6 +39,8 @@ pub fn main(init: std.process.Init, linked: ?abi.Sketch) !void { while (args.next()) |arg| { if (std.mem.eql(u8, arg, "--state")) { options.state = args.next() orelse fatal("--state needs a file"); + } else if (std.mem.eql(u8, arg, "--9p")) { + options.ninep = args.next() orelse fatal("--9p needs a socket path"); } else if (std.mem.eql(u8, arg, "--fresh")) { options.fresh = true; } else if (std.mem.eql(u8, arg, "--headless")) { @@ -121,6 +123,7 @@ pub fn main(init: std.process.Init, linked: ?abi.Sketch) !void { const usage = \\usage: sketchbook [options] [LIBRARY] + \\ --9p SOCKET local 9P controls: ctl, status, log, screen.png \\ --state FILE persistent state (default: sketch.state) \\ --headless offscreen video, silent audio, no vsync \\ --script FILE play a script instead of reading devices @@ -191,9 +194,11 @@ const sdl_heap = struct { }; test { + _ = Host; _ = memory; _ = fields; _ = timeline; _ = @import("audio.zig"); _ = @import("Console.zig"); + _ = @import("control.zig"); } diff --git a/src/sketch/root.zig b/src/sketch/root.zig index 52f05b2..434478c 100644 --- a/src/sketch/root.zig +++ b/src/sketch/root.zig @@ -10,6 +10,7 @@ //! pub const Store = struct { ... }; // on disk: survives restarts too //! pub const commands = .{"hello"}; // console completions //! pub fn init(state: *State, host: sk.Host) void +//! pub fn setup(session: *Session, init: *sk.Init) !void //! pub fn update(state: *State, in: *const sk.Input) void //! pub fn draw(state: *const State, session: *Session, store: *Store, f: *sk.Frame) void //! pub fn command(state: *State, store: *Store, c: *sk.Console, line: []const u8) !bool @@ -59,6 +60,14 @@ pub const Voice = abi.Voice; pub const BlendMode = abi.BlendMode; pub const Face = abi.Face; +/// Resource initialization, once per fresh Session (also when State is restored). +/// No State, Input, scratch allocator, or drawing commands are available here. +pub const Init = struct { + host: Host, + session: std.mem.Allocator, + store: std.mem.Allocator, +}; + /// What `draw` receives: input, host services, memory by lifetime and the /// command list. Commands may be built from anything: the methods copy what /// they keep (text, GPU descriptions) into `scratch`, except bulk data @@ -288,7 +297,7 @@ pub const Console = struct { /// The entry points of `App`, for a host that links it statically. pub fn sketch(comptime App: type) abi.Sketch { const G = Glue(App); - return .{ .info = G.info, .defaults = G.defaults, .init = G.init, .update = G.update, .draw = G.draw, .command = G.command }; + return .{ .info = G.info, .defaults = G.defaults, .init = G.init, .setup = G.setup, .update = G.update, .draw = G.draw, .command = G.command }; } /// Exports `App` under `abi.Sketch.symbols`, for a hot-reloaded library. @@ -298,6 +307,7 @@ pub fn exportSketch(comptime App: type) void { @export(&G.info, .{ .name = names.info }); @export(&G.defaults, .{ .name = names.defaults }); @export(&G.init, .{ .name = names.init }); + @export(&G.setup, .{ .name = names.setup }); @export(&G.update, .{ .name = names.update }); @export(&G.draw, .{ .name = names.draw }); @export(&G.command, .{ .name = names.command }); @@ -325,6 +335,7 @@ pub fn Glue(comptime App: type) type { ctx: *const abi.Context, state: [*]u8, frame: ?*Frame = null, + resource_init: ?*Init = null, console: ?*Console = null, line: []const u8 = "", }; @@ -342,6 +353,9 @@ pub fn Glue(comptime App: type) type { }; if (comptime is.named("update") and (T == *Session or T == *Store)) @compileError("update must be deterministic: it gets State and Input only, so a replay reproduces it"); + if (comptime is.named("setup") and (T == *State or T == *const State or T == *const Input)) + @compileError("setup initializes resources: it gets Session, Store, Init and Host only"); + if (comptime (T == *Init or T == *const Init) and !is.named("setup")) @compileError(name ++ " gets no Init: only setup does"); if (comptime is.named("draw") and T == *State) @compileError("draw only reads State: take *const State"); if (comptime T == *Frame and !is.named("draw")) @compileError(name ++ " gets no Frame: only draw does"); if (comptime T == *Console and !is.named("command")) @compileError(name ++ " gets no Console: only command does"); @@ -355,6 +369,8 @@ pub fn Glue(comptime App: type) type { offer.ctx.input else if (T == Host) offer.ctx.host + else if (T == *Init or T == *const Init) + offer.resource_init.? else if (T == *Frame) offer.frame.? else if (T == *Console) @@ -380,6 +396,16 @@ pub fn Glue(comptime App: type) type { pub fn init(ctx: *const abi.Context, s: [*]u8) callconv(.c) void { if (@hasDecl(App, "init")) call(App.init, "init", .{ .ctx = ctx, .state = s }); } + pub fn setup(ctx: *const abi.Context) callconv(.c) bool { + if (!@hasDecl(App, "setup")) return true; + var resource_init: Init = .{ .host = ctx.host, .session = ctx.session, .store = ctx.store }; + const result = call(App.setup, "setup", .{ .ctx = ctx, .state = undefined, .resource_init = &resource_init }); + if (@typeInfo(@TypeOf(result)) == .error_union) result catch |err| { + ctx.host.print("session setup failed: {t}", .{err}); + return false; + }; + return true; + } pub fn update(ctx: *const abi.Context, s: [*]u8) callconv(.c) void { if (@hasDecl(App, "update")) call(App.update, "update", .{ .ctx = ctx, .state = s }); } @@ -411,3 +437,35 @@ test { _ = @import("list.zig"); _ = @import("derived.zig"); } + +test "setup receives session resources without a Frame and reports errors" { + const App = struct { + pub const Session = struct { bytes: []u8 = &.{}, calls: u32 = 0 }; + pub fn setup(session: *Session, resources: *Init) !void { + session.calls += 1; + session.bytes = try resources.session.dupe(u8, "ready"); + return error.TestSetupFailure; + } + }; + const Log = struct { + fn log(ctx: *anyopaque, message: []const u8) void { + const seen: *bool = @ptrCast(@alignCast(ctx)); + seen.* = std.mem.eql(u8, message, "session setup failed: TestSetupFailure"); + } + }; + var seen = false; + var vtable: abi.Host.VTable = undefined; + vtable.log = Log.log; + var session: App.Session = .{}; + var ctx: abi.Context = undefined; + ctx.host = .{ .ctx = &seen, .vtable = &vtable }; + ctx.session_root = std.mem.asBytes(&session); + ctx.session = std.testing.allocator; + ctx.store = std.testing.allocator; + const app = sketch(App); + try std.testing.expect(!app.setup(&ctx)); + defer std.testing.allocator.free(session.bytes); + try std.testing.expectEqualStrings("ready", session.bytes); + try std.testing.expectEqual(@as(u32, 1), session.calls); + try std.testing.expect(seen); +} diff --git a/src/sketch/web.zig b/src/sketch/web.zig index 3e102ad..682bff6 100644 --- a/src/sketch/web.zig +++ b/src/sketch/web.zig @@ -39,7 +39,7 @@ const js = struct { extern "gpu" fn available() u32; extern "gpu" fn newBuffer(size: u32) u32; extern "gpu" fn freeBuffer(id: u32) void; - extern "gpu" fn write(id: u32, offset: u32, ptr: [*]const u8, len: usize) void; + extern "gpu" fn write(id: u32, offset: u32, ptr: [*]const u8, len: usize) u32; /// A `Dispatch` or a `Pass`, described in JSON (see `describe`). extern "gpu" fn compute(ptr: [*]const u8, len: usize) void; extern "gpu" fn pass(ptr: [*]const u8, len: usize) void; @@ -78,6 +78,7 @@ fn Driver(comptime App: type) type { const G = root.Glue(App); const gpa = std.heap.wasm_allocator; return struct { + var ready = false; var state: G.State = undefined; var session: G.Session = undefined; // No disk on the web: the store lasts as long as the page. @@ -124,6 +125,7 @@ fn Driver(comptime App: type) type { js.canvas(G.description.width, G.description.height); const ctx = context(); G.init(&ctx, std.mem.asBytes(&state)); + ready = G.setup(&ctx); } /// The page's room for the canvas, in CSS pixels. @@ -144,6 +146,10 @@ fn Driver(comptime App: type) type { } fn frame(ms: f64) callconv(.c) void { + if (!ready) { + event_count = 0; + return; + } const now: u64 = @intFromFloat(@max(0, ms) * std.time.ns_per_ms); const dt = if (last == 0) 0 else now -| last; last = now; @@ -219,7 +225,7 @@ fn Driver(comptime App: type) type { js.push(v.key, v.samples.ptr, v.samples.len, @intFromBool(v.clear)); }, .microphone => js.listen(), - .upload => |v| js.write(@backingInt(v.buffer), v.offset, v.bytes.ptr, v.bytes.len), + .upload => |v| _ = js.write(@backingInt(v.buffer), v.offset, v.bytes.ptr, v.bytes.len), .compute => |v| { const json = describe(v); js.compute(json.ptr, json.len); @@ -243,6 +249,7 @@ fn Driver(comptime App: type) type { } fn run(line: []const u8) void { + if (!ready) return; const ctx = context(); if (G.command(&ctx, std.mem.asBytes(&state), &line) == .unknown) { var buf: [160]u8 = undefined; @@ -394,6 +401,7 @@ fn Driver(comptime App: type) type { .gpu = gpu, .newBuffer = newBuffer, .freeBuffer = freeBuffer, + .writeBuffer = writeBuffer, .imageSize = imageSize, .textSize = textSize, .loadSound = loadSound, @@ -424,6 +432,9 @@ fn Driver(comptime App: type) type { fn newBuffer(_: *anyopaque, size: u32) abi.Buffer { return @fromBackingInt(js.newBuffer(size)); } + fn writeBuffer(_: *anyopaque, b: abi.Buffer, offset: u32, bytes: []const u8) !void { + if (js.write(@backingInt(b), offset, bytes.ptr, bytes.len) == 0) return error.BufferUploadFailed; + } fn freeBuffer(_: *anyopaque, b: abi.Buffer) void { js.freeBuffer(@backingInt(b)); } diff --git a/tools/gltf_bindings.zig b/tools/gltf_bindings.zig new file mode 100644 index 0000000..59695d8 --- /dev/null +++ b/tools/gltf_bindings.zig @@ -0,0 +1,14 @@ +//! Host build tool: input glTF/GLB -> output Zig source, before app compilation. +const std = @import("std"); +const gltf = @import("gltf"); + +pub fn main(init: std.process.Init) !void { + var args = init.minimal.args.iterate(); + _ = args.skip(); + const input = args.next() orelse return error.ExpectedGltfPath; + const output = args.next() orelse return error.ExpectedZigPath; + const a = init.arena.allocator(); + const bytes = try std.Io.Dir.cwd().readFileAlloc(init.io, input, a, .limited(64 << 20)); + const source = try gltf.generate(a, bytes, input); + try std.Io.Dir.cwd().writeFile(init.io, .{ .sub_path = output, .data = source }); +} diff --git a/vendor/README.md b/vendor/README.md index 97c311d..2d01105 100644 --- a/vendor/README.md +++ b/vendor/README.md @@ -5,3 +5,6 @@ Single-file codecs, vendored unchanged; `codecs.c` compiles them for the host. | `dr_wav.h` | https://github.com/mackron/dr_libs | 0.14.6 | | `dr_flac.h` | https://github.com/mackron/dr_libs | 0.13.4 | | `stb_vorbis.c` | https://github.com/nothings/stb | v1.22 | +| `cgltf.h` | https://github.com/jkuhlmann/cgltf | 1.15, commit `85cd62382dfea638278962690cf515023f33ed00` (MIT, license in header) | + +`cgltf.c` compiles the unchanged cgltf header for the optional `gltf` module. diff --git a/vendor/cgltf.c b/vendor/cgltf.c new file mode 100644 index 0000000..ad581e3 --- /dev/null +++ b/vendor/cgltf.c @@ -0,0 +1,2 @@ +#define CGLTF_IMPLEMENTATION +#include "cgltf.h" diff --git a/vendor/cgltf.h b/vendor/cgltf.h new file mode 100644 index 0000000..316a11d --- /dev/null +++ b/vendor/cgltf.h @@ -0,0 +1,7240 @@ +/** + * cgltf - a single-file glTF 2.0 parser written in C99. + * + * Version: 1.15 + * + * Website: https://github.com/jkuhlmann/cgltf + * + * Distributed under the MIT License, see notice at the end of this file. + * + * Building: + * Include this file where you need the struct and function + * declarations. Have exactly one source file where you define + * `CGLTF_IMPLEMENTATION` before including this file to get the + * function definitions. + * + * Reference: + * `cgltf_result cgltf_parse(const cgltf_options*, const void*, + * cgltf_size, cgltf_data**)` parses both glTF and GLB data. If + * this function returns `cgltf_result_success`, you have to call + * `cgltf_free()` on the created `cgltf_data*` variable. + * Note that contents of external files for buffers and images are not + * automatically loaded. You'll need to read these files yourself using + * URIs in the `cgltf_data` structure. + * + * `cgltf_options` is the struct passed to `cgltf_parse()` to control + * parts of the parsing process. You can use it to force the file type + * and provide memory allocation as well as file operation callbacks. + * Should be zero-initialized to trigger default behavior. + * + * `cgltf_data` is the struct allocated and filled by `cgltf_parse()`. + * It generally mirrors the glTF format as described by the spec (see + * https://github.com/KhronosGroup/glTF/tree/master/specification/2.0). + * + * `void cgltf_free(cgltf_data*)` frees the allocated `cgltf_data` + * variable. + * + * `cgltf_result cgltf_load_buffers(const cgltf_options*, cgltf_data*, + * const char* gltf_path)` can be optionally called to open and read buffer + * files using the `FILE*` APIs. The `gltf_path` argument is the path to + * the original glTF file, which allows the parser to resolve the path to + * buffer files. + * + * `cgltf_result cgltf_load_buffer_base64(const cgltf_options* options, + * cgltf_size size, const char* base64, void** out_data)` decodes + * base64-encoded data content. Used internally by `cgltf_load_buffers()`. + * This is useful when decoding data URIs in images. + * + * `cgltf_result cgltf_parse_file(const cgltf_options* options, const + * char* path, cgltf_data** out_data)` can be used to open the given + * file using `FILE*` APIs and parse the data using `cgltf_parse()`. + * + * `cgltf_result cgltf_validate(cgltf_data*)` can be used to do additional + * checks to make sure the parsed glTF data is valid. + * + * `cgltf_node_transform_local` converts the translation / rotation / scale properties of a node + * into a mat4. + * + * `cgltf_node_transform_world` calls `cgltf_node_transform_local` on every ancestor in order + * to compute the root-to-node transformation. + * + * `cgltf_accessor_unpack_floats` reads in the data from an accessor, applies sparse data (if any), + * and converts them to floating point. Assumes that `cgltf_load_buffers` has already been called. + * By passing null for the output pointer, users can find out how many floats are required in the + * output buffer. + * + * `cgltf_accessor_unpack_indices` reads in the index data from an accessor. Assumes that + * `cgltf_load_buffers` has already been called. By passing null for the output pointer, users can + * find out how many indices are required in the output buffer. Returns 0 if the accessor is + * sparse or if the output component size is less than the accessor's component size. + * + * `cgltf_num_components` is a tiny utility that tells you the dimensionality of + * a certain accessor type. This can be used before `cgltf_accessor_unpack_floats` to help allocate + * the necessary amount of memory. `cgltf_component_size` and `cgltf_calc_size` exist for + * similar purposes. + * + * `cgltf_accessor_read_float` reads a certain element from a non-sparse accessor and converts it to + * floating point, assuming that `cgltf_load_buffers` has already been called. The passed-in element + * size is the number of floats in the output buffer, which should be in the range [1, 16]. Returns + * false if the passed-in element_size is too small, or if the accessor is sparse. + * + * `cgltf_accessor_read_uint` is similar to its floating-point counterpart, but limited to reading + * vector types and does not support matrix types. The passed-in element size is the number of uints + * in the output buffer, which should be in the range [1, 4]. Returns false if the passed-in + * element_size is too small, or if the accessor is sparse. + * + * `cgltf_accessor_read_index` is similar to its floating-point counterpart, but it returns size_t + * and only works with single-component data types. + * + * `cgltf_copy_extras_json` allows users to retrieve the "extras" data that can be attached to many + * glTF objects (which can be arbitrary JSON data). This is a legacy function, consider using + * cgltf_extras::data directly instead. You can parse this data using your own JSON parser + * or, if you've included the cgltf implementation using the integrated JSMN JSON parser. + */ +#ifndef CGLTF_H_INCLUDED__ +#define CGLTF_H_INCLUDED__ + +#include <stddef.h> +#include <stdint.h> /* For uint8_t, uint32_t */ + +#ifdef __cplusplus +extern "C" { +#endif + +typedef size_t cgltf_size; +typedef long long int cgltf_ssize; +typedef float cgltf_float; +typedef int cgltf_int; +typedef unsigned int cgltf_uint; +typedef int cgltf_bool; + +typedef enum cgltf_file_type +{ + cgltf_file_type_invalid, + cgltf_file_type_gltf, + cgltf_file_type_glb, + cgltf_file_type_max_enum +} cgltf_file_type; + +typedef enum cgltf_result +{ + cgltf_result_success, + cgltf_result_data_too_short, + cgltf_result_unknown_format, + cgltf_result_invalid_json, + cgltf_result_invalid_gltf, + cgltf_result_invalid_options, + cgltf_result_file_not_found, + cgltf_result_io_error, + cgltf_result_out_of_memory, + cgltf_result_legacy_gltf, + cgltf_result_max_enum +} cgltf_result; + +typedef struct cgltf_memory_options +{ + void* (*alloc_func)(void* user, cgltf_size size); + void (*free_func) (void* user, void* ptr); + void* user_data; +} cgltf_memory_options; + +typedef struct cgltf_file_options +{ + cgltf_result(*read)(const struct cgltf_memory_options* memory_options, const struct cgltf_file_options* file_options, const char* path, cgltf_size* size, void** data); + void (*release)(const struct cgltf_memory_options* memory_options, const struct cgltf_file_options* file_options, void* data, cgltf_size size); + void* user_data; +} cgltf_file_options; + +typedef struct cgltf_options +{ + cgltf_file_type type; /* invalid == auto detect */ + cgltf_size json_token_count; /* 0 == auto */ + cgltf_memory_options memory; + cgltf_file_options file; +} cgltf_options; + +typedef enum cgltf_buffer_view_type +{ + cgltf_buffer_view_type_invalid, + cgltf_buffer_view_type_indices, + cgltf_buffer_view_type_vertices, + cgltf_buffer_view_type_max_enum +} cgltf_buffer_view_type; + +typedef enum cgltf_attribute_type +{ + cgltf_attribute_type_invalid, + cgltf_attribute_type_position, + cgltf_attribute_type_normal, + cgltf_attribute_type_tangent, + cgltf_attribute_type_texcoord, + cgltf_attribute_type_color, + cgltf_attribute_type_joints, + cgltf_attribute_type_weights, + cgltf_attribute_type_custom, + cgltf_attribute_type_max_enum +} cgltf_attribute_type; + +typedef enum cgltf_component_type +{ + cgltf_component_type_invalid, + cgltf_component_type_r_8, /* BYTE */ + cgltf_component_type_r_8u, /* UNSIGNED_BYTE */ + cgltf_component_type_r_16, /* SHORT */ + cgltf_component_type_r_16u, /* UNSIGNED_SHORT */ + cgltf_component_type_r_32u, /* UNSIGNED_INT */ + cgltf_component_type_r_32f, /* FLOAT */ + cgltf_component_type_max_enum +} cgltf_component_type; + +typedef enum cgltf_type +{ + cgltf_type_invalid, + cgltf_type_scalar, + cgltf_type_vec2, + cgltf_type_vec3, + cgltf_type_vec4, + cgltf_type_mat2, + cgltf_type_mat3, + cgltf_type_mat4, + cgltf_type_max_enum +} cgltf_type; + +typedef enum cgltf_primitive_type +{ + cgltf_primitive_type_invalid, + cgltf_primitive_type_points, + cgltf_primitive_type_lines, + cgltf_primitive_type_line_loop, + cgltf_primitive_type_line_strip, + cgltf_primitive_type_triangles, + cgltf_primitive_type_triangle_strip, + cgltf_primitive_type_triangle_fan, + cgltf_primitive_type_max_enum +} cgltf_primitive_type; + +typedef enum cgltf_alpha_mode +{ + cgltf_alpha_mode_opaque, + cgltf_alpha_mode_mask, + cgltf_alpha_mode_blend, + cgltf_alpha_mode_max_enum +} cgltf_alpha_mode; + +typedef enum cgltf_animation_path_type { + cgltf_animation_path_type_invalid, + cgltf_animation_path_type_translation, + cgltf_animation_path_type_rotation, + cgltf_animation_path_type_scale, + cgltf_animation_path_type_weights, + cgltf_animation_path_type_max_enum +} cgltf_animation_path_type; + +typedef enum cgltf_interpolation_type { + cgltf_interpolation_type_linear, + cgltf_interpolation_type_step, + cgltf_interpolation_type_cubic_spline, + cgltf_interpolation_type_max_enum +} cgltf_interpolation_type; + +typedef enum cgltf_camera_type { + cgltf_camera_type_invalid, + cgltf_camera_type_perspective, + cgltf_camera_type_orthographic, + cgltf_camera_type_max_enum +} cgltf_camera_type; + +typedef enum cgltf_light_type { + cgltf_light_type_invalid, + cgltf_light_type_directional, + cgltf_light_type_point, + cgltf_light_type_spot, + cgltf_light_type_max_enum +} cgltf_light_type; + +typedef enum cgltf_data_free_method { + cgltf_data_free_method_none, + cgltf_data_free_method_file_release, + cgltf_data_free_method_memory_free, + cgltf_data_free_method_max_enum +} cgltf_data_free_method; + +typedef struct cgltf_extras { + cgltf_size start_offset; /* this field is deprecated and will be removed in the future; use data instead */ + cgltf_size end_offset; /* this field is deprecated and will be removed in the future; use data instead */ + + char* data; +} cgltf_extras; + +typedef struct cgltf_extension { + char* name; + char* data; +} cgltf_extension; + +typedef struct cgltf_buffer +{ + char* name; + cgltf_size size; + char* uri; + void* data; /* loaded by cgltf_load_buffers */ + cgltf_data_free_method data_free_method; + cgltf_extras extras; + cgltf_size extensions_count; + cgltf_extension* extensions; +} cgltf_buffer; + +typedef enum cgltf_meshopt_compression_mode { + cgltf_meshopt_compression_mode_invalid, + cgltf_meshopt_compression_mode_attributes, + cgltf_meshopt_compression_mode_triangles, + cgltf_meshopt_compression_mode_indices, + cgltf_meshopt_compression_mode_max_enum +} cgltf_meshopt_compression_mode; + +typedef enum cgltf_meshopt_compression_filter { + cgltf_meshopt_compression_filter_none, + cgltf_meshopt_compression_filter_octahedral, + cgltf_meshopt_compression_filter_quaternion, + cgltf_meshopt_compression_filter_exponential, + cgltf_meshopt_compression_filter_color, + cgltf_meshopt_compression_filter_max_enum +} cgltf_meshopt_compression_filter; + +typedef struct cgltf_meshopt_compression +{ + cgltf_buffer* buffer; + cgltf_size offset; + cgltf_size size; + cgltf_size stride; + cgltf_size count; + cgltf_meshopt_compression_mode mode; + cgltf_meshopt_compression_filter filter; + cgltf_bool is_khr; +} cgltf_meshopt_compression; + +typedef struct cgltf_buffer_view +{ + char *name; + cgltf_buffer* buffer; + cgltf_size offset; + cgltf_size size; + cgltf_size stride; /* 0 == automatically determined by accessor */ + cgltf_buffer_view_type type; + void* data; /* overrides buffer->data if present, filled by extensions */ + cgltf_bool has_meshopt_compression; + cgltf_meshopt_compression meshopt_compression; + cgltf_extras extras; + cgltf_size extensions_count; + cgltf_extension* extensions; +} cgltf_buffer_view; + +typedef struct cgltf_accessor_sparse +{ + cgltf_size count; + cgltf_buffer_view* indices_buffer_view; + cgltf_size indices_byte_offset; + cgltf_component_type indices_component_type; + cgltf_buffer_view* values_buffer_view; + cgltf_size values_byte_offset; +} cgltf_accessor_sparse; + +typedef struct cgltf_accessor +{ + char* name; + cgltf_component_type component_type; + cgltf_bool normalized; + cgltf_type type; + cgltf_size offset; + cgltf_size count; + cgltf_size stride; + cgltf_buffer_view* buffer_view; + cgltf_bool has_min; + cgltf_float min[16]; + cgltf_bool has_max; + cgltf_float max[16]; + cgltf_bool is_sparse; + cgltf_accessor_sparse sparse; + cgltf_extras extras; + cgltf_size extensions_count; + cgltf_extension* extensions; +} cgltf_accessor; + +typedef struct cgltf_attribute +{ + char* name; + cgltf_attribute_type type; + cgltf_int index; + cgltf_accessor* data; +} cgltf_attribute; + +typedef struct cgltf_image +{ + char* name; + char* uri; + cgltf_buffer_view* buffer_view; + char* mime_type; + cgltf_extras extras; + cgltf_size extensions_count; + cgltf_extension* extensions; +} cgltf_image; + +typedef enum cgltf_filter_type { + cgltf_filter_type_undefined = 0, + cgltf_filter_type_nearest = 9728, + cgltf_filter_type_linear = 9729, + cgltf_filter_type_nearest_mipmap_nearest = 9984, + cgltf_filter_type_linear_mipmap_nearest = 9985, + cgltf_filter_type_nearest_mipmap_linear = 9986, + cgltf_filter_type_linear_mipmap_linear = 9987 +} cgltf_filter_type; + +typedef enum cgltf_wrap_mode { + cgltf_wrap_mode_clamp_to_edge = 33071, + cgltf_wrap_mode_mirrored_repeat = 33648, + cgltf_wrap_mode_repeat = 10497 +} cgltf_wrap_mode; + +typedef struct cgltf_sampler +{ + char* name; + cgltf_filter_type mag_filter; + cgltf_filter_type min_filter; + cgltf_wrap_mode wrap_s; + cgltf_wrap_mode wrap_t; + cgltf_extras extras; + cgltf_size extensions_count; + cgltf_extension* extensions; +} cgltf_sampler; + +typedef struct cgltf_texture +{ + char* name; + cgltf_image* image; + cgltf_sampler* sampler; + cgltf_bool has_basisu; + cgltf_image* basisu_image; + cgltf_bool has_webp; + cgltf_image* webp_image; + cgltf_extras extras; + cgltf_size extensions_count; + cgltf_extension* extensions; +} cgltf_texture; + +typedef struct cgltf_texture_transform +{ + cgltf_float offset[2]; + cgltf_float rotation; + cgltf_float scale[2]; + cgltf_bool has_texcoord; + cgltf_int texcoord; +} cgltf_texture_transform; + +typedef struct cgltf_texture_view +{ + cgltf_texture* texture; + cgltf_int texcoord; + cgltf_float scale; /* equivalent to strength for occlusion_texture */ + cgltf_bool has_transform; + cgltf_texture_transform transform; +} cgltf_texture_view; + +typedef struct cgltf_pbr_metallic_roughness +{ + cgltf_texture_view base_color_texture; + cgltf_texture_view metallic_roughness_texture; + + cgltf_float base_color_factor[4]; + cgltf_float metallic_factor; + cgltf_float roughness_factor; +} cgltf_pbr_metallic_roughness; + +typedef struct cgltf_pbr_specular_glossiness +{ + cgltf_texture_view diffuse_texture; + cgltf_texture_view specular_glossiness_texture; + + cgltf_float diffuse_factor[4]; + cgltf_float specular_factor[3]; + cgltf_float glossiness_factor; +} cgltf_pbr_specular_glossiness; + +typedef struct cgltf_clearcoat +{ + cgltf_texture_view clearcoat_texture; + cgltf_texture_view clearcoat_roughness_texture; + cgltf_texture_view clearcoat_normal_texture; + + cgltf_float clearcoat_factor; + cgltf_float clearcoat_roughness_factor; +} cgltf_clearcoat; + +typedef struct cgltf_transmission +{ + cgltf_texture_view transmission_texture; + cgltf_float transmission_factor; +} cgltf_transmission; + +typedef struct cgltf_ior +{ + cgltf_float ior; +} cgltf_ior; + +typedef struct cgltf_specular +{ + cgltf_texture_view specular_texture; + cgltf_texture_view specular_color_texture; + cgltf_float specular_color_factor[3]; + cgltf_float specular_factor; +} cgltf_specular; + +typedef struct cgltf_volume +{ + cgltf_texture_view thickness_texture; + cgltf_float thickness_factor; + cgltf_float attenuation_color[3]; + cgltf_float attenuation_distance; +} cgltf_volume; + +typedef struct cgltf_sheen +{ + cgltf_texture_view sheen_color_texture; + cgltf_float sheen_color_factor[3]; + cgltf_texture_view sheen_roughness_texture; + cgltf_float sheen_roughness_factor; +} cgltf_sheen; + +typedef struct cgltf_emissive_strength +{ + cgltf_float emissive_strength; +} cgltf_emissive_strength; + +typedef struct cgltf_iridescence +{ + cgltf_float iridescence_factor; + cgltf_texture_view iridescence_texture; + cgltf_float iridescence_ior; + cgltf_float iridescence_thickness_min; + cgltf_float iridescence_thickness_max; + cgltf_texture_view iridescence_thickness_texture; +} cgltf_iridescence; + +typedef struct cgltf_diffuse_transmission +{ + cgltf_texture_view diffuse_transmission_texture; + cgltf_float diffuse_transmission_factor; + cgltf_float diffuse_transmission_color_factor[3]; + cgltf_texture_view diffuse_transmission_color_texture; +} cgltf_diffuse_transmission; + +typedef struct cgltf_anisotropy +{ + cgltf_float anisotropy_strength; + cgltf_float anisotropy_rotation; + cgltf_texture_view anisotropy_texture; +} cgltf_anisotropy; + +typedef struct cgltf_dispersion +{ + cgltf_float dispersion; +} cgltf_dispersion; + +typedef struct cgltf_material +{ + char* name; + cgltf_bool has_pbr_metallic_roughness; + cgltf_bool has_pbr_specular_glossiness; + cgltf_bool has_clearcoat; + cgltf_bool has_transmission; + cgltf_bool has_volume; + cgltf_bool has_ior; + cgltf_bool has_specular; + cgltf_bool has_sheen; + cgltf_bool has_emissive_strength; + cgltf_bool has_iridescence; + cgltf_bool has_diffuse_transmission; + cgltf_bool has_anisotropy; + cgltf_bool has_dispersion; + cgltf_pbr_metallic_roughness pbr_metallic_roughness; + cgltf_pbr_specular_glossiness pbr_specular_glossiness; + cgltf_clearcoat clearcoat; + cgltf_ior ior; + cgltf_specular specular; + cgltf_sheen sheen; + cgltf_transmission transmission; + cgltf_volume volume; + cgltf_emissive_strength emissive_strength; + cgltf_iridescence iridescence; + cgltf_diffuse_transmission diffuse_transmission; + cgltf_anisotropy anisotropy; + cgltf_dispersion dispersion; + cgltf_texture_view normal_texture; + cgltf_texture_view occlusion_texture; + cgltf_texture_view emissive_texture; + cgltf_float emissive_factor[3]; + cgltf_alpha_mode alpha_mode; + cgltf_float alpha_cutoff; + cgltf_bool double_sided; + cgltf_bool unlit; + cgltf_extras extras; + cgltf_size extensions_count; + cgltf_extension* extensions; +} cgltf_material; + +typedef struct cgltf_material_mapping +{ + cgltf_size variant; + cgltf_material* material; + cgltf_extras extras; +} cgltf_material_mapping; + +typedef struct cgltf_morph_target { + cgltf_attribute* attributes; + cgltf_size attributes_count; +} cgltf_morph_target; + +typedef struct cgltf_draco_mesh_compression { + cgltf_buffer_view* buffer_view; + cgltf_attribute* attributes; + cgltf_size attributes_count; +} cgltf_draco_mesh_compression; + +typedef struct cgltf_mesh_gpu_instancing { + cgltf_attribute* attributes; + cgltf_size attributes_count; +} cgltf_mesh_gpu_instancing; + +typedef struct cgltf_primitive { + cgltf_primitive_type type; + cgltf_accessor* indices; + cgltf_material* material; + cgltf_attribute* attributes; + cgltf_size attributes_count; + cgltf_morph_target* targets; + cgltf_size targets_count; + cgltf_extras extras; + cgltf_bool has_draco_mesh_compression; + cgltf_draco_mesh_compression draco_mesh_compression; + cgltf_material_mapping* mappings; + cgltf_size mappings_count; + cgltf_size extensions_count; + cgltf_extension* extensions; +} cgltf_primitive; + +typedef struct cgltf_mesh { + char* name; + cgltf_primitive* primitives; + cgltf_size primitives_count; + cgltf_float* weights; + cgltf_size weights_count; + char** target_names; + cgltf_size target_names_count; + cgltf_extras extras; + cgltf_size extensions_count; + cgltf_extension* extensions; +} cgltf_mesh; + +typedef struct cgltf_node cgltf_node; + +typedef struct cgltf_skin { + char* name; + cgltf_node** joints; + cgltf_size joints_count; + cgltf_node* skeleton; + cgltf_accessor* inverse_bind_matrices; + cgltf_extras extras; + cgltf_size extensions_count; + cgltf_extension* extensions; +} cgltf_skin; + +typedef struct cgltf_camera_perspective { + cgltf_bool has_aspect_ratio; + cgltf_float aspect_ratio; + cgltf_float yfov; + cgltf_bool has_zfar; + cgltf_float zfar; + cgltf_float znear; + cgltf_extras extras; +} cgltf_camera_perspective; + +typedef struct cgltf_camera_orthographic { + cgltf_float xmag; + cgltf_float ymag; + cgltf_float zfar; + cgltf_float znear; + cgltf_extras extras; +} cgltf_camera_orthographic; + +typedef struct cgltf_camera { + char* name; + cgltf_camera_type type; + union { + cgltf_camera_perspective perspective; + cgltf_camera_orthographic orthographic; + } data; + cgltf_extras extras; + cgltf_size extensions_count; + cgltf_extension* extensions; +} cgltf_camera; + +typedef struct cgltf_light { + char* name; + cgltf_float color[3]; + cgltf_float intensity; + cgltf_light_type type; + cgltf_float range; + cgltf_float spot_inner_cone_angle; + cgltf_float spot_outer_cone_angle; + cgltf_extras extras; +} cgltf_light; + +struct cgltf_node { + char* name; + cgltf_node* parent; + cgltf_node** children; + cgltf_size children_count; + cgltf_skin* skin; + cgltf_mesh* mesh; + cgltf_camera* camera; + cgltf_light* light; + cgltf_float* weights; + cgltf_size weights_count; + cgltf_bool has_translation; + cgltf_bool has_rotation; + cgltf_bool has_scale; + cgltf_bool has_matrix; + cgltf_float translation[3]; + cgltf_float rotation[4]; + cgltf_float scale[3]; + cgltf_float matrix[16]; + cgltf_extras extras; + cgltf_bool has_mesh_gpu_instancing; + cgltf_mesh_gpu_instancing mesh_gpu_instancing; + cgltf_size extensions_count; + cgltf_extension* extensions; +}; + +typedef struct cgltf_scene { + char* name; + cgltf_node** nodes; + cgltf_size nodes_count; + cgltf_extras extras; + cgltf_size extensions_count; + cgltf_extension* extensions; +} cgltf_scene; + +typedef struct cgltf_animation_sampler { + cgltf_accessor* input; + cgltf_accessor* output; + cgltf_interpolation_type interpolation; + cgltf_extras extras; + cgltf_size extensions_count; + cgltf_extension* extensions; +} cgltf_animation_sampler; + +typedef struct cgltf_animation_channel { + cgltf_animation_sampler* sampler; + cgltf_node* target_node; + cgltf_animation_path_type target_path; + cgltf_extras extras; + cgltf_size extensions_count; + cgltf_extension* extensions; +} cgltf_animation_channel; + +typedef struct cgltf_animation { + char* name; + cgltf_animation_sampler* samplers; + cgltf_size samplers_count; + cgltf_animation_channel* channels; + cgltf_size channels_count; + cgltf_extras extras; + cgltf_size extensions_count; + cgltf_extension* extensions; +} cgltf_animation; + +typedef struct cgltf_material_variant +{ + char* name; + cgltf_extras extras; +} cgltf_material_variant; + +typedef struct cgltf_asset { + char* copyright; + char* generator; + char* version; + char* min_version; + cgltf_extras extras; + cgltf_size extensions_count; + cgltf_extension* extensions; +} cgltf_asset; + +typedef struct cgltf_data +{ + cgltf_file_type file_type; + void* file_data; + cgltf_size file_size; + + cgltf_asset asset; + + cgltf_mesh* meshes; + cgltf_size meshes_count; + + cgltf_material* materials; + cgltf_size materials_count; + + cgltf_accessor* accessors; + cgltf_size accessors_count; + + cgltf_buffer_view* buffer_views; + cgltf_size buffer_views_count; + + cgltf_buffer* buffers; + cgltf_size buffers_count; + + cgltf_image* images; + cgltf_size images_count; + + cgltf_texture* textures; + cgltf_size textures_count; + + cgltf_sampler* samplers; + cgltf_size samplers_count; + + cgltf_skin* skins; + cgltf_size skins_count; + + cgltf_camera* cameras; + cgltf_size cameras_count; + + cgltf_light* lights; + cgltf_size lights_count; + + cgltf_node* nodes; + cgltf_size nodes_count; + + cgltf_scene* scenes; + cgltf_size scenes_count; + + cgltf_scene* scene; + + cgltf_animation* animations; + cgltf_size animations_count; + + cgltf_material_variant* variants; + cgltf_size variants_count; + + cgltf_extras extras; + + cgltf_size data_extensions_count; + cgltf_extension* data_extensions; + + char** extensions_used; + cgltf_size extensions_used_count; + + char** extensions_required; + cgltf_size extensions_required_count; + + const char* json; + cgltf_size json_size; + + const void* bin; + cgltf_size bin_size; + + cgltf_memory_options memory; + cgltf_file_options file; +} cgltf_data; + +cgltf_result cgltf_parse( + const cgltf_options* options, + const void* data, + cgltf_size size, + cgltf_data** out_data); + +cgltf_result cgltf_parse_file( + const cgltf_options* options, + const char* path, + cgltf_data** out_data); + +cgltf_result cgltf_load_buffers( + const cgltf_options* options, + cgltf_data* data, + const char* gltf_path); + +cgltf_result cgltf_load_buffer_base64(const cgltf_options* options, cgltf_size size, const char* base64, void** out_data); + +cgltf_size cgltf_decode_string(char* string); +cgltf_size cgltf_decode_uri(char* uri); + +cgltf_result cgltf_validate(cgltf_data* data); + +void cgltf_free(cgltf_data* data); + +void cgltf_node_transform_local(const cgltf_node* node, cgltf_float* out_matrix); +void cgltf_node_transform_world(const cgltf_node* node, cgltf_float* out_matrix); + +const uint8_t* cgltf_buffer_view_data(const cgltf_buffer_view* view); + +const cgltf_accessor* cgltf_find_accessor(const cgltf_primitive* prim, cgltf_attribute_type type, cgltf_int index); + +cgltf_bool cgltf_accessor_read_float(const cgltf_accessor* accessor, cgltf_size index, cgltf_float* out, cgltf_size element_size); +cgltf_bool cgltf_accessor_read_uint(const cgltf_accessor* accessor, cgltf_size index, cgltf_uint* out, cgltf_size element_size); +cgltf_size cgltf_accessor_read_index(const cgltf_accessor* accessor, cgltf_size index); + +cgltf_size cgltf_num_components(cgltf_type type); +cgltf_size cgltf_component_size(cgltf_component_type component_type); +cgltf_size cgltf_calc_size(cgltf_type type, cgltf_component_type component_type); + +cgltf_size cgltf_accessor_unpack_floats(const cgltf_accessor* accessor, cgltf_float* out, cgltf_size float_count); +cgltf_size cgltf_accessor_unpack_indices(const cgltf_accessor* accessor, void* out, cgltf_size out_component_size, cgltf_size index_count); + +/* this function is deprecated and will be removed in the future; use cgltf_extras::data instead */ +cgltf_result cgltf_copy_extras_json(const cgltf_data* data, const cgltf_extras* extras, char* dest, cgltf_size* dest_size); + +cgltf_size cgltf_mesh_index(const cgltf_data* data, const cgltf_mesh* object); +cgltf_size cgltf_material_index(const cgltf_data* data, const cgltf_material* object); +cgltf_size cgltf_accessor_index(const cgltf_data* data, const cgltf_accessor* object); +cgltf_size cgltf_buffer_view_index(const cgltf_data* data, const cgltf_buffer_view* object); +cgltf_size cgltf_buffer_index(const cgltf_data* data, const cgltf_buffer* object); +cgltf_size cgltf_image_index(const cgltf_data* data, const cgltf_image* object); +cgltf_size cgltf_texture_index(const cgltf_data* data, const cgltf_texture* object); +cgltf_size cgltf_sampler_index(const cgltf_data* data, const cgltf_sampler* object); +cgltf_size cgltf_skin_index(const cgltf_data* data, const cgltf_skin* object); +cgltf_size cgltf_camera_index(const cgltf_data* data, const cgltf_camera* object); +cgltf_size cgltf_light_index(const cgltf_data* data, const cgltf_light* object); +cgltf_size cgltf_node_index(const cgltf_data* data, const cgltf_node* object); +cgltf_size cgltf_scene_index(const cgltf_data* data, const cgltf_scene* object); +cgltf_size cgltf_animation_index(const cgltf_data* data, const cgltf_animation* object); +cgltf_size cgltf_animation_sampler_index(const cgltf_animation* animation, const cgltf_animation_sampler* object); +cgltf_size cgltf_animation_channel_index(const cgltf_animation* animation, const cgltf_animation_channel* object); + +#ifdef __cplusplus +} +#endif + +#endif /* #ifndef CGLTF_H_INCLUDED__ */ + +/* + * + * Stop now, if you are only interested in the API. + * Below, you find the implementation. + * + */ + +#if defined(__INTELLISENSE__) || defined(__JETBRAINS_IDE__) +/* This makes MSVC/CLion intellisense work. */ +#define CGLTF_IMPLEMENTATION +#endif + +#ifdef CGLTF_IMPLEMENTATION + +#include <assert.h> /* For assert */ +#include <string.h> /* For strncpy */ +#include <stdio.h> /* For fopen */ +#include <limits.h> /* For UINT_MAX etc */ +#include <float.h> /* For FLT_MAX */ + +#if !defined(CGLTF_MALLOC) || !defined(CGLTF_FREE) || !defined(CGLTF_ATOI) || !defined(CGLTF_ATOF) || !defined(CGLTF_ATOLL) +#include <stdlib.h> /* For malloc, free, atoi, atof */ +#endif + +/* JSMN_PARENT_LINKS is necessary to make parsing large structures linear in input size */ +#define JSMN_PARENT_LINKS + +/* JSMN_STRICT is necessary to reject invalid JSON documents */ +#define JSMN_STRICT + +/* + * -- jsmn.h start -- + * Source: https://github.com/zserge/jsmn + * License: MIT + */ +typedef enum { + JSMN_UNDEFINED = 0, + JSMN_OBJECT = 1, + JSMN_ARRAY = 2, + JSMN_STRING = 3, + JSMN_PRIMITIVE = 4 +} jsmntype_t; +enum jsmnerr { + /* Not enough tokens were provided */ + JSMN_ERROR_NOMEM = -1, + /* Invalid character inside JSON string */ + JSMN_ERROR_INVAL = -2, + /* The string is not a full JSON packet, more bytes expected */ + JSMN_ERROR_PART = -3 +}; +typedef struct { + jsmntype_t type; + ptrdiff_t start; + ptrdiff_t end; + int size; +#ifdef JSMN_PARENT_LINKS + int parent; +#endif +} jsmntok_t; +typedef struct { + size_t pos; /* offset in the JSON string */ + unsigned int toknext; /* next token to allocate */ + int toksuper; /* superior token node, e.g parent object or array */ +} jsmn_parser; +static void jsmn_init(jsmn_parser *parser); +static int jsmn_parse(jsmn_parser *parser, const char *js, size_t len, jsmntok_t *tokens, size_t num_tokens); +/* + * -- jsmn.h end -- + */ + + +#ifndef CGLTF_CONSTS +#define GlbHeaderSize 12 +#define GlbChunkHeaderSize 8 +static const uint32_t GlbVersion = 2; +static const uint32_t GlbMagic = 0x46546C67; +static const uint32_t GlbMagicJsonChunk = 0x4E4F534A; +static const uint32_t GlbMagicBinChunk = 0x004E4942; +#define CGLTF_CONSTS +#endif + +#ifndef CGLTF_MALLOC +#define CGLTF_MALLOC(size) malloc(size) +#endif +#ifndef CGLTF_FREE +#define CGLTF_FREE(ptr) free(ptr) +#endif +#ifndef CGLTF_ATOI +#define CGLTF_ATOI(str) atoi(str) +#endif +#ifndef CGLTF_ATOF +#define CGLTF_ATOF(str) atof(str) +#endif +#ifndef CGLTF_ATOLL +#define CGLTF_ATOLL(str) atoll(str) +#endif +#ifndef CGLTF_VALIDATE_ENABLE_ASSERTS +#define CGLTF_VALIDATE_ENABLE_ASSERTS 0 +#endif + +static void* cgltf_default_alloc(void* user, cgltf_size size) +{ + (void)user; + return CGLTF_MALLOC(size); +} + +static void cgltf_default_free(void* user, void* ptr) +{ + (void)user; + CGLTF_FREE(ptr); +} + +static void* cgltf_calloc(cgltf_options* options, size_t element_size, cgltf_size count) +{ + if (SIZE_MAX / element_size < count) + { + return NULL; + } + void* result = options->memory.alloc_func(options->memory.user_data, element_size * count); + if (!result) + { + return NULL; + } + memset(result, 0, element_size * count); + return result; +} + +static cgltf_result cgltf_default_file_read(const struct cgltf_memory_options* memory_options, const struct cgltf_file_options* file_options, const char* path, cgltf_size* size, void** data) +{ + (void)file_options; + void* (*memory_alloc)(void*, cgltf_size) = memory_options->alloc_func ? memory_options->alloc_func : &cgltf_default_alloc; + void (*memory_free)(void*, void*) = memory_options->free_func ? memory_options->free_func : &cgltf_default_free; + + FILE* file = fopen(path, "rb"); + if (!file) + { + return cgltf_result_file_not_found; + } + + cgltf_size file_size = size ? *size : 0; + + if (file_size == 0) + { + fseek(file, 0, SEEK_END); + +#ifdef _MSC_VER + __int64 length = _ftelli64(file); +#else + long length = ftell(file); +#endif + + if (length < 0) + { + fclose(file); + return cgltf_result_io_error; + } + + fseek(file, 0, SEEK_SET); + file_size = (cgltf_size)length; + } + + char* file_data = (char*)memory_alloc(memory_options->user_data, file_size); + if (!file_data) + { + fclose(file); + return cgltf_result_out_of_memory; + } + + cgltf_size read_size = fread(file_data, 1, file_size, file); + + fclose(file); + + if (read_size != file_size) + { + memory_free(memory_options->user_data, file_data); + return cgltf_result_io_error; + } + + if (size) + { + *size = file_size; + } + if (data) + { + *data = file_data; + } + + return cgltf_result_success; +} + +static void cgltf_default_file_release(const struct cgltf_memory_options* memory_options, const struct cgltf_file_options* file_options, void* data, cgltf_size size) +{ + (void)file_options; + (void)size; + void (*memfree)(void*, void*) = memory_options->free_func ? memory_options->free_func : &cgltf_default_free; + memfree(memory_options->user_data, data); +} + +static cgltf_result cgltf_parse_json(cgltf_options* options, const uint8_t* json_chunk, cgltf_size size, cgltf_data** out_data); + +cgltf_result cgltf_parse(const cgltf_options* options, const void* data, cgltf_size size, cgltf_data** out_data) +{ + if (size < GlbHeaderSize) + { + return cgltf_result_data_too_short; + } + + if (options == NULL) + { + return cgltf_result_invalid_options; + } + + cgltf_options fixed_options = *options; + if (fixed_options.memory.alloc_func == NULL) + { + fixed_options.memory.alloc_func = &cgltf_default_alloc; + } + if (fixed_options.memory.free_func == NULL) + { + fixed_options.memory.free_func = &cgltf_default_free; + } + + uint32_t tmp; + // Magic + memcpy(&tmp, data, 4); + if (tmp != GlbMagic) + { + if (fixed_options.type == cgltf_file_type_invalid) + { + fixed_options.type = cgltf_file_type_gltf; + } + else if (fixed_options.type == cgltf_file_type_glb) + { + return cgltf_result_unknown_format; + } + } + + if (fixed_options.type == cgltf_file_type_gltf) + { + cgltf_result json_result = cgltf_parse_json(&fixed_options, (const uint8_t*)data, size, out_data); + if (json_result != cgltf_result_success) + { + return json_result; + } + + (*out_data)->file_type = cgltf_file_type_gltf; + + return cgltf_result_success; + } + + const uint8_t* ptr = (const uint8_t*)data; + // Version + memcpy(&tmp, ptr + 4, 4); + uint32_t version = tmp; + if (version != GlbVersion) + { + return version < GlbVersion ? cgltf_result_legacy_gltf : cgltf_result_unknown_format; + } + + // Total length + memcpy(&tmp, ptr + 8, 4); + if (tmp > size) + { + return cgltf_result_data_too_short; + } + + const uint8_t* json_chunk = ptr + GlbHeaderSize; + + if (GlbHeaderSize + GlbChunkHeaderSize > size) + { + return cgltf_result_data_too_short; + } + + // JSON chunk: length + uint32_t json_length; + memcpy(&json_length, json_chunk, 4); + if (json_length > size - GlbHeaderSize - GlbChunkHeaderSize) + { + return cgltf_result_data_too_short; + } + + // JSON chunk: magic + memcpy(&tmp, json_chunk + 4, 4); + if (tmp != GlbMagicJsonChunk) + { + return cgltf_result_unknown_format; + } + + json_chunk += GlbChunkHeaderSize; + + const void* bin = NULL; + cgltf_size bin_size = 0; + + if (GlbChunkHeaderSize <= size - GlbHeaderSize - GlbChunkHeaderSize - json_length) + { + // We can read another chunk + const uint8_t* bin_chunk = json_chunk + json_length; + + // Bin chunk: length + uint32_t bin_length; + memcpy(&bin_length, bin_chunk, 4); + if (bin_length > size - GlbHeaderSize - GlbChunkHeaderSize - json_length - GlbChunkHeaderSize) + { + return cgltf_result_data_too_short; + } + + // Bin chunk: magic + memcpy(&tmp, bin_chunk + 4, 4); + if (tmp != GlbMagicBinChunk) + { + return cgltf_result_unknown_format; + } + + bin_chunk += GlbChunkHeaderSize; + + bin = bin_chunk; + bin_size = bin_length; + } + + cgltf_result json_result = cgltf_parse_json(&fixed_options, json_chunk, json_length, out_data); + if (json_result != cgltf_result_success) + { + return json_result; + } + + (*out_data)->file_type = cgltf_file_type_glb; + (*out_data)->bin = bin; + (*out_data)->bin_size = bin_size; + + return cgltf_result_success; +} + +cgltf_result cgltf_parse_file(const cgltf_options* options, const char* path, cgltf_data** out_data) +{ + if (options == NULL) + { + return cgltf_result_invalid_options; + } + + cgltf_result (*file_read)(const struct cgltf_memory_options*, const struct cgltf_file_options*, const char*, cgltf_size*, void**) = options->file.read ? options->file.read : &cgltf_default_file_read; + void (*file_release)(const struct cgltf_memory_options*, const struct cgltf_file_options*, void* data, cgltf_size size) = options->file.release ? options->file.release : cgltf_default_file_release; + + void* file_data = NULL; + cgltf_size file_size = 0; + cgltf_result result = file_read(&options->memory, &options->file, path, &file_size, &file_data); + if (result != cgltf_result_success) + { + return result; + } + + result = cgltf_parse(options, file_data, file_size, out_data); + + if (result != cgltf_result_success) + { + file_release(&options->memory, &options->file, file_data, file_size); + return result; + } + + (*out_data)->file_data = file_data; + (*out_data)->file_size = file_size; + + return cgltf_result_success; +} + +static void cgltf_combine_paths(char* path, const char* base, const char* uri) +{ + const char* s0 = strrchr(base, '/'); + const char* s1 = strrchr(base, '\\'); + const char* slash = s0 ? (s1 && s1 > s0 ? s1 : s0) : s1; + + if (slash) + { + size_t prefix = slash - base + 1; + + strncpy(path, base, prefix); + strcpy(path + prefix, uri); + } + else + { + strcpy(path, uri); + } +} + +static cgltf_result cgltf_load_buffer_file(const cgltf_options* options, cgltf_size size, const char* uri, const char* gltf_path, void** out_data) +{ + void* (*memory_alloc)(void*, cgltf_size) = options->memory.alloc_func ? options->memory.alloc_func : &cgltf_default_alloc; + void (*memory_free)(void*, void*) = options->memory.free_func ? options->memory.free_func : &cgltf_default_free; + cgltf_result (*file_read)(const struct cgltf_memory_options*, const struct cgltf_file_options*, const char*, cgltf_size*, void**) = options->file.read ? options->file.read : &cgltf_default_file_read; + + char* path = (char*)memory_alloc(options->memory.user_data, strlen(uri) + strlen(gltf_path) + 1); + if (!path) + { + return cgltf_result_out_of_memory; + } + + cgltf_combine_paths(path, gltf_path, uri); + + // after combining, the tail of the resulting path is a uri; decode_uri converts it into path + cgltf_decode_uri(path + strlen(path) - strlen(uri)); + + void* file_data = NULL; + cgltf_result result = file_read(&options->memory, &options->file, path, &size, &file_data); + + memory_free(options->memory.user_data, path); + + *out_data = (result == cgltf_result_success) ? file_data : NULL; + + return result; +} + +cgltf_result cgltf_load_buffer_base64(const cgltf_options* options, cgltf_size size, const char* base64, void** out_data) +{ + void* (*memory_alloc)(void*, cgltf_size) = options->memory.alloc_func ? options->memory.alloc_func : &cgltf_default_alloc; + void (*memory_free)(void*, void*) = options->memory.free_func ? options->memory.free_func : &cgltf_default_free; + + unsigned char* data = (unsigned char*)memory_alloc(options->memory.user_data, size); + if (!data) + { + return cgltf_result_out_of_memory; + } + + unsigned int buffer = 0; + unsigned int buffer_bits = 0; + + for (cgltf_size i = 0; i < size; ++i) + { + while (buffer_bits < 8) + { + char ch = *base64++; + + int index = + (unsigned)(ch - 'A') < 26 ? (ch - 'A') : + (unsigned)(ch - 'a') < 26 ? (ch - 'a') + 26 : + (unsigned)(ch - '0') < 10 ? (ch - '0') + 52 : + ch == '+' ? 62 : + ch == '/' ? 63 : + -1; + + if (index < 0) + { + memory_free(options->memory.user_data, data); + return cgltf_result_io_error; + } + + buffer = (buffer << 6) | index; + buffer_bits += 6; + } + + data[i] = (unsigned char)(buffer >> (buffer_bits - 8)); + buffer_bits -= 8; + } + + *out_data = data; + + return cgltf_result_success; +} + +static int cgltf_unhex(char ch) +{ + return + (unsigned)(ch - '0') < 10 ? (ch - '0') : + (unsigned)(ch - 'A') < 6 ? (ch - 'A') + 10 : + (unsigned)(ch - 'a') < 6 ? (ch - 'a') + 10 : + -1; +} + +cgltf_size cgltf_decode_string(char* string) +{ + char* read = string + strcspn(string, "\\"); + if (*read == 0) + { + return read - string; + } + char* write = string; + char* last = string; + + for (;;) + { + // Copy characters since last escaped sequence + cgltf_size written = read - last; + memmove(write, last, written); + write += written; + + if (*read++ == 0) + { + break; + } + + // jsmn already checked that all escape sequences are valid + switch (*read++) + { + case '\"': *write++ = '\"'; break; + case '/': *write++ = '/'; break; + case '\\': *write++ = '\\'; break; + case 'b': *write++ = '\b'; break; + case 'f': *write++ = '\f'; break; + case 'r': *write++ = '\r'; break; + case 'n': *write++ = '\n'; break; + case 't': *write++ = '\t'; break; + case 'u': + { + // UCS-2 codepoint \uXXXX to UTF-8 + int character = 0; + for (cgltf_size i = 0; i < 4; ++i) + { + character = (character << 4) + cgltf_unhex(*read++); + } + + if (character <= 0x7F) + { + *write++ = character & 0xFF; + } + else if (character <= 0x7FF) + { + *write++ = 0xC0 | ((character >> 6) & 0xFF); + *write++ = 0x80 | (character & 0x3F); + } + else + { + *write++ = 0xE0 | ((character >> 12) & 0xFF); + *write++ = 0x80 | ((character >> 6) & 0x3F); + *write++ = 0x80 | (character & 0x3F); + } + break; + } + default: + break; + } + + last = read; + read += strcspn(read, "\\"); + } + + *write = 0; + return write - string; +} + +cgltf_size cgltf_decode_uri(char* uri) +{ + char* write = uri; + char* i = uri; + + while (*i) + { + if (*i == '%') + { + int ch1 = cgltf_unhex(i[1]); + + if (ch1 >= 0) + { + int ch2 = cgltf_unhex(i[2]); + + if (ch2 >= 0) + { + *write++ = (char)(ch1 * 16 + ch2); + i += 3; + continue; + } + } + } + + *write++ = *i++; + } + + *write = 0; + return write - uri; +} + +cgltf_result cgltf_load_buffers(const cgltf_options* options, cgltf_data* data, const char* gltf_path) +{ + if (options == NULL) + { + return cgltf_result_invalid_options; + } + + if (data->buffers_count && data->buffers[0].data == NULL && data->buffers[0].uri == NULL && data->bin) + { + if (data->bin_size < data->buffers[0].size) + { + return cgltf_result_data_too_short; + } + + data->buffers[0].data = (void*)data->bin; + data->buffers[0].data_free_method = cgltf_data_free_method_none; + } + + for (cgltf_size i = 0; i < data->buffers_count; ++i) + { + if (data->buffers[i].data) + { + continue; + } + + const char* uri = data->buffers[i].uri; + + if (uri == NULL) + { + continue; + } + + if (strncmp(uri, "data:", 5) == 0) + { + const char* comma = strchr(uri, ','); + + if (comma && comma - uri >= 7 && strncmp(comma - 7, ";base64", 7) == 0) + { + cgltf_result res = cgltf_load_buffer_base64(options, data->buffers[i].size, comma + 1, &data->buffers[i].data); + data->buffers[i].data_free_method = cgltf_data_free_method_memory_free; + + if (res != cgltf_result_success) + { + return res; + } + } + else + { + return cgltf_result_unknown_format; + } + } + else if (strstr(uri, "://") == NULL && gltf_path) + { + cgltf_result res = cgltf_load_buffer_file(options, data->buffers[i].size, uri, gltf_path, &data->buffers[i].data); + data->buffers[i].data_free_method = cgltf_data_free_method_file_release; + + if (res != cgltf_result_success) + { + return res; + } + } + else + { + return cgltf_result_unknown_format; + } + } + + return cgltf_result_success; +} + +static cgltf_size cgltf_calc_index_bound(cgltf_buffer_view* buffer_view, cgltf_size offset, cgltf_component_type component_type, cgltf_size count) +{ + char* data = (char*)buffer_view->buffer->data + offset + buffer_view->offset; + cgltf_size bound = 0; + + switch (component_type) + { + case cgltf_component_type_r_8u: + for (size_t i = 0; i < count; ++i) + { + cgltf_size v = ((unsigned char*)data)[i]; + bound = bound > v ? bound : v; + } + break; + + case cgltf_component_type_r_16u: + for (size_t i = 0; i < count; ++i) + { + cgltf_size v = ((unsigned short*)data)[i]; + bound = bound > v ? bound : v; + } + break; + + case cgltf_component_type_r_32u: + for (size_t i = 0; i < count; ++i) + { + cgltf_size v = ((unsigned int*)data)[i]; + bound = bound > v ? bound : v; + } + break; + + default: + ; + } + + return bound; +} + +#if CGLTF_VALIDATE_ENABLE_ASSERTS +#define CGLTF_ASSERT_IF(cond, result) assert(!(cond)); if (cond) return result; +#else +#define CGLTF_ASSERT_IF(cond, result) if (cond) return result; +#endif + +cgltf_result cgltf_validate(cgltf_data* data) +{ + for (cgltf_size i = 0; i < data->accessors_count; ++i) + { + cgltf_accessor* accessor = &data->accessors[i]; + + CGLTF_ASSERT_IF(data->accessors[i].component_type == cgltf_component_type_invalid, cgltf_result_invalid_gltf); + CGLTF_ASSERT_IF(data->accessors[i].type == cgltf_type_invalid, cgltf_result_invalid_gltf); + + cgltf_size element_size = cgltf_calc_size(accessor->type, accessor->component_type); + + if (accessor->buffer_view) + { + cgltf_size req_size = accessor->offset + accessor->stride * (accessor->count - 1) + element_size; + + CGLTF_ASSERT_IF(accessor->buffer_view->size < req_size, cgltf_result_data_too_short); + } + + if (accessor->is_sparse) + { + cgltf_accessor_sparse* sparse = &accessor->sparse; + + cgltf_size indices_component_size = cgltf_component_size(sparse->indices_component_type); + cgltf_size indices_req_size = sparse->indices_byte_offset + indices_component_size * sparse->count; + cgltf_size values_req_size = sparse->values_byte_offset + element_size * sparse->count; + + CGLTF_ASSERT_IF(sparse->indices_buffer_view->size < indices_req_size || + sparse->values_buffer_view->size < values_req_size, cgltf_result_data_too_short); + + CGLTF_ASSERT_IF(sparse->indices_component_type != cgltf_component_type_r_8u && + sparse->indices_component_type != cgltf_component_type_r_16u && + sparse->indices_component_type != cgltf_component_type_r_32u, cgltf_result_invalid_gltf); + + if (sparse->indices_buffer_view->buffer->data) + { + cgltf_size index_bound = cgltf_calc_index_bound(sparse->indices_buffer_view, sparse->indices_byte_offset, sparse->indices_component_type, sparse->count); + + CGLTF_ASSERT_IF(index_bound >= accessor->count, cgltf_result_data_too_short); + } + } + } + + for (cgltf_size i = 0; i < data->buffer_views_count; ++i) + { + cgltf_size req_size = data->buffer_views[i].offset + data->buffer_views[i].size; + + CGLTF_ASSERT_IF(data->buffer_views[i].buffer && data->buffer_views[i].buffer->size < req_size, cgltf_result_data_too_short); + + if (data->buffer_views[i].has_meshopt_compression) + { + cgltf_meshopt_compression* mc = &data->buffer_views[i].meshopt_compression; + + CGLTF_ASSERT_IF(mc->buffer == NULL || mc->buffer->size < mc->offset + mc->size, cgltf_result_data_too_short); + + CGLTF_ASSERT_IF(data->buffer_views[i].stride && mc->stride != data->buffer_views[i].stride, cgltf_result_invalid_gltf); + + CGLTF_ASSERT_IF(data->buffer_views[i].size != mc->stride * mc->count, cgltf_result_invalid_gltf); + + CGLTF_ASSERT_IF(mc->mode == cgltf_meshopt_compression_mode_invalid, cgltf_result_invalid_gltf); + + CGLTF_ASSERT_IF(mc->mode == cgltf_meshopt_compression_mode_attributes && !(mc->stride % 4 == 0 && mc->stride <= 256), cgltf_result_invalid_gltf); + + CGLTF_ASSERT_IF(mc->mode == cgltf_meshopt_compression_mode_triangles && mc->count % 3 != 0, cgltf_result_invalid_gltf); + + CGLTF_ASSERT_IF((mc->mode == cgltf_meshopt_compression_mode_triangles || mc->mode == cgltf_meshopt_compression_mode_indices) && mc->stride != 2 && mc->stride != 4, cgltf_result_invalid_gltf); + + CGLTF_ASSERT_IF((mc->mode == cgltf_meshopt_compression_mode_triangles || mc->mode == cgltf_meshopt_compression_mode_indices) && mc->filter != cgltf_meshopt_compression_filter_none, cgltf_result_invalid_gltf); + + CGLTF_ASSERT_IF(mc->filter == cgltf_meshopt_compression_filter_octahedral && mc->stride != 4 && mc->stride != 8, cgltf_result_invalid_gltf); + CGLTF_ASSERT_IF(mc->filter == cgltf_meshopt_compression_filter_quaternion && mc->stride != 8, cgltf_result_invalid_gltf); + CGLTF_ASSERT_IF(mc->filter == cgltf_meshopt_compression_filter_color && mc->stride != 4 && mc->stride != 8, cgltf_result_invalid_gltf); + } + } + + for (cgltf_size i = 0; i < data->meshes_count; ++i) + { + if (data->meshes[i].weights) + { + CGLTF_ASSERT_IF(data->meshes[i].primitives_count && data->meshes[i].primitives[0].targets_count != data->meshes[i].weights_count, cgltf_result_invalid_gltf); + } + + if (data->meshes[i].target_names) + { + CGLTF_ASSERT_IF(data->meshes[i].primitives_count && data->meshes[i].primitives[0].targets_count != data->meshes[i].target_names_count, cgltf_result_invalid_gltf); + } + + for (cgltf_size j = 0; j < data->meshes[i].primitives_count; ++j) + { + CGLTF_ASSERT_IF(data->meshes[i].primitives[j].type == cgltf_primitive_type_invalid, cgltf_result_invalid_gltf); + CGLTF_ASSERT_IF(data->meshes[i].primitives[j].targets_count != data->meshes[i].primitives[0].targets_count, cgltf_result_invalid_gltf); + + CGLTF_ASSERT_IF(data->meshes[i].primitives[j].attributes_count == 0, cgltf_result_invalid_gltf); + + cgltf_accessor* first = data->meshes[i].primitives[j].attributes[0].data; + + CGLTF_ASSERT_IF(first->count == 0, cgltf_result_invalid_gltf); + + for (cgltf_size k = 0; k < data->meshes[i].primitives[j].attributes_count; ++k) + { + CGLTF_ASSERT_IF(data->meshes[i].primitives[j].attributes[k].data->count != first->count, cgltf_result_invalid_gltf); + } + + for (cgltf_size k = 0; k < data->meshes[i].primitives[j].targets_count; ++k) + { + for (cgltf_size m = 0; m < data->meshes[i].primitives[j].targets[k].attributes_count; ++m) + { + CGLTF_ASSERT_IF(data->meshes[i].primitives[j].targets[k].attributes[m].data->count != first->count, cgltf_result_invalid_gltf); + } + } + + cgltf_accessor* indices = data->meshes[i].primitives[j].indices; + + CGLTF_ASSERT_IF(indices && + indices->component_type != cgltf_component_type_r_8u && + indices->component_type != cgltf_component_type_r_16u && + indices->component_type != cgltf_component_type_r_32u, cgltf_result_invalid_gltf); + + CGLTF_ASSERT_IF(indices && indices->type != cgltf_type_scalar, cgltf_result_invalid_gltf); + CGLTF_ASSERT_IF(indices && indices->stride != cgltf_component_size(indices->component_type), cgltf_result_invalid_gltf); + + if (indices && indices->buffer_view && indices->buffer_view->buffer->data) + { + cgltf_size index_bound = cgltf_calc_index_bound(indices->buffer_view, indices->offset, indices->component_type, indices->count); + + CGLTF_ASSERT_IF(index_bound >= first->count, cgltf_result_data_too_short); + } + + for (cgltf_size k = 0; k < data->meshes[i].primitives[j].mappings_count; ++k) + { + CGLTF_ASSERT_IF(data->meshes[i].primitives[j].mappings[k].variant >= data->variants_count, cgltf_result_invalid_gltf); + } + } + } + + for (cgltf_size i = 0; i < data->nodes_count; ++i) + { + if (data->nodes[i].weights && data->nodes[i].mesh) + { + CGLTF_ASSERT_IF(data->nodes[i].mesh->primitives_count && data->nodes[i].mesh->primitives[0].targets_count != data->nodes[i].weights_count, cgltf_result_invalid_gltf); + } + + if (data->nodes[i].has_mesh_gpu_instancing) + { + CGLTF_ASSERT_IF(data->nodes[i].mesh == NULL, cgltf_result_invalid_gltf); + CGLTF_ASSERT_IF(data->nodes[i].mesh_gpu_instancing.attributes_count == 0, cgltf_result_invalid_gltf); + + cgltf_accessor* first = data->nodes[i].mesh_gpu_instancing.attributes[0].data; + + for (cgltf_size k = 0; k < data->nodes[i].mesh_gpu_instancing.attributes_count; ++k) + { + CGLTF_ASSERT_IF(data->nodes[i].mesh_gpu_instancing.attributes[k].data->count != first->count, cgltf_result_invalid_gltf); + } + } + } + + for (cgltf_size i = 0; i < data->nodes_count; ++i) + { + cgltf_node* p1 = data->nodes[i].parent; + cgltf_node* p2 = p1 ? p1->parent : NULL; + + while (p1 && p2) + { + CGLTF_ASSERT_IF(p1 == p2, cgltf_result_invalid_gltf); + + p1 = p1->parent; + p2 = p2->parent ? p2->parent->parent : NULL; + } + } + + for (cgltf_size i = 0; i < data->scenes_count; ++i) + { + for (cgltf_size j = 0; j < data->scenes[i].nodes_count; ++j) + { + CGLTF_ASSERT_IF(data->scenes[i].nodes[j]->parent, cgltf_result_invalid_gltf); + } + } + + for (cgltf_size i = 0; i < data->animations_count; ++i) + { + for (cgltf_size j = 0; j < data->animations[i].channels_count; ++j) + { + cgltf_animation_channel* channel = &data->animations[i].channels[j]; + + if (!channel->target_node) + { + continue; + } + + cgltf_size components = 1; + + if (channel->target_path == cgltf_animation_path_type_weights) + { + CGLTF_ASSERT_IF(!channel->target_node->mesh || !channel->target_node->mesh->primitives_count, cgltf_result_invalid_gltf); + + components = channel->target_node->mesh->primitives[0].targets_count; + } + + cgltf_size values = channel->sampler->interpolation == cgltf_interpolation_type_cubic_spline ? 3 : 1; + + CGLTF_ASSERT_IF(channel->sampler->input->count * components * values != channel->sampler->output->count, cgltf_result_invalid_gltf); + } + } + + for (cgltf_size i = 0; i < data->variants_count; ++i) + { + CGLTF_ASSERT_IF(!data->variants[i].name, cgltf_result_invalid_gltf); + } + + return cgltf_result_success; +} + +cgltf_result cgltf_copy_extras_json(const cgltf_data* data, const cgltf_extras* extras, char* dest, cgltf_size* dest_size) +{ + cgltf_size json_size = extras->end_offset - extras->start_offset; + + if (!dest) + { + if (dest_size) + { + *dest_size = json_size + 1; + return cgltf_result_success; + } + return cgltf_result_invalid_options; + } + + if (*dest_size + 1 < json_size) + { + strncpy(dest, data->json + extras->start_offset, *dest_size - 1); + dest[*dest_size - 1] = 0; + } + else + { + strncpy(dest, data->json + extras->start_offset, json_size); + dest[json_size] = 0; + } + + return cgltf_result_success; +} + +static void cgltf_free_extras(cgltf_data* data, cgltf_extras* extras) +{ + data->memory.free_func(data->memory.user_data, extras->data); +} + +static void cgltf_free_extensions(cgltf_data* data, cgltf_extension* extensions, cgltf_size extensions_count) +{ + for (cgltf_size i = 0; i < extensions_count; ++i) + { + data->memory.free_func(data->memory.user_data, extensions[i].name); + data->memory.free_func(data->memory.user_data, extensions[i].data); + } + data->memory.free_func(data->memory.user_data, extensions); +} + +void cgltf_free(cgltf_data* data) +{ + if (!data) + { + return; + } + + void (*file_release)(const struct cgltf_memory_options*, const struct cgltf_file_options*, void* data, cgltf_size size) = data->file.release ? data->file.release : cgltf_default_file_release; + + data->memory.free_func(data->memory.user_data, data->asset.copyright); + data->memory.free_func(data->memory.user_data, data->asset.generator); + data->memory.free_func(data->memory.user_data, data->asset.version); + data->memory.free_func(data->memory.user_data, data->asset.min_version); + + cgltf_free_extensions(data, data->asset.extensions, data->asset.extensions_count); + cgltf_free_extras(data, &data->asset.extras); + + for (cgltf_size i = 0; i < data->accessors_count; ++i) + { + data->memory.free_func(data->memory.user_data, data->accessors[i].name); + + cgltf_free_extensions(data, data->accessors[i].extensions, data->accessors[i].extensions_count); + cgltf_free_extras(data, &data->accessors[i].extras); + } + data->memory.free_func(data->memory.user_data, data->accessors); + + for (cgltf_size i = 0; i < data->buffer_views_count; ++i) + { + data->memory.free_func(data->memory.user_data, data->buffer_views[i].name); + data->memory.free_func(data->memory.user_data, data->buffer_views[i].data); + + cgltf_free_extensions(data, data->buffer_views[i].extensions, data->buffer_views[i].extensions_count); + cgltf_free_extras(data, &data->buffer_views[i].extras); + } + data->memory.free_func(data->memory.user_data, data->buffer_views); + + for (cgltf_size i = 0; i < data->buffers_count; ++i) + { + data->memory.free_func(data->memory.user_data, data->buffers[i].name); + + if (data->buffers[i].data_free_method == cgltf_data_free_method_file_release) + { + file_release(&data->memory, &data->file, data->buffers[i].data, data->buffers[i].size); + } + else if (data->buffers[i].data_free_method == cgltf_data_free_method_memory_free) + { + data->memory.free_func(data->memory.user_data, data->buffers[i].data); + } + + data->memory.free_func(data->memory.user_data, data->buffers[i].uri); + + cgltf_free_extensions(data, data->buffers[i].extensions, data->buffers[i].extensions_count); + cgltf_free_extras(data, &data->buffers[i].extras); + } + data->memory.free_func(data->memory.user_data, data->buffers); + + for (cgltf_size i = 0; i < data->meshes_count; ++i) + { + data->memory.free_func(data->memory.user_data, data->meshes[i].name); + + for (cgltf_size j = 0; j < data->meshes[i].primitives_count; ++j) + { + for (cgltf_size k = 0; k < data->meshes[i].primitives[j].attributes_count; ++k) + { + data->memory.free_func(data->memory.user_data, data->meshes[i].primitives[j].attributes[k].name); + } + + data->memory.free_func(data->memory.user_data, data->meshes[i].primitives[j].attributes); + + for (cgltf_size k = 0; k < data->meshes[i].primitives[j].targets_count; ++k) + { + for (cgltf_size m = 0; m < data->meshes[i].primitives[j].targets[k].attributes_count; ++m) + { + data->memory.free_func(data->memory.user_data, data->meshes[i].primitives[j].targets[k].attributes[m].name); + } + + data->memory.free_func(data->memory.user_data, data->meshes[i].primitives[j].targets[k].attributes); + } + + data->memory.free_func(data->memory.user_data, data->meshes[i].primitives[j].targets); + + if (data->meshes[i].primitives[j].has_draco_mesh_compression) + { + for (cgltf_size k = 0; k < data->meshes[i].primitives[j].draco_mesh_compression.attributes_count; ++k) + { + data->memory.free_func(data->memory.user_data, data->meshes[i].primitives[j].draco_mesh_compression.attributes[k].name); + } + + data->memory.free_func(data->memory.user_data, data->meshes[i].primitives[j].draco_mesh_compression.attributes); + } + + for (cgltf_size k = 0; k < data->meshes[i].primitives[j].mappings_count; ++k) + { + cgltf_free_extras(data, &data->meshes[i].primitives[j].mappings[k].extras); + } + + data->memory.free_func(data->memory.user_data, data->meshes[i].primitives[j].mappings); + + cgltf_free_extensions(data, data->meshes[i].primitives[j].extensions, data->meshes[i].primitives[j].extensions_count); + cgltf_free_extras(data, &data->meshes[i].primitives[j].extras); + } + + data->memory.free_func(data->memory.user_data, data->meshes[i].primitives); + data->memory.free_func(data->memory.user_data, data->meshes[i].weights); + + for (cgltf_size j = 0; j < data->meshes[i].target_names_count; ++j) + { + data->memory.free_func(data->memory.user_data, data->meshes[i].target_names[j]); + } + + cgltf_free_extensions(data, data->meshes[i].extensions, data->meshes[i].extensions_count); + cgltf_free_extras(data, &data->meshes[i].extras); + + data->memory.free_func(data->memory.user_data, data->meshes[i].target_names); + } + + data->memory.free_func(data->memory.user_data, data->meshes); + + for (cgltf_size i = 0; i < data->materials_count; ++i) + { + data->memory.free_func(data->memory.user_data, data->materials[i].name); + + cgltf_free_extensions(data, data->materials[i].extensions, data->materials[i].extensions_count); + cgltf_free_extras(data, &data->materials[i].extras); + } + + data->memory.free_func(data->memory.user_data, data->materials); + + for (cgltf_size i = 0; i < data->images_count; ++i) + { + data->memory.free_func(data->memory.user_data, data->images[i].name); + data->memory.free_func(data->memory.user_data, data->images[i].uri); + data->memory.free_func(data->memory.user_data, data->images[i].mime_type); + + cgltf_free_extensions(data, data->images[i].extensions, data->images[i].extensions_count); + cgltf_free_extras(data, &data->images[i].extras); + } + + data->memory.free_func(data->memory.user_data, data->images); + + for (cgltf_size i = 0; i < data->textures_count; ++i) + { + data->memory.free_func(data->memory.user_data, data->textures[i].name); + + cgltf_free_extensions(data, data->textures[i].extensions, data->textures[i].extensions_count); + cgltf_free_extras(data, &data->textures[i].extras); + } + + data->memory.free_func(data->memory.user_data, data->textures); + + for (cgltf_size i = 0; i < data->samplers_count; ++i) + { + data->memory.free_func(data->memory.user_data, data->samplers[i].name); + + cgltf_free_extensions(data, data->samplers[i].extensions, data->samplers[i].extensions_count); + cgltf_free_extras(data, &data->samplers[i].extras); + } + + data->memory.free_func(data->memory.user_data, data->samplers); + + for (cgltf_size i = 0; i < data->skins_count; ++i) + { + data->memory.free_func(data->memory.user_data, data->skins[i].name); + data->memory.free_func(data->memory.user_data, data->skins[i].joints); + + cgltf_free_extensions(data, data->skins[i].extensions, data->skins[i].extensions_count); + cgltf_free_extras(data, &data->skins[i].extras); + } + + data->memory.free_func(data->memory.user_data, data->skins); + + for (cgltf_size i = 0; i < data->cameras_count; ++i) + { + data->memory.free_func(data->memory.user_data, data->cameras[i].name); + + if (data->cameras[i].type == cgltf_camera_type_perspective) + { + cgltf_free_extras(data, &data->cameras[i].data.perspective.extras); + } + else if (data->cameras[i].type == cgltf_camera_type_orthographic) + { + cgltf_free_extras(data, &data->cameras[i].data.orthographic.extras); + } + + cgltf_free_extensions(data, data->cameras[i].extensions, data->cameras[i].extensions_count); + cgltf_free_extras(data, &data->cameras[i].extras); + } + + data->memory.free_func(data->memory.user_data, data->cameras); + + for (cgltf_size i = 0; i < data->lights_count; ++i) + { + data->memory.free_func(data->memory.user_data, data->lights[i].name); + + cgltf_free_extras(data, &data->lights[i].extras); + } + + data->memory.free_func(data->memory.user_data, data->lights); + + for (cgltf_size i = 0; i < data->nodes_count; ++i) + { + data->memory.free_func(data->memory.user_data, data->nodes[i].name); + data->memory.free_func(data->memory.user_data, data->nodes[i].children); + data->memory.free_func(data->memory.user_data, data->nodes[i].weights); + + if (data->nodes[i].has_mesh_gpu_instancing) + { + for (cgltf_size j = 0; j < data->nodes[i].mesh_gpu_instancing.attributes_count; ++j) + { + data->memory.free_func(data->memory.user_data, data->nodes[i].mesh_gpu_instancing.attributes[j].name); + } + + data->memory.free_func(data->memory.user_data, data->nodes[i].mesh_gpu_instancing.attributes); + } + + cgltf_free_extensions(data, data->nodes[i].extensions, data->nodes[i].extensions_count); + cgltf_free_extras(data, &data->nodes[i].extras); + } + + data->memory.free_func(data->memory.user_data, data->nodes); + + for (cgltf_size i = 0; i < data->scenes_count; ++i) + { + data->memory.free_func(data->memory.user_data, data->scenes[i].name); + data->memory.free_func(data->memory.user_data, data->scenes[i].nodes); + + cgltf_free_extensions(data, data->scenes[i].extensions, data->scenes[i].extensions_count); + cgltf_free_extras(data, &data->scenes[i].extras); + } + + data->memory.free_func(data->memory.user_data, data->scenes); + + for (cgltf_size i = 0; i < data->animations_count; ++i) + { + data->memory.free_func(data->memory.user_data, data->animations[i].name); + for (cgltf_size j = 0; j < data->animations[i].samplers_count; ++j) + { + cgltf_free_extensions(data, data->animations[i].samplers[j].extensions, data->animations[i].samplers[j].extensions_count); + cgltf_free_extras(data, &data->animations[i].samplers[j].extras); + } + data->memory.free_func(data->memory.user_data, data->animations[i].samplers); + + for (cgltf_size j = 0; j < data->animations[i].channels_count; ++j) + { + cgltf_free_extensions(data, data->animations[i].channels[j].extensions, data->animations[i].channels[j].extensions_count); + cgltf_free_extras(data, &data->animations[i].channels[j].extras); + } + data->memory.free_func(data->memory.user_data, data->animations[i].channels); + + cgltf_free_extensions(data, data->animations[i].extensions, data->animations[i].extensions_count); + cgltf_free_extras(data, &data->animations[i].extras); + } + + data->memory.free_func(data->memory.user_data, data->animations); + + for (cgltf_size i = 0; i < data->variants_count; ++i) + { + data->memory.free_func(data->memory.user_data, data->variants[i].name); + + cgltf_free_extras(data, &data->variants[i].extras); + } + + data->memory.free_func(data->memory.user_data, data->variants); + + cgltf_free_extensions(data, data->data_extensions, data->data_extensions_count); + cgltf_free_extras(data, &data->extras); + + for (cgltf_size i = 0; i < data->extensions_used_count; ++i) + { + data->memory.free_func(data->memory.user_data, data->extensions_used[i]); + } + + data->memory.free_func(data->memory.user_data, data->extensions_used); + + for (cgltf_size i = 0; i < data->extensions_required_count; ++i) + { + data->memory.free_func(data->memory.user_data, data->extensions_required[i]); + } + + data->memory.free_func(data->memory.user_data, data->extensions_required); + + file_release(&data->memory, &data->file, data->file_data, data->file_size); + + data->memory.free_func(data->memory.user_data, data); +} + +void cgltf_node_transform_local(const cgltf_node* node, cgltf_float* out_matrix) +{ + cgltf_float* lm = out_matrix; + + if (node->has_matrix) + { + memcpy(lm, node->matrix, sizeof(float) * 16); + } + else + { + float tx = node->translation[0]; + float ty = node->translation[1]; + float tz = node->translation[2]; + + float qx = node->rotation[0]; + float qy = node->rotation[1]; + float qz = node->rotation[2]; + float qw = node->rotation[3]; + + float sx = node->scale[0]; + float sy = node->scale[1]; + float sz = node->scale[2]; + + lm[0] = (1 - 2 * qy*qy - 2 * qz*qz) * sx; + lm[1] = (2 * qx*qy + 2 * qz*qw) * sx; + lm[2] = (2 * qx*qz - 2 * qy*qw) * sx; + lm[3] = 0.f; + + lm[4] = (2 * qx*qy - 2 * qz*qw) * sy; + lm[5] = (1 - 2 * qx*qx - 2 * qz*qz) * sy; + lm[6] = (2 * qy*qz + 2 * qx*qw) * sy; + lm[7] = 0.f; + + lm[8] = (2 * qx*qz + 2 * qy*qw) * sz; + lm[9] = (2 * qy*qz - 2 * qx*qw) * sz; + lm[10] = (1 - 2 * qx*qx - 2 * qy*qy) * sz; + lm[11] = 0.f; + + lm[12] = tx; + lm[13] = ty; + lm[14] = tz; + lm[15] = 1.f; + } +} + +void cgltf_node_transform_world(const cgltf_node* node, cgltf_float* out_matrix) +{ + cgltf_float* lm = out_matrix; + cgltf_node_transform_local(node, lm); + + const cgltf_node* parent = node->parent; + + while (parent) + { + float pm[16]; + cgltf_node_transform_local(parent, pm); + + for (int i = 0; i < 4; ++i) + { + float l0 = lm[i * 4 + 0]; + float l1 = lm[i * 4 + 1]; + float l2 = lm[i * 4 + 2]; + + float r0 = l0 * pm[0] + l1 * pm[4] + l2 * pm[8]; + float r1 = l0 * pm[1] + l1 * pm[5] + l2 * pm[9]; + float r2 = l0 * pm[2] + l1 * pm[6] + l2 * pm[10]; + + lm[i * 4 + 0] = r0; + lm[i * 4 + 1] = r1; + lm[i * 4 + 2] = r2; + } + + lm[12] += pm[12]; + lm[13] += pm[13]; + lm[14] += pm[14]; + + parent = parent->parent; + } +} + +static cgltf_ssize cgltf_component_read_integer(const void* in, cgltf_component_type component_type) +{ + switch (component_type) + { + case cgltf_component_type_r_16: + return *((const int16_t*) in); + case cgltf_component_type_r_16u: + return *((const uint16_t*) in); + case cgltf_component_type_r_32u: + return *((const uint32_t*) in); + case cgltf_component_type_r_8: + return *((const int8_t*) in); + case cgltf_component_type_r_8u: + return *((const uint8_t*) in); + default: + return 0; + } +} + +static cgltf_size cgltf_component_read_index(const void* in, cgltf_component_type component_type) +{ + switch (component_type) + { + case cgltf_component_type_r_16u: + return *((const uint16_t*) in); + case cgltf_component_type_r_32u: + return *((const uint32_t*) in); + case cgltf_component_type_r_8u: + return *((const uint8_t*) in); + default: + return 0; + } +} + +static cgltf_float cgltf_component_read_float(const void* in, cgltf_component_type component_type, cgltf_bool normalized) +{ + if (component_type == cgltf_component_type_r_32f) + { + return *((const float*) in); + } + + if (normalized) + { + switch (component_type) + { + // note: glTF spec doesn't currently define normalized conversions for 32-bit integers + case cgltf_component_type_r_16: + return *((const int16_t*) in) / (cgltf_float)32767; + case cgltf_component_type_r_16u: + return *((const uint16_t*) in) / (cgltf_float)65535; + case cgltf_component_type_r_8: + return *((const int8_t*) in) / (cgltf_float)127; + case cgltf_component_type_r_8u: + return *((const uint8_t*) in) / (cgltf_float)255; + default: + return 0; + } + } + + return (cgltf_float)cgltf_component_read_integer(in, component_type); +} + +static cgltf_bool cgltf_element_read_float(const uint8_t* element, cgltf_type type, cgltf_component_type component_type, cgltf_bool normalized, cgltf_float* out, cgltf_size element_size) +{ + cgltf_size num_components = cgltf_num_components(type); + + if (element_size < num_components) { + return 0; + } + + // There are three special cases for component extraction, see #data-alignment in the 2.0 spec. + + cgltf_size component_size = cgltf_component_size(component_type); + + if (type == cgltf_type_mat2 && component_size == 1) + { + out[0] = cgltf_component_read_float(element, component_type, normalized); + out[1] = cgltf_component_read_float(element + 1, component_type, normalized); + out[2] = cgltf_component_read_float(element + 4, component_type, normalized); + out[3] = cgltf_component_read_float(element + 5, component_type, normalized); + return 1; + } + + if (type == cgltf_type_mat3 && component_size == 1) + { + out[0] = cgltf_component_read_float(element, component_type, normalized); + out[1] = cgltf_component_read_float(element + 1, component_type, normalized); + out[2] = cgltf_component_read_float(element + 2, component_type, normalized); + out[3] = cgltf_component_read_float(element + 4, component_type, normalized); + out[4] = cgltf_component_read_float(element + 5, component_type, normalized); + out[5] = cgltf_component_read_float(element + 6, component_type, normalized); + out[6] = cgltf_component_read_float(element + 8, component_type, normalized); + out[7] = cgltf_component_read_float(element + 9, component_type, normalized); + out[8] = cgltf_component_read_float(element + 10, component_type, normalized); + return 1; + } + + if (type == cgltf_type_mat3 && component_size == 2) + { + out[0] = cgltf_component_read_float(element, component_type, normalized); + out[1] = cgltf_component_read_float(element + 2, component_type, normalized); + out[2] = cgltf_component_read_float(element + 4, component_type, normalized); + out[3] = cgltf_component_read_float(element + 8, component_type, normalized); + out[4] = cgltf_component_read_float(element + 10, component_type, normalized); + out[5] = cgltf_component_read_float(element + 12, component_type, normalized); + out[6] = cgltf_component_read_float(element + 16, component_type, normalized); + out[7] = cgltf_component_read_float(element + 18, component_type, normalized); + out[8] = cgltf_component_read_float(element + 20, component_type, normalized); + return 1; + } + + for (cgltf_size i = 0; i < num_components; ++i) + { + out[i] = cgltf_component_read_float(element + component_size * i, component_type, normalized); + } + return 1; +} + +const uint8_t* cgltf_buffer_view_data(const cgltf_buffer_view* view) +{ + if (view->data) + return (const uint8_t*)view->data; + + if (!view->buffer->data) + return NULL; + + const uint8_t* result = (const uint8_t*)view->buffer->data; + result += view->offset; + return result; +} + +const cgltf_accessor* cgltf_find_accessor(const cgltf_primitive* prim, cgltf_attribute_type type, cgltf_int index) +{ + for (cgltf_size i = 0; i < prim->attributes_count; ++i) + { + const cgltf_attribute* attr = &prim->attributes[i]; + if (attr->type == type && attr->index == index) + return attr->data; + } + + return NULL; +} + +static const uint8_t* cgltf_find_sparse_index(const cgltf_accessor* accessor, cgltf_size needle) +{ + const cgltf_accessor_sparse* sparse = &accessor->sparse; + const uint8_t* index_data = cgltf_buffer_view_data(sparse->indices_buffer_view); + const uint8_t* value_data = cgltf_buffer_view_data(sparse->values_buffer_view); + + if (index_data == NULL || value_data == NULL) + return NULL; + + index_data += sparse->indices_byte_offset; + value_data += sparse->values_byte_offset; + + cgltf_size index_stride = cgltf_component_size(sparse->indices_component_type); + + cgltf_size offset = 0; + cgltf_size length = sparse->count; + + while (length) + { + cgltf_size rem = length % 2; + length /= 2; + + cgltf_size index = cgltf_component_read_index(index_data + (offset + length) * index_stride, sparse->indices_component_type); + offset += index < needle ? length + rem : 0; + } + + if (offset == sparse->count) + return NULL; + + cgltf_size index = cgltf_component_read_index(index_data + offset * index_stride, sparse->indices_component_type); + return index == needle ? value_data + offset * accessor->stride : NULL; +} + +cgltf_bool cgltf_accessor_read_float(const cgltf_accessor* accessor, cgltf_size index, cgltf_float* out, cgltf_size element_size) +{ + if (accessor->is_sparse) + { + const uint8_t* element = cgltf_find_sparse_index(accessor, index); + if (element) + return cgltf_element_read_float(element, accessor->type, accessor->component_type, accessor->normalized, out, element_size); + } + if (accessor->buffer_view == NULL) + { + memset(out, 0, element_size * sizeof(cgltf_float)); + return 1; + } + const uint8_t* element = cgltf_buffer_view_data(accessor->buffer_view); + if (element == NULL) + { + return 0; + } + element += accessor->offset + accessor->stride * index; + return cgltf_element_read_float(element, accessor->type, accessor->component_type, accessor->normalized, out, element_size); +} + +cgltf_size cgltf_accessor_unpack_floats(const cgltf_accessor* accessor, cgltf_float* out, cgltf_size float_count) +{ + cgltf_size floats_per_element = cgltf_num_components(accessor->type); + cgltf_size available_floats = accessor->count * floats_per_element; + if (out == NULL) + { + return available_floats; + } + + float_count = available_floats < float_count ? available_floats : float_count; + cgltf_size element_count = float_count / floats_per_element; + + // First pass: convert each element in the base accessor. + if (accessor->buffer_view == NULL) + { + memset(out, 0, element_count * floats_per_element * sizeof(cgltf_float)); + } + else + { + const uint8_t* element = cgltf_buffer_view_data(accessor->buffer_view); + if (element == NULL) + { + return 0; + } + element += accessor->offset; + + if (accessor->component_type == cgltf_component_type_r_32f && accessor->stride == floats_per_element * sizeof(cgltf_float)) + { + memcpy(out, element, element_count * floats_per_element * sizeof(cgltf_float)); + } + else + { + cgltf_float* dest = out; + + for (cgltf_size index = 0; index < element_count; index++, dest += floats_per_element, element += accessor->stride) + { + if (!cgltf_element_read_float(element, accessor->type, accessor->component_type, accessor->normalized, dest, floats_per_element)) + { + return 0; + } + } + } + } + + // Second pass: write out each element in the sparse accessor. + if (accessor->is_sparse) + { + const cgltf_accessor_sparse* sparse = &accessor->sparse; + + const uint8_t* index_data = cgltf_buffer_view_data(sparse->indices_buffer_view); + const uint8_t* reader_head = cgltf_buffer_view_data(sparse->values_buffer_view); + + if (index_data == NULL || reader_head == NULL) + { + return 0; + } + + index_data += sparse->indices_byte_offset; + reader_head += sparse->values_byte_offset; + + cgltf_size index_stride = cgltf_component_size(sparse->indices_component_type); + for (cgltf_size reader_index = 0; reader_index < sparse->count; reader_index++, index_data += index_stride, reader_head += accessor->stride) + { + size_t writer_index = cgltf_component_read_index(index_data, sparse->indices_component_type); + float* writer_head = out + writer_index * floats_per_element; + + if (!cgltf_element_read_float(reader_head, accessor->type, accessor->component_type, accessor->normalized, writer_head, floats_per_element)) + { + return 0; + } + } + } + + return element_count * floats_per_element; +} + +static cgltf_uint cgltf_component_read_uint(const void* in, cgltf_component_type component_type) +{ + switch (component_type) + { + case cgltf_component_type_r_8: + return *((const int8_t*) in); + + case cgltf_component_type_r_8u: + return *((const uint8_t*) in); + + case cgltf_component_type_r_16: + return *((const int16_t*) in); + + case cgltf_component_type_r_16u: + return *((const uint16_t*) in); + + case cgltf_component_type_r_32u: + return *((const uint32_t*) in); + + default: + return 0; + } +} + +static cgltf_bool cgltf_element_read_uint(const uint8_t* element, cgltf_type type, cgltf_component_type component_type, cgltf_uint* out, cgltf_size element_size) +{ + cgltf_size num_components = cgltf_num_components(type); + + if (element_size < num_components) + { + return 0; + } + + // Reading integer matrices is not a valid use case + if (type == cgltf_type_mat2 || type == cgltf_type_mat3 || type == cgltf_type_mat4) + { + return 0; + } + + cgltf_size component_size = cgltf_component_size(component_type); + + for (cgltf_size i = 0; i < num_components; ++i) + { + out[i] = cgltf_component_read_uint(element + component_size * i, component_type); + } + return 1; +} + +cgltf_bool cgltf_accessor_read_uint(const cgltf_accessor* accessor, cgltf_size index, cgltf_uint* out, cgltf_size element_size) +{ + if (accessor->is_sparse) + { + const uint8_t* element = cgltf_find_sparse_index(accessor, index); + if (element) + return cgltf_element_read_uint(element, accessor->type, accessor->component_type, out, element_size); + } + if (accessor->buffer_view == NULL) + { + memset(out, 0, element_size * sizeof(cgltf_uint)); + return 1; + } + const uint8_t* element = cgltf_buffer_view_data(accessor->buffer_view); + if (element == NULL) + { + return 0; + } + element += accessor->offset + accessor->stride * index; + return cgltf_element_read_uint(element, accessor->type, accessor->component_type, out, element_size); +} + +cgltf_size cgltf_accessor_read_index(const cgltf_accessor* accessor, cgltf_size index) +{ + if (accessor->is_sparse) + { + const uint8_t* element = cgltf_find_sparse_index(accessor, index); + if (element) + return cgltf_component_read_index(element, accessor->component_type); + } + if (accessor->buffer_view == NULL) + { + return 0; + } + const uint8_t* element = cgltf_buffer_view_data(accessor->buffer_view); + if (element == NULL) + { + return 0; // This is an error case, but we can't communicate the error with existing interface. + } + element += accessor->offset + accessor->stride * index; + return cgltf_component_read_index(element, accessor->component_type); +} + +cgltf_size cgltf_mesh_index(const cgltf_data* data, const cgltf_mesh* object) +{ + assert(object && (cgltf_size)(object - data->meshes) < data->meshes_count); + return (cgltf_size)(object - data->meshes); +} + +cgltf_size cgltf_material_index(const cgltf_data* data, const cgltf_material* object) +{ + assert(object && (cgltf_size)(object - data->materials) < data->materials_count); + return (cgltf_size)(object - data->materials); +} + +cgltf_size cgltf_accessor_index(const cgltf_data* data, const cgltf_accessor* object) +{ + assert(object && (cgltf_size)(object - data->accessors) < data->accessors_count); + return (cgltf_size)(object - data->accessors); +} + +cgltf_size cgltf_buffer_view_index(const cgltf_data* data, const cgltf_buffer_view* object) +{ + assert(object && (cgltf_size)(object - data->buffer_views) < data->buffer_views_count); + return (cgltf_size)(object - data->buffer_views); +} + +cgltf_size cgltf_buffer_index(const cgltf_data* data, const cgltf_buffer* object) +{ + assert(object && (cgltf_size)(object - data->buffers) < data->buffers_count); + return (cgltf_size)(object - data->buffers); +} + +cgltf_size cgltf_image_index(const cgltf_data* data, const cgltf_image* object) +{ + assert(object && (cgltf_size)(object - data->images) < data->images_count); + return (cgltf_size)(object - data->images); +} + +cgltf_size cgltf_texture_index(const cgltf_data* data, const cgltf_texture* object) +{ + assert(object && (cgltf_size)(object - data->textures) < data->textures_count); + return (cgltf_size)(object - data->textures); +} + +cgltf_size cgltf_sampler_index(const cgltf_data* data, const cgltf_sampler* object) +{ + assert(object && (cgltf_size)(object - data->samplers) < data->samplers_count); + return (cgltf_size)(object - data->samplers); +} + +cgltf_size cgltf_skin_index(const cgltf_data* data, const cgltf_skin* object) +{ + assert(object && (cgltf_size)(object - data->skins) < data->skins_count); + return (cgltf_size)(object - data->skins); +} + +cgltf_size cgltf_camera_index(const cgltf_data* data, const cgltf_camera* object) +{ + assert(object && (cgltf_size)(object - data->cameras) < data->cameras_count); + return (cgltf_size)(object - data->cameras); +} + +cgltf_size cgltf_light_index(const cgltf_data* data, const cgltf_light* object) +{ + assert(object && (cgltf_size)(object - data->lights) < data->lights_count); + return (cgltf_size)(object - data->lights); +} + +cgltf_size cgltf_node_index(const cgltf_data* data, const cgltf_node* object) +{ + assert(object && (cgltf_size)(object - data->nodes) < data->nodes_count); + return (cgltf_size)(object - data->nodes); +} + +cgltf_size cgltf_scene_index(const cgltf_data* data, const cgltf_scene* object) +{ + assert(object && (cgltf_size)(object - data->scenes) < data->scenes_count); + return (cgltf_size)(object - data->scenes); +} + +cgltf_size cgltf_animation_index(const cgltf_data* data, const cgltf_animation* object) +{ + assert(object && (cgltf_size)(object - data->animations) < data->animations_count); + return (cgltf_size)(object - data->animations); +} + +cgltf_size cgltf_animation_sampler_index(const cgltf_animation* animation, const cgltf_animation_sampler* object) +{ + assert(object && (cgltf_size)(object - animation->samplers) < animation->samplers_count); + return (cgltf_size)(object - animation->samplers); +} + +cgltf_size cgltf_animation_channel_index(const cgltf_animation* animation, const cgltf_animation_channel* object) +{ + assert(object && (cgltf_size)(object - animation->channels) < animation->channels_count); + return (cgltf_size)(object - animation->channels); +} + +cgltf_size cgltf_accessor_unpack_indices(const cgltf_accessor* accessor, void* out, cgltf_size out_component_size, cgltf_size index_count) +{ + if (out == NULL) + { + return accessor->count; + } + + cgltf_size numbers_per_element = cgltf_num_components(accessor->type); + cgltf_size available_numbers = accessor->count * numbers_per_element; + + index_count = available_numbers < index_count ? available_numbers : index_count; + cgltf_size index_component_size = cgltf_component_size(accessor->component_type); + + if (accessor->is_sparse) + { + return 0; + } + if (accessor->buffer_view == NULL) + { + return 0; + } + if (index_component_size > out_component_size) + { + return 0; + } + const uint8_t* element = cgltf_buffer_view_data(accessor->buffer_view); + if (element == NULL) + { + return 0; + } + element += accessor->offset; + + if (index_component_size == out_component_size && accessor->stride == out_component_size * numbers_per_element) + { + memcpy(out, element, index_count * index_component_size); + return index_count; + } + + // Data couldn't be copied with memcpy due to stride being larger than the component size. + // OR + // The component size of the output array is larger than the component size of the index data, so index data will be padded. + switch (out_component_size) + { + case 1: + for (cgltf_size index = 0; index < index_count; index++, element += accessor->stride) + { + ((uint8_t*)out)[index] = (uint8_t)cgltf_component_read_index(element, accessor->component_type); + } + break; + case 2: + for (cgltf_size index = 0; index < index_count; index++, element += accessor->stride) + { + ((uint16_t*)out)[index] = (uint16_t)cgltf_component_read_index(element, accessor->component_type); + } + break; + case 4: + for (cgltf_size index = 0; index < index_count; index++, element += accessor->stride) + { + ((uint32_t*)out)[index] = (uint32_t)cgltf_component_read_index(element, accessor->component_type); + } + break; + default: + return 0; + } + + return index_count; +} + +#define CGLTF_ERROR_JSON -1 +#define CGLTF_ERROR_NOMEM -2 +#define CGLTF_ERROR_LEGACY -3 + +#define CGLTF_CHECK_TOKTYPE(tok_, type_) if ((tok_).type != (type_)) { return CGLTF_ERROR_JSON; } +#define CGLTF_CHECK_TOKTYPE_RET(tok_, type_, ret_) if ((tok_).type != (type_)) { return ret_; } +#define CGLTF_CHECK_KEY(tok_) if ((tok_).type != JSMN_STRING || (tok_).size == 0) { return CGLTF_ERROR_JSON; } /* checking size for 0 verifies that a value follows the key */ + +#define CGLTF_PTRINDEX(type, idx) (type*)((cgltf_size)idx + 1) +#define CGLTF_PTRFIXUP(var, data, size) if (var) { if ((cgltf_size)var > size) { return CGLTF_ERROR_JSON; } var = &data[(cgltf_size)var-1]; } +#define CGLTF_PTRFIXUP_REQ(var, data, size) if (!var || (cgltf_size)var > size) { return CGLTF_ERROR_JSON; } var = &data[(cgltf_size)var-1]; + +static int cgltf_json_strcmp(jsmntok_t const* tok, const uint8_t* json_chunk, const char* str) +{ + CGLTF_CHECK_TOKTYPE(*tok, JSMN_STRING); + size_t const str_len = strlen(str); + size_t const name_length = (size_t)(tok->end - tok->start); + return (str_len == name_length) ? strncmp((const char*)json_chunk + tok->start, str, str_len) : 128; +} + +static int cgltf_json_to_int(jsmntok_t const* tok, const uint8_t* json_chunk) +{ + CGLTF_CHECK_TOKTYPE(*tok, JSMN_PRIMITIVE); + char tmp[128]; + int size = (size_t)(tok->end - tok->start) < sizeof(tmp) ? (int)(tok->end - tok->start) : (int)(sizeof(tmp) - 1); + strncpy(tmp, (const char*)json_chunk + tok->start, size); + tmp[size] = 0; + return CGLTF_ATOI(tmp); +} + +static cgltf_size cgltf_json_to_size(jsmntok_t const* tok, const uint8_t* json_chunk) +{ + CGLTF_CHECK_TOKTYPE_RET(*tok, JSMN_PRIMITIVE, 0); + char tmp[128]; + int size = (size_t)(tok->end - tok->start) < sizeof(tmp) ? (int)(tok->end - tok->start) : (int)(sizeof(tmp) - 1); + strncpy(tmp, (const char*)json_chunk + tok->start, size); + tmp[size] = 0; + long long res = CGLTF_ATOLL(tmp); + return res < 0 ? 0 : (cgltf_size)res; +} + +static cgltf_float cgltf_json_to_float(jsmntok_t const* tok, const uint8_t* json_chunk) +{ + CGLTF_CHECK_TOKTYPE(*tok, JSMN_PRIMITIVE); + char tmp[128]; + int size = (size_t)(tok->end - tok->start) < sizeof(tmp) ? (int)(tok->end - tok->start) : (int)(sizeof(tmp) - 1); + strncpy(tmp, (const char*)json_chunk + tok->start, size); + tmp[size] = 0; + return (cgltf_float)CGLTF_ATOF(tmp); +} + +static cgltf_bool cgltf_json_to_bool(jsmntok_t const* tok, const uint8_t* json_chunk) +{ + int size = (int)(tok->end - tok->start); + return size == 4 && memcmp(json_chunk + tok->start, "true", 4) == 0; +} + +static int cgltf_skip_json(jsmntok_t const* tokens, int i) +{ + int end = i + 1; + + while (i < end) + { + switch (tokens[i].type) + { + case JSMN_OBJECT: + end += tokens[i].size * 2; + break; + + case JSMN_ARRAY: + end += tokens[i].size; + break; + + case JSMN_PRIMITIVE: + case JSMN_STRING: + break; + + default: + return -1; + } + + i++; + } + + return i; +} + +static void cgltf_fill_float_array(float* out_array, int size, float value) +{ + for (int j = 0; j < size; ++j) + { + out_array[j] = value; + } +} + +static int cgltf_parse_json_float_array(jsmntok_t const* tokens, int i, const uint8_t* json_chunk, float* out_array, int size) +{ + CGLTF_CHECK_TOKTYPE(tokens[i], JSMN_ARRAY); + if (tokens[i].size != size) + { + return CGLTF_ERROR_JSON; + } + ++i; + for (int j = 0; j < size; ++j) + { + CGLTF_CHECK_TOKTYPE(tokens[i], JSMN_PRIMITIVE); + out_array[j] = cgltf_json_to_float(tokens + i, json_chunk); + ++i; + } + return i; +} + +static int cgltf_parse_json_string(cgltf_options* options, jsmntok_t const* tokens, int i, const uint8_t* json_chunk, char** out_string) +{ + CGLTF_CHECK_TOKTYPE(tokens[i], JSMN_STRING); + if (*out_string) + { + return CGLTF_ERROR_JSON; + } + int size = (int)(tokens[i].end - tokens[i].start); + char* result = (char*)options->memory.alloc_func(options->memory.user_data, size + 1); + if (!result) + { + return CGLTF_ERROR_NOMEM; + } + strncpy(result, (const char*)json_chunk + tokens[i].start, size); + result[size] = 0; + *out_string = result; + return i + 1; +} + +static int cgltf_parse_json_array(cgltf_options* options, jsmntok_t const* tokens, int i, const uint8_t* json_chunk, size_t element_size, void** out_array, cgltf_size* out_size) +{ + (void)json_chunk; + if (tokens[i].type != JSMN_ARRAY) + { + return tokens[i].type == JSMN_OBJECT ? CGLTF_ERROR_LEGACY : CGLTF_ERROR_JSON; + } + if (*out_array) + { + return CGLTF_ERROR_JSON; + } + int size = tokens[i].size; + void* result = cgltf_calloc(options, element_size, size); + if (!result) + { + return CGLTF_ERROR_NOMEM; + } + *out_array = result; + *out_size = size; + return i + 1; +} + +static int cgltf_parse_json_string_array(cgltf_options* options, jsmntok_t const* tokens, int i, const uint8_t* json_chunk, char*** out_array, cgltf_size* out_size) +{ + CGLTF_CHECK_TOKTYPE(tokens[i], JSMN_ARRAY); + i = cgltf_parse_json_array(options, tokens, i, json_chunk, sizeof(char*), (void**)out_array, out_size); + if (i < 0) + { + return i; + } + + for (cgltf_size j = 0; j < *out_size; ++j) + { + i = cgltf_parse_json_string(options, tokens, i, json_chunk, j + (*out_array)); + if (i < 0) + { + return i; + } + } + return i; +} + +static void cgltf_parse_attribute_type(const char* name, cgltf_attribute_type* out_type, int* out_index) +{ + if (*name == '_') + { + *out_type = cgltf_attribute_type_custom; + return; + } + + const char* us = strchr(name, '_'); + size_t len = us ? (size_t)(us - name) : strlen(name); + + if (len == 8 && strncmp(name, "POSITION", 8) == 0) + { + *out_type = cgltf_attribute_type_position; + } + else if (len == 6 && strncmp(name, "NORMAL", 6) == 0) + { + *out_type = cgltf_attribute_type_normal; + } + else if (len == 7 && strncmp(name, "TANGENT", 7) == 0) + { + *out_type = cgltf_attribute_type_tangent; + } + else if (len == 8 && strncmp(name, "TEXCOORD", 8) == 0) + { + *out_type = cgltf_attribute_type_texcoord; + } + else if (len == 5 && strncmp(name, "COLOR", 5) == 0) + { + *out_type = cgltf_attribute_type_color; + } + else if (len == 6 && strncmp(name, "JOINTS", 6) == 0) + { + *out_type = cgltf_attribute_type_joints; + } + else if (len == 7 && strncmp(name, "WEIGHTS", 7) == 0) + { + *out_type = cgltf_attribute_type_weights; + } + else + { + *out_type = cgltf_attribute_type_invalid; + } + + if (us && *out_type != cgltf_attribute_type_invalid) + { + *out_index = CGLTF_ATOI(us + 1); + if (*out_index < 0) + { + *out_type = cgltf_attribute_type_invalid; + *out_index = 0; + } + } +} + +static int cgltf_parse_json_attribute_list(cgltf_options* options, jsmntok_t const* tokens, int i, const uint8_t* json_chunk, cgltf_attribute** out_attributes, cgltf_size* out_attributes_count) +{ + CGLTF_CHECK_TOKTYPE(tokens[i], JSMN_OBJECT); + + if (*out_attributes) + { + return CGLTF_ERROR_JSON; + } + + *out_attributes_count = tokens[i].size; + *out_attributes = (cgltf_attribute*)cgltf_calloc(options, sizeof(cgltf_attribute), *out_attributes_count); + ++i; + + if (!*out_attributes) + { + return CGLTF_ERROR_NOMEM; + } + + for (cgltf_size j = 0; j < *out_attributes_count; ++j) + { + CGLTF_CHECK_KEY(tokens[i]); + + i = cgltf_parse_json_string(options, tokens, i, json_chunk, &(*out_attributes)[j].name); + if (i < 0) + { + return CGLTF_ERROR_JSON; + } + + cgltf_parse_attribute_type((*out_attributes)[j].name, &(*out_attributes)[j].type, &(*out_attributes)[j].index); + + (*out_attributes)[j].data = CGLTF_PTRINDEX(cgltf_accessor, cgltf_json_to_int(tokens + i, json_chunk)); + ++i; + } + + return i; +} + +static int cgltf_parse_json_extras(cgltf_options* options, jsmntok_t const* tokens, int i, const uint8_t* json_chunk, cgltf_extras* out_extras) +{ + if (out_extras->data) + { + return CGLTF_ERROR_JSON; + } + + /* fill deprecated fields for now, this will be removed in the future */ + out_extras->start_offset = tokens[i].start; + out_extras->end_offset = tokens[i].end; + + size_t start = tokens[i].start; + size_t size = tokens[i].end - start; + out_extras->data = (char*)options->memory.alloc_func(options->memory.user_data, size + 1); + if (!out_extras->data) + { + return CGLTF_ERROR_NOMEM; + } + strncpy(out_extras->data, (const char*)json_chunk + start, size); + out_extras->data[size] = '\0'; + + i = cgltf_skip_json(tokens, i); + return i; +} + +static int cgltf_parse_json_unprocessed_extension(cgltf_options* options, jsmntok_t const* tokens, int i, const uint8_t* json_chunk, cgltf_extension* out_extension) +{ + CGLTF_CHECK_TOKTYPE(tokens[i], JSMN_STRING); + CGLTF_CHECK_TOKTYPE(tokens[i+1], JSMN_OBJECT); + if (out_extension->name) + { + return CGLTF_ERROR_JSON; + } + + cgltf_size name_length = tokens[i].end - tokens[i].start; + out_extension->name = (char*)options->memory.alloc_func(options->memory.user_data, name_length + 1); + if (!out_extension->name) + { + return CGLTF_ERROR_NOMEM; + } + strncpy(out_extension->name, (const char*)json_chunk + tokens[i].start, name_length); + out_extension->name[name_length] = 0; + i++; + + size_t start = tokens[i].start; + size_t size = tokens[i].end - start; + out_extension->data = (char*)options->memory.alloc_func(options->memory.user_data, size + 1); + if (!out_extension->data) + { + return CGLTF_ERROR_NOMEM; + } + strncpy(out_extension->data, (const char*)json_chunk + start, size); + out_extension->data[size] = '\0'; + + i = cgltf_skip_json(tokens, i); + + return i; +} + +static int cgltf_parse_json_unprocessed_extensions(cgltf_options* options, jsmntok_t const* tokens, int i, const uint8_t* json_chunk, cgltf_size* out_extensions_count, cgltf_extension** out_extensions) +{ + ++i; + + CGLTF_CHECK_TOKTYPE(tokens[i], JSMN_OBJECT); + if(*out_extensions) + { + return CGLTF_ERROR_JSON; + } + + int extensions_size = tokens[i].size; + *out_extensions_count = 0; + *out_extensions = (cgltf_extension*)cgltf_calloc(options, sizeof(cgltf_extension), extensions_size); + + if (!*out_extensions) + { + return CGLTF_ERROR_NOMEM; + } + + ++i; + + for (int j = 0; j < extensions_size; ++j) + { + CGLTF_CHECK_KEY(tokens[i]); + + cgltf_size extension_index = (*out_extensions_count)++; + cgltf_extension* extension = &((*out_extensions)[extension_index]); + i = cgltf_parse_json_unprocessed_extension(options, tokens, i, json_chunk, extension); + + if (i < 0) + { + return i; + } + } + return i; +} + +static int cgltf_parse_json_draco_mesh_compression(cgltf_options* options, jsmntok_t const* tokens, int i, const uint8_t* json_chunk, cgltf_draco_mesh_compression* out_draco_mesh_compression) +{ + CGLTF_CHECK_TOKTYPE(tokens[i], JSMN_OBJECT); + + int size = tokens[i].size; + ++i; + + for (int j = 0; j < size; ++j) + { + CGLTF_CHECK_KEY(tokens[i]); + + if (cgltf_json_strcmp(tokens + i, json_chunk, "attributes") == 0) + { + i = cgltf_parse_json_attribute_list(options, tokens, i + 1, json_chunk, &out_draco_mesh_compression->attributes, &out_draco_mesh_compression->attributes_count); + } + else if (cgltf_json_strcmp(tokens + i, json_chunk, "bufferView") == 0) + { + ++i; + out_draco_mesh_compression->buffer_view = CGLTF_PTRINDEX(cgltf_buffer_view, cgltf_json_to_int(tokens + i, json_chunk)); + ++i; + } + else + { + i = cgltf_skip_json(tokens, i+1); + } + + if (i < 0) + { + return i; + } + } + + return i; +} + +static int cgltf_parse_json_mesh_gpu_instancing(cgltf_options* options, jsmntok_t const* tokens, int i, const uint8_t* json_chunk, cgltf_mesh_gpu_instancing* out_mesh_gpu_instancing) +{ + CGLTF_CHECK_TOKTYPE(tokens[i], JSMN_OBJECT); + + int size = tokens[i].size; + ++i; + + for (int j = 0; j < size; ++j) + { + CGLTF_CHECK_KEY(tokens[i]); + + if (cgltf_json_strcmp(tokens + i, json_chunk, "attributes") == 0) + { + i = cgltf_parse_json_attribute_list(options, tokens, i + 1, json_chunk, &out_mesh_gpu_instancing->attributes, &out_mesh_gpu_instancing->attributes_count); + } + else + { + i = cgltf_skip_json(tokens, i+1); + } + + if (i < 0) + { + return i; + } + } + + return i; +} + +static int cgltf_parse_json_material_mapping_data(cgltf_options* options, jsmntok_t const* tokens, int i, const uint8_t* json_chunk, cgltf_material_mapping* out_mappings, cgltf_size* offset) +{ + (void)options; + CGLTF_CHECK_TOKTYPE(tokens[i], JSMN_ARRAY); + + int size = tokens[i].size; + ++i; + + for (int j = 0; j < size; ++j) + { + CGLTF_CHECK_TOKTYPE(tokens[i], JSMN_OBJECT); + + int obj_size = tokens[i].size; + ++i; + + int material = -1; + int variants_tok = -1; + int extras_tok = -1; + + for (int k = 0; k < obj_size; ++k) + { + CGLTF_CHECK_KEY(tokens[i]); + + if (cgltf_json_strcmp(tokens + i, json_chunk, "material") == 0) + { + ++i; + material = cgltf_json_to_int(tokens + i, json_chunk); + ++i; + } + else if (cgltf_json_strcmp(tokens + i, json_chunk, "variants") == 0) + { + variants_tok = i+1; + CGLTF_CHECK_TOKTYPE(tokens[variants_tok], JSMN_ARRAY); + + i = cgltf_skip_json(tokens, i+1); + } + else if (cgltf_json_strcmp(tokens + i, json_chunk, "extras") == 0) + { + extras_tok = i + 1; + i = cgltf_skip_json(tokens, extras_tok); + } + else + { + i = cgltf_skip_json(tokens, i+1); + } + + if (i < 0) + { + return i; + } + } + + if (material < 0 || variants_tok < 0) + { + return CGLTF_ERROR_JSON; + } + + if (out_mappings) + { + for (int k = 0; k < tokens[variants_tok].size; ++k) + { + int variant = cgltf_json_to_int(&tokens[variants_tok + 1 + k], json_chunk); + if (variant < 0) + return variant; + + out_mappings[*offset].material = CGLTF_PTRINDEX(cgltf_material, material); + out_mappings[*offset].variant = variant; + + if (extras_tok >= 0) + { + int e = cgltf_parse_json_extras(options, tokens, extras_tok, json_chunk, &out_mappings[*offset].extras); + if (e < 0) + return e; + } + + (*offset)++; + } + } + else + { + (*offset) += tokens[variants_tok].size; + } + } + + return i; +} + +static int cgltf_parse_json_material_mappings(cgltf_options* options, jsmntok_t const* tokens, int i, const uint8_t* json_chunk, cgltf_primitive* out_prim) +{ + CGLTF_CHECK_TOKTYPE(tokens[i], JSMN_OBJECT); + + int size = tokens[i].size; + ++i; + + for (int j = 0; j < size; ++j) + { + CGLTF_CHECK_KEY(tokens[i]); + + if (cgltf_json_strcmp(tokens + i, json_chunk, "mappings") == 0) + { + if (out_prim->mappings) + { + return CGLTF_ERROR_JSON; + } + + cgltf_size mappings_offset = 0; + int k = cgltf_parse_json_material_mapping_data(options, tokens, i + 1, json_chunk, NULL, &mappings_offset); + if (k < 0) + { + return k; + } + + out_prim->mappings_count = mappings_offset; + out_prim->mappings = (cgltf_material_mapping*)cgltf_calloc(options, sizeof(cgltf_material_mapping), out_prim->mappings_count); + + mappings_offset = 0; + i = cgltf_parse_json_material_mapping_data(options, tokens, i + 1, json_chunk, out_prim->mappings, &mappings_offset); + } + else + { + i = cgltf_skip_json(tokens, i+1); + } + + if (i < 0) + { + return i; + } + } + + return i; +} + +static cgltf_primitive_type cgltf_json_to_primitive_type(jsmntok_t const* tok, const uint8_t* json_chunk) +{ + int type = cgltf_json_to_int(tok, json_chunk); + + switch (type) + { + case 0: + return cgltf_primitive_type_points; + case 1: + return cgltf_primitive_type_lines; + case 2: + return cgltf_primitive_type_line_loop; + case 3: + return cgltf_primitive_type_line_strip; + case 4: + return cgltf_primitive_type_triangles; + case 5: + return cgltf_primitive_type_triangle_strip; + case 6: + return cgltf_primitive_type_triangle_fan; + default: + return cgltf_primitive_type_invalid; + } +} + +static int cgltf_parse_json_primitive(cgltf_options* options, jsmntok_t const* tokens, int i, const uint8_t* json_chunk, cgltf_primitive* out_prim) +{ + CGLTF_CHECK_TOKTYPE(tokens[i], JSMN_OBJECT); + + out_prim->type = cgltf_primitive_type_triangles; + + int size = tokens[i].size; + ++i; + + for (int j = 0; j < size; ++j) + { + CGLTF_CHECK_KEY(tokens[i]); + + if (cgltf_json_strcmp(tokens+i, json_chunk, "mode") == 0) + { + ++i; + out_prim->type = cgltf_json_to_primitive_type(tokens+i, json_chunk); + ++i; + } + else if (cgltf_json_strcmp(tokens+i, json_chunk, "indices") == 0) + { + ++i; + out_prim->indices = CGLTF_PTRINDEX(cgltf_accessor, cgltf_json_to_int(tokens + i, json_chunk)); + ++i; + } + else if (cgltf_json_strcmp(tokens+i, json_chunk, "material") == 0) + { + ++i; + out_prim->material = CGLTF_PTRINDEX(cgltf_material, cgltf_json_to_int(tokens + i, json_chunk)); + ++i; + } + else if (cgltf_json_strcmp(tokens+i, json_chunk, "attributes") == 0) + { + i = cgltf_parse_json_attribute_list(options, tokens, i + 1, json_chunk, &out_prim->attributes, &out_prim->attributes_count); + } + else if (cgltf_json_strcmp(tokens+i, json_chunk, "targets") == 0) + { + i = cgltf_parse_json_array(options, tokens, i + 1, json_chunk, sizeof(cgltf_morph_target), (void**)&out_prim->targets, &out_prim->targets_count); + if (i < 0) + { + return i; + } + + for (cgltf_size k = 0; k < out_prim->targets_count; ++k) + { + i = cgltf_parse_json_attribute_list(options, tokens, i, json_chunk, &out_prim->targets[k].attributes, &out_prim->targets[k].attributes_count); + if (i < 0) + { + return i; + } + } + } + else if (cgltf_json_strcmp(tokens + i, json_chunk, "extras") == 0) + { + i = cgltf_parse_json_extras(options, tokens, i + 1, json_chunk, &out_prim->extras); + } + else if (cgltf_json_strcmp(tokens + i, json_chunk, "extensions") == 0) + { + ++i; + + CGLTF_CHECK_TOKTYPE(tokens[i], JSMN_OBJECT); + if(out_prim->extensions) + { + return CGLTF_ERROR_JSON; + } + + int extensions_size = tokens[i].size; + out_prim->extensions_count = 0; + out_prim->extensions = (cgltf_extension*)cgltf_calloc(options, sizeof(cgltf_extension), extensions_size); + + if (!out_prim->extensions) + { + return CGLTF_ERROR_NOMEM; + } + + ++i; + for (int k = 0; k < extensions_size; ++k) + { + CGLTF_CHECK_KEY(tokens[i]); + + if (cgltf_json_strcmp(tokens+i, json_chunk, "KHR_draco_mesh_compression") == 0) + { + out_prim->has_draco_mesh_compression = 1; + i = cgltf_parse_json_draco_mesh_compression(options, tokens, i + 1, json_chunk, &out_prim->draco_mesh_compression); + } + else if (cgltf_json_strcmp(tokens+i, json_chunk, "KHR_materials_variants") == 0) + { + i = cgltf_parse_json_material_mappings(options, tokens, i + 1, json_chunk, out_prim); + } + else + { + i = cgltf_parse_json_unprocessed_extension(options, tokens, i, json_chunk, &(out_prim->extensions[out_prim->extensions_count++])); + } + + if (i < 0) + { + return i; + } + } + } + else + { + i = cgltf_skip_json(tokens, i+1); + } + + if (i < 0) + { + return i; + } + } + + return i; +} + +static int cgltf_parse_json_mesh(cgltf_options* options, jsmntok_t const* tokens, int i, const uint8_t* json_chunk, cgltf_mesh* out_mesh) +{ + CGLTF_CHECK_TOKTYPE(tokens[i], JSMN_OBJECT); + + int size = tokens[i].size; + ++i; + + for (int j = 0; j < size; ++j) + { + CGLTF_CHECK_KEY(tokens[i]); + + if (cgltf_json_strcmp(tokens+i, json_chunk, "name") == 0) + { + i = cgltf_parse_json_string(options, tokens, i + 1, json_chunk, &out_mesh->name); + } + else if (cgltf_json_strcmp(tokens+i, json_chunk, "primitives") == 0) + { + i = cgltf_parse_json_array(options, tokens, i + 1, json_chunk, sizeof(cgltf_primitive), (void**)&out_mesh->primitives, &out_mesh->primitives_count); + if (i < 0) + { + return i; + } + + for (cgltf_size prim_index = 0; prim_index < out_mesh->primitives_count; ++prim_index) + { + i = cgltf_parse_json_primitive(options, tokens, i, json_chunk, &out_mesh->primitives[prim_index]); + if (i < 0) + { + return i; + } + } + } + else if (cgltf_json_strcmp(tokens + i, json_chunk, "weights") == 0) + { + i = cgltf_parse_json_array(options, tokens, i + 1, json_chunk, sizeof(cgltf_float), (void**)&out_mesh->weights, &out_mesh->weights_count); + if (i < 0) + { + return i; + } + + i = cgltf_parse_json_float_array(tokens, i - 1, json_chunk, out_mesh->weights, (int)out_mesh->weights_count); + } + else if (cgltf_json_strcmp(tokens + i, json_chunk, "extras") == 0) + { + ++i; + + out_mesh->extras.start_offset = tokens[i].start; + out_mesh->extras.end_offset = tokens[i].end; + + if (tokens[i].type == JSMN_OBJECT) + { + int extras_size = tokens[i].size; + ++i; + + for (int k = 0; k < extras_size; ++k) + { + CGLTF_CHECK_KEY(tokens[i]); + + if (cgltf_json_strcmp(tokens+i, json_chunk, "targetNames") == 0 && tokens[i+1].type == JSMN_ARRAY) + { + i = cgltf_parse_json_string_array(options, tokens, i + 1, json_chunk, &out_mesh->target_names, &out_mesh->target_names_count); + } + else + { + i = cgltf_skip_json(tokens, i+1); + } + + if (i < 0) + { + return i; + } + } + } + else + { + i = cgltf_skip_json(tokens, i); + } + } + else if (cgltf_json_strcmp(tokens + i, json_chunk, "extensions") == 0) + { + i = cgltf_parse_json_unprocessed_extensions(options, tokens, i, json_chunk, &out_mesh->extensions_count, &out_mesh->extensions); + } + else + { + i = cgltf_skip_json(tokens, i+1); + } + + if (i < 0) + { + return i; + } + } + + return i; +} + +static int cgltf_parse_json_meshes(cgltf_options* options, jsmntok_t const* tokens, int i, const uint8_t* json_chunk, cgltf_data* out_data) +{ + i = cgltf_parse_json_array(options, tokens, i, json_chunk, sizeof(cgltf_mesh), (void**)&out_data->meshes, &out_data->meshes_count); + if (i < 0) + { + return i; + } + + for (cgltf_size j = 0; j < out_data->meshes_count; ++j) + { + i = cgltf_parse_json_mesh(options, tokens, i, json_chunk, &out_data->meshes[j]); + if (i < 0) + { + return i; + } + } + return i; +} + +static cgltf_component_type cgltf_json_to_component_type(jsmntok_t const* tok, const uint8_t* json_chunk) +{ + int type = cgltf_json_to_int(tok, json_chunk); + + switch (type) + { + case 5120: + return cgltf_component_type_r_8; + case 5121: + return cgltf_component_type_r_8u; + case 5122: + return cgltf_component_type_r_16; + case 5123: + return cgltf_component_type_r_16u; + case 5125: + return cgltf_component_type_r_32u; + case 5126: + return cgltf_component_type_r_32f; + default: + return cgltf_component_type_invalid; + } +} + +static int cgltf_parse_json_accessor_sparse(jsmntok_t const* tokens, int i, const uint8_t* json_chunk, cgltf_accessor_sparse* out_sparse) +{ + CGLTF_CHECK_TOKTYPE(tokens[i], JSMN_OBJECT); + + int size = tokens[i].size; + ++i; + + for (int j = 0; j < size; ++j) + { + CGLTF_CHECK_KEY(tokens[i]); + + if (cgltf_json_strcmp(tokens+i, json_chunk, "count") == 0) + { + ++i; + out_sparse->count = cgltf_json_to_size(tokens + i, json_chunk); + ++i; + } + else if (cgltf_json_strcmp(tokens+i, json_chunk, "indices") == 0) + { + ++i; + CGLTF_CHECK_TOKTYPE(tokens[i], JSMN_OBJECT); + + int indices_size = tokens[i].size; + ++i; + + for (int k = 0; k < indices_size; ++k) + { + CGLTF_CHECK_KEY(tokens[i]); + + if (cgltf_json_strcmp(tokens+i, json_chunk, "bufferView") == 0) + { + ++i; + out_sparse->indices_buffer_view = CGLTF_PTRINDEX(cgltf_buffer_view, cgltf_json_to_int(tokens + i, json_chunk)); + ++i; + } + else if (cgltf_json_strcmp(tokens+i, json_chunk, "byteOffset") == 0) + { + ++i; + out_sparse->indices_byte_offset = cgltf_json_to_size(tokens + i, json_chunk); + ++i; + } + else if (cgltf_json_strcmp(tokens+i, json_chunk, "componentType") == 0) + { + ++i; + out_sparse->indices_component_type = cgltf_json_to_component_type(tokens + i, json_chunk); + ++i; + } + else + { + i = cgltf_skip_json(tokens, i+1); + } + + if (i < 0) + { + return i; + } + } + } + else if (cgltf_json_strcmp(tokens+i, json_chunk, "values") == 0) + { + ++i; + CGLTF_CHECK_TOKTYPE(tokens[i], JSMN_OBJECT); + + int values_size = tokens[i].size; + ++i; + + for (int k = 0; k < values_size; ++k) + { + CGLTF_CHECK_KEY(tokens[i]); + + if (cgltf_json_strcmp(tokens+i, json_chunk, "bufferView") == 0) + { + ++i; + out_sparse->values_buffer_view = CGLTF_PTRINDEX(cgltf_buffer_view, cgltf_json_to_int(tokens + i, json_chunk)); + ++i; + } + else if (cgltf_json_strcmp(tokens+i, json_chunk, "byteOffset") == 0) + { + ++i; + out_sparse->values_byte_offset = cgltf_json_to_size(tokens + i, json_chunk); + ++i; + } + else + { + i = cgltf_skip_json(tokens, i+1); + } + + if (i < 0) + { + return i; + } + } + } + else + { + i = cgltf_skip_json(tokens, i+1); + } + + if (i < 0) + { + return i; + } + } + + return i; +} + +static int cgltf_parse_json_accessor(cgltf_options* options, jsmntok_t const* tokens, int i, const uint8_t* json_chunk, cgltf_accessor* out_accessor) +{ + CGLTF_CHECK_TOKTYPE(tokens[i], JSMN_OBJECT); + + int size = tokens[i].size; + ++i; + + for (int j = 0; j < size; ++j) + { + CGLTF_CHECK_KEY(tokens[i]); + + if (cgltf_json_strcmp(tokens + i, json_chunk, "name") == 0) + { + i = cgltf_parse_json_string(options, tokens, i + 1, json_chunk, &out_accessor->name); + } + else if (cgltf_json_strcmp(tokens+i, json_chunk, "bufferView") == 0) + { + ++i; + out_accessor->buffer_view = CGLTF_PTRINDEX(cgltf_buffer_view, cgltf_json_to_int(tokens + i, json_chunk)); + ++i; + } + else if (cgltf_json_strcmp(tokens+i, json_chunk, "byteOffset") == 0) + { + ++i; + out_accessor->offset = + cgltf_json_to_size(tokens+i, json_chunk); + ++i; + } + else if (cgltf_json_strcmp(tokens+i, json_chunk, "componentType") == 0) + { + ++i; + out_accessor->component_type = cgltf_json_to_component_type(tokens + i, json_chunk); + ++i; + } + else if (cgltf_json_strcmp(tokens+i, json_chunk, "normalized") == 0) + { + ++i; + out_accessor->normalized = cgltf_json_to_bool(tokens+i, json_chunk); + ++i; + } + else if (cgltf_json_strcmp(tokens+i, json_chunk, "count") == 0) + { + ++i; + out_accessor->count = cgltf_json_to_size(tokens+i, json_chunk); + ++i; + } + else if (cgltf_json_strcmp(tokens+i, json_chunk, "type") == 0) + { + ++i; + if (cgltf_json_strcmp(tokens+i, json_chunk, "SCALAR") == 0) + { + out_accessor->type = cgltf_type_scalar; + } + else if (cgltf_json_strcmp(tokens+i, json_chunk, "VEC2") == 0) + { + out_accessor->type = cgltf_type_vec2; + } + else if (cgltf_json_strcmp(tokens+i, json_chunk, "VEC3") == 0) + { + out_accessor->type = cgltf_type_vec3; + } + else if (cgltf_json_strcmp(tokens+i, json_chunk, "VEC4") == 0) + { + out_accessor->type = cgltf_type_vec4; + } + else if (cgltf_json_strcmp(tokens+i, json_chunk, "MAT2") == 0) + { + out_accessor->type = cgltf_type_mat2; + } + else if (cgltf_json_strcmp(tokens+i, json_chunk, "MAT3") == 0) + { + out_accessor->type = cgltf_type_mat3; + } + else if (cgltf_json_strcmp(tokens+i, json_chunk, "MAT4") == 0) + { + out_accessor->type = cgltf_type_mat4; + } + ++i; + } + else if (cgltf_json_strcmp(tokens + i, json_chunk, "min") == 0) + { + ++i; + out_accessor->has_min = 1; + // note: we can't parse the precise number of elements since type may not have been computed yet + int min_size = tokens[i].size > 16 ? 16 : tokens[i].size; + i = cgltf_parse_json_float_array(tokens, i, json_chunk, out_accessor->min, min_size); + } + else if (cgltf_json_strcmp(tokens + i, json_chunk, "max") == 0) + { + ++i; + out_accessor->has_max = 1; + // note: we can't parse the precise number of elements since type may not have been computed yet + int max_size = tokens[i].size > 16 ? 16 : tokens[i].size; + i = cgltf_parse_json_float_array(tokens, i, json_chunk, out_accessor->max, max_size); + } + else if (cgltf_json_strcmp(tokens + i, json_chunk, "sparse") == 0) + { + out_accessor->is_sparse = 1; + i = cgltf_parse_json_accessor_sparse(tokens, i + 1, json_chunk, &out_accessor->sparse); + } + else if (cgltf_json_strcmp(tokens + i, json_chunk, "extras") == 0) + { + i = cgltf_parse_json_extras(options, tokens, i + 1, json_chunk, &out_accessor->extras); + } + else if (cgltf_json_strcmp(tokens + i, json_chunk, "extensions") == 0) + { + i = cgltf_parse_json_unprocessed_extensions(options, tokens, i, json_chunk, &out_accessor->extensions_count, &out_accessor->extensions); + } + else + { + i = cgltf_skip_json(tokens, i+1); + } + + if (i < 0) + { + return i; + } + } + + return i; +} + +static int cgltf_parse_json_texture_transform(jsmntok_t const* tokens, int i, const uint8_t* json_chunk, cgltf_texture_transform* out_texture_transform) +{ + CGLTF_CHECK_TOKTYPE(tokens[i], JSMN_OBJECT); + + int size = tokens[i].size; + ++i; + + for (int j = 0; j < size; ++j) + { + CGLTF_CHECK_KEY(tokens[i]); + + if (cgltf_json_strcmp(tokens + i, json_chunk, "offset") == 0) + { + i = cgltf_parse_json_float_array(tokens, i + 1, json_chunk, out_texture_transform->offset, 2); + } + else if (cgltf_json_strcmp(tokens + i, json_chunk, "rotation") == 0) + { + ++i; + out_texture_transform->rotation = cgltf_json_to_float(tokens + i, json_chunk); + ++i; + } + else if (cgltf_json_strcmp(tokens + i, json_chunk, "scale") == 0) + { + i = cgltf_parse_json_float_array(tokens, i + 1, json_chunk, out_texture_transform->scale, 2); + } + else if (cgltf_json_strcmp(tokens + i, json_chunk, "texCoord") == 0) + { + ++i; + out_texture_transform->has_texcoord = 1; + out_texture_transform->texcoord = cgltf_json_to_int(tokens + i, json_chunk); + ++i; + } + else + { + i = cgltf_skip_json(tokens, i + 1); + } + + if (i < 0) + { + return i; + } + } + + return i; +} + +static int cgltf_parse_json_texture_view(cgltf_options* options, jsmntok_t const* tokens, int i, const uint8_t* json_chunk, cgltf_texture_view* out_texture_view) +{ + (void)options; + + CGLTF_CHECK_TOKTYPE(tokens[i], JSMN_OBJECT); + + out_texture_view->scale = 1.0f; + cgltf_fill_float_array(out_texture_view->transform.scale, 2, 1.0f); + + int size = tokens[i].size; + ++i; + + for (int j = 0; j < size; ++j) + { + CGLTF_CHECK_KEY(tokens[i]); + + if (cgltf_json_strcmp(tokens + i, json_chunk, "index") == 0) + { + ++i; + out_texture_view->texture = CGLTF_PTRINDEX(cgltf_texture, cgltf_json_to_int(tokens + i, json_chunk)); + ++i; + } + else if (cgltf_json_strcmp(tokens + i, json_chunk, "texCoord") == 0) + { + ++i; + out_texture_view->texcoord = cgltf_json_to_int(tokens + i, json_chunk); + ++i; + } + else if (cgltf_json_strcmp(tokens + i, json_chunk, "scale") == 0) + { + ++i; + out_texture_view->scale = cgltf_json_to_float(tokens + i, json_chunk); + ++i; + } + else if (cgltf_json_strcmp(tokens + i, json_chunk, "strength") == 0) + { + ++i; + out_texture_view->scale = cgltf_json_to_float(tokens + i, json_chunk); + ++i; + } + else if (cgltf_json_strcmp(tokens + i, json_chunk, "extensions") == 0) + { + ++i; + + CGLTF_CHECK_TOKTYPE(tokens[i], JSMN_OBJECT); + int extensions_size = tokens[i].size; + + ++i; + + for (int k = 0; k < extensions_size; ++k) + { + CGLTF_CHECK_KEY(tokens[i]); + + if (cgltf_json_strcmp(tokens+i, json_chunk, "KHR_texture_transform") == 0) + { + out_texture_view->has_transform = 1; + i = cgltf_parse_json_texture_transform(tokens, i + 1, json_chunk, &out_texture_view->transform); + } + else + { + i = cgltf_skip_json(tokens, i + 1); + } + + if (i < 0) + { + return i; + } + } + } + else + { + i = cgltf_skip_json(tokens, i + 1); + } + + if (i < 0) + { + return i; + } + } + + return i; +} + +static int cgltf_parse_json_pbr_metallic_roughness(cgltf_options* options, jsmntok_t const* tokens, int i, const uint8_t* json_chunk, cgltf_pbr_metallic_roughness* out_pbr) +{ + CGLTF_CHECK_TOKTYPE(tokens[i], JSMN_OBJECT); + + int size = tokens[i].size; + ++i; + + for (int j = 0; j < size; ++j) + { + CGLTF_CHECK_KEY(tokens[i]); + + if (cgltf_json_strcmp(tokens+i, json_chunk, "metallicFactor") == 0) + { + ++i; + out_pbr->metallic_factor = + cgltf_json_to_float(tokens + i, json_chunk); + ++i; + } + else if (cgltf_json_strcmp(tokens+i, json_chunk, "roughnessFactor") == 0) + { + ++i; + out_pbr->roughness_factor = + cgltf_json_to_float(tokens+i, json_chunk); + ++i; + } + else if (cgltf_json_strcmp(tokens+i, json_chunk, "baseColorFactor") == 0) + { + i = cgltf_parse_json_float_array(tokens, i + 1, json_chunk, out_pbr->base_color_factor, 4); + } + else if (cgltf_json_strcmp(tokens+i, json_chunk, "baseColorTexture") == 0) + { + i = cgltf_parse_json_texture_view(options, tokens, i + 1, json_chunk, &out_pbr->base_color_texture); + } + else if (cgltf_json_strcmp(tokens + i, json_chunk, "metallicRoughnessTexture") == 0) + { + i = cgltf_parse_json_texture_view(options, tokens, i + 1, json_chunk, &out_pbr->metallic_roughness_texture); + } + else + { + i = cgltf_skip_json(tokens, i+1); + } + + if (i < 0) + { + return i; + } + } + + return i; +} + +static int cgltf_parse_json_pbr_specular_glossiness(cgltf_options* options, jsmntok_t const* tokens, int i, const uint8_t* json_chunk, cgltf_pbr_specular_glossiness* out_pbr) +{ + CGLTF_CHECK_TOKTYPE(tokens[i], JSMN_OBJECT); + int size = tokens[i].size; + ++i; + + for (int j = 0; j < size; ++j) + { + CGLTF_CHECK_KEY(tokens[i]); + + if (cgltf_json_strcmp(tokens+i, json_chunk, "diffuseFactor") == 0) + { + i = cgltf_parse_json_float_array(tokens, i + 1, json_chunk, out_pbr->diffuse_factor, 4); + } + else if (cgltf_json_strcmp(tokens+i, json_chunk, "specularFactor") == 0) + { + i = cgltf_parse_json_float_array(tokens, i + 1, json_chunk, out_pbr->specular_factor, 3); + } + else if (cgltf_json_strcmp(tokens+i, json_chunk, "glossinessFactor") == 0) + { + ++i; + out_pbr->glossiness_factor = cgltf_json_to_float(tokens + i, json_chunk); + ++i; + } + else if (cgltf_json_strcmp(tokens+i, json_chunk, "diffuseTexture") == 0) + { + i = cgltf_parse_json_texture_view(options, tokens, i + 1, json_chunk, &out_pbr->diffuse_texture); + } + else if (cgltf_json_strcmp(tokens+i, json_chunk, "specularGlossinessTexture") == 0) + { + i = cgltf_parse_json_texture_view(options, tokens, i + 1, json_chunk, &out_pbr->specular_glossiness_texture); + } + else + { + i = cgltf_skip_json(tokens, i+1); + } + + if (i < 0) + { + return i; + } + } + + return i; +} + +static int cgltf_parse_json_clearcoat(cgltf_options* options, jsmntok_t const* tokens, int i, const uint8_t* json_chunk, cgltf_clearcoat* out_clearcoat) +{ + CGLTF_CHECK_TOKTYPE(tokens[i], JSMN_OBJECT); + int size = tokens[i].size; + ++i; + + for (int j = 0; j < size; ++j) + { + CGLTF_CHECK_KEY(tokens[i]); + + if (cgltf_json_strcmp(tokens+i, json_chunk, "clearcoatFactor") == 0) + { + ++i; + out_clearcoat->clearcoat_factor = cgltf_json_to_float(tokens + i, json_chunk); + ++i; + } + else if (cgltf_json_strcmp(tokens+i, json_chunk, "clearcoatRoughnessFactor") == 0) + { + ++i; + out_clearcoat->clearcoat_roughness_factor = cgltf_json_to_float(tokens + i, json_chunk); + ++i; + } + else if (cgltf_json_strcmp(tokens+i, json_chunk, "clearcoatTexture") == 0) + { + i = cgltf_parse_json_texture_view(options, tokens, i + 1, json_chunk, &out_clearcoat->clearcoat_texture); + } + else if (cgltf_json_strcmp(tokens+i, json_chunk, "clearcoatRoughnessTexture") == 0) + { + i = cgltf_parse_json_texture_view(options, tokens, i + 1, json_chunk, &out_clearcoat->clearcoat_roughness_texture); + } + else if (cgltf_json_strcmp(tokens+i, json_chunk, "clearcoatNormalTexture") == 0) + { + i = cgltf_parse_json_texture_view(options, tokens, i + 1, json_chunk, &out_clearcoat->clearcoat_normal_texture); + } + else + { + i = cgltf_skip_json(tokens, i+1); + } + + if (i < 0) + { + return i; + } + } + + return i; +} + +static int cgltf_parse_json_ior(jsmntok_t const* tokens, int i, const uint8_t* json_chunk, cgltf_ior* out_ior) +{ + CGLTF_CHECK_TOKTYPE(tokens[i], JSMN_OBJECT); + int size = tokens[i].size; + ++i; + + // Default values + out_ior->ior = 1.5f; + + for (int j = 0; j < size; ++j) + { + CGLTF_CHECK_KEY(tokens[i]); + + if (cgltf_json_strcmp(tokens+i, json_chunk, "ior") == 0) + { + ++i; + out_ior->ior = cgltf_json_to_float(tokens + i, json_chunk); + ++i; + } + else + { + i = cgltf_skip_json(tokens, i+1); + } + + if (i < 0) + { + return i; + } + } + + return i; +} + +static int cgltf_parse_json_specular(cgltf_options* options, jsmntok_t const* tokens, int i, const uint8_t* json_chunk, cgltf_specular* out_specular) +{ + CGLTF_CHECK_TOKTYPE(tokens[i], JSMN_OBJECT); + int size = tokens[i].size; + ++i; + + // Default values + out_specular->specular_factor = 1.0f; + cgltf_fill_float_array(out_specular->specular_color_factor, 3, 1.0f); + + for (int j = 0; j < size; ++j) + { + CGLTF_CHECK_KEY(tokens[i]); + + if (cgltf_json_strcmp(tokens+i, json_chunk, "specularFactor") == 0) + { + ++i; + out_specular->specular_factor = cgltf_json_to_float(tokens + i, json_chunk); + ++i; + } + else if (cgltf_json_strcmp(tokens+i, json_chunk, "specularColorFactor") == 0) + { + i = cgltf_parse_json_float_array(tokens, i + 1, json_chunk, out_specular->specular_color_factor, 3); + } + else if (cgltf_json_strcmp(tokens+i, json_chunk, "specularTexture") == 0) + { + i = cgltf_parse_json_texture_view(options, tokens, i + 1, json_chunk, &out_specular->specular_texture); + } + else if (cgltf_json_strcmp(tokens + i, json_chunk, "specularColorTexture") == 0) + { + i = cgltf_parse_json_texture_view(options, tokens, i + 1, json_chunk, &out_specular->specular_color_texture); + } + else + { + i = cgltf_skip_json(tokens, i+1); + } + + if (i < 0) + { + return i; + } + } + + return i; +} + +static int cgltf_parse_json_transmission(cgltf_options* options, jsmntok_t const* tokens, int i, const uint8_t* json_chunk, cgltf_transmission* out_transmission) +{ + CGLTF_CHECK_TOKTYPE(tokens[i], JSMN_OBJECT); + int size = tokens[i].size; + ++i; + + for (int j = 0; j < size; ++j) + { + CGLTF_CHECK_KEY(tokens[i]); + + if (cgltf_json_strcmp(tokens+i, json_chunk, "transmissionFactor") == 0) + { + ++i; + out_transmission->transmission_factor = cgltf_json_to_float(tokens + i, json_chunk); + ++i; + } + else if (cgltf_json_strcmp(tokens+i, json_chunk, "transmissionTexture") == 0) + { + i = cgltf_parse_json_texture_view(options, tokens, i + 1, json_chunk, &out_transmission->transmission_texture); + } + else + { + i = cgltf_skip_json(tokens, i+1); + } + + if (i < 0) + { + return i; + } + } + + return i; +} + +static int cgltf_parse_json_volume(cgltf_options* options, jsmntok_t const* tokens, int i, const uint8_t* json_chunk, cgltf_volume* out_volume) +{ + CGLTF_CHECK_TOKTYPE(tokens[i], JSMN_OBJECT); + int size = tokens[i].size; + ++i; + + for (int j = 0; j < size; ++j) + { + CGLTF_CHECK_KEY(tokens[i]); + + if (cgltf_json_strcmp(tokens + i, json_chunk, "thicknessFactor") == 0) + { + ++i; + out_volume->thickness_factor = cgltf_json_to_float(tokens + i, json_chunk); + ++i; + } + else if (cgltf_json_strcmp(tokens + i, json_chunk, "thicknessTexture") == 0) + { + i = cgltf_parse_json_texture_view(options, tokens, i + 1, json_chunk, &out_volume->thickness_texture); + } + else if (cgltf_json_strcmp(tokens + i, json_chunk, "attenuationColor") == 0) + { + i = cgltf_parse_json_float_array(tokens, i + 1, json_chunk, out_volume->attenuation_color, 3); + } + else if (cgltf_json_strcmp(tokens + i, json_chunk, "attenuationDistance") == 0) + { + ++i; + out_volume->attenuation_distance = cgltf_json_to_float(tokens + i, json_chunk); + ++i; + } + else + { + i = cgltf_skip_json(tokens, i + 1); + } + + if (i < 0) + { + return i; + } + } + + return i; +} + +static int cgltf_parse_json_sheen(cgltf_options* options, jsmntok_t const* tokens, int i, const uint8_t* json_chunk, cgltf_sheen* out_sheen) +{ + CGLTF_CHECK_TOKTYPE(tokens[i], JSMN_OBJECT); + int size = tokens[i].size; + ++i; + + for (int j = 0; j < size; ++j) + { + CGLTF_CHECK_KEY(tokens[i]); + + if (cgltf_json_strcmp(tokens+i, json_chunk, "sheenColorFactor") == 0) + { + i = cgltf_parse_json_float_array(tokens, i + 1, json_chunk, out_sheen->sheen_color_factor, 3); + } + else if (cgltf_json_strcmp(tokens+i, json_chunk, "sheenColorTexture") == 0) + { + i = cgltf_parse_json_texture_view(options, tokens, i + 1, json_chunk, &out_sheen->sheen_color_texture); + } + else if (cgltf_json_strcmp(tokens+i, json_chunk, "sheenRoughnessFactor") == 0) + { + ++i; + out_sheen->sheen_roughness_factor = cgltf_json_to_float(tokens + i, json_chunk); + ++i; + } + else if (cgltf_json_strcmp(tokens+i, json_chunk, "sheenRoughnessTexture") == 0) + { + i = cgltf_parse_json_texture_view(options, tokens, i + 1, json_chunk, &out_sheen->sheen_roughness_texture); + } + else + { + i = cgltf_skip_json(tokens, i+1); + } + + if (i < 0) + { + return i; + } + } + + return i; +} + +static int cgltf_parse_json_emissive_strength(jsmntok_t const* tokens, int i, const uint8_t* json_chunk, cgltf_emissive_strength* out_emissive_strength) +{ + CGLTF_CHECK_TOKTYPE(tokens[i], JSMN_OBJECT); + int size = tokens[i].size; + ++i; + + // Default + out_emissive_strength->emissive_strength = 1.f; + + for (int j = 0; j < size; ++j) + { + CGLTF_CHECK_KEY(tokens[i]); + + if (cgltf_json_strcmp(tokens + i, json_chunk, "emissiveStrength") == 0) + { + ++i; + out_emissive_strength->emissive_strength = cgltf_json_to_float(tokens + i, json_chunk); + ++i; + } + else + { + i = cgltf_skip_json(tokens, i + 1); + } + + if (i < 0) + { + return i; + } + } + + return i; +} + +static int cgltf_parse_json_iridescence(cgltf_options* options, jsmntok_t const* tokens, int i, const uint8_t* json_chunk, cgltf_iridescence* out_iridescence) +{ + CGLTF_CHECK_TOKTYPE(tokens[i], JSMN_OBJECT); + int size = tokens[i].size; + ++i; + + // Default + out_iridescence->iridescence_ior = 1.3f; + out_iridescence->iridescence_thickness_min = 100.f; + out_iridescence->iridescence_thickness_max = 400.f; + + for (int j = 0; j < size; ++j) + { + CGLTF_CHECK_KEY(tokens[i]); + + if (cgltf_json_strcmp(tokens + i, json_chunk, "iridescenceFactor") == 0) + { + ++i; + out_iridescence->iridescence_factor = cgltf_json_to_float(tokens + i, json_chunk); + ++i; + } + else if (cgltf_json_strcmp(tokens + i, json_chunk, "iridescenceTexture") == 0) + { + i = cgltf_parse_json_texture_view(options, tokens, i + 1, json_chunk, &out_iridescence->iridescence_texture); + } + else if (cgltf_json_strcmp(tokens + i, json_chunk, "iridescenceIor") == 0) + { + ++i; + out_iridescence->iridescence_ior = cgltf_json_to_float(tokens + i, json_chunk); + ++i; + } + else if (cgltf_json_strcmp(tokens + i, json_chunk, "iridescenceThicknessMinimum") == 0) + { + ++i; + out_iridescence->iridescence_thickness_min = cgltf_json_to_float(tokens + i, json_chunk); + ++i; + } + else if (cgltf_json_strcmp(tokens + i, json_chunk, "iridescenceThicknessMaximum") == 0) + { + ++i; + out_iridescence->iridescence_thickness_max = cgltf_json_to_float(tokens + i, json_chunk); + ++i; + } + else if (cgltf_json_strcmp(tokens + i, json_chunk, "iridescenceThicknessTexture") == 0) + { + i = cgltf_parse_json_texture_view(options, tokens, i + 1, json_chunk, &out_iridescence->iridescence_thickness_texture); + } + else + { + i = cgltf_skip_json(tokens, i + 1); + } + + if (i < 0) + { + return i; + } + } + + return i; +} + +static int cgltf_parse_json_diffuse_transmission(cgltf_options* options, jsmntok_t const* tokens, int i, const uint8_t* json_chunk, cgltf_diffuse_transmission* out_diff_transmission) +{ + CGLTF_CHECK_TOKTYPE(tokens[i], JSMN_OBJECT); + int size = tokens[i].size; + ++i; + + // Defaults + cgltf_fill_float_array(out_diff_transmission->diffuse_transmission_color_factor, 3, 1.0f); + out_diff_transmission->diffuse_transmission_factor = 0.f; + + for (int j = 0; j < size; ++j) + { + CGLTF_CHECK_KEY(tokens[i]); + + if (cgltf_json_strcmp(tokens + i, json_chunk, "diffuseTransmissionFactor") == 0) + { + ++i; + out_diff_transmission->diffuse_transmission_factor = cgltf_json_to_float(tokens + i, json_chunk); + ++i; + } + else if (cgltf_json_strcmp(tokens + i, json_chunk, "diffuseTransmissionTexture") == 0) + { + i = cgltf_parse_json_texture_view(options, tokens, i + 1, json_chunk, &out_diff_transmission->diffuse_transmission_texture); + } + else if (cgltf_json_strcmp(tokens + i, json_chunk, "diffuseTransmissionColorFactor") == 0) + { + i = cgltf_parse_json_float_array(tokens, i + 1, json_chunk, out_diff_transmission->diffuse_transmission_color_factor, 3); + } + else if (cgltf_json_strcmp(tokens + i, json_chunk, "diffuseTransmissionColorTexture") == 0) + { + i = cgltf_parse_json_texture_view(options, tokens, i + 1, json_chunk, &out_diff_transmission->diffuse_transmission_color_texture); + } + else + { + i = cgltf_skip_json(tokens, i + 1); + } + + if (i < 0) + { + return i; + } + } + + return i; +} + +static int cgltf_parse_json_anisotropy(cgltf_options* options, jsmntok_t const* tokens, int i, const uint8_t* json_chunk, cgltf_anisotropy* out_anisotropy) +{ + CGLTF_CHECK_TOKTYPE(tokens[i], JSMN_OBJECT); + int size = tokens[i].size; + ++i; + + + for (int j = 0; j < size; ++j) + { + CGLTF_CHECK_KEY(tokens[i]); + + if (cgltf_json_strcmp(tokens + i, json_chunk, "anisotropyStrength") == 0) + { + ++i; + out_anisotropy->anisotropy_strength = cgltf_json_to_float(tokens + i, json_chunk); + ++i; + } + else if (cgltf_json_strcmp(tokens + i, json_chunk, "anisotropyRotation") == 0) + { + ++i; + out_anisotropy->anisotropy_rotation = cgltf_json_to_float(tokens + i, json_chunk); + ++i; + } + else if (cgltf_json_strcmp(tokens + i, json_chunk, "anisotropyTexture") == 0) + { + i = cgltf_parse_json_texture_view(options, tokens, i + 1, json_chunk, &out_anisotropy->anisotropy_texture); + } + else + { + i = cgltf_skip_json(tokens, i + 1); + } + + if (i < 0) + { + return i; + } + } + + return i; +} + +static int cgltf_parse_json_dispersion(jsmntok_t const* tokens, int i, const uint8_t* json_chunk, cgltf_dispersion* out_dispersion) +{ + CGLTF_CHECK_TOKTYPE(tokens[i], JSMN_OBJECT); + int size = tokens[i].size; + ++i; + + + for (int j = 0; j < size; ++j) + { + CGLTF_CHECK_KEY(tokens[i]); + + if (cgltf_json_strcmp(tokens + i, json_chunk, "dispersion") == 0) + { + ++i; + out_dispersion->dispersion = cgltf_json_to_float(tokens + i, json_chunk); + ++i; + } + else + { + i = cgltf_skip_json(tokens, i + 1); + } + + if (i < 0) + { + return i; + } + } + + return i; +} + +static int cgltf_parse_json_image(cgltf_options* options, jsmntok_t const* tokens, int i, const uint8_t* json_chunk, cgltf_image* out_image) +{ + CGLTF_CHECK_TOKTYPE(tokens[i], JSMN_OBJECT); + + int size = tokens[i].size; + ++i; + + for (int j = 0; j < size; ++j) + { + CGLTF_CHECK_KEY(tokens[i]); + + if (cgltf_json_strcmp(tokens + i, json_chunk, "uri") == 0) + { + i = cgltf_parse_json_string(options, tokens, i + 1, json_chunk, &out_image->uri); + } + else if (cgltf_json_strcmp(tokens+i, json_chunk, "bufferView") == 0) + { + ++i; + out_image->buffer_view = CGLTF_PTRINDEX(cgltf_buffer_view, cgltf_json_to_int(tokens + i, json_chunk)); + ++i; + } + else if (cgltf_json_strcmp(tokens + i, json_chunk, "mimeType") == 0) + { + i = cgltf_parse_json_string(options, tokens, i + 1, json_chunk, &out_image->mime_type); + } + else if (cgltf_json_strcmp(tokens + i, json_chunk, "name") == 0) + { + i = cgltf_parse_json_string(options, tokens, i + 1, json_chunk, &out_image->name); + } + else if (cgltf_json_strcmp(tokens + i, json_chunk, "extras") == 0) + { + i = cgltf_parse_json_extras(options, tokens, i + 1, json_chunk, &out_image->extras); + } + else if (cgltf_json_strcmp(tokens + i, json_chunk, "extensions") == 0) + { + i = cgltf_parse_json_unprocessed_extensions(options, tokens, i, json_chunk, &out_image->extensions_count, &out_image->extensions); + } + else + { + i = cgltf_skip_json(tokens, i + 1); + } + + if (i < 0) + { + return i; + } + } + + return i; +} + +static int cgltf_parse_json_sampler(cgltf_options* options, jsmntok_t const* tokens, int i, const uint8_t* json_chunk, cgltf_sampler* out_sampler) +{ + (void)options; + CGLTF_CHECK_TOKTYPE(tokens[i], JSMN_OBJECT); + + out_sampler->wrap_s = cgltf_wrap_mode_repeat; + out_sampler->wrap_t = cgltf_wrap_mode_repeat; + + int size = tokens[i].size; + ++i; + + for (int j = 0; j < size; ++j) + { + CGLTF_CHECK_KEY(tokens[i]); + + if (cgltf_json_strcmp(tokens + i, json_chunk, "name") == 0) + { + i = cgltf_parse_json_string(options, tokens, i + 1, json_chunk, &out_sampler->name); + } + else if (cgltf_json_strcmp(tokens + i, json_chunk, "magFilter") == 0) + { + ++i; + out_sampler->mag_filter + = (cgltf_filter_type)cgltf_json_to_int(tokens + i, json_chunk); + ++i; + } + else if (cgltf_json_strcmp(tokens + i, json_chunk, "minFilter") == 0) + { + ++i; + out_sampler->min_filter + = (cgltf_filter_type)cgltf_json_to_int(tokens + i, json_chunk); + ++i; + } + else if (cgltf_json_strcmp(tokens + i, json_chunk, "wrapS") == 0) + { + ++i; + out_sampler->wrap_s + = (cgltf_wrap_mode)cgltf_json_to_int(tokens + i, json_chunk); + ++i; + } + else if (cgltf_json_strcmp(tokens + i, json_chunk, "wrapT") == 0) + { + ++i; + out_sampler->wrap_t + = (cgltf_wrap_mode)cgltf_json_to_int(tokens + i, json_chunk); + ++i; + } + else if (cgltf_json_strcmp(tokens + i, json_chunk, "extras") == 0) + { + i = cgltf_parse_json_extras(options, tokens, i + 1, json_chunk, &out_sampler->extras); + } + else if (cgltf_json_strcmp(tokens + i, json_chunk, "extensions") == 0) + { + i = cgltf_parse_json_unprocessed_extensions(options, tokens, i, json_chunk, &out_sampler->extensions_count, &out_sampler->extensions); + } + else + { + i = cgltf_skip_json(tokens, i + 1); + } + + if (i < 0) + { + return i; + } + } + + return i; +} + +static int cgltf_parse_json_texture(cgltf_options* options, jsmntok_t const* tokens, int i, const uint8_t* json_chunk, cgltf_texture* out_texture) +{ + CGLTF_CHECK_TOKTYPE(tokens[i], JSMN_OBJECT); + + int size = tokens[i].size; + ++i; + + for (int j = 0; j < size; ++j) + { + CGLTF_CHECK_KEY(tokens[i]); + + if (cgltf_json_strcmp(tokens+i, json_chunk, "name") == 0) + { + i = cgltf_parse_json_string(options, tokens, i + 1, json_chunk, &out_texture->name); + } + else if (cgltf_json_strcmp(tokens + i, json_chunk, "sampler") == 0) + { + ++i; + out_texture->sampler = CGLTF_PTRINDEX(cgltf_sampler, cgltf_json_to_int(tokens + i, json_chunk)); + ++i; + } + else if (cgltf_json_strcmp(tokens + i, json_chunk, "source") == 0) + { + ++i; + out_texture->image = CGLTF_PTRINDEX(cgltf_image, cgltf_json_to_int(tokens + i, json_chunk)); + ++i; + } + else if (cgltf_json_strcmp(tokens + i, json_chunk, "extras") == 0) + { + i = cgltf_parse_json_extras(options, tokens, i + 1, json_chunk, &out_texture->extras); + } + else if (cgltf_json_strcmp(tokens + i, json_chunk, "extensions") == 0) + { + ++i; + + CGLTF_CHECK_TOKTYPE(tokens[i], JSMN_OBJECT); + if (out_texture->extensions) + { + return CGLTF_ERROR_JSON; + } + + int extensions_size = tokens[i].size; + ++i; + out_texture->extensions = (cgltf_extension*)cgltf_calloc(options, sizeof(cgltf_extension), extensions_size); + out_texture->extensions_count = 0; + + if (!out_texture->extensions) + { + return CGLTF_ERROR_NOMEM; + } + + for (int k = 0; k < extensions_size; ++k) + { + CGLTF_CHECK_KEY(tokens[i]); + + if (cgltf_json_strcmp(tokens + i, json_chunk, "KHR_texture_basisu") == 0) + { + out_texture->has_basisu = 1; + ++i; + CGLTF_CHECK_TOKTYPE(tokens[i], JSMN_OBJECT); + int num_properties = tokens[i].size; + ++i; + + for (int t = 0; t < num_properties; ++t) + { + CGLTF_CHECK_KEY(tokens[i]); + + if (cgltf_json_strcmp(tokens + i, json_chunk, "source") == 0) + { + ++i; + out_texture->basisu_image = CGLTF_PTRINDEX(cgltf_image, cgltf_json_to_int(tokens + i, json_chunk)); + ++i; + } + else + { + i = cgltf_skip_json(tokens, i + 1); + } + if (i < 0) + { + return i; + } + } + } + else if (cgltf_json_strcmp(tokens + i, json_chunk, "EXT_texture_webp") == 0) + { + out_texture->has_webp = 1; + ++i; + CGLTF_CHECK_TOKTYPE(tokens[i], JSMN_OBJECT); + int num_properties = tokens[i].size; + ++i; + + for (int t = 0; t < num_properties; ++t) + { + CGLTF_CHECK_KEY(tokens[i]); + + if (cgltf_json_strcmp(tokens + i, json_chunk, "source") == 0) + { + ++i; + out_texture->webp_image = CGLTF_PTRINDEX(cgltf_image, cgltf_json_to_int(tokens + i, json_chunk)); + ++i; + } + else + { + i = cgltf_skip_json(tokens, i + 1); + } + if (i < 0) + { + return i; + } + } + } + else + { + i = cgltf_parse_json_unprocessed_extension(options, tokens, i, json_chunk, &(out_texture->extensions[out_texture->extensions_count++])); + } + + if (i < 0) + { + return i; + } + } + } + else + { + i = cgltf_skip_json(tokens, i + 1); + } + + if (i < 0) + { + return i; + } + } + + return i; +} + +static int cgltf_parse_json_material(cgltf_options* options, jsmntok_t const* tokens, int i, const uint8_t* json_chunk, cgltf_material* out_material) +{ + CGLTF_CHECK_TOKTYPE(tokens[i], JSMN_OBJECT); + + cgltf_fill_float_array(out_material->pbr_metallic_roughness.base_color_factor, 4, 1.0f); + out_material->pbr_metallic_roughness.metallic_factor = 1.0f; + out_material->pbr_metallic_roughness.roughness_factor = 1.0f; + + cgltf_fill_float_array(out_material->pbr_specular_glossiness.diffuse_factor, 4, 1.0f); + cgltf_fill_float_array(out_material->pbr_specular_glossiness.specular_factor, 3, 1.0f); + out_material->pbr_specular_glossiness.glossiness_factor = 1.0f; + + cgltf_fill_float_array(out_material->volume.attenuation_color, 3, 1.0f); + out_material->volume.attenuation_distance = FLT_MAX; + + out_material->alpha_cutoff = 0.5f; + + int size = tokens[i].size; + ++i; + + for (int j = 0; j < size; ++j) + { + CGLTF_CHECK_KEY(tokens[i]); + + if (cgltf_json_strcmp(tokens+i, json_chunk, "name") == 0) + { + i = cgltf_parse_json_string(options, tokens, i + 1, json_chunk, &out_material->name); + } + else if (cgltf_json_strcmp(tokens+i, json_chunk, "pbrMetallicRoughness") == 0) + { + out_material->has_pbr_metallic_roughness = 1; + i = cgltf_parse_json_pbr_metallic_roughness(options, tokens, i + 1, json_chunk, &out_material->pbr_metallic_roughness); + } + else if (cgltf_json_strcmp(tokens+i, json_chunk, "emissiveFactor") == 0) + { + i = cgltf_parse_json_float_array(tokens, i + 1, json_chunk, out_material->emissive_factor, 3); + } + else if (cgltf_json_strcmp(tokens + i, json_chunk, "normalTexture") == 0) + { + i = cgltf_parse_json_texture_view(options, tokens, i + 1, json_chunk, + &out_material->normal_texture); + } + else if (cgltf_json_strcmp(tokens + i, json_chunk, "occlusionTexture") == 0) + { + i = cgltf_parse_json_texture_view(options, tokens, i + 1, json_chunk, + &out_material->occlusion_texture); + } + else if (cgltf_json_strcmp(tokens + i, json_chunk, "emissiveTexture") == 0) + { + i = cgltf_parse_json_texture_view(options, tokens, i + 1, json_chunk, + &out_material->emissive_texture); + } + else if (cgltf_json_strcmp(tokens + i, json_chunk, "alphaMode") == 0) + { + ++i; + if (cgltf_json_strcmp(tokens + i, json_chunk, "OPAQUE") == 0) + { + out_material->alpha_mode = cgltf_alpha_mode_opaque; + } + else if (cgltf_json_strcmp(tokens + i, json_chunk, "MASK") == 0) + { + out_material->alpha_mode = cgltf_alpha_mode_mask; + } + else if (cgltf_json_strcmp(tokens + i, json_chunk, "BLEND") == 0) + { + out_material->alpha_mode = cgltf_alpha_mode_blend; + } + ++i; + } + else if (cgltf_json_strcmp(tokens + i, json_chunk, "alphaCutoff") == 0) + { + ++i; + out_material->alpha_cutoff = cgltf_json_to_float(tokens + i, json_chunk); + ++i; + } + else if (cgltf_json_strcmp(tokens + i, json_chunk, "doubleSided") == 0) + { + ++i; + out_material->double_sided = + cgltf_json_to_bool(tokens + i, json_chunk); + ++i; + } + else if (cgltf_json_strcmp(tokens + i, json_chunk, "extras") == 0) + { + i = cgltf_parse_json_extras(options, tokens, i + 1, json_chunk, &out_material->extras); + } + else if (cgltf_json_strcmp(tokens + i, json_chunk, "extensions") == 0) + { + ++i; + + CGLTF_CHECK_TOKTYPE(tokens[i], JSMN_OBJECT); + if(out_material->extensions) + { + return CGLTF_ERROR_JSON; + } + + int extensions_size = tokens[i].size; + ++i; + out_material->extensions = (cgltf_extension*)cgltf_calloc(options, sizeof(cgltf_extension), extensions_size); + out_material->extensions_count= 0; + + if (!out_material->extensions) + { + return CGLTF_ERROR_NOMEM; + } + + for (int k = 0; k < extensions_size; ++k) + { + CGLTF_CHECK_KEY(tokens[i]); + + if (cgltf_json_strcmp(tokens+i, json_chunk, "KHR_materials_pbrSpecularGlossiness") == 0) + { + out_material->has_pbr_specular_glossiness = 1; + i = cgltf_parse_json_pbr_specular_glossiness(options, tokens, i + 1, json_chunk, &out_material->pbr_specular_glossiness); + } + else if (cgltf_json_strcmp(tokens+i, json_chunk, "KHR_materials_unlit") == 0) + { + out_material->unlit = 1; + i = cgltf_skip_json(tokens, i+1); + } + else if (cgltf_json_strcmp(tokens+i, json_chunk, "KHR_materials_clearcoat") == 0) + { + out_material->has_clearcoat = 1; + i = cgltf_parse_json_clearcoat(options, tokens, i + 1, json_chunk, &out_material->clearcoat); + } + else if (cgltf_json_strcmp(tokens+i, json_chunk, "KHR_materials_ior") == 0) + { + out_material->has_ior = 1; + i = cgltf_parse_json_ior(tokens, i + 1, json_chunk, &out_material->ior); + } + else if (cgltf_json_strcmp(tokens+i, json_chunk, "KHR_materials_specular") == 0) + { + out_material->has_specular = 1; + i = cgltf_parse_json_specular(options, tokens, i + 1, json_chunk, &out_material->specular); + } + else if (cgltf_json_strcmp(tokens+i, json_chunk, "KHR_materials_transmission") == 0) + { + out_material->has_transmission = 1; + i = cgltf_parse_json_transmission(options, tokens, i + 1, json_chunk, &out_material->transmission); + } + else if (cgltf_json_strcmp(tokens + i, json_chunk, "KHR_materials_volume") == 0) + { + out_material->has_volume = 1; + i = cgltf_parse_json_volume(options, tokens, i + 1, json_chunk, &out_material->volume); + } + else if (cgltf_json_strcmp(tokens+i, json_chunk, "KHR_materials_sheen") == 0) + { + out_material->has_sheen = 1; + i = cgltf_parse_json_sheen(options, tokens, i + 1, json_chunk, &out_material->sheen); + } + else if (cgltf_json_strcmp(tokens + i, json_chunk, "KHR_materials_emissive_strength") == 0) + { + out_material->has_emissive_strength = 1; + i = cgltf_parse_json_emissive_strength(tokens, i + 1, json_chunk, &out_material->emissive_strength); + } + else if (cgltf_json_strcmp(tokens + i, json_chunk, "KHR_materials_iridescence") == 0) + { + out_material->has_iridescence = 1; + i = cgltf_parse_json_iridescence(options, tokens, i + 1, json_chunk, &out_material->iridescence); + } + else if (cgltf_json_strcmp(tokens + i, json_chunk, "KHR_materials_diffuse_transmission") == 0) + { + out_material->has_diffuse_transmission = 1; + i = cgltf_parse_json_diffuse_transmission(options, tokens, i + 1, json_chunk, &out_material->diffuse_transmission); + } + else if (cgltf_json_strcmp(tokens + i, json_chunk, "KHR_materials_anisotropy") == 0) + { + out_material->has_anisotropy = 1; + i = cgltf_parse_json_anisotropy(options, tokens, i + 1, json_chunk, &out_material->anisotropy); + } + else if (cgltf_json_strcmp(tokens + i, json_chunk, "KHR_materials_dispersion") == 0) + { + out_material->has_dispersion = 1; + i = cgltf_parse_json_dispersion(tokens, i + 1, json_chunk, &out_material->dispersion); + } + else + { + i = cgltf_parse_json_unprocessed_extension(options, tokens, i, json_chunk, &(out_material->extensions[out_material->extensions_count++])); + } + + if (i < 0) + { + return i; + } + } + } + else + { + i = cgltf_skip_json(tokens, i+1); + } + + if (i < 0) + { + return i; + } + } + + return i; +} + +static int cgltf_parse_json_accessors(cgltf_options* options, jsmntok_t const* tokens, int i, const uint8_t* json_chunk, cgltf_data* out_data) +{ + i = cgltf_parse_json_array(options, tokens, i, json_chunk, sizeof(cgltf_accessor), (void**)&out_data->accessors, &out_data->accessors_count); + if (i < 0) + { + return i; + } + + for (cgltf_size j = 0; j < out_data->accessors_count; ++j) + { + i = cgltf_parse_json_accessor(options, tokens, i, json_chunk, &out_data->accessors[j]); + if (i < 0) + { + return i; + } + } + return i; +} + +static int cgltf_parse_json_materials(cgltf_options* options, jsmntok_t const* tokens, int i, const uint8_t* json_chunk, cgltf_data* out_data) +{ + i = cgltf_parse_json_array(options, tokens, i, json_chunk, sizeof(cgltf_material), (void**)&out_data->materials, &out_data->materials_count); + if (i < 0) + { + return i; + } + + for (cgltf_size j = 0; j < out_data->materials_count; ++j) + { + i = cgltf_parse_json_material(options, tokens, i, json_chunk, &out_data->materials[j]); + if (i < 0) + { + return i; + } + } + return i; +} + +static int cgltf_parse_json_images(cgltf_options* options, jsmntok_t const* tokens, int i, const uint8_t* json_chunk, cgltf_data* out_data) +{ + i = cgltf_parse_json_array(options, tokens, i, json_chunk, sizeof(cgltf_image), (void**)&out_data->images, &out_data->images_count); + if (i < 0) + { + return i; + } + + for (cgltf_size j = 0; j < out_data->images_count; ++j) + { + i = cgltf_parse_json_image(options, tokens, i, json_chunk, &out_data->images[j]); + if (i < 0) + { + return i; + } + } + return i; +} + +static int cgltf_parse_json_textures(cgltf_options* options, jsmntok_t const* tokens, int i, const uint8_t* json_chunk, cgltf_data* out_data) +{ + i = cgltf_parse_json_array(options, tokens, i, json_chunk, sizeof(cgltf_texture), (void**)&out_data->textures, &out_data->textures_count); + if (i < 0) + { + return i; + } + + for (cgltf_size j = 0; j < out_data->textures_count; ++j) + { + i = cgltf_parse_json_texture(options, tokens, i, json_chunk, &out_data->textures[j]); + if (i < 0) + { + return i; + } + } + return i; +} + +static int cgltf_parse_json_samplers(cgltf_options* options, jsmntok_t const* tokens, int i, const uint8_t* json_chunk, cgltf_data* out_data) +{ + i = cgltf_parse_json_array(options, tokens, i, json_chunk, sizeof(cgltf_sampler), (void**)&out_data->samplers, &out_data->samplers_count); + if (i < 0) + { + return i; + } + + for (cgltf_size j = 0; j < out_data->samplers_count; ++j) + { + i = cgltf_parse_json_sampler(options, tokens, i, json_chunk, &out_data->samplers[j]); + if (i < 0) + { + return i; + } + } + return i; +} + +static int cgltf_parse_json_meshopt_compression(cgltf_options* options, jsmntok_t const* tokens, int i, const uint8_t* json_chunk, cgltf_meshopt_compression* out_meshopt_compression) +{ + (void)options; + CGLTF_CHECK_TOKTYPE(tokens[i], JSMN_OBJECT); + + int size = tokens[i].size; + ++i; + + for (int j = 0; j < size; ++j) + { + CGLTF_CHECK_KEY(tokens[i]); + + if (cgltf_json_strcmp(tokens+i, json_chunk, "buffer") == 0) + { + ++i; + out_meshopt_compression->buffer = CGLTF_PTRINDEX(cgltf_buffer, cgltf_json_to_int(tokens + i, json_chunk)); + ++i; + } + else if (cgltf_json_strcmp(tokens+i, json_chunk, "byteOffset") == 0) + { + ++i; + out_meshopt_compression->offset = cgltf_json_to_size(tokens+i, json_chunk); + ++i; + } + else if (cgltf_json_strcmp(tokens+i, json_chunk, "byteLength") == 0) + { + ++i; + out_meshopt_compression->size = cgltf_json_to_size(tokens+i, json_chunk); + ++i; + } + else if (cgltf_json_strcmp(tokens+i, json_chunk, "byteStride") == 0) + { + ++i; + out_meshopt_compression->stride = cgltf_json_to_size(tokens+i, json_chunk); + ++i; + } + else if (cgltf_json_strcmp(tokens+i, json_chunk, "count") == 0) + { + ++i; + out_meshopt_compression->count = cgltf_json_to_size(tokens+i, json_chunk); + ++i; + } + else if (cgltf_json_strcmp(tokens+i, json_chunk, "mode") == 0) + { + ++i; + if (cgltf_json_strcmp(tokens+i, json_chunk, "ATTRIBUTES") == 0) + { + out_meshopt_compression->mode = cgltf_meshopt_compression_mode_attributes; + } + else if (cgltf_json_strcmp(tokens+i, json_chunk, "TRIANGLES") == 0) + { + out_meshopt_compression->mode = cgltf_meshopt_compression_mode_triangles; + } + else if (cgltf_json_strcmp(tokens+i, json_chunk, "INDICES") == 0) + { + out_meshopt_compression->mode = cgltf_meshopt_compression_mode_indices; + } + ++i; + } + else if (cgltf_json_strcmp(tokens+i, json_chunk, "filter") == 0) + { + ++i; + if (cgltf_json_strcmp(tokens+i, json_chunk, "NONE") == 0) + { + out_meshopt_compression->filter = cgltf_meshopt_compression_filter_none; + } + else if (cgltf_json_strcmp(tokens+i, json_chunk, "OCTAHEDRAL") == 0) + { + out_meshopt_compression->filter = cgltf_meshopt_compression_filter_octahedral; + } + else if (cgltf_json_strcmp(tokens+i, json_chunk, "QUATERNION") == 0) + { + out_meshopt_compression->filter = cgltf_meshopt_compression_filter_quaternion; + } + else if (cgltf_json_strcmp(tokens+i, json_chunk, "EXPONENTIAL") == 0) + { + out_meshopt_compression->filter = cgltf_meshopt_compression_filter_exponential; + } + else if (cgltf_json_strcmp(tokens+i, json_chunk, "COLOR") == 0) + { + out_meshopt_compression->filter = cgltf_meshopt_compression_filter_color; + } + ++i; + } + else + { + i = cgltf_skip_json(tokens, i+1); + } + + if (i < 0) + { + return i; + } + } + + return i; +} + +static int cgltf_parse_json_buffer_view(cgltf_options* options, jsmntok_t const* tokens, int i, const uint8_t* json_chunk, cgltf_buffer_view* out_buffer_view) +{ + CGLTF_CHECK_TOKTYPE(tokens[i], JSMN_OBJECT); + + int size = tokens[i].size; + ++i; + + for (int j = 0; j < size; ++j) + { + CGLTF_CHECK_KEY(tokens[i]); + + if (cgltf_json_strcmp(tokens + i, json_chunk, "name") == 0) + { + i = cgltf_parse_json_string(options, tokens, i + 1, json_chunk, &out_buffer_view->name); + } + else if (cgltf_json_strcmp(tokens+i, json_chunk, "buffer") == 0) + { + ++i; + out_buffer_view->buffer = CGLTF_PTRINDEX(cgltf_buffer, cgltf_json_to_int(tokens + i, json_chunk)); + ++i; + } + else if (cgltf_json_strcmp(tokens+i, json_chunk, "byteOffset") == 0) + { + ++i; + out_buffer_view->offset = + cgltf_json_to_size(tokens+i, json_chunk); + ++i; + } + else if (cgltf_json_strcmp(tokens+i, json_chunk, "byteLength") == 0) + { + ++i; + out_buffer_view->size = + cgltf_json_to_size(tokens+i, json_chunk); + ++i; + } + else if (cgltf_json_strcmp(tokens+i, json_chunk, "byteStride") == 0) + { + ++i; + out_buffer_view->stride = + cgltf_json_to_size(tokens+i, json_chunk); + ++i; + } + else if (cgltf_json_strcmp(tokens+i, json_chunk, "target") == 0) + { + ++i; + int type = cgltf_json_to_int(tokens+i, json_chunk); + switch (type) + { + case 34962: + type = cgltf_buffer_view_type_vertices; + break; + case 34963: + type = cgltf_buffer_view_type_indices; + break; + default: + type = cgltf_buffer_view_type_invalid; + break; + } + out_buffer_view->type = (cgltf_buffer_view_type)type; + ++i; + } + else if (cgltf_json_strcmp(tokens + i, json_chunk, "extras") == 0) + { + i = cgltf_parse_json_extras(options, tokens, i + 1, json_chunk, &out_buffer_view->extras); + } + else if (cgltf_json_strcmp(tokens + i, json_chunk, "extensions") == 0) + { + ++i; + + CGLTF_CHECK_TOKTYPE(tokens[i], JSMN_OBJECT); + if(out_buffer_view->extensions) + { + return CGLTF_ERROR_JSON; + } + + int extensions_size = tokens[i].size; + out_buffer_view->extensions_count = 0; + out_buffer_view->extensions = (cgltf_extension*)cgltf_calloc(options, sizeof(cgltf_extension), extensions_size); + + if (!out_buffer_view->extensions) + { + return CGLTF_ERROR_NOMEM; + } + + ++i; + for (int k = 0; k < extensions_size; ++k) + { + CGLTF_CHECK_KEY(tokens[i]); + + if (cgltf_json_strcmp(tokens+i, json_chunk, "EXT_meshopt_compression") == 0) + { + out_buffer_view->has_meshopt_compression = 1; + i = cgltf_parse_json_meshopt_compression(options, tokens, i + 1, json_chunk, &out_buffer_view->meshopt_compression); + } + else if (cgltf_json_strcmp(tokens+i, json_chunk, "KHR_meshopt_compression") == 0) + { + out_buffer_view->has_meshopt_compression = 1; + out_buffer_view->meshopt_compression.is_khr = 1; + i = cgltf_parse_json_meshopt_compression(options, tokens, i + 1, json_chunk, &out_buffer_view->meshopt_compression); + } + else + { + i = cgltf_parse_json_unprocessed_extension(options, tokens, i, json_chunk, &(out_buffer_view->extensions[out_buffer_view->extensions_count++])); + } + + if (i < 0) + { + return i; + } + } + } + else + { + i = cgltf_skip_json(tokens, i+1); + } + + if (i < 0) + { + return i; + } + } + + return i; +} + +static int cgltf_parse_json_buffer_views(cgltf_options* options, jsmntok_t const* tokens, int i, const uint8_t* json_chunk, cgltf_data* out_data) +{ + i = cgltf_parse_json_array(options, tokens, i, json_chunk, sizeof(cgltf_buffer_view), (void**)&out_data->buffer_views, &out_data->buffer_views_count); + if (i < 0) + { + return i; + } + + for (cgltf_size j = 0; j < out_data->buffer_views_count; ++j) + { + i = cgltf_parse_json_buffer_view(options, tokens, i, json_chunk, &out_data->buffer_views[j]); + if (i < 0) + { + return i; + } + } + return i; +} + +static int cgltf_parse_json_buffer(cgltf_options* options, jsmntok_t const* tokens, int i, const uint8_t* json_chunk, cgltf_buffer* out_buffer) +{ + CGLTF_CHECK_TOKTYPE(tokens[i], JSMN_OBJECT); + + int size = tokens[i].size; + ++i; + + for (int j = 0; j < size; ++j) + { + CGLTF_CHECK_KEY(tokens[i]); + + if (cgltf_json_strcmp(tokens + i, json_chunk, "name") == 0) + { + i = cgltf_parse_json_string(options, tokens, i + 1, json_chunk, &out_buffer->name); + } + else if (cgltf_json_strcmp(tokens+i, json_chunk, "byteLength") == 0) + { + ++i; + out_buffer->size = + cgltf_json_to_size(tokens+i, json_chunk); + ++i; + } + else if (cgltf_json_strcmp(tokens+i, json_chunk, "uri") == 0) + { + i = cgltf_parse_json_string(options, tokens, i + 1, json_chunk, &out_buffer->uri); + } + else if (cgltf_json_strcmp(tokens + i, json_chunk, "extras") == 0) + { + i = cgltf_parse_json_extras(options, tokens, i + 1, json_chunk, &out_buffer->extras); + } + else if (cgltf_json_strcmp(tokens + i, json_chunk, "extensions") == 0) + { + i = cgltf_parse_json_unprocessed_extensions(options, tokens, i, json_chunk, &out_buffer->extensions_count, &out_buffer->extensions); + } + else + { + i = cgltf_skip_json(tokens, i+1); + } + + if (i < 0) + { + return i; + } + } + + return i; +} + +static int cgltf_parse_json_buffers(cgltf_options* options, jsmntok_t const* tokens, int i, const uint8_t* json_chunk, cgltf_data* out_data) +{ + i = cgltf_parse_json_array(options, tokens, i, json_chunk, sizeof(cgltf_buffer), (void**)&out_data->buffers, &out_data->buffers_count); + if (i < 0) + { + return i; + } + + for (cgltf_size j = 0; j < out_data->buffers_count; ++j) + { + i = cgltf_parse_json_buffer(options, tokens, i, json_chunk, &out_data->buffers[j]); + if (i < 0) + { + return i; + } + } + return i; +} + +static int cgltf_parse_json_skin(cgltf_options* options, jsmntok_t const* tokens, int i, const uint8_t* json_chunk, cgltf_skin* out_skin) +{ + CGLTF_CHECK_TOKTYPE(tokens[i], JSMN_OBJECT); + + int size = tokens[i].size; + ++i; + + for (int j = 0; j < size; ++j) + { + CGLTF_CHECK_KEY(tokens[i]); + + if (cgltf_json_strcmp(tokens+i, json_chunk, "name") == 0) + { + i = cgltf_parse_json_string(options, tokens, i + 1, json_chunk, &out_skin->name); + } + else if (cgltf_json_strcmp(tokens+i, json_chunk, "joints") == 0) + { + i = cgltf_parse_json_array(options, tokens, i + 1, json_chunk, sizeof(cgltf_node*), (void**)&out_skin->joints, &out_skin->joints_count); + if (i < 0) + { + return i; + } + + for (cgltf_size k = 0; k < out_skin->joints_count; ++k) + { + out_skin->joints[k] = CGLTF_PTRINDEX(cgltf_node, cgltf_json_to_int(tokens + i, json_chunk)); + ++i; + } + } + else if (cgltf_json_strcmp(tokens+i, json_chunk, "skeleton") == 0) + { + ++i; + CGLTF_CHECK_TOKTYPE(tokens[i], JSMN_PRIMITIVE); + out_skin->skeleton = CGLTF_PTRINDEX(cgltf_node, cgltf_json_to_int(tokens + i, json_chunk)); + ++i; + } + else if (cgltf_json_strcmp(tokens+i, json_chunk, "inverseBindMatrices") == 0) + { + ++i; + CGLTF_CHECK_TOKTYPE(tokens[i], JSMN_PRIMITIVE); + out_skin->inverse_bind_matrices = CGLTF_PTRINDEX(cgltf_accessor, cgltf_json_to_int(tokens + i, json_chunk)); + ++i; + } + else if (cgltf_json_strcmp(tokens + i, json_chunk, "extras") == 0) + { + i = cgltf_parse_json_extras(options, tokens, i + 1, json_chunk, &out_skin->extras); + } + else if (cgltf_json_strcmp(tokens + i, json_chunk, "extensions") == 0) + { + i = cgltf_parse_json_unprocessed_extensions(options, tokens, i, json_chunk, &out_skin->extensions_count, &out_skin->extensions); + } + else + { + i = cgltf_skip_json(tokens, i+1); + } + + if (i < 0) + { + return i; + } + } + + return i; +} + +static int cgltf_parse_json_skins(cgltf_options* options, jsmntok_t const* tokens, int i, const uint8_t* json_chunk, cgltf_data* out_data) +{ + i = cgltf_parse_json_array(options, tokens, i, json_chunk, sizeof(cgltf_skin), (void**)&out_data->skins, &out_data->skins_count); + if (i < 0) + { + return i; + } + + for (cgltf_size j = 0; j < out_data->skins_count; ++j) + { + i = cgltf_parse_json_skin(options, tokens, i, json_chunk, &out_data->skins[j]); + if (i < 0) + { + return i; + } + } + return i; +} + +static int cgltf_parse_json_camera(cgltf_options* options, jsmntok_t const* tokens, int i, const uint8_t* json_chunk, cgltf_camera* out_camera) +{ + CGLTF_CHECK_TOKTYPE(tokens[i], JSMN_OBJECT); + + int size = tokens[i].size; + ++i; + + for (int j = 0; j < size; ++j) + { + CGLTF_CHECK_KEY(tokens[i]); + + if (cgltf_json_strcmp(tokens+i, json_chunk, "name") == 0) + { + i = cgltf_parse_json_string(options, tokens, i + 1, json_chunk, &out_camera->name); + } + else if (cgltf_json_strcmp(tokens+i, json_chunk, "perspective") == 0) + { + ++i; + + CGLTF_CHECK_TOKTYPE(tokens[i], JSMN_OBJECT); + + int data_size = tokens[i].size; + ++i; + + if (out_camera->type != cgltf_camera_type_invalid) + { + return CGLTF_ERROR_JSON; + } + + out_camera->type = cgltf_camera_type_perspective; + + for (int k = 0; k < data_size; ++k) + { + CGLTF_CHECK_KEY(tokens[i]); + + if (cgltf_json_strcmp(tokens+i, json_chunk, "aspectRatio") == 0) + { + ++i; + out_camera->data.perspective.has_aspect_ratio = 1; + out_camera->data.perspective.aspect_ratio = cgltf_json_to_float(tokens + i, json_chunk); + ++i; + } + else if (cgltf_json_strcmp(tokens+i, json_chunk, "yfov") == 0) + { + ++i; + out_camera->data.perspective.yfov = cgltf_json_to_float(tokens + i, json_chunk); + ++i; + } + else if (cgltf_json_strcmp(tokens+i, json_chunk, "zfar") == 0) + { + ++i; + out_camera->data.perspective.has_zfar = 1; + out_camera->data.perspective.zfar = cgltf_json_to_float(tokens + i, json_chunk); + ++i; + } + else if (cgltf_json_strcmp(tokens+i, json_chunk, "znear") == 0) + { + ++i; + out_camera->data.perspective.znear = cgltf_json_to_float(tokens + i, json_chunk); + ++i; + } + else if (cgltf_json_strcmp(tokens + i, json_chunk, "extras") == 0) + { + i = cgltf_parse_json_extras(options, tokens, i + 1, json_chunk, &out_camera->data.perspective.extras); + } + else + { + i = cgltf_skip_json(tokens, i+1); + } + + if (i < 0) + { + return i; + } + } + } + else if (cgltf_json_strcmp(tokens+i, json_chunk, "orthographic") == 0) + { + ++i; + + CGLTF_CHECK_TOKTYPE(tokens[i], JSMN_OBJECT); + + int data_size = tokens[i].size; + ++i; + + if (out_camera->type != cgltf_camera_type_invalid) + { + return CGLTF_ERROR_JSON; + } + + out_camera->type = cgltf_camera_type_orthographic; + + for (int k = 0; k < data_size; ++k) + { + CGLTF_CHECK_KEY(tokens[i]); + + if (cgltf_json_strcmp(tokens+i, json_chunk, "xmag") == 0) + { + ++i; + out_camera->data.orthographic.xmag = cgltf_json_to_float(tokens + i, json_chunk); + ++i; + } + else if (cgltf_json_strcmp(tokens+i, json_chunk, "ymag") == 0) + { + ++i; + out_camera->data.orthographic.ymag = cgltf_json_to_float(tokens + i, json_chunk); + ++i; + } + else if (cgltf_json_strcmp(tokens+i, json_chunk, "zfar") == 0) + { + ++i; + out_camera->data.orthographic.zfar = cgltf_json_to_float(tokens + i, json_chunk); + ++i; + } + else if (cgltf_json_strcmp(tokens+i, json_chunk, "znear") == 0) + { + ++i; + out_camera->data.orthographic.znear = cgltf_json_to_float(tokens + i, json_chunk); + ++i; + } + else if (cgltf_json_strcmp(tokens + i, json_chunk, "extras") == 0) + { + i = cgltf_parse_json_extras(options, tokens, i + 1, json_chunk, &out_camera->data.orthographic.extras); + } + else + { + i = cgltf_skip_json(tokens, i+1); + } + + if (i < 0) + { + return i; + } + } + } + else if (cgltf_json_strcmp(tokens + i, json_chunk, "extras") == 0) + { + i = cgltf_parse_json_extras(options, tokens, i + 1, json_chunk, &out_camera->extras); + } + else if (cgltf_json_strcmp(tokens + i, json_chunk, "extensions") == 0) + { + i = cgltf_parse_json_unprocessed_extensions(options, tokens, i, json_chunk, &out_camera->extensions_count, &out_camera->extensions); + } + else + { + i = cgltf_skip_json(tokens, i+1); + } + + if (i < 0) + { + return i; + } + } + + return i; +} + +static int cgltf_parse_json_cameras(cgltf_options* options, jsmntok_t const* tokens, int i, const uint8_t* json_chunk, cgltf_data* out_data) +{ + i = cgltf_parse_json_array(options, tokens, i, json_chunk, sizeof(cgltf_camera), (void**)&out_data->cameras, &out_data->cameras_count); + if (i < 0) + { + return i; + } + + for (cgltf_size j = 0; j < out_data->cameras_count; ++j) + { + i = cgltf_parse_json_camera(options, tokens, i, json_chunk, &out_data->cameras[j]); + if (i < 0) + { + return i; + } + } + return i; +} + +static int cgltf_parse_json_light(cgltf_options* options, jsmntok_t const* tokens, int i, const uint8_t* json_chunk, cgltf_light* out_light) +{ + CGLTF_CHECK_TOKTYPE(tokens[i], JSMN_OBJECT); + + out_light->color[0] = 1.f; + out_light->color[1] = 1.f; + out_light->color[2] = 1.f; + out_light->intensity = 1.f; + + out_light->spot_inner_cone_angle = 0.f; + out_light->spot_outer_cone_angle = 3.1415926535f / 4.0f; + + int size = tokens[i].size; + ++i; + + for (int j = 0; j < size; ++j) + { + CGLTF_CHECK_KEY(tokens[i]); + + if (cgltf_json_strcmp(tokens+i, json_chunk, "name") == 0) + { + i = cgltf_parse_json_string(options, tokens, i + 1, json_chunk, &out_light->name); + } + else if (cgltf_json_strcmp(tokens + i, json_chunk, "color") == 0) + { + i = cgltf_parse_json_float_array(tokens, i + 1, json_chunk, out_light->color, 3); + } + else if (cgltf_json_strcmp(tokens + i, json_chunk, "intensity") == 0) + { + ++i; + out_light->intensity = cgltf_json_to_float(tokens + i, json_chunk); + ++i; + } + else if (cgltf_json_strcmp(tokens+i, json_chunk, "type") == 0) + { + ++i; + if (cgltf_json_strcmp(tokens + i, json_chunk, "directional") == 0) + { + out_light->type = cgltf_light_type_directional; + } + else if (cgltf_json_strcmp(tokens + i, json_chunk, "point") == 0) + { + out_light->type = cgltf_light_type_point; + } + else if (cgltf_json_strcmp(tokens + i, json_chunk, "spot") == 0) + { + out_light->type = cgltf_light_type_spot; + } + ++i; + } + else if (cgltf_json_strcmp(tokens + i, json_chunk, "range") == 0) + { + ++i; + out_light->range = cgltf_json_to_float(tokens + i, json_chunk); + ++i; + } + else if (cgltf_json_strcmp(tokens+i, json_chunk, "spot") == 0) + { + ++i; + + CGLTF_CHECK_TOKTYPE(tokens[i], JSMN_OBJECT); + + int data_size = tokens[i].size; + ++i; + + for (int k = 0; k < data_size; ++k) + { + CGLTF_CHECK_KEY(tokens[i]); + + if (cgltf_json_strcmp(tokens+i, json_chunk, "innerConeAngle") == 0) + { + ++i; + out_light->spot_inner_cone_angle = cgltf_json_to_float(tokens + i, json_chunk); + ++i; + } + else if (cgltf_json_strcmp(tokens+i, json_chunk, "outerConeAngle") == 0) + { + ++i; + out_light->spot_outer_cone_angle = cgltf_json_to_float(tokens + i, json_chunk); + ++i; + } + else + { + i = cgltf_skip_json(tokens, i+1); + } + + if (i < 0) + { + return i; + } + } + } + else if (cgltf_json_strcmp(tokens + i, json_chunk, "extras") == 0) + { + i = cgltf_parse_json_extras(options, tokens, i + 1, json_chunk, &out_light->extras); + } + else + { + i = cgltf_skip_json(tokens, i+1); + } + + if (i < 0) + { + return i; + } + } + + return i; +} + +static int cgltf_parse_json_lights(cgltf_options* options, jsmntok_t const* tokens, int i, const uint8_t* json_chunk, cgltf_data* out_data) +{ + i = cgltf_parse_json_array(options, tokens, i, json_chunk, sizeof(cgltf_light), (void**)&out_data->lights, &out_data->lights_count); + if (i < 0) + { + return i; + } + + for (cgltf_size j = 0; j < out_data->lights_count; ++j) + { + i = cgltf_parse_json_light(options, tokens, i, json_chunk, &out_data->lights[j]); + if (i < 0) + { + return i; + } + } + return i; +} + +static int cgltf_parse_json_node(cgltf_options* options, jsmntok_t const* tokens, int i, const uint8_t* json_chunk, cgltf_node* out_node) +{ + CGLTF_CHECK_TOKTYPE(tokens[i], JSMN_OBJECT); + + out_node->rotation[3] = 1.0f; + out_node->scale[0] = 1.0f; + out_node->scale[1] = 1.0f; + out_node->scale[2] = 1.0f; + out_node->matrix[0] = 1.0f; + out_node->matrix[5] = 1.0f; + out_node->matrix[10] = 1.0f; + out_node->matrix[15] = 1.0f; + + int size = tokens[i].size; + ++i; + + for (int j = 0; j < size; ++j) + { + CGLTF_CHECK_KEY(tokens[i]); + + if (cgltf_json_strcmp(tokens+i, json_chunk, "name") == 0) + { + i = cgltf_parse_json_string(options, tokens, i + 1, json_chunk, &out_node->name); + } + else if (cgltf_json_strcmp(tokens+i, json_chunk, "children") == 0) + { + i = cgltf_parse_json_array(options, tokens, i + 1, json_chunk, sizeof(cgltf_node*), (void**)&out_node->children, &out_node->children_count); + if (i < 0) + { + return i; + } + + for (cgltf_size k = 0; k < out_node->children_count; ++k) + { + out_node->children[k] = CGLTF_PTRINDEX(cgltf_node, cgltf_json_to_int(tokens + i, json_chunk)); + ++i; + } + } + else if (cgltf_json_strcmp(tokens+i, json_chunk, "mesh") == 0) + { + ++i; + CGLTF_CHECK_TOKTYPE(tokens[i], JSMN_PRIMITIVE); + out_node->mesh = CGLTF_PTRINDEX(cgltf_mesh, cgltf_json_to_int(tokens + i, json_chunk)); + ++i; + } + else if (cgltf_json_strcmp(tokens+i, json_chunk, "skin") == 0) + { + ++i; + CGLTF_CHECK_TOKTYPE(tokens[i], JSMN_PRIMITIVE); + out_node->skin = CGLTF_PTRINDEX(cgltf_skin, cgltf_json_to_int(tokens + i, json_chunk)); + ++i; + } + else if (cgltf_json_strcmp(tokens+i, json_chunk, "camera") == 0) + { + ++i; + CGLTF_CHECK_TOKTYPE(tokens[i], JSMN_PRIMITIVE); + out_node->camera = CGLTF_PTRINDEX(cgltf_camera, cgltf_json_to_int(tokens + i, json_chunk)); + ++i; + } + else if (cgltf_json_strcmp(tokens+i, json_chunk, "translation") == 0) + { + out_node->has_translation = 1; + i = cgltf_parse_json_float_array(tokens, i + 1, json_chunk, out_node->translation, 3); + } + else if (cgltf_json_strcmp(tokens+i, json_chunk, "rotation") == 0) + { + out_node->has_rotation = 1; + i = cgltf_parse_json_float_array(tokens, i + 1, json_chunk, out_node->rotation, 4); + } + else if (cgltf_json_strcmp(tokens+i, json_chunk, "scale") == 0) + { + out_node->has_scale = 1; + i = cgltf_parse_json_float_array(tokens, i + 1, json_chunk, out_node->scale, 3); + } + else if (cgltf_json_strcmp(tokens+i, json_chunk, "matrix") == 0) + { + out_node->has_matrix = 1; + i = cgltf_parse_json_float_array(tokens, i + 1, json_chunk, out_node->matrix, 16); + } + else if (cgltf_json_strcmp(tokens + i, json_chunk, "weights") == 0) + { + i = cgltf_parse_json_array(options, tokens, i + 1, json_chunk, sizeof(cgltf_float), (void**)&out_node->weights, &out_node->weights_count); + if (i < 0) + { + return i; + } + + i = cgltf_parse_json_float_array(tokens, i - 1, json_chunk, out_node->weights, (int)out_node->weights_count); + } + else if (cgltf_json_strcmp(tokens + i, json_chunk, "extras") == 0) + { + i = cgltf_parse_json_extras(options, tokens, i + 1, json_chunk, &out_node->extras); + } + else if (cgltf_json_strcmp(tokens + i, json_chunk, "extensions") == 0) + { + ++i; + + CGLTF_CHECK_TOKTYPE(tokens[i], JSMN_OBJECT); + if(out_node->extensions) + { + return CGLTF_ERROR_JSON; + } + + int extensions_size = tokens[i].size; + out_node->extensions_count= 0; + out_node->extensions = (cgltf_extension*)cgltf_calloc(options, sizeof(cgltf_extension), extensions_size); + + if (!out_node->extensions) + { + return CGLTF_ERROR_NOMEM; + } + + ++i; + + for (int k = 0; k < extensions_size; ++k) + { + CGLTF_CHECK_KEY(tokens[i]); + + if (cgltf_json_strcmp(tokens+i, json_chunk, "KHR_lights_punctual") == 0) + { + ++i; + + CGLTF_CHECK_TOKTYPE(tokens[i], JSMN_OBJECT); + + int data_size = tokens[i].size; + ++i; + + for (int m = 0; m < data_size; ++m) + { + CGLTF_CHECK_KEY(tokens[i]); + + if (cgltf_json_strcmp(tokens + i, json_chunk, "light") == 0) + { + ++i; + CGLTF_CHECK_TOKTYPE(tokens[i], JSMN_PRIMITIVE); + out_node->light = CGLTF_PTRINDEX(cgltf_light, cgltf_json_to_int(tokens + i, json_chunk)); + ++i; + } + else + { + i = cgltf_skip_json(tokens, i + 1); + } + + if (i < 0) + { + return i; + } + } + } + else if (cgltf_json_strcmp(tokens + i, json_chunk, "EXT_mesh_gpu_instancing") == 0) + { + out_node->has_mesh_gpu_instancing = 1; + i = cgltf_parse_json_mesh_gpu_instancing(options, tokens, i + 1, json_chunk, &out_node->mesh_gpu_instancing); + } + else + { + i = cgltf_parse_json_unprocessed_extension(options, tokens, i, json_chunk, &(out_node->extensions[out_node->extensions_count++])); + } + + if (i < 0) + { + return i; + } + } + } + else + { + i = cgltf_skip_json(tokens, i+1); + } + + if (i < 0) + { + return i; + } + } + + return i; +} + +static int cgltf_parse_json_nodes(cgltf_options* options, jsmntok_t const* tokens, int i, const uint8_t* json_chunk, cgltf_data* out_data) +{ + i = cgltf_parse_json_array(options, tokens, i, json_chunk, sizeof(cgltf_node), (void**)&out_data->nodes, &out_data->nodes_count); + if (i < 0) + { + return i; + } + + for (cgltf_size j = 0; j < out_data->nodes_count; ++j) + { + i = cgltf_parse_json_node(options, tokens, i, json_chunk, &out_data->nodes[j]); + if (i < 0) + { + return i; + } + } + return i; +} + +static int cgltf_parse_json_scene(cgltf_options* options, jsmntok_t const* tokens, int i, const uint8_t* json_chunk, cgltf_scene* out_scene) +{ + CGLTF_CHECK_TOKTYPE(tokens[i], JSMN_OBJECT); + + int size = tokens[i].size; + ++i; + + for (int j = 0; j < size; ++j) + { + CGLTF_CHECK_KEY(tokens[i]); + + if (cgltf_json_strcmp(tokens+i, json_chunk, "name") == 0) + { + i = cgltf_parse_json_string(options, tokens, i + 1, json_chunk, &out_scene->name); + } + else if (cgltf_json_strcmp(tokens+i, json_chunk, "nodes") == 0) + { + i = cgltf_parse_json_array(options, tokens, i + 1, json_chunk, sizeof(cgltf_node*), (void**)&out_scene->nodes, &out_scene->nodes_count); + if (i < 0) + { + return i; + } + + for (cgltf_size k = 0; k < out_scene->nodes_count; ++k) + { + out_scene->nodes[k] = CGLTF_PTRINDEX(cgltf_node, cgltf_json_to_int(tokens + i, json_chunk)); + ++i; + } + } + else if (cgltf_json_strcmp(tokens + i, json_chunk, "extras") == 0) + { + i = cgltf_parse_json_extras(options, tokens, i + 1, json_chunk, &out_scene->extras); + } + else if (cgltf_json_strcmp(tokens + i, json_chunk, "extensions") == 0) + { + i = cgltf_parse_json_unprocessed_extensions(options, tokens, i, json_chunk, &out_scene->extensions_count, &out_scene->extensions); + } + else + { + i = cgltf_skip_json(tokens, i+1); + } + + if (i < 0) + { + return i; + } + } + + return i; +} + +static int cgltf_parse_json_scenes(cgltf_options* options, jsmntok_t const* tokens, int i, const uint8_t* json_chunk, cgltf_data* out_data) +{ + i = cgltf_parse_json_array(options, tokens, i, json_chunk, sizeof(cgltf_scene), (void**)&out_data->scenes, &out_data->scenes_count); + if (i < 0) + { + return i; + } + + for (cgltf_size j = 0; j < out_data->scenes_count; ++j) + { + i = cgltf_parse_json_scene(options, tokens, i, json_chunk, &out_data->scenes[j]); + if (i < 0) + { + return i; + } + } + return i; +} + +static int cgltf_parse_json_animation_sampler(cgltf_options* options, jsmntok_t const* tokens, int i, const uint8_t* json_chunk, cgltf_animation_sampler* out_sampler) +{ + (void)options; + CGLTF_CHECK_TOKTYPE(tokens[i], JSMN_OBJECT); + + int size = tokens[i].size; + ++i; + + for (int j = 0; j < size; ++j) + { + CGLTF_CHECK_KEY(tokens[i]); + + if (cgltf_json_strcmp(tokens+i, json_chunk, "input") == 0) + { + ++i; + out_sampler->input = CGLTF_PTRINDEX(cgltf_accessor, cgltf_json_to_int(tokens + i, json_chunk)); + ++i; + } + else if (cgltf_json_strcmp(tokens+i, json_chunk, "output") == 0) + { + ++i; + out_sampler->output = CGLTF_PTRINDEX(cgltf_accessor, cgltf_json_to_int(tokens + i, json_chunk)); + ++i; + } + else if (cgltf_json_strcmp(tokens+i, json_chunk, "interpolation") == 0) + { + ++i; + if (cgltf_json_strcmp(tokens + i, json_chunk, "LINEAR") == 0) + { + out_sampler->interpolation = cgltf_interpolation_type_linear; + } + else if (cgltf_json_strcmp(tokens + i, json_chunk, "STEP") == 0) + { + out_sampler->interpolation = cgltf_interpolation_type_step; + } + else if (cgltf_json_strcmp(tokens + i, json_chunk, "CUBICSPLINE") == 0) + { + out_sampler->interpolation = cgltf_interpolation_type_cubic_spline; + } + ++i; + } + else if (cgltf_json_strcmp(tokens + i, json_chunk, "extras") == 0) + { + i = cgltf_parse_json_extras(options, tokens, i + 1, json_chunk, &out_sampler->extras); + } + else if (cgltf_json_strcmp(tokens + i, json_chunk, "extensions") == 0) + { + i = cgltf_parse_json_unprocessed_extensions(options, tokens, i, json_chunk, &out_sampler->extensions_count, &out_sampler->extensions); + } + else + { + i = cgltf_skip_json(tokens, i+1); + } + + if (i < 0) + { + return i; + } + } + + return i; +} + +static int cgltf_parse_json_animation_channel(cgltf_options* options, jsmntok_t const* tokens, int i, const uint8_t* json_chunk, cgltf_animation_channel* out_channel) +{ + (void)options; + CGLTF_CHECK_TOKTYPE(tokens[i], JSMN_OBJECT); + + int size = tokens[i].size; + ++i; + + for (int j = 0; j < size; ++j) + { + CGLTF_CHECK_KEY(tokens[i]); + + if (cgltf_json_strcmp(tokens+i, json_chunk, "sampler") == 0) + { + ++i; + out_channel->sampler = CGLTF_PTRINDEX(cgltf_animation_sampler, cgltf_json_to_int(tokens + i, json_chunk)); + ++i; + } + else if (cgltf_json_strcmp(tokens+i, json_chunk, "target") == 0) + { + ++i; + + CGLTF_CHECK_TOKTYPE(tokens[i], JSMN_OBJECT); + + int target_size = tokens[i].size; + ++i; + + for (int k = 0; k < target_size; ++k) + { + CGLTF_CHECK_KEY(tokens[i]); + + if (cgltf_json_strcmp(tokens+i, json_chunk, "node") == 0) + { + ++i; + out_channel->target_node = CGLTF_PTRINDEX(cgltf_node, cgltf_json_to_int(tokens + i, json_chunk)); + ++i; + } + else if (cgltf_json_strcmp(tokens+i, json_chunk, "path") == 0) + { + ++i; + if (cgltf_json_strcmp(tokens+i, json_chunk, "translation") == 0) + { + out_channel->target_path = cgltf_animation_path_type_translation; + } + else if (cgltf_json_strcmp(tokens+i, json_chunk, "rotation") == 0) + { + out_channel->target_path = cgltf_animation_path_type_rotation; + } + else if (cgltf_json_strcmp(tokens+i, json_chunk, "scale") == 0) + { + out_channel->target_path = cgltf_animation_path_type_scale; + } + else if (cgltf_json_strcmp(tokens+i, json_chunk, "weights") == 0) + { + out_channel->target_path = cgltf_animation_path_type_weights; + } + ++i; + } + else if (cgltf_json_strcmp(tokens + i, json_chunk, "extras") == 0) + { + i = cgltf_parse_json_extras(options, tokens, i + 1, json_chunk, &out_channel->extras); + } + else if (cgltf_json_strcmp(tokens + i, json_chunk, "extensions") == 0) + { + i = cgltf_parse_json_unprocessed_extensions(options, tokens, i, json_chunk, &out_channel->extensions_count, &out_channel->extensions); + } + else + { + i = cgltf_skip_json(tokens, i+1); + } + + if (i < 0) + { + return i; + } + } + } + else + { + i = cgltf_skip_json(tokens, i+1); + } + + if (i < 0) + { + return i; + } + } + + return i; +} + +static int cgltf_parse_json_animation(cgltf_options* options, jsmntok_t const* tokens, int i, const uint8_t* json_chunk, cgltf_animation* out_animation) +{ + CGLTF_CHECK_TOKTYPE(tokens[i], JSMN_OBJECT); + + int size = tokens[i].size; + ++i; + + for (int j = 0; j < size; ++j) + { + CGLTF_CHECK_KEY(tokens[i]); + + if (cgltf_json_strcmp(tokens+i, json_chunk, "name") == 0) + { + i = cgltf_parse_json_string(options, tokens, i + 1, json_chunk, &out_animation->name); + } + else if (cgltf_json_strcmp(tokens+i, json_chunk, "samplers") == 0) + { + i = cgltf_parse_json_array(options, tokens, i + 1, json_chunk, sizeof(cgltf_animation_sampler), (void**)&out_animation->samplers, &out_animation->samplers_count); + if (i < 0) + { + return i; + } + + for (cgltf_size k = 0; k < out_animation->samplers_count; ++k) + { + i = cgltf_parse_json_animation_sampler(options, tokens, i, json_chunk, &out_animation->samplers[k]); + if (i < 0) + { + return i; + } + } + } + else if (cgltf_json_strcmp(tokens+i, json_chunk, "channels") == 0) + { + i = cgltf_parse_json_array(options, tokens, i + 1, json_chunk, sizeof(cgltf_animation_channel), (void**)&out_animation->channels, &out_animation->channels_count); + if (i < 0) + { + return i; + } + + for (cgltf_size k = 0; k < out_animation->channels_count; ++k) + { + i = cgltf_parse_json_animation_channel(options, tokens, i, json_chunk, &out_animation->channels[k]); + if (i < 0) + { + return i; + } + } + } + else if (cgltf_json_strcmp(tokens + i, json_chunk, "extras") == 0) + { + i = cgltf_parse_json_extras(options, tokens, i + 1, json_chunk, &out_animation->extras); + } + else if (cgltf_json_strcmp(tokens + i, json_chunk, "extensions") == 0) + { + i = cgltf_parse_json_unprocessed_extensions(options, tokens, i, json_chunk, &out_animation->extensions_count, &out_animation->extensions); + } + else + { + i = cgltf_skip_json(tokens, i+1); + } + + if (i < 0) + { + return i; + } + } + + return i; +} + +static int cgltf_parse_json_animations(cgltf_options* options, jsmntok_t const* tokens, int i, const uint8_t* json_chunk, cgltf_data* out_data) +{ + i = cgltf_parse_json_array(options, tokens, i, json_chunk, sizeof(cgltf_animation), (void**)&out_data->animations, &out_data->animations_count); + if (i < 0) + { + return i; + } + + for (cgltf_size j = 0; j < out_data->animations_count; ++j) + { + i = cgltf_parse_json_animation(options, tokens, i, json_chunk, &out_data->animations[j]); + if (i < 0) + { + return i; + } + } + return i; +} + +static int cgltf_parse_json_variant(cgltf_options* options, jsmntok_t const* tokens, int i, const uint8_t* json_chunk, cgltf_material_variant* out_variant) +{ + CGLTF_CHECK_TOKTYPE(tokens[i], JSMN_OBJECT); + + int size = tokens[i].size; + ++i; + + for (int j = 0; j < size; ++j) + { + CGLTF_CHECK_KEY(tokens[i]); + + if (cgltf_json_strcmp(tokens+i, json_chunk, "name") == 0) + { + i = cgltf_parse_json_string(options, tokens, i + 1, json_chunk, &out_variant->name); + } + else if (cgltf_json_strcmp(tokens + i, json_chunk, "extras") == 0) + { + i = cgltf_parse_json_extras(options, tokens, i + 1, json_chunk, &out_variant->extras); + } + else + { + i = cgltf_skip_json(tokens, i+1); + } + + if (i < 0) + { + return i; + } + } + + return i; +} + +static int cgltf_parse_json_variants(cgltf_options* options, jsmntok_t const* tokens, int i, const uint8_t* json_chunk, cgltf_data* out_data) +{ + i = cgltf_parse_json_array(options, tokens, i, json_chunk, sizeof(cgltf_material_variant), (void**)&out_data->variants, &out_data->variants_count); + if (i < 0) + { + return i; + } + + for (cgltf_size j = 0; j < out_data->variants_count; ++j) + { + i = cgltf_parse_json_variant(options, tokens, i, json_chunk, &out_data->variants[j]); + if (i < 0) + { + return i; + } + } + return i; +} + +static int cgltf_parse_json_asset(cgltf_options* options, jsmntok_t const* tokens, int i, const uint8_t* json_chunk, cgltf_asset* out_asset) +{ + CGLTF_CHECK_TOKTYPE(tokens[i], JSMN_OBJECT); + + int size = tokens[i].size; + ++i; + + for (int j = 0; j < size; ++j) + { + CGLTF_CHECK_KEY(tokens[i]); + + if (cgltf_json_strcmp(tokens+i, json_chunk, "copyright") == 0) + { + i = cgltf_parse_json_string(options, tokens, i + 1, json_chunk, &out_asset->copyright); + } + else if (cgltf_json_strcmp(tokens+i, json_chunk, "generator") == 0) + { + i = cgltf_parse_json_string(options, tokens, i + 1, json_chunk, &out_asset->generator); + } + else if (cgltf_json_strcmp(tokens+i, json_chunk, "version") == 0) + { + i = cgltf_parse_json_string(options, tokens, i + 1, json_chunk, &out_asset->version); + } + else if (cgltf_json_strcmp(tokens+i, json_chunk, "minVersion") == 0) + { + i = cgltf_parse_json_string(options, tokens, i + 1, json_chunk, &out_asset->min_version); + } + else if (cgltf_json_strcmp(tokens + i, json_chunk, "extras") == 0) + { + i = cgltf_parse_json_extras(options, tokens, i + 1, json_chunk, &out_asset->extras); + } + else if (cgltf_json_strcmp(tokens + i, json_chunk, "extensions") == 0) + { + i = cgltf_parse_json_unprocessed_extensions(options, tokens, i, json_chunk, &out_asset->extensions_count, &out_asset->extensions); + } + else + { + i = cgltf_skip_json(tokens, i+1); + } + + if (i < 0) + { + return i; + } + } + + if (out_asset->version && CGLTF_ATOF(out_asset->version) < 2) + { + return CGLTF_ERROR_LEGACY; + } + + return i; +} + +cgltf_size cgltf_num_components(cgltf_type type) { + switch (type) + { + case cgltf_type_vec2: + return 2; + case cgltf_type_vec3: + return 3; + case cgltf_type_vec4: + return 4; + case cgltf_type_mat2: + return 4; + case cgltf_type_mat3: + return 9; + case cgltf_type_mat4: + return 16; + case cgltf_type_invalid: + case cgltf_type_scalar: + default: + return 1; + } +} + +cgltf_size cgltf_component_size(cgltf_component_type component_type) { + switch (component_type) + { + case cgltf_component_type_r_8: + case cgltf_component_type_r_8u: + return 1; + case cgltf_component_type_r_16: + case cgltf_component_type_r_16u: + return 2; + case cgltf_component_type_r_32u: + case cgltf_component_type_r_32f: + return 4; + case cgltf_component_type_invalid: + default: + return 0; + } +} + +cgltf_size cgltf_calc_size(cgltf_type type, cgltf_component_type component_type) +{ + cgltf_size component_size = cgltf_component_size(component_type); + if (type == cgltf_type_mat2 && component_size == 1) + { + return 8 * component_size; + } + else if (type == cgltf_type_mat3 && (component_size == 1 || component_size == 2)) + { + return 12 * component_size; + } + return component_size * cgltf_num_components(type); +} + +static int cgltf_fixup_pointers(cgltf_data* out_data); + +static int cgltf_parse_json_root(cgltf_options* options, jsmntok_t const* tokens, int i, const uint8_t* json_chunk, cgltf_data* out_data) +{ + CGLTF_CHECK_TOKTYPE(tokens[i], JSMN_OBJECT); + + int size = tokens[i].size; + ++i; + + for (int j = 0; j < size; ++j) + { + CGLTF_CHECK_KEY(tokens[i]); + + if (cgltf_json_strcmp(tokens + i, json_chunk, "asset") == 0) + { + i = cgltf_parse_json_asset(options, tokens, i + 1, json_chunk, &out_data->asset); + } + else if (cgltf_json_strcmp(tokens + i, json_chunk, "meshes") == 0) + { + i = cgltf_parse_json_meshes(options, tokens, i + 1, json_chunk, out_data); + } + else if (cgltf_json_strcmp(tokens + i, json_chunk, "accessors") == 0) + { + i = cgltf_parse_json_accessors(options, tokens, i + 1, json_chunk, out_data); + } + else if (cgltf_json_strcmp(tokens + i, json_chunk, "bufferViews") == 0) + { + i = cgltf_parse_json_buffer_views(options, tokens, i + 1, json_chunk, out_data); + } + else if (cgltf_json_strcmp(tokens + i, json_chunk, "buffers") == 0) + { + i = cgltf_parse_json_buffers(options, tokens, i + 1, json_chunk, out_data); + } + else if (cgltf_json_strcmp(tokens + i, json_chunk, "materials") == 0) + { + i = cgltf_parse_json_materials(options, tokens, i + 1, json_chunk, out_data); + } + else if (cgltf_json_strcmp(tokens + i, json_chunk, "images") == 0) + { + i = cgltf_parse_json_images(options, tokens, i + 1, json_chunk, out_data); + } + else if (cgltf_json_strcmp(tokens + i, json_chunk, "textures") == 0) + { + i = cgltf_parse_json_textures(options, tokens, i + 1, json_chunk, out_data); + } + else if (cgltf_json_strcmp(tokens + i, json_chunk, "samplers") == 0) + { + i = cgltf_parse_json_samplers(options, tokens, i + 1, json_chunk, out_data); + } + else if (cgltf_json_strcmp(tokens + i, json_chunk, "skins") == 0) + { + i = cgltf_parse_json_skins(options, tokens, i + 1, json_chunk, out_data); + } + else if (cgltf_json_strcmp(tokens + i, json_chunk, "cameras") == 0) + { + i = cgltf_parse_json_cameras(options, tokens, i + 1, json_chunk, out_data); + } + else if (cgltf_json_strcmp(tokens + i, json_chunk, "nodes") == 0) + { + i = cgltf_parse_json_nodes(options, tokens, i + 1, json_chunk, out_data); + } + else if (cgltf_json_strcmp(tokens + i, json_chunk, "scenes") == 0) + { + i = cgltf_parse_json_scenes(options, tokens, i + 1, json_chunk, out_data); + } + else if (cgltf_json_strcmp(tokens + i, json_chunk, "scene") == 0) + { + ++i; + out_data->scene = CGLTF_PTRINDEX(cgltf_scene, cgltf_json_to_int(tokens + i, json_chunk)); + ++i; + } + else if (cgltf_json_strcmp(tokens + i, json_chunk, "animations") == 0) + { + i = cgltf_parse_json_animations(options, tokens, i + 1, json_chunk, out_data); + } + else if (cgltf_json_strcmp(tokens+i, json_chunk, "extras") == 0) + { + i = cgltf_parse_json_extras(options, tokens, i + 1, json_chunk, &out_data->extras); + } + else if (cgltf_json_strcmp(tokens + i, json_chunk, "extensions") == 0) + { + ++i; + + CGLTF_CHECK_TOKTYPE(tokens[i], JSMN_OBJECT); + if(out_data->data_extensions) + { + return CGLTF_ERROR_JSON; + } + + int extensions_size = tokens[i].size; + out_data->data_extensions_count = 0; + out_data->data_extensions = (cgltf_extension*)cgltf_calloc(options, sizeof(cgltf_extension), extensions_size); + + if (!out_data->data_extensions) + { + return CGLTF_ERROR_NOMEM; + } + + ++i; + + for (int k = 0; k < extensions_size; ++k) + { + CGLTF_CHECK_KEY(tokens[i]); + + if (cgltf_json_strcmp(tokens+i, json_chunk, "KHR_lights_punctual") == 0) + { + ++i; + + CGLTF_CHECK_TOKTYPE(tokens[i], JSMN_OBJECT); + + int data_size = tokens[i].size; + ++i; + + for (int m = 0; m < data_size; ++m) + { + CGLTF_CHECK_KEY(tokens[i]); + + if (cgltf_json_strcmp(tokens + i, json_chunk, "lights") == 0) + { + i = cgltf_parse_json_lights(options, tokens, i + 1, json_chunk, out_data); + } + else + { + i = cgltf_skip_json(tokens, i + 1); + } + + if (i < 0) + { + return i; + } + } + } + else if (cgltf_json_strcmp(tokens+i, json_chunk, "KHR_materials_variants") == 0) + { + ++i; + + CGLTF_CHECK_TOKTYPE(tokens[i], JSMN_OBJECT); + + int data_size = tokens[i].size; + ++i; + + for (int m = 0; m < data_size; ++m) + { + CGLTF_CHECK_KEY(tokens[i]); + + if (cgltf_json_strcmp(tokens + i, json_chunk, "variants") == 0) + { + i = cgltf_parse_json_variants(options, tokens, i + 1, json_chunk, out_data); + } + else + { + i = cgltf_skip_json(tokens, i + 1); + } + + if (i < 0) + { + return i; + } + } + } + else + { + i = cgltf_parse_json_unprocessed_extension(options, tokens, i, json_chunk, &(out_data->data_extensions[out_data->data_extensions_count++])); + } + + if (i < 0) + { + return i; + } + } + } + else if (cgltf_json_strcmp(tokens + i, json_chunk, "extensionsUsed") == 0) + { + i = cgltf_parse_json_string_array(options, tokens, i + 1, json_chunk, &out_data->extensions_used, &out_data->extensions_used_count); + } + else if (cgltf_json_strcmp(tokens + i, json_chunk, "extensionsRequired") == 0) + { + i = cgltf_parse_json_string_array(options, tokens, i + 1, json_chunk, &out_data->extensions_required, &out_data->extensions_required_count); + } + else + { + i = cgltf_skip_json(tokens, i + 1); + } + + if (i < 0) + { + return i; + } + } + + return i; +} + +cgltf_result cgltf_parse_json(cgltf_options* options, const uint8_t* json_chunk, cgltf_size size, cgltf_data** out_data) +{ + jsmn_parser parser = { 0, 0, 0 }; + + if (options->json_token_count == 0) + { + int token_count = jsmn_parse(&parser, (const char*)json_chunk, size, NULL, 0); + + if (token_count <= 0) + { + return cgltf_result_invalid_json; + } + + options->json_token_count = token_count; + } + + jsmntok_t* tokens = (jsmntok_t*)options->memory.alloc_func(options->memory.user_data, sizeof(jsmntok_t) * (options->json_token_count + 1)); + + if (!tokens) + { + return cgltf_result_out_of_memory; + } + + jsmn_init(&parser); + + int token_count = jsmn_parse(&parser, (const char*)json_chunk, size, tokens, options->json_token_count); + + if (token_count <= 0) + { + options->memory.free_func(options->memory.user_data, tokens); + return cgltf_result_invalid_json; + } + + // this makes sure that we always have an UNDEFINED token at the end of the stream + // for invalid JSON inputs this makes sure we don't perform out of bound reads of token data + tokens[token_count].type = JSMN_UNDEFINED; + + cgltf_data* data = (cgltf_data*)options->memory.alloc_func(options->memory.user_data, sizeof(cgltf_data)); + + if (!data) + { + options->memory.free_func(options->memory.user_data, tokens); + return cgltf_result_out_of_memory; + } + + memset(data, 0, sizeof(cgltf_data)); + data->memory = options->memory; + data->file = options->file; + + int i = cgltf_parse_json_root(options, tokens, 0, json_chunk, data); + + options->memory.free_func(options->memory.user_data, tokens); + + if (i < 0) + { + cgltf_free(data); + + switch (i) + { + case CGLTF_ERROR_NOMEM: return cgltf_result_out_of_memory; + case CGLTF_ERROR_LEGACY: return cgltf_result_legacy_gltf; + default: return cgltf_result_invalid_gltf; + } + } + + if (cgltf_fixup_pointers(data) < 0) + { + cgltf_free(data); + return cgltf_result_invalid_gltf; + } + + data->json = (const char*)json_chunk; + data->json_size = size; + + *out_data = data; + + return cgltf_result_success; +} + +static int cgltf_fixup_pointers(cgltf_data* data) +{ + for (cgltf_size i = 0; i < data->meshes_count; ++i) + { + for (cgltf_size j = 0; j < data->meshes[i].primitives_count; ++j) + { + CGLTF_PTRFIXUP(data->meshes[i].primitives[j].indices, data->accessors, data->accessors_count); + CGLTF_PTRFIXUP(data->meshes[i].primitives[j].material, data->materials, data->materials_count); + + for (cgltf_size k = 0; k < data->meshes[i].primitives[j].attributes_count; ++k) + { + CGLTF_PTRFIXUP_REQ(data->meshes[i].primitives[j].attributes[k].data, data->accessors, data->accessors_count); + } + + for (cgltf_size k = 0; k < data->meshes[i].primitives[j].targets_count; ++k) + { + for (cgltf_size m = 0; m < data->meshes[i].primitives[j].targets[k].attributes_count; ++m) + { + CGLTF_PTRFIXUP_REQ(data->meshes[i].primitives[j].targets[k].attributes[m].data, data->accessors, data->accessors_count); + } + } + + if (data->meshes[i].primitives[j].has_draco_mesh_compression) + { + CGLTF_PTRFIXUP_REQ(data->meshes[i].primitives[j].draco_mesh_compression.buffer_view, data->buffer_views, data->buffer_views_count); + for (cgltf_size m = 0; m < data->meshes[i].primitives[j].draco_mesh_compression.attributes_count; ++m) + { + CGLTF_PTRFIXUP_REQ(data->meshes[i].primitives[j].draco_mesh_compression.attributes[m].data, data->accessors, data->accessors_count); + } + } + + for (cgltf_size k = 0; k < data->meshes[i].primitives[j].mappings_count; ++k) + { + CGLTF_PTRFIXUP_REQ(data->meshes[i].primitives[j].mappings[k].material, data->materials, data->materials_count); + } + } + } + + for (cgltf_size i = 0; i < data->accessors_count; ++i) + { + CGLTF_PTRFIXUP(data->accessors[i].buffer_view, data->buffer_views, data->buffer_views_count); + + if (data->accessors[i].is_sparse) + { + CGLTF_PTRFIXUP_REQ(data->accessors[i].sparse.indices_buffer_view, data->buffer_views, data->buffer_views_count); + CGLTF_PTRFIXUP_REQ(data->accessors[i].sparse.values_buffer_view, data->buffer_views, data->buffer_views_count); + } + + if (data->accessors[i].buffer_view) + { + data->accessors[i].stride = data->accessors[i].buffer_view->stride; + } + + if (data->accessors[i].stride == 0) + { + data->accessors[i].stride = cgltf_calc_size(data->accessors[i].type, data->accessors[i].component_type); + } + } + + for (cgltf_size i = 0; i < data->textures_count; ++i) + { + CGLTF_PTRFIXUP(data->textures[i].image, data->images, data->images_count); + CGLTF_PTRFIXUP(data->textures[i].basisu_image, data->images, data->images_count); + CGLTF_PTRFIXUP(data->textures[i].webp_image, data->images, data->images_count); + CGLTF_PTRFIXUP(data->textures[i].sampler, data->samplers, data->samplers_count); + } + + for (cgltf_size i = 0; i < data->images_count; ++i) + { + CGLTF_PTRFIXUP(data->images[i].buffer_view, data->buffer_views, data->buffer_views_count); + } + + for (cgltf_size i = 0; i < data->materials_count; ++i) + { + CGLTF_PTRFIXUP(data->materials[i].normal_texture.texture, data->textures, data->textures_count); + CGLTF_PTRFIXUP(data->materials[i].emissive_texture.texture, data->textures, data->textures_count); + CGLTF_PTRFIXUP(data->materials[i].occlusion_texture.texture, data->textures, data->textures_count); + + CGLTF_PTRFIXUP(data->materials[i].pbr_metallic_roughness.base_color_texture.texture, data->textures, data->textures_count); + CGLTF_PTRFIXUP(data->materials[i].pbr_metallic_roughness.metallic_roughness_texture.texture, data->textures, data->textures_count); + + CGLTF_PTRFIXUP(data->materials[i].pbr_specular_glossiness.diffuse_texture.texture, data->textures, data->textures_count); + CGLTF_PTRFIXUP(data->materials[i].pbr_specular_glossiness.specular_glossiness_texture.texture, data->textures, data->textures_count); + + CGLTF_PTRFIXUP(data->materials[i].clearcoat.clearcoat_texture.texture, data->textures, data->textures_count); + CGLTF_PTRFIXUP(data->materials[i].clearcoat.clearcoat_roughness_texture.texture, data->textures, data->textures_count); + CGLTF_PTRFIXUP(data->materials[i].clearcoat.clearcoat_normal_texture.texture, data->textures, data->textures_count); + + CGLTF_PTRFIXUP(data->materials[i].specular.specular_texture.texture, data->textures, data->textures_count); + CGLTF_PTRFIXUP(data->materials[i].specular.specular_color_texture.texture, data->textures, data->textures_count); + + CGLTF_PTRFIXUP(data->materials[i].transmission.transmission_texture.texture, data->textures, data->textures_count); + + CGLTF_PTRFIXUP(data->materials[i].volume.thickness_texture.texture, data->textures, data->textures_count); + + CGLTF_PTRFIXUP(data->materials[i].sheen.sheen_color_texture.texture, data->textures, data->textures_count); + CGLTF_PTRFIXUP(data->materials[i].sheen.sheen_roughness_texture.texture, data->textures, data->textures_count); + + CGLTF_PTRFIXUP(data->materials[i].iridescence.iridescence_texture.texture, data->textures, data->textures_count); + CGLTF_PTRFIXUP(data->materials[i].iridescence.iridescence_thickness_texture.texture, data->textures, data->textures_count); + + CGLTF_PTRFIXUP(data->materials[i].diffuse_transmission.diffuse_transmission_texture.texture, data->textures, data->textures_count); + CGLTF_PTRFIXUP(data->materials[i].diffuse_transmission.diffuse_transmission_color_texture.texture, data->textures, data->textures_count); + + CGLTF_PTRFIXUP(data->materials[i].anisotropy.anisotropy_texture.texture, data->textures, data->textures_count); + } + + for (cgltf_size i = 0; i < data->buffer_views_count; ++i) + { + CGLTF_PTRFIXUP_REQ(data->buffer_views[i].buffer, data->buffers, data->buffers_count); + + if (data->buffer_views[i].has_meshopt_compression) + { + CGLTF_PTRFIXUP_REQ(data->buffer_views[i].meshopt_compression.buffer, data->buffers, data->buffers_count); + } + } + + for (cgltf_size i = 0; i < data->skins_count; ++i) + { + for (cgltf_size j = 0; j < data->skins[i].joints_count; ++j) + { + CGLTF_PTRFIXUP_REQ(data->skins[i].joints[j], data->nodes, data->nodes_count); + } + + CGLTF_PTRFIXUP(data->skins[i].skeleton, data->nodes, data->nodes_count); + CGLTF_PTRFIXUP(data->skins[i].inverse_bind_matrices, data->accessors, data->accessors_count); + } + + for (cgltf_size i = 0; i < data->nodes_count; ++i) + { + for (cgltf_size j = 0; j < data->nodes[i].children_count; ++j) + { + CGLTF_PTRFIXUP_REQ(data->nodes[i].children[j], data->nodes, data->nodes_count); + + if (data->nodes[i].children[j]->parent) + { + return CGLTF_ERROR_JSON; + } + + data->nodes[i].children[j]->parent = &data->nodes[i]; + } + + CGLTF_PTRFIXUP(data->nodes[i].mesh, data->meshes, data->meshes_count); + CGLTF_PTRFIXUP(data->nodes[i].skin, data->skins, data->skins_count); + CGLTF_PTRFIXUP(data->nodes[i].camera, data->cameras, data->cameras_count); + CGLTF_PTRFIXUP(data->nodes[i].light, data->lights, data->lights_count); + + if (data->nodes[i].has_mesh_gpu_instancing) + { + for (cgltf_size m = 0; m < data->nodes[i].mesh_gpu_instancing.attributes_count; ++m) + { + CGLTF_PTRFIXUP_REQ(data->nodes[i].mesh_gpu_instancing.attributes[m].data, data->accessors, data->accessors_count); + } + } + } + + for (cgltf_size i = 0; i < data->scenes_count; ++i) + { + for (cgltf_size j = 0; j < data->scenes[i].nodes_count; ++j) + { + CGLTF_PTRFIXUP_REQ(data->scenes[i].nodes[j], data->nodes, data->nodes_count); + + if (data->scenes[i].nodes[j]->parent) + { + return CGLTF_ERROR_JSON; + } + } + } + + CGLTF_PTRFIXUP(data->scene, data->scenes, data->scenes_count); + + for (cgltf_size i = 0; i < data->animations_count; ++i) + { + for (cgltf_size j = 0; j < data->animations[i].samplers_count; ++j) + { + CGLTF_PTRFIXUP_REQ(data->animations[i].samplers[j].input, data->accessors, data->accessors_count); + CGLTF_PTRFIXUP_REQ(data->animations[i].samplers[j].output, data->accessors, data->accessors_count); + } + + for (cgltf_size j = 0; j < data->animations[i].channels_count; ++j) + { + CGLTF_PTRFIXUP_REQ(data->animations[i].channels[j].sampler, data->animations[i].samplers, data->animations[i].samplers_count); + CGLTF_PTRFIXUP(data->animations[i].channels[j].target_node, data->nodes, data->nodes_count); + } + } + + return 0; +} + +/* + * -- jsmn.c start -- + * Source: https://github.com/zserge/jsmn + * License: MIT + * + * Copyright (c) 2010 Serge A. Zaitsev + + * 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. + */ + +/** + * Allocates a fresh unused token from the token pull. + */ +static jsmntok_t *jsmn_alloc_token(jsmn_parser *parser, + jsmntok_t *tokens, size_t num_tokens) { + jsmntok_t *tok; + if (parser->toknext >= num_tokens) { + return NULL; + } + tok = &tokens[parser->toknext++]; + tok->start = tok->end = -1; + tok->size = 0; +#ifdef JSMN_PARENT_LINKS + tok->parent = -1; +#endif + return tok; +} + +/** + * Fills token type and boundaries. + */ +static void jsmn_fill_token(jsmntok_t *token, jsmntype_t type, + ptrdiff_t start, ptrdiff_t end) { + token->type = type; + token->start = start; + token->end = end; + token->size = 0; +} + +/** + * Fills next available token with JSON primitive. + */ +static int jsmn_parse_primitive(jsmn_parser *parser, const char *js, + size_t len, jsmntok_t *tokens, size_t num_tokens) { + jsmntok_t *token; + ptrdiff_t start; + + start = parser->pos; + + for (; parser->pos < len && js[parser->pos] != '\0'; parser->pos++) { + switch (js[parser->pos]) { +#ifndef JSMN_STRICT + /* In strict mode primitive must be followed by "," or "}" or "]" */ + case ':': +#endif + case '\t' : case '\r' : case '\n' : case ' ' : + case ',' : case ']' : case '}' : + goto found; + } + if (js[parser->pos] < 32 || js[parser->pos] >= 127) { + parser->pos = start; + return JSMN_ERROR_INVAL; + } + } +#ifdef JSMN_STRICT + /* In strict mode primitive must be followed by a comma/object/array */ + parser->pos = start; + return JSMN_ERROR_PART; +#endif + +found: + if (tokens == NULL) { + parser->pos--; + return 0; + } + token = jsmn_alloc_token(parser, tokens, num_tokens); + if (token == NULL) { + parser->pos = start; + return JSMN_ERROR_NOMEM; + } + jsmn_fill_token(token, JSMN_PRIMITIVE, start, parser->pos); +#ifdef JSMN_PARENT_LINKS + token->parent = parser->toksuper; +#endif + parser->pos--; + return 0; +} + +/** + * Fills next token with JSON string. + */ +static int jsmn_parse_string(jsmn_parser *parser, const char *js, + size_t len, jsmntok_t *tokens, size_t num_tokens) { + jsmntok_t *token; + + ptrdiff_t start = parser->pos; + + parser->pos++; + + /* Skip starting quote */ + for (; parser->pos < len && js[parser->pos] != '\0'; parser->pos++) { + char c = js[parser->pos]; + + /* Quote: end of string */ + if (c == '\"') { + if (tokens == NULL) { + return 0; + } + token = jsmn_alloc_token(parser, tokens, num_tokens); + if (token == NULL) { + parser->pos = start; + return JSMN_ERROR_NOMEM; + } + jsmn_fill_token(token, JSMN_STRING, start+1, parser->pos); +#ifdef JSMN_PARENT_LINKS + token->parent = parser->toksuper; +#endif + return 0; + } + + /* Backslash: Quoted symbol expected */ + if (c == '\\' && parser->pos + 1 < len) { + int i; + parser->pos++; + switch (js[parser->pos]) { + /* Allowed escaped symbols */ + case '\"': case '/' : case '\\' : case 'b' : + case 'f' : case 'r' : case 'n' : case 't' : + break; + /* Allows escaped symbol \uXXXX */ + case 'u': + parser->pos++; + for(i = 0; i < 4 && parser->pos < len && js[parser->pos] != '\0'; i++) { + /* If it isn't a hex character we have an error */ + if(!((js[parser->pos] >= 48 && js[parser->pos] <= 57) || /* 0-9 */ + (js[parser->pos] >= 65 && js[parser->pos] <= 70) || /* A-F */ + (js[parser->pos] >= 97 && js[parser->pos] <= 102))) { /* a-f */ + parser->pos = start; + return JSMN_ERROR_INVAL; + } + parser->pos++; + } + parser->pos--; + break; + /* Unexpected symbol */ + default: + parser->pos = start; + return JSMN_ERROR_INVAL; + } + } + } + parser->pos = start; + return JSMN_ERROR_PART; +} + +/** + * Parse JSON string and fill tokens. + */ +static int jsmn_parse(jsmn_parser *parser, const char *js, size_t len, + jsmntok_t *tokens, size_t num_tokens) { + int r; + int i; + jsmntok_t *token; + int count = parser->toknext; + + for (; parser->pos < len && js[parser->pos] != '\0'; parser->pos++) { + char c; + jsmntype_t type; + + c = js[parser->pos]; + switch (c) { + case '{': case '[': + count++; + if (tokens == NULL) { + break; + } + token = jsmn_alloc_token(parser, tokens, num_tokens); + if (token == NULL) + return JSMN_ERROR_NOMEM; + if (parser->toksuper != -1) { + tokens[parser->toksuper].size++; +#ifdef JSMN_PARENT_LINKS + token->parent = parser->toksuper; +#endif + } + token->type = (c == '{' ? JSMN_OBJECT : JSMN_ARRAY); + token->start = parser->pos; + parser->toksuper = parser->toknext - 1; + break; + case '}': case ']': + if (tokens == NULL) + break; + type = (c == '}' ? JSMN_OBJECT : JSMN_ARRAY); +#ifdef JSMN_PARENT_LINKS + if (parser->toknext < 1) { + return JSMN_ERROR_INVAL; + } + token = &tokens[parser->toknext - 1]; + for (;;) { + if (token->start != -1 && token->end == -1) { + if (token->type != type) { + return JSMN_ERROR_INVAL; + } + token->end = parser->pos + 1; + parser->toksuper = token->parent; + break; + } + if (token->parent == -1) { + if(token->type != type || parser->toksuper == -1) { + return JSMN_ERROR_INVAL; + } + break; + } + token = &tokens[token->parent]; + } +#else + for (i = parser->toknext - 1; i >= 0; i--) { + token = &tokens[i]; + if (token->start != -1 && token->end == -1) { + if (token->type != type) { + return JSMN_ERROR_INVAL; + } + parser->toksuper = -1; + token->end = parser->pos + 1; + break; + } + } + /* Error if unmatched closing bracket */ + if (i == -1) return JSMN_ERROR_INVAL; + for (; i >= 0; i--) { + token = &tokens[i]; + if (token->start != -1 && token->end == -1) { + parser->toksuper = i; + break; + } + } +#endif + break; + case '\"': + r = jsmn_parse_string(parser, js, len, tokens, num_tokens); + if (r < 0) return r; + count++; + if (parser->toksuper != -1 && tokens != NULL) + tokens[parser->toksuper].size++; + break; + case '\t' : case '\r' : case '\n' : case ' ': + break; + case ':': + parser->toksuper = parser->toknext - 1; + break; + case ',': + if (tokens != NULL && parser->toksuper != -1 && + tokens[parser->toksuper].type != JSMN_ARRAY && + tokens[parser->toksuper].type != JSMN_OBJECT) { +#ifdef JSMN_PARENT_LINKS + parser->toksuper = tokens[parser->toksuper].parent; +#else + for (i = parser->toknext - 1; i >= 0; i--) { + if (tokens[i].type == JSMN_ARRAY || tokens[i].type == JSMN_OBJECT) { + if (tokens[i].start != -1 && tokens[i].end == -1) { + parser->toksuper = i; + break; + } + } + } +#endif + } + break; +#ifdef JSMN_STRICT + /* In strict mode primitives are: numbers and booleans */ + case '-': case '0': case '1' : case '2': case '3' : case '4': + case '5': case '6': case '7' : case '8': case '9': + case 't': case 'f': case 'n' : + /* And they must not be keys of the object */ + if (tokens != NULL && parser->toksuper != -1) { + jsmntok_t *t = &tokens[parser->toksuper]; + if (t->type == JSMN_OBJECT || + (t->type == JSMN_STRING && t->size != 0)) { + return JSMN_ERROR_INVAL; + } + } +#else + /* In non-strict mode every unquoted value is a primitive */ + default: +#endif + r = jsmn_parse_primitive(parser, js, len, tokens, num_tokens); + if (r < 0) return r; + count++; + if (parser->toksuper != -1 && tokens != NULL) + tokens[parser->toksuper].size++; + break; + +#ifdef JSMN_STRICT + /* Unexpected char in strict mode */ + default: + return JSMN_ERROR_INVAL; +#endif + } + } + + if (tokens != NULL) { + for (i = parser->toknext - 1; i >= 0; i--) { + /* Unmatched opened object or array */ + if (tokens[i].start != -1 && tokens[i].end == -1) { + return JSMN_ERROR_PART; + } + } + } + + return count; +} + +/** + * Creates a new parser based over a given buffer with an array of tokens + * available. + */ +static void jsmn_init(jsmn_parser *parser) { + parser->pos = 0; + parser->toknext = 0; + parser->toksuper = -1; +} +/* + * -- jsmn.c end -- + */ + +#endif /* #ifdef CGLTF_IMPLEMENTATION */ + +/* cgltf is distributed under MIT license: + * + * Copyright (c) 2018-2021 Johannes Kuhlmann + + * 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. + */ diff --git a/web/host.js b/web/host.js index 2c410f7..7559dfc 100644 --- a/web/host.js +++ b/web/host.js @@ -190,7 +190,7 @@ const gpu = { }, pipeline(p, samples, stencil) { - const key = JSON.stringify([p.vertex.hash, p.fragment.hash, p.stride, p.attributes, p.primitive, p.blend, p.write_color, p.stencil, samples, stencil]); + const key = JSON.stringify([p.vertex.hash, p.fragment.hash, p.stride, p.attributes, p.primitive, p.blend, p.write_color, p.stencil, p.depth_test, p.depth_write, samples, stencil]); let pipeline = gpu.pipelines.get(key); if (pipeline) return pipeline; const formats = {float: 'float32', float2: 'float32x2', float3: 'float32x3', float4: 'float32x4', ubyte4_norm: 'unorm8x4'}; @@ -212,7 +212,7 @@ const gpu = { primitive: {topology: dashed(p.primitive)}, multisample: {count: samples}, depthStencil: stencil ? { - format: 'depth24plus-stencil8', depthWriteEnabled: false, depthCompare: 'always', + format: 'depth24plus-stencil8', depthWriteEnabled: p.depth_write ?? false, depthCompare: dashed(p.depth_test ?? 'always'), stencilFront: p.stencil ? face(p.stencil.front) : keep, stencilBack: p.stencil ? face(p.stencil.back) : keep, } : undefined, }); @@ -232,7 +232,7 @@ const gpu = { clearValue: p.clear ? {r: p.clear[0], g: p.clear[1], b: p.clear[2], a: p.clear[3]} : undefined, storeOp: 'store', }; - const depthStencil = p.stencil ? { + const depthStencil = p.stencil || p.depth ? { view: gpu.attachment(entry, 'stencil', 'depth24plus-stencil8', samples).createView(), depthLoadOp: 'clear', depthClearValue: 1, depthStoreOp: 'discard', stencilLoadOp: 'clear', stencilClearValue: 0, stencilStoreOp: 'discard', @@ -247,7 +247,7 @@ const gpu = { const commands = gpu.device.createCommandEncoder(); const pass = commands.beginRenderPass({colorAttachments: [color], depthStencilAttachment: depthStencil}); for (const {d, vertices, vertexUniforms, fragmentUniforms} of draws) { - const pipeline = gpu.pipeline(p.pipelines[d.pipeline], samples, p.stencil); + const pipeline = gpu.pipeline(p.pipelines[d.pipeline], samples, p.stencil || p.depth); pass.setPipeline(pipeline); gpu.bind(pass, pipeline, [gpu.storage(d.vertex_storage), gpu.uniform(vertexUniforms), gpu.storage(d.fragment_storage), gpu.uniform(fragmentUniforms)]); if (vertices) pass.setVertexBuffer(0, vertices.buffer, vertices.offset, vertices.size); @@ -596,7 +596,12 @@ const imports = { available: () => gpu.device ? 1 : gpu.absent(), newBuffer: size => gpu.device ? gpu.newBuffer(size) : 0, freeBuffer(id) { gpu.buffers[id]?.destroy(); gpu.buffers[id] = null; }, - write(id, offset, ptr, len) { if (gpu.buffers[id]) gpu.device.queue.writeBuffer(gpu.buffers[id], offset, bytes(ptr, len).slice()); }, + write(id, offset, ptr, len) { + const buffer = gpu.buffers[id]; + if (!gpu.device || !buffer || offset % 4 || len % 4 || offset + len > buffer.size) return 0; + try { gpu.device.queue.writeBuffer(buffer, offset, bytes(ptr, len).slice()); return 1; } + catch { return 0; } + }, compute(ptr, len) { if (gpu.device) gpu.compute(JSON.parse(string(ptr, len))); }, pass(ptr, len) { if (gpu.device) gpu.pass(JSON.parse(string(ptr, len))); }, download(id, offset, size, key) { if (gpu.buffers[id]) gpu.download(id, offset, size, key); }, |
