Initial Commit

This commit is contained in:
SoraKatadzuma committed 2026-10-30 13:52:09 -05:00
commit aa254a2a0a
16 files changed
+2405

No files matched your search

+240
View File
@@ -0,0 +1,240 @@
#! Contains buffers, the views of them, and accessors, which say how a view's
#! bytes are read as numbers; and reading an accessor's numbers, as floats or
#! as integers, its sparse values put in place.
import std::math;
module gltf;
#! A buffer: bytes, read from its file, a `data:` URI, or a `.glb` file's
#! binary chunk.
pub struct buffer {
pub var name: string;
#! Its URI, as the JSON writes it, or empty for a `.glb` file's binary chunk.
pub var uri: string;
#! How many bytes it is, as the JSON says, which its bytes are at least.
pub var length: u64;
pub var bytes: vector<u8>;
}
#! A part of a buffer, which accessors read.
pub struct buffer_view {
pub var name: string;
pub var buffer: u64;
pub var offset: u64;
pub var length: u64;
#! The bytes from one element to the next, or zero where they're packed.
pub var stride: u64;
}
#! The type of each number of an accessor.
pub enum component: u8 { byte, unsigned_byte, short, unsigned_short, unsigned_int, float }
#! How many bytes a number of the type takes.
pub val component::bytes: u64 {
get => match this {
byte, unsigned_byte => 1,
short, unsigned_short => 2,
unsigned_int, float => 4,
};
}
#! What each element of an accessor is.
pub enum element: u8 { scalar, vec2, vec3, vec4, mat2, mat3, mat4 }
#! How many numbers an element holds.
pub val element::components: u64 {
get => match this {
scalar => 1,
vec2 => 2,
vec3 => 3,
vec4, mat2 => 4,
mat3 => 9,
mat4 => 16,
};
}
# How many rows a matrix has, or 1 for a vector, as a column of a matrix is
# kept on its own, at a multiple of 4 bytes.
def element::rows(&this): u64 {
return match this {
mat2 => 2,
mat3 => 3,
mat4 => 4,
else => 0,
};
}
#! Values an accessor puts in place of some of its elements, of `count`
#! indices, in a view of integers, and as many values, in a view of the
#! accessor's own type.
pub struct sparse {
pub var count: u64;
pub var indices_view: u64;
pub var indices_offset: u64;
pub var indices_type := component::unsigned_int;
pub var values_view: u64;
pub var values_offset: u64;
}
#! How the bytes of a view are read as `count` elements, each of `kind`'s
#! numbers of `type`, from `offset`.
pub struct accessor {
pub var name: string;
#! Its view, or none where every element is zero but its sparse ones.
pub var view: maybe<u64>;
pub var offset: u64;
pub var component_type := component::float;
#! Whether its integers are read as fractions, 0 to 1, or -1 to 1 where signed.
pub var normalized: bool;
pub var count: u64;
pub var kind := element::scalar;
#! The least and the most of each of its numbers, where the JSON says.
pub var min: vector<f64>;
pub var max: vector<f64>;
pub var sparse: maybe<sparse>;
}
# How many bytes an element of an accessor takes, each column of a matrix
# begun at a multiple of 4.
def accessor::element_bytes(&this): u64 {
val rows := this.kind.rows();
return this.kind.components * this.component_type.bytes if rows == 0;
return rows * column_stride(rows, this.component_type);
}
# The bytes from one column of a matrix to the next.
def column_stride(rows: u64, numbers: component): u64 {
val bytes := rows * numbers.bytes;
return (bytes + 3) / 4 * 4;
}
# Where the number `k` of an element is, from the element's first byte.
def accessor::component_at(&this, k: u64): u64 {
val rows := this.kind.rows();
return k * this.component_type.bytes if rows == 0;
return (k / rows) * column_stride(rows, this.component_type) + (k % rows) * this.component_type.bytes;
}
#! The numbers of an accessor, as floats: each element's in turn, `count` of
#! them, integers made floats, normalized ones made fractions as glTF says, and
#! its sparse values put in place.
#! @param this The asset.
#! @param which The accessor.
#! @returns `count * kind.components` floats.
pub def asset::floats(&this, which: u64): vector<f32> {
val read := &this.accessors[which];
val width := read.kind.components;
var made := vector::<f32>::new();
made.resize(read.count * width);
if read.view is some(v) {
val at := this.place_of(read, v);
val stride := this.stride_of(read, v);
for e in 0..read.count {
for k in 0..width {
made[e * width + k] = float_at(at.bytes, at.start + e * stride + read.component_at(k), read.component_type, read.normalized);
}
}
}
if read.sparse is some(&s) {
val indices := this.place_of_view(s.indices_view, s.indices_offset);
val values := this.place_of_view(s.values_view, s.values_offset);
val size := read.element_bytes();
for i in 0..s.count {
val e := integer_at(indices.bytes, indices.start + i * s.indices_type.bytes, s.indices_type);
for k in 0..width {
made[e * width + k] = float_at(values.bytes, values.start + i * size + read.component_at(k), read.component_type, read.normalized);
}
}
}
return made;
}
#! The numbers of an accessor of integers, as indices and joints are: each
#! element's in turn, its sparse values put in place.
#! @param this The asset.
#! @param which The accessor, of a type of integers, not normalized.
#! @returns `count * kind.components` integers.
pub def asset::integers(&this, which: u64): vector<u32> {
val read := &this.accessors[which];
val width := read.kind.components;
var made := vector::<u32>::new();
made.resize(read.count * width);
if read.view is some(v) {
val at := this.place_of(read, v);
val stride := this.stride_of(read, v);
for e in 0..read.count {
for k in 0..width {
made[e * width + k] = integer_at(at.bytes, at.start + e * stride + read.component_at(k), read.component_type) as u32;
}
}
}
if read.sparse is some(&s) {
val indices := this.place_of_view(s.indices_view, s.indices_offset);
val values := this.place_of_view(s.values_view, s.values_offset);
val size := read.element_bytes();
for i in 0..s.count {
val e := integer_at(indices.bytes, indices.start + i * s.indices_type.bytes, s.indices_type);
for k in 0..width {
made[e * width + k] = integer_at(values.bytes, values.start + i * size + read.component_at(k), read.component_type) as u32;
}
}
}
return made;
}
# Where an accessor's, or a view's, bytes begin, in its buffer's.
struct place {
var bytes: span<u8>;
var start: u64;
}
def asset::place_of(&this, read: &accessor, view: u64): place {
return this.place_of_view(view, read.offset);
}
def asset::place_of_view(&this, view: u64, offset: u64): place {
val v := &this.views[view];
return place{ bytes = this.buffers[v.buffer].bytes.view(), start = v.offset + offset };
}
# The bytes from one element of an accessor to the next.
def asset::stride_of(&this, read: &accessor, view: u64): u64 {
val given := this.views[view].stride;
return given != 0 ? given : read.element_bytes();
}
# A number of a type, at a byte, as a float, made a fraction where it's
# normalized.
def float_at(bytes: span<u8>, at: u64, numbers: component, normalized: bool): f32 {
if numbers == component::float {
return math::real_of_bits(integer_at(bytes, at, component::unsigned_int) as u32);
}
val raw := integer_at(bytes, at, numbers);
val signed := signed_value(raw, numbers);
return signed as f32 if !normalized;
return match numbers {
byte => math::max(signed as f32 / 127, -1f),
unsigned_byte => raw as f32 / 255,
short => math::max(signed as f32 / 32767, -1f),
unsigned_short => raw as f32 / 65535,
else => raw as f32 / 4294967295,
};
}
# The bytes of an integer of a type, at a byte, little-endian, unsigned.
def integer_at(bytes: span<u8>, at: u64, numbers: component): u64 {
var value: u64 = 0;
for i in 0..numbers.bytes {
value = value | (bytes[at + i] as u64 << (8 * i) as u32);
}
return value;
}
# An integer's bytes as the signed value they are, of a signed type.
def signed_value(raw: u64, numbers: component): i64 {
return match numbers {
byte => raw >= 0x80 ? raw as i64 - 0x100 : raw as i64,
short => raw >= 0x8000 ? raw as i64 - 0x10000 : raw as i64,
else => raw as i64,
};
}
+157
View File
@@ -0,0 +1,157 @@
#! Contains the files an asset is read from: a `.glb` file's chunks, and the
#! bytes a URI names, the data of a `data:` URI, in base64, or a file's, beside
#! the asset's, its path percent-decoded.
import std::io;
module gltf;
const glb_magic: u32 = 0x46546C67; # `glTF`, little-endian.
const json_chunk: u32 = 0x4E4F534A; # `JSON`.
const bin_chunk: u32 = 0x004E4942; # `BIN`, and a zero.
# Whether bytes are a `.glb` file's, by their first four.
def is_binary(bytes: span<u8>): bool {
return bytes.length >= 4 && word_at(bytes, 0) == glb_magic;
}
# A little-endian `u32` at a byte.
def word_at(bytes: span<u8>, at: u64): u32 {
return bytes[at] as u32 | (bytes[at + 1] as u32 << 8) | (bytes[at + 2] as u32 << 16) | (bytes[at + 3] as u32 << 24);
}
# The chunks of a `.glb` file: its JSON, and its binary chunk, where it has one.
struct chunks {
var json: strview;
var bin: span<u8>;
var has_bin: bool;
}
# Finds a `.glb` file's chunks: the JSON first, as it must be, then the first
# binary chunk, passing over others, as glTF says to.
def binary_chunks(bytes: span<u8>): result<chunks, gltf_error> {
return failed(failure::malformed, "Its .glb header is cut short.") if bytes.length < 20;
val version := word_at(bytes, 4);
return failed(failure::unsupported, $"Its .glb container is of version {version}, not 2.".view()) if version != 2;
val length := word_at(bytes, 8) as u64;
return failed(failure::malformed, $"Its .glb header says it's {length} bytes, but it's {bytes.length}.".view()) if length > bytes.length || length < 20;
var made := chunks{};
var found_json := false;
var at: u64 = 12;
while at + 8 <= length {
val size := word_at(bytes, at) as u64;
val kind := word_at(bytes, at + 4);
at += 8;
return failed(failure::malformed, "A chunk of its .glb container reaches past its end.") if size > length - at;
if !found_json {
return failed(failure::malformed, "Its .glb container's first chunk isn't its JSON.") if kind != json_chunk;
made.json = strview::over(bytes.data + at, size);
found_json = true;
} else if kind == bin_chunk && !made.has_bin {
made.bin = span::<u8>::over(bytes.data + at, size);
made.has_bin = true;
}
at += size;
}
return failed(failure::malformed, "Its .glb container holds no JSON.") if !found_json;
return made;
}
# The bytes a URI names: a `data:` URI's, decoded from base64, its type kept;
# or a file's, its path, percent-decoded, taken from the folder.
# @param uri The URI.
# @param folder The folder the asset's files are in, or empty for none.
# @param whose Whose URI, as `buffers[1]`, for what's wrong with it.
# @param type The type a `data:` URI says, as `image/png`, kept.
# @returns The bytes, or why they couldn't be had.
def bytes_of_uri(uri: strview, folder: strview, whose: strview, mime: &mut string): result<vector<u8>, gltf_error> {
if uri.starts_with("data:") {
var comma := uri.length;
for i in 5..uri.length {
if uri[i] == ',' {
comma = i;
break;
}
}
return failed(failure::malformed, $"{whose}: its data URI has no comma.".view()) if comma == uri.length;
val head := uri.substr(5, comma - 5);
return failed(failure::unsupported, $"{whose}: its data URI isn't base64.".view()) if !head.ends_with(";base64");
mime = string::from(head.substr(0, head.length - 7), nothing{});
val decoded := base64(uri.substr(comma + 1, uri.length - comma - 1)) else {
return failed(failure::malformed, $"{whose}: its data URI's base64 isn't.".view());
};
return decoded;
}
for i in 0..uri.length {
if uri[i] == ':' {
return failed(failure::unsupported, $"{whose}: {uri} names another place than a file beside it, which isn't read.".view());
}
break if uri[i] == '/';
}
val named := percent_decoded(uri) else { return failed(failure::malformed, $"{whose}: {uri} isn't percent-encoded right.".view()); };
val at := folder.length == 0 ? string::from(named.view(), nothing{}) : $"{folder}/{named.view()}";
val file := path::parse(at.view()) else (_) { return failed(failure::unreadable, $"{whose}: {at.view()} isn't a path.".view()); };
val text := io::read_file(&file) else (_) { return failed(failure::unreadable, $"{whose}: {at.view()} couldn't be read.".view()); };
var made := vector::<u8>::new();
made.extend(text.view());
return made;
}
# Text of `%XX` escapes decoded, or nothing where an escape isn't two hex
# digits.
def percent_decoded(text: strview): maybe<string> {
var made := string::new(nothing{});
var i: u64 = 0;
while i < text.length {
if text[i] != '%' {
made.push(text[i]);
i++;
continue;
}
return nothing{} if i + 2 >= text.length;
val high := hex_value(text[i + 1]) else { return nothing{}; };
val low := hex_value(text[i + 2]) else { return nothing{}; };
made.push(high << 4 | low);
i += 3;
}
return made;
}
def hex_value(c: u8): maybe<u8> {
return c - '0' if c >= '0' && c <= '9';
return c - 'a' + 10 if c >= 'a' && c <= 'f';
return c - 'A' + 10 if c >= 'A' && c <= 'F';
return nothing{};
}
# Base64's bytes, its padding optional, or nothing where it isn't base64.
def base64(text: strview): maybe<vector<u8>> {
var made := vector::<u8>::new();
var held: u32 = 0;
var bits: u32 = 0;
var ended := false;
for i in 0..text.length {
val c := text[i];
if c == '=' {
ended = true;
continue;
}
return nothing{} if ended;
val value := base64_value(c) else { return nothing{}; };
held = ((held << 6) | value as u32) & 0xFFFFFF;
bits += 6;
if bits >= 8 {
bits -= 8;
made.append(((held >> bits) & 0xFF) as u8);
}
}
return made;
}
def base64_value(c: u8): maybe<u8> {
return c - 'A' if c >= 'A' && c <= 'Z';
return c - 'a' + 26 if c >= 'a' && c <= 'z';
return c - '0' + 52 if c >= '0' && c <= '9';
return 62 if c == '+';
return 63 if c == '/';
return nothing{};
}
+123
View File
@@ -0,0 +1,123 @@
#! Contains `asset`, a model read from glTF 2.0, why one couldn't be, and
#! reading one, from a file or from bytes.
#!
#! A `.gltf` file is JSON, naming its buffers and images as files beside it or
#! as data in `data:` URIs; a `.glb` file is the same JSON and its first buffer
#! in one file, as chunks. Either is read whole: its JSON into the parts of an
#! `asset`, each index between them checked, its buffers' and images' bytes read,
#! and every accessor checked to lie within its buffer, so what an asset holds
#! is read without failing after. What an accessor holds is read as numbers by
#! `asset::floats` and `asset::integers`.
#!
#! Indices into an asset's lists are `u64`s, as glTF's are, and one that's
#! optional a `maybe<u64>`. Each part keeps glTF's defaults where its JSON leaves
#! them out, and a node its translation, rotation, and scale and its matrix both,
#! whichever the JSON gave.
import std::io;
import linear;
module gltf;
#! What kind of thing kept an asset from being read.
pub enum failure: u8 {
unreadable, #! A file couldn't be read: the asset's, or a buffer's or an image's it names.
malformed, #! The data breaks glTF: JSON that isn't, a member of the wrong kind or missing, an index past what it names, an accessor past its buffer.
unsupported, #! It's well formed, but asks for what isn't read: a version but 2, or an extension it requires that isn't read.
}
#! Why an asset couldn't be read: the kind of thing, and what, as
#! `meshes[2].primitives[0]: its material is 9, of the 4 there are`. It holds
#! its text itself, its first 240 bytes, so it's plain data, as std's errors
#! are.
pub struct gltf_error {
pub var kind: failure;
var text: u8[240];
var length: u64;
}
#! What was wrong, and where.
pub def gltf_error::describe(&this): string {
return string::from(strview::over(&this.text[0] as *u8, this.length), nothing{});
}
# An error of a kind, saying why.
def failed(kind: failure, why: strview): gltf_error {
var made := gltf_error{ kind = kind };
made.length = why.length < 240 ? why.length : 240;
for i in 0..made.length {
made.text[i] = why[i];
}
return made;
}
#! The extensions read. An asset requiring another is `unsupported`; one using
#! another, without requiring it, is read without what it adds.
pub const extensions_read: strview[4] = [
"KHR_lights_punctual",
"KHR_materials_unlit",
"KHR_materials_emissive_strength",
"KHR_mesh_quantization",
];
#! A model read from glTF 2.0: its scenes, the tree of nodes they hold, and
#! what those draw with, each part in the list glTF keeps it in, by index.
pub struct asset {
#! The glTF version it says it's of, as `2.0`.
pub var version: string;
#! What wrote it, where it says.
pub var generator: string;
#! The scene shown at first, where it says.
pub var scene: maybe<u64>;
pub var scenes: vector<scene>;
pub var nodes: vector<node>;
pub var meshes: vector<mesh>;
pub var materials: vector<material>;
pub var textures: vector<texture>;
pub var samplers: vector<sampler>;
pub var images: vector<image>;
pub var accessors: vector<accessor>;
pub var views: vector<buffer_view>;
pub var buffers: vector<buffer>;
pub var cameras: vector<camera>;
pub var skins: vector<skin>;
pub var animations: vector<animation>;
#! Its lights, of `KHR_lights_punctual`.
pub var lights: vector<light>;
#! The extensions it uses, those not read among them.
pub var extensions: vector<string>;
}
#! Reads an asset from a file: `.gltf` or `.glb`, whichever its first bytes
#! say, the files it names read from beside it.
#! @param at The file's path.
#! @returns The asset, or why it couldn't be read: `unreadable` where the file,
#! or one it names, couldn't be.
pub def load(at: &path): result<asset, gltf_error> {
val bytes := io::read_file(at) else (_) { return failed(failure::unreadable, $"{at.view()} couldn't be read.".view()); };
var folder := path::new();
if at.parent() is some(&above) {
folder = path::copy_of(&above);
}
return decode(bytes.view(), folder.view());
}
#! Reads an asset from a file named by text, as `load` does.
pub def load(at: strview): result<asset, gltf_error> {
val named := path::parse(at) else (_) { return failed(failure::unreadable, $"{at} isn't a path.".view()); };
return load(&named);
}
#! Reads an asset from bytes: a `.glb` file's, whose first four are `glTF`, or
#! else a `.gltf` file's JSON.
#! @param bytes The bytes.
#! @param folder The folder the files it names are found in, or empty where
#! it names none but data, as a `.glb` file of one buffer.
#! @returns The asset, or why it couldn't be read.
pub def decode(bytes: span<u8>, folder: strview = ""): result<asset, gltf_error> {
if is_binary(bytes) {
val chunks := binary_chunks(bytes) else (e) { return e; };
return read_json(chunks.json, chunks.bin, chunks.has_bin, folder);
}
val text := strview::over(bytes.data, bytes.length);
return read_json(text, span::<u8>::over(bytes.data, 0), false, folder);
}
+161
View File
@@ -0,0 +1,161 @@
#! Contains reading the members of the JSON's objects, each of the kind glTF
#! says, with its default where it's left out or null, and an index checked to
#! name one of the parts there are; what's wrong said with where it is, as
#! `meshes[2].primitives[0]`.
import std::json;
module gltf;
# What's wrong with a value of the JSON, and where it is.
def wrong(site: strview, why: strview): gltf_error {
return failed(failure::malformed, $"{site}: {why}.".view());
}
# A member of an object, where it has it, and it isn't null.
def member_of(v: &json::value, key: strview): maybe<json::value> {
if v.get(key) is some(found) {
return found if !found.is_null;
}
return nothing{};
}
# A member that must be an object, where there is one.
def object_member(v: &json::value, key: strview, site: strview): result<maybe<json::value>, gltf_error> {
var none: maybe<json::value> = nothing{};
val found := member_of(v, key) else { return none; };
return wrong(site, $"its {key} isn't an object".view()) if found.kind != json::kind::object;
val held: maybe<json::value> = found;
return held;
}
# A member that must be an array, where there is one.
def array_member(v: &json::value, key: strview, site: strview): result<maybe<json::value>, gltf_error> {
var none: maybe<json::value> = nothing{};
val found := member_of(v, key) else { return none; };
return wrong(site, $"its {key} isn't an array".view()) if found.kind != json::kind::array;
val held: maybe<json::value> = found;
return held;
}
# How many elements an array member holds, or none where it's missing.
def length_of(v: &json::value, key: strview): u64 {
if member_of(v, key) is some(found) {
return found.length if found.kind == json::kind::array;
}
return 0;
}
# A number, or its default.
def number_member(v: &json::value, key: strview, site: strview, given: f64): result<f64, gltf_error> {
val found := member_of(v, key) else { return given; };
val n := found.as_f64() else (_) { return wrong(site, $"its {key} isn't a number".view()); };
return n;
}
# A number as an `f32`, or its default.
def float_member(v: &json::value, key: strview, site: strview, given: f32): result<f32, gltf_error> {
val n := number_member(v, key, site, given as f64) else (e) { return e; };
return n as f32;
}
# A number that may be left out.
def maybe_number(v: &json::value, key: strview, site: strview): result<maybe<f32>, gltf_error> {
var none: maybe<f32> = nothing{};
val found := member_of(v, key) else { return none; };
val n := found.as_f64() else (_) { return wrong(site, $"its {key} isn't a number".view()); };
val held: maybe<f32> = n as f32;
return held;
}
# A whole number of 0 or more, or its default.
def count_member(v: &json::value, key: strview, site: strview, given: u64): result<u64, gltf_error> {
val found := member_of(v, key) else { return given; };
val n := found.as_u64() else (_) { return wrong(site, $"its {key} isn't a whole number of 0 or more".view()); };
return n;
}
# A whole number that must be there.
def needed_count(v: &json::value, key: strview, site: strview): result<u64, gltf_error> {
return wrong(site, $"it has no {key}".view()) if member_of(v, key) is none;
return count_member(v, key, site, 0);
}
# An index of one of `count` parts of a list, as `meshes`, where it's there.
def index_member(v: &json::value, key: strview, site: strview, count: u64, list: strview): result<maybe<u64>, gltf_error> {
var none: maybe<u64> = nothing{};
return none if member_of(v, key) is none;
val n := count_member(v, key, site, 0) else (e) { return e; };
return wrong(site, $"its {key} is {n}, of the {count} {list} there are".view()) if n >= count;
val held: maybe<u64> = n;
return held;
}
# An index that must be there.
def needed_index(v: &json::value, key: strview, site: strview, count: u64, list: strview): result<u64, gltf_error> {
val found := index_member(v, key, site, count, list) else (e) { return e; };
val n := found else { return wrong(site, $"it has no {key}".view()); };
return n;
}
# Text, or empty.
def text_member(v: &json::value, key: strview, site: strview): result<string, gltf_error> {
val found := member_of(v, key) else { return string::new(nothing{}); };
val text := found.as_text() else (_) { return wrong(site, $"its {key} isn't text".view()); };
return string::from(text, nothing{});
}
# `true` or `false`, or its default.
def bool_member(v: &json::value, key: strview, site: strview, given: bool): result<bool, gltf_error> {
val found := member_of(v, key) else { return given; };
val truth := found.as_bool() else (_) { return wrong(site, $"its {key} isn't true or false".view()); };
return truth;
}
# An array of numbers: exactly `wanted` of them where that isn't 0, or none
# where it's left out.
def floats_member(v: &json::value, key: strview, site: strview, wanted: u64): result<vector<f32>, gltf_error> {
var made := vector::<f32>::new();
val found := array_member(v, key, site) else (e) { return e; };
val list := found else { return made; };
return wrong(site, $"its {key} holds {list.length} numbers, not {wanted}".view()) if wanted != 0 && list.length != wanted;
for i in 0..list.length {
val each := list.at(i) else { break; };
val n := each.as_f64() else (_) { return wrong(site, $"its {key} holds what isn't a number".view()); };
made.append(n as f32);
}
return made;
}
# An array of numbers kept as `f64`, as an accessor's least and most.
def reals_member(v: &json::value, key: strview, site: strview): result<vector<f64>, gltf_error> {
var made := vector::<f64>::new();
val found := array_member(v, key, site) else (e) { return e; };
val list := found else { return made; };
for i in 0..list.length {
val each := list.at(i) else { break; };
val n := each.as_f64() else (_) { return wrong(site, $"its {key} holds what isn't a number".view()); };
made.append(n);
}
return made;
}
# An array of indices of one of `count` parts of a list.
def indices_member(v: &json::value, key: strview, site: strview, count: u64, list: strview): result<vector<u64>, gltf_error> {
var made := vector::<u64>::new();
val found := array_member(v, key, site) else (e) { return e; };
val items := found else { return made; };
for i in 0..items.length {
val each := items.at(i) else { break; };
val n := each.as_u64() else (_) { return wrong(site, $"its {key} holds what isn't an index".view()); };
return wrong(site, $"its {key} names {n}, of the {count} {list} there are".view()) if n >= count;
made.append(n);
}
return made;
}
# An array's elements, each an object, as the parts of a list are.
def object_at(list: &json::value, i: u64, site: strview): result<json::value, gltf_error> {
val each := list.at(i) else { return wrong(site, "it's missing"); };
return wrong(site, "it isn't an object") if each.kind != json::kind::object;
return each;
}
+133
View File
@@ -0,0 +1,133 @@
#! Contains the tree of nodes: each read with where it is within its parent, as
#! a translation, rotation, and scale, or as a matrix, the other worked out of
#! it; each child's parent found, and the tree checked to have no node of two
#! parents and no loop; and where a node is in the world, through its parents.
import std::json;
import std::math;
import linear;
module gltf;
def read_nodes(made: &mut asset, root: &json::value, n: &counts): result<void, gltf_error> {
val found := array_member(root, "nodes", "nodes") else (e) { return e; };
val list := found else { return; };
for i in 0..list.length {
val site := $"nodes[{i}]";
val each := object_at(&list, i, site.view()) else (e) { return e; };
var read := node{};
read.name = text_member(&each, "name", site.view()) else (e) { return e; };
read.children = indices_member(&each, "children", site.view(), n.nodes, "nodes") else (e) { return e; };
read.mesh = index_member(&each, "mesh", site.view(), n.meshes, "meshes") else (e) { return e; };
read.camera = index_member(&each, "camera", site.view(), n.cameras, "cameras") else (e) { return e; };
read.skin = index_member(&each, "skin", site.view(), n.skins, "skins") else (e) { return e; };
read.weights = floats_member(&each, "weights", site.view(), 0) else (e) { return e; };
val extensions := object_member(&each, "extensions", site.view()) else (e) { return e; };
if extensions is some(x) {
if member_of(&x, "KHR_lights_punctual") is some(lit) {
read.light = index_member(&lit, "light", site.view(), n.lights, "lights") else (e) { return e; };
}
}
place_node(&mut read, &each, site.view()) else (e) { return e; };
made.nodes.append(move(read));
}
# Each child has one parent, and following parents up ends.
for i in 0..made.nodes.length {
for k in 0..made.nodes[i].children.length {
val child := made.nodes[i].children[k];
return failed(failure::malformed, $"nodes[{i}]: it's a child of itself.".view()) if child == i;
if made.nodes[child].parent is some(other) {
return failed(failure::malformed, $"nodes[{child}]: it's a child of both {other} and {i}.".view());
}
made.nodes[child].parent = i;
}
}
for i in 0..made.nodes.length {
var at := i;
var steps: u64 = 0;
while made.nodes[at].parent is some(up) {
at = up;
steps++;
return failed(failure::malformed, $"nodes[{i}]: following its parents up comes back to it.".view()) if steps > made.nodes.length;
}
}
return;
}
# Where a node is within its parent: its matrix, taken apart into its
# translation, rotation, and scale; or those, put together into its matrix.
def place_node(read: &mut node, v: &json::value, site: strview): result<void, gltf_error> {
val matrix := floats_member(v, "matrix", site, 16) else (e) { return e; };
if matrix.length == 16 {
for i in 0..16u {
read.matrix.m[i] = matrix[i];
}
take_apart(read);
return;
}
val t := floats_member(v, "translation", site, 3) else (e) { return e; };
val r := floats_member(v, "rotation", site, 4) else (e) { return e; };
val s := floats_member(v, "scale", site, 3) else (e) { return e; };
if t.length == 3 {
read.translation = vec3{ t[0], t[1], t[2] };
}
if r.length == 4 {
val q := quat{ r[0], r[1], r[2], r[3] };
read.rotation = q.length > 0 ? q.normalized() : quat::identity;
}
if s.length == 3 {
read.scale = vec3{ s[0], s[1], s[2] };
}
read.matrix = mat4::compose(read.translation, read.rotation, read.scale);
return;
}
# Takes a node's matrix apart: its translation, the lengths of its axes as its
# scale, x's negative where the matrix mirrors, and the rotation of its axes
# made unit length. glTF holds that a node's matrix is no more than that.
def take_apart(read: &mut node): void {
val m := &read.matrix.m;
read.translation = vec3{ m[12], m[13], m[14] };
val x := vec3{ m[0], m[1], m[2] };
val y := vec3{ m[4], m[5], m[6] };
val z := vec3{ m[8], m[9], m[10] };
var sx := x.length;
val sy := y.length;
val sz := z.length;
if x.cross(y).dot(z) < 0 {
sx = -sx;
}
read.scale = vec3{ sx, sy, sz };
if sx == 0 || sy == 0 || sz == 0 {
read.rotation = quat::identity;
return;
}
read.rotation = quat::of_basis(x / sx, y / sy, z / sz).normalized();
}
#! Where a node is in the world: its matrix, by its parent's, by its parent's,
#! up to its root.
#! @param this The asset.
#! @param which The node.
#! @returns The matrix taking its space to its scene's.
pub def asset::world_matrix(&this, which: u64): mat4 {
var made := this.nodes[which].matrix;
var at := which;
while this.nodes[at].parent is some(up) {
made = this.nodes[up].matrix * made;
at = up;
}
return made;
}
#! The nodes at the roots of the tree: those of no parent, in the order the
#! asset holds them, as a scene of every one would hold them.
pub def asset::roots(&this): vector<u64> {
var made := vector::<u64>::new();
for i in 0..this.nodes.length {
if this.nodes[i].parent is none {
made.append(i);
}
}
return made;
}
+630
View File
@@ -0,0 +1,630 @@
#! Contains reading an asset's JSON into its parts, in the order they need one
#! another: its buffers and their bytes, the views of them, the accessors of
#! those, each checked to lie within its view, then images, samplers, textures,
#! materials, meshes, cameras, lights, skins, the nodes and their tree, scenes,
#! and animations.
import std::json;
import std::math;
import linear;
module gltf;
# How many of each part the JSON holds, so an index is checked as it's read,
# whichever comes first.
struct counts {
var nodes: u64;
var meshes: u64;
var materials: u64;
var textures: u64;
var samplers: u64;
var images: u64;
var accessors: u64;
var views: u64;
var buffers: u64;
var cameras: u64;
var skins: u64;
var lights: u64;
}
# Reads an asset of its JSON, the binary chunk of its `.glb` file where it has
# one, and the folder its files are found in.
def read_json(text: strview, bin: span<u8>, has_bin: bool, folder: strview): result<asset, gltf_error> {
val doc := json::parse(text) else (e) {
val why := e.describe();
return failed(failure::malformed, $"Its JSON isn't JSON: {why.view()}".view());
};
val root := doc.root;
return failed(failure::malformed, "Its JSON isn't an object.") if root.kind != json::kind::object;
var made := asset{};
val info := object_member(&root, "asset", "asset") else (e) { return e; };
val about := info else { return failed(failure::malformed, "It says no asset, of which version of glTF it is."); };
made.version = text_member(&about, "version", "asset") else (e) { return e; };
made.generator = text_member(&about, "generator", "asset") else (e) { return e; };
return failed(failure::unsupported, $"It's of glTF {made.version.view()}, not 2.".view()) if !made.version.view().starts_with("2.");
val used := array_member(&root, "extensionsUsed", "extensionsUsed") else (e) { return e; };
if used is some(list) {
for i in 0..list.length {
if list.at(i) is some(each) && each.as_text() is value(name) {
made.extensions.append(string::from(name, nothing{}));
}
}
}
val required := array_member(&root, "extensionsRequired", "extensionsRequired") else (e) { return e; };
if required is some(list) {
for i in 0..list.length {
val each := list.at(i) else { break; };
val name := each.as_text() else (_) { return failed(failure::malformed, "extensionsRequired: it holds what isn't text."); };
return failed(failure::unsupported, $"It requires {name}, which isn't read.".view()) if !is_read(name);
}
}
val n := counts{
nodes = length_of(&root, "nodes"), meshes = length_of(&root, "meshes"), materials = length_of(&root, "materials"),
textures = length_of(&root, "textures"), samplers = length_of(&root, "samplers"), images = length_of(&root, "images"),
accessors = length_of(&root, "accessors"), views = length_of(&root, "bufferViews"), buffers = length_of(&root, "buffers"),
cameras = length_of(&root, "cameras"), skins = length_of(&root, "skins"), lights = light_count(&root),
};
read_buffers(&mut made, &root, bin, has_bin, folder) else (e) { return e; };
read_views(&mut made, &root, &n) else (e) { return e; };
read_accessors(&mut made, &root, &n) else (e) { return e; };
read_images(&mut made, &root, &n, folder) else (e) { return e; };
read_samplers(&mut made, &root) else (e) { return e; };
read_textures(&mut made, &root, &n) else (e) { return e; };
read_materials(&mut made, &root, &n) else (e) { return e; };
read_meshes(&mut made, &root, &n) else (e) { return e; };
read_cameras(&mut made, &root) else (e) { return e; };
read_lights(&mut made, &root) else (e) { return e; };
read_skins(&mut made, &root, &n) else (e) { return e; };
read_nodes(&mut made, &root, &n) else (e) { return e; };
read_scenes(&mut made, &root, &n) else (e) { return e; };
read_animations(&mut made, &root, &n) else (e) { return e; };
made.scene = index_member(&root, "scene", "scene", made.scenes.length, "scenes") else (e) { return e; };
return made;
}
# Whether an extension is among those read.
def is_read(name: strview): bool {
for each in extensions_read {
return true if each == name;
}
return false;
}
# The lights `KHR_lights_punctual` gives, where it gives them.
def lights_of(root: &json::value): maybe<json::value> {
val extensions := member_of(root, "extensions") else { return nothing{}; };
val lights := member_of(&extensions, "KHR_lights_punctual") else { return nothing{}; };
return member_of(&lights, "lights");
}
def light_count(root: &json::value): u64 {
if lights_of(root) is some(list) {
return list.length if list.kind == json::kind::array;
}
return 0;
}
def read_buffers(made: &mut asset, root: &json::value, bin: span<u8>, has_bin: bool, folder: strview): result<void, gltf_error> {
val found := array_member(root, "buffers", "buffers") else (e) { return e; };
val list := found else { return; };
for i in 0..list.length {
val site := $"buffers[{i}]";
val each := object_at(&list, i, site.view()) else (e) { return e; };
var read := buffer{};
read.name = text_member(&each, "name", site.view()) else (e) { return e; };
read.uri = text_member(&each, "uri", site.view()) else (e) { return e; };
read.length = needed_count(&each, "byteLength", site.view()) else (e) { return e; };
if read.uri.length != 0 {
var mime := string::new(nothing{});
read.bytes = bytes_of_uri(read.uri.view(), folder, site.view(), &mut mime) else (e) { return e; };
} else if i == 0 && has_bin {
read.bytes.extend(bin);
} else {
return wrong(site.view(), "it has no URI, and isn't a .glb file's binary chunk");
}
return wrong(site.view(), $"it says it's {read.length} bytes, but it's {read.bytes.length}".view()) if read.bytes.length < read.length;
made.buffers.append(move(read));
}
return;
}
def read_views(made: &mut asset, root: &json::value, n: &counts): result<void, gltf_error> {
val found := array_member(root, "bufferViews", "bufferViews") else (e) { return e; };
val list := found else { return; };
for i in 0..list.length {
val site := $"bufferViews[{i}]";
val each := object_at(&list, i, site.view()) else (e) { return e; };
var read := buffer_view{};
read.name = text_member(&each, "name", site.view()) else (e) { return e; };
read.buffer = needed_index(&each, "buffer", site.view(), n.buffers, "buffers") else (e) { return e; };
read.offset = count_member(&each, "byteOffset", site.view(), 0) else (e) { return e; };
read.length = needed_count(&each, "byteLength", site.view()) else (e) { return e; };
read.stride = count_member(&each, "byteStride", site.view(), 0) else (e) { return e; };
val held := made.buffers[read.buffer].length;
return wrong(site.view(), $"it reaches byte {read.offset + read.length} of its buffer's {held}".view()) if read.offset > held || read.length > held - read.offset;
return wrong(site.view(), $"its byteStride is {read.stride}, not a multiple of 4 from 4 to 252".view())
if read.stride != 0 && (read.stride < 4 || read.stride > 252 || read.stride % 4 != 0);
made.views.append(move(read));
}
return;
}
# The type of an accessor's numbers, by glTF's code for it.
def component_of(code: u64): maybe<component> {
return match code {
5120 => component::byte,
5121 => component::unsigned_byte,
5122 => component::short,
5123 => component::unsigned_short,
5125 => component::unsigned_int,
5126 => component::float,
else => nothing{},
};
}
# What an accessor's elements are, by glTF's name for it.
def element_of(name: strview): maybe<element> {
return element::scalar if name == "SCALAR";
return element::vec2 if name == "VEC2";
return element::vec3 if name == "VEC3";
return element::vec4 if name == "VEC4";
return element::mat2 if name == "MAT2";
return element::mat3 if name == "MAT3";
return element::mat4 if name == "MAT4";
return nothing{};
}
def read_accessors(made: &mut asset, root: &json::value, n: &counts): result<void, gltf_error> {
val found := array_member(root, "accessors", "accessors") else (e) { return e; };
val list := found else { return; };
for i in 0..list.length {
val site := $"accessors[{i}]";
val each := object_at(&list, i, site.view()) else (e) { return e; };
var read := accessor{};
read.name = text_member(&each, "name", site.view()) else (e) { return e; };
read.view = index_member(&each, "bufferView", site.view(), n.views, "bufferViews") else (e) { return e; };
read.offset = count_member(&each, "byteOffset", site.view(), 0) else (e) { return e; };
val code := needed_count(&each, "componentType", site.view()) else (e) { return e; };
read.component_type = component_of(code) else { return wrong(site.view(), $"its componentType {code} is none of glTF's".view()); };
read.normalized = bool_member(&each, "normalized", site.view(), false) else (e) { return e; };
read.count = needed_count(&each, "count", site.view()) else (e) { return e; };
return wrong(site.view(), "its count is 0") if read.count == 0;
val kind := text_member(&each, "type", site.view()) else (e) { return e; };
read.kind = element_of(kind.view()) else { return wrong(site.view(), $"its type {kind.view()} is none of glTF's".view()); };
read.min = reals_member(&each, "min", site.view()) else (e) { return e; };
read.max = reals_member(&each, "max", site.view()) else (e) { return e; };
if read.view is some(v) {
val view := &made.views[v];
val size := read.element_bytes();
return wrong(site.view(), $"its bufferView's byteStride, {view.stride}, is less than an element's {size} bytes".view())
if view.stride != 0 && view.stride < size;
val stride := view.stride != 0 ? view.stride : size;
return wrong(site.view(), $"its {read.count} elements reach past its bufferView's {view.length} bytes".view())
if read.offset > view.length || (read.count - 1) * stride + size > view.length - read.offset;
}
val holds_sparse := object_member(&each, "sparse", site.view()) else (e) { return e; };
if holds_sparse is some(s) {
read.sparse = read_sparse(made, &s, &read, $"{site.view()}.sparse".view(), n) else (e) { return e; };
}
made.accessors.append(move(read));
}
return;
}
# An accessor's sparse values: where their indices and values are, each
# checked to lie within its view, and each index to name an element.
def read_sparse(made: &asset, s: &json::value, read: &accessor, site: strview, n: &counts): result<sparse, gltf_error> {
var held := sparse{};
held.count = needed_count(s, "count", site) else (e) { return e; };
return wrong(site, $"its count is {held.count}, of the accessor's {read.count}".view()) if held.count == 0 || held.count > read.count;
val indices_found := object_member(s, "indices", site) else (e) { return e; };
val indices := indices_found else { return wrong(site, "it has no indices"); };
val values_found := object_member(s, "values", site) else (e) { return e; };
val values := values_found else { return wrong(site, "it has no values"); };
held.indices_view = needed_index(&indices, "bufferView", site, n.views, "bufferViews") else (e) { return e; };
held.indices_offset = count_member(&indices, "byteOffset", site, 0) else (e) { return e; };
val code := needed_count(&indices, "componentType", site) else (e) { return e; };
held.indices_type = component_of(code) else { return wrong(site, $"its indices' componentType {code} is none of glTF's".view()); };
return wrong(site, "its indices aren't of unsigned integers")
if held.indices_type != component::unsigned_byte && held.indices_type != component::unsigned_short && held.indices_type != component::unsigned_int;
held.values_view = needed_index(&values, "bufferView", site, n.views, "bufferViews") else (e) { return e; };
held.values_offset = count_member(&values, "byteOffset", site, 0) else (e) { return e; };
val index_view := &made.views[held.indices_view];
val value_view := &made.views[held.values_view];
val index_bytes := held.count * held.indices_type.bytes;
val value_bytes := held.count * read.element_bytes();
return wrong(site, "its indices reach past their bufferView") if held.indices_offset > index_view.length || index_bytes > index_view.length - held.indices_offset;
return wrong(site, "its values reach past their bufferView") if held.values_offset > value_view.length || value_bytes > value_view.length - held.values_offset;
val bytes := made.buffers[index_view.buffer].bytes.view();
for i in 0..held.count {
val e := integer_at(bytes, index_view.offset + held.indices_offset + i * held.indices_type.bytes, held.indices_type);
return wrong(site, $"its index {e} is past the accessor's {read.count} elements".view()) if e >= read.count;
}
return held;
}
def read_images(made: &mut asset, root: &json::value, n: &counts, folder: strview): result<void, gltf_error> {
val found := array_member(root, "images", "images") else (e) { return e; };
val list := found else { return; };
for i in 0..list.length {
val site := $"images[{i}]";
val each := object_at(&list, i, site.view()) else (e) { return e; };
var read := image{};
read.name = text_member(&each, "name", site.view()) else (e) { return e; };
read.uri = text_member(&each, "uri", site.view()) else (e) { return e; };
read.mime_type = text_member(&each, "mimeType", site.view()) else (e) { return e; };
read.view = index_member(&each, "bufferView", site.view(), n.views, "bufferViews") else (e) { return e; };
if read.uri.length != 0 {
var mime := string::new(nothing{});
read.bytes = bytes_of_uri(read.uri.view(), folder, site.view(), &mut mime) else (e) { return e; };
if read.mime_type.length == 0 {
read.mime_type = move(mime);
}
} else if read.view is some(v) {
val view := &made.views[v];
read.bytes.extend(made.buffers[view.buffer].bytes.view()[view.offset:view.length]);
} else {
return wrong(site.view(), "it has neither a URI nor a bufferView");
}
made.images.append(move(read));
}
return;
}
def read_samplers(made: &mut asset, root: &json::value): result<void, gltf_error> {
val found := array_member(root, "samplers", "samplers") else (e) { return e; };
val list := found else { return; };
for i in 0..list.length {
val site := $"samplers[{i}]";
val each := object_at(&list, i, site.view()) else (e) { return e; };
var read := sampler{};
read.name = text_member(&each, "name", site.view()) else (e) { return e; };
val mag := count_member(&each, "magFilter", site.view(), 0) else (e) { return e; };
val min := count_member(&each, "minFilter", site.view(), 0) else (e) { return e; };
val s := count_member(&each, "wrapS", site.view(), 10497) else (e) { return e; };
val t := count_member(&each, "wrapT", site.view(), 10497) else (e) { return e; };
read.mag_filter = mag == 9728 ? filter::nearest : mag == 9729 ? filter::linear : filter::unset;
# 9984 to 9987: nearest or linear, between the nearest mip level or two.
read.min_filter = min == 9728 || min == 9984 || min == 9986 ? filter::nearest : min == 9729 || min == 9985 || min == 9987 ? filter::linear : filter::unset;
read.mip_filter = min == 9984 || min == 9985 ? filter::nearest : min == 9986 || min == 9987 ? filter::linear : filter::unset;
read.wrap_s = wrap_of(s) else { return wrong(site.view(), $"its wrapS {s} is none of glTF's".view()); };
read.wrap_t = wrap_of(t) else { return wrong(site.view(), $"its wrapT {t} is none of glTF's".view()); };
made.samplers.append(move(read));
}
return;
}
def wrap_of(code: u64): maybe<wrap> {
return match code {
10497 => wrap::repeat,
33071 => wrap::clamp,
33648 => wrap::mirror,
else => nothing{},
};
}
def read_textures(made: &mut asset, root: &json::value, n: &counts): result<void, gltf_error> {
val found := array_member(root, "textures", "textures") else (e) { return e; };
val list := found else { return; };
for i in 0..list.length {
val site := $"textures[{i}]";
val each := object_at(&list, i, site.view()) else (e) { return e; };
var read := texture{};
read.name = text_member(&each, "name", site.view()) else (e) { return e; };
read.sampler = index_member(&each, "sampler", site.view(), n.samplers, "samplers") else (e) { return e; };
read.source = index_member(&each, "source", site.view(), n.images, "images") else (e) { return e; };
made.textures.append(move(read));
}
return;
}
# A texture a material names, where it names one, and its scale or strength.
def texture_member(v: &json::value, key: strview, site: strview, n: &counts, scale_key: strview): result<maybe<texture_ref>, gltf_error> {
var none: maybe<texture_ref> = nothing{};
val found := object_member(v, key, site) else (e) { return e; };
val info := found else { return none; };
val inner := $"{site}.{key}";
var made := texture_ref{};
made.texture = needed_index(&info, "index", inner.view(), n.textures, "textures") else (e) { return e; };
made.set = count_member(&info, "texCoord", inner.view(), 0) else (e) { return e; };
if scale_key.length != 0 {
made.scale = float_member(&info, scale_key, inner.view(), 1) else (e) { return e; };
}
val held: maybe<texture_ref> = made;
return held;
}
def read_materials(made: &mut asset, root: &json::value, n: &counts): result<void, gltf_error> {
val found := array_member(root, "materials", "materials") else (e) { return e; };
val list := found else { return; };
for i in 0..list.length {
val site := $"materials[{i}]";
val each := object_at(&list, i, site.view()) else (e) { return e; };
var read := material{};
read.name = text_member(&each, "name", site.view()) else (e) { return e; };
val pbr_found := object_member(&each, "pbrMetallicRoughness", site.view()) else (e) { return e; };
if pbr_found is some(pbr) {
val inner := $"{site.view()}.pbrMetallicRoughness";
val color := floats_member(&pbr, "baseColorFactor", inner.view(), 4) else (e) { return e; };
if color.length == 4 {
read.base_color = [color[0], color[1], color[2], color[3]];
}
read.base_color_texture = texture_member(&pbr, "baseColorTexture", inner.view(), n, "") else (e) { return e; };
read.metallic = float_member(&pbr, "metallicFactor", inner.view(), 1) else (e) { return e; };
read.roughness = float_member(&pbr, "roughnessFactor", inner.view(), 1) else (e) { return e; };
read.metallic_roughness_texture = texture_member(&pbr, "metallicRoughnessTexture", inner.view(), n, "") else (e) { return e; };
}
read.normal_texture = texture_member(&each, "normalTexture", site.view(), n, "scale") else (e) { return e; };
read.occlusion_texture = texture_member(&each, "occlusionTexture", site.view(), n, "strength") else (e) { return e; };
read.emissive_texture = texture_member(&each, "emissiveTexture", site.view(), n, "") else (e) { return e; };
val emissive := floats_member(&each, "emissiveFactor", site.view(), 3) else (e) { return e; };
if emissive.length == 3 {
read.emissive = [emissive[0], emissive[1], emissive[2]];
}
val mode := text_member(&each, "alphaMode", site.view()) else (e) { return e; };
if mode.view() == "MASK" {
read.alpha_mode = alpha_mode::mask;
} else if mode.view() == "BLEND" {
read.alpha_mode = alpha_mode::blend;
} else if mode.length != 0 && mode.view() != "OPAQUE" {
return wrong(site.view(), $"its alphaMode {mode.view()} is none of glTF's".view());
}
read.alpha_cutoff = float_member(&each, "alphaCutoff", site.view(), 0.5) else (e) { return e; };
read.double_sided = bool_member(&each, "doubleSided", site.view(), false) else (e) { return e; };
val extensions := object_member(&each, "extensions", site.view()) else (e) { return e; };
if extensions is some(x) {
read.unlit = member_of(&x, "KHR_materials_unlit") is some(_);
if member_of(&x, "KHR_materials_emissive_strength") is some(strength) {
val by := float_member(&strength, "emissiveStrength", site.view(), 1) else (e) { return e; };
read.emissive = [read.emissive[0] * by, read.emissive[1] * by, read.emissive[2] * by];
}
}
made.materials.append(move(read));
}
return;
}
# A primitive's attributes, or a morph target's, each naming an accessor.
def attributes_of(v: &json::value, site: strview, n: &counts): result<vector<attribute>, gltf_error> {
var made := vector::<attribute>::new();
for each in v.members() {
val index := each.value.as_u64() else (_) { return wrong(site, $"its {each.key} isn't an accessor's index".view()); };
return wrong(site, $"its {each.key} is {index}, of the {n.accessors} accessors there are".view()) if index >= n.accessors;
made.append(attribute{ name = string::from(each.key, nothing{}), accessor = index });
}
return made;
}
def read_meshes(made: &mut asset, root: &json::value, n: &counts): result<void, gltf_error> {
val found := array_member(root, "meshes", "meshes") else (e) { return e; };
val list := found else { return; };
for i in 0..list.length {
val site := $"meshes[{i}]";
val each := object_at(&list, i, site.view()) else (e) { return e; };
var read := mesh{};
read.name = text_member(&each, "name", site.view()) else (e) { return e; };
read.weights = floats_member(&each, "weights", site.view(), 0) else (e) { return e; };
val parts_found := array_member(&each, "primitives", site.view()) else (e) { return e; };
val parts := parts_found else { return wrong(site.view(), "it has no primitives"); };
return wrong(site.view(), "it has no primitives") if parts.length == 0;
for k in 0..parts.length {
val inner := $"{site.view()}.primitives[{k}]";
val part := object_at(&parts, k, inner.view()) else (e) { return e; };
var drawn := read_primitive(made, &part, inner.view(), n) else (e) { return e; };
read.primitives.append(move(drawn));
}
made.meshes.append(move(read));
}
return;
}
# A primitive, its accessors checked: its attributes of one count, and its
# indices whole numbers naming vertices it has.
def read_primitive(made: &asset, v: &json::value, site: strview, n: &counts): result<primitive, gltf_error> {
var read := primitive{};
val held := object_member(v, "attributes", site) else (e) { return e; };
val attributes := held else { return wrong(site, "it has no attributes"); };
read.attributes = attributes_of(&attributes, site, n) else (e) { return e; };
read.indices = index_member(v, "indices", site, n.accessors, "accessors") else (e) { return e; };
read.material = index_member(v, "material", site, n.materials, "materials") else (e) { return e; };
val mode := count_member(v, "mode", site, 4) else (e) { return e; };
val modes: topology[7] = [
topology::points, topology::lines, topology::line_loop, topology::line_strip,
topology::triangles, topology::triangle_strip, topology::triangle_fan,
];
return wrong(site, $"its mode {mode} is none of glTF's".view()) if mode > 6;
read.mode = modes[mode];
val targets_found := array_member(v, "targets", site) else (e) { return e; };
if targets_found is some(targets) {
for t in 0..targets.length {
val inner := $"{site}.targets[{t}]";
val target := object_at(&targets, t, inner.view()) else (e) { return e; };
var moved := attributes_of(&target, inner.view(), n) else (e) { return e; };
read.targets.append(move(moved));
}
}
var vertices: u64 = 0;
for i in 0..read.attributes.length {
val count := made.accessors[read.attributes[i].accessor].count;
return wrong(site, $"its {read.attributes[i].name.view()} has {count} elements, of the other attributes' {vertices}".view())
if vertices != 0 && count != vertices;
vertices = count;
}
if read.indices is some(at) {
val list := &made.accessors[at];
return wrong(site, "its indices are of other than unsigned integers, one each")
if list.kind != element::scalar || list.normalized
|| (list.component_type != component::unsigned_byte && list.component_type != component::unsigned_short && list.component_type != component::unsigned_int);
if vertices != 0 {
val indices := made.integers(at);
for i in 0..indices.length {
return wrong(site, $"its index {indices[i]} is past its {vertices} vertices".view()) if indices[i] as u64 >= vertices;
}
}
}
return read;
}
def read_cameras(made: &mut asset, root: &json::value): result<void, gltf_error> {
val found := array_member(root, "cameras", "cameras") else (e) { return e; };
val list := found else { return; };
for i in 0..list.length {
val site := $"cameras[{i}]";
val each := object_at(&list, i, site.view()) else (e) { return e; };
var read := camera{};
read.name = text_member(&each, "name", site.view()) else (e) { return e; };
val kind := text_member(&each, "type", site.view()) else (e) { return e; };
if kind.view() == "perspective" {
val held := object_member(&each, "perspective", site.view()) else (e) { return e; };
val p := held else { return wrong(site.view(), "it's a perspective but says none"); };
read.fov_y = float_member(&p, "yfov", site.view(), 0) else (e) { return e; };
read.aspect = maybe_number(&p, "aspectRatio", site.view()) else (e) { return e; };
read.near = float_member(&p, "znear", site.view(), 0) else (e) { return e; };
read.far = maybe_number(&p, "zfar", site.view()) else (e) { return e; };
} else if kind.view() == "orthographic" {
read.kind = camera_kind::orthographic;
val held := object_member(&each, "orthographic", site.view()) else (e) { return e; };
val o := held else { return wrong(site.view(), "it's orthographic but says nothing of it"); };
read.x_mag = float_member(&o, "xmag", site.view(), 1) else (e) { return e; };
read.y_mag = float_member(&o, "ymag", site.view(), 1) else (e) { return e; };
read.near = float_member(&o, "znear", site.view(), 0) else (e) { return e; };
read.far = maybe_number(&o, "zfar", site.view()) else (e) { return e; };
} else {
return wrong(site.view(), $"its type {kind.view()} is none of glTF's".view());
}
made.cameras.append(move(read));
}
return;
}
def read_lights(made: &mut asset, root: &json::value): result<void, gltf_error> {
val list := lights_of(root) else { return; };
return failed(failure::malformed, "KHR_lights_punctual: its lights aren't an array.") if list.kind != json::kind::array;
for i in 0..list.length {
val site := $"KHR_lights_punctual.lights[{i}]";
val each := object_at(&list, i, site.view()) else (e) { return e; };
var read := light{};
read.name = text_member(&each, "name", site.view()) else (e) { return e; };
val kind := text_member(&each, "type", site.view()) else (e) { return e; };
if kind.view() == "directional" {
read.kind = light_kind::directional;
} else if kind.view() == "spot" {
read.kind = light_kind::spot;
} else if kind.view() != "point" {
return wrong(site.view(), $"its type {kind.view()} is none of the extension's".view());
}
val color := floats_member(&each, "color", site.view(), 3) else (e) { return e; };
if color.length == 3 {
read.color = [color[0], color[1], color[2]];
}
read.intensity = float_member(&each, "intensity", site.view(), 1) else (e) { return e; };
read.range = maybe_number(&each, "range", site.view()) else (e) { return e; };
val cone := object_member(&each, "spot", site.view()) else (e) { return e; };
if cone is some(s) {
read.inner_cone = float_member(&s, "innerConeAngle", site.view(), 0) else (e) { return e; };
read.outer_cone = float_member(&s, "outerConeAngle", site.view(), 0.7853981633974483) else (e) { return e; };
}
made.lights.append(move(read));
}
return;
}
def read_skins(made: &mut asset, root: &json::value, n: &counts): result<void, gltf_error> {
val found := array_member(root, "skins", "skins") else (e) { return e; };
val list := found else { return; };
for i in 0..list.length {
val site := $"skins[{i}]";
val each := object_at(&list, i, site.view()) else (e) { return e; };
var read := skin{};
read.name = text_member(&each, "name", site.view()) else (e) { return e; };
read.joints = indices_member(&each, "joints", site.view(), n.nodes, "nodes") else (e) { return e; };
return wrong(site.view(), "it has no joints") if read.joints.length == 0;
read.inverse_binds = index_member(&each, "inverseBindMatrices", site.view(), n.accessors, "accessors") else (e) { return e; };
read.skeleton = index_member(&each, "skeleton", site.view(), n.nodes, "nodes") else (e) { return e; };
if read.inverse_binds is some(at) {
val binds := &made.accessors[at];
return wrong(site.view(), "its inverseBindMatrices aren't a matrix of floats for each joint")
if binds.kind != element::mat4 || binds.component_type != component::float || binds.count < read.joints.length;
}
made.skins.append(move(read));
}
return;
}
def read_scenes(made: &mut asset, root: &json::value, n: &counts): result<void, gltf_error> {
val found := array_member(root, "scenes", "scenes") else (e) { return e; };
val list := found else { return; };
for i in 0..list.length {
val site := $"scenes[{i}]";
val each := object_at(&list, i, site.view()) else (e) { return e; };
var read := scene{};
read.name = text_member(&each, "name", site.view()) else (e) { return e; };
read.nodes = indices_member(&each, "nodes", site.view(), n.nodes, "nodes") else (e) { return e; };
for k in 0..read.nodes.length {
return wrong(site.view(), $"its node {read.nodes[k]} is another's child, not a root".view()) if made.nodes[read.nodes[k]].parent is some(_);
}
made.scenes.append(move(read));
}
return;
}
def read_animations(made: &mut asset, root: &json::value, n: &counts): result<void, gltf_error> {
val found := array_member(root, "animations", "animations") else (e) { return e; };
val list := found else { return; };
for i in 0..list.length {
val site := $"animations[{i}]";
val each := object_at(&list, i, site.view()) else (e) { return e; };
var read := animation{};
read.name = text_member(&each, "name", site.view()) else (e) { return e; };
val samplers_found := array_member(&each, "samplers", site.view()) else (e) { return e; };
val samplers := samplers_found else { return wrong(site.view(), "it has no samplers"); };
for k in 0..samplers.length {
val inner := $"{site.view()}.samplers[{k}]";
val s := object_at(&samplers, k, inner.view()) else (e) { return e; };
var keys := animation_sampler{};
keys.input = needed_index(&s, "input", inner.view(), n.accessors, "accessors") else (e) { return e; };
keys.output = needed_index(&s, "output", inner.view(), n.accessors, "accessors") else (e) { return e; };
val how := text_member(&s, "interpolation", inner.view()) else (e) { return e; };
if how.view() == "STEP" {
keys.interpolation = interpolation::step;
} else if how.view() == "CUBICSPLINE" {
keys.interpolation = interpolation::cubic_spline;
} else if how.length != 0 && how.view() != "LINEAR" {
return wrong(inner.view(), $"its interpolation {how.view()} is none of glTF's".view());
}
val times := &made.accessors[keys.input];
return wrong(inner.view(), "its input isn't of floats, one each") if times.kind != element::scalar || times.component_type != component::float;
read.samplers.append(keys);
}
val channels_found := array_member(&each, "channels", site.view()) else (e) { return e; };
val channels := channels_found else { return wrong(site.view(), "it has no channels"); };
for k in 0..channels.length {
val inner := $"{site.view()}.channels[{k}]";
val c := object_at(&channels, k, inner.view()) else (e) { return e; };
var moved := channel{};
moved.sampler = needed_index(&c, "sampler", inner.view(), read.samplers.length, "samplers") else (e) { return e; };
val target_found := object_member(&c, "target", inner.view()) else (e) { return e; };
val target := target_found else { return wrong(inner.view(), "it has no target"); };
moved.node = index_member(&target, "node", inner.view(), n.nodes, "nodes") else (e) { return e; };
val path := text_member(&target, "path", inner.view()) else (e) { return e; };
if path.view() == "translation" {
moved.path = target_path::translation;
} else if path.view() == "rotation" {
moved.path = target_path::rotation;
} else if path.view() == "scale" {
moved.path = target_path::scale;
} else if path.view() == "weights" {
moved.path = target_path::weights;
} else {
return wrong(inner.view(), $"its path {path.view()} is none of glTF's".view());
}
read.channels.append(moved);
}
made.animations.append(move(read));
}
return;
}
+243
View File
@@ -0,0 +1,243 @@
#! Contains the parts of an asset, as glTF lays them out: scenes and their nodes,
#! meshes and their primitives, materials, textures, samplers, images, cameras,
#! skins, animations, and lights, each with glTF's defaults where its JSON
#! leaves a member out.
import linear;
module gltf;
#! A scene: the nodes at its roots.
pub struct scene {
pub var name: string;
pub var nodes: vector<u64>;
}
#! A node of the tree a scene holds: where it is within its parent, and what's
#! there, a mesh, a camera, a light, or nothing but its children.
pub struct node {
pub var name: string;
pub var children: vector<u64>;
#! The node it's a child of, or none at a root.
pub var parent: maybe<u64>;
pub var mesh: maybe<u64>;
pub var camera: maybe<u64>;
#! The skin its mesh is bound to.
pub var skin: maybe<u64>;
#! Its light, of `KHR_lights_punctual`.
pub var light: maybe<u64>;
#! Where it is within its parent: its translation, rotation, and scale, and
#! the matrix of them, whichever the JSON gave, the other worked out of it.
pub var translation := vec3::zero;
pub var rotation := quat::identity;
pub var scale := vec3::one;
pub var matrix := mat4::identity;
#! The weights of its mesh's morph targets, where it gives its own.
pub var weights: vector<f32>;
}
#! What a primitive's vertices make.
pub enum topology: u8 { points, lines, line_loop, line_strip, triangles, triangle_strip, triangle_fan }
#! An attribute of a primitive's vertices: its name, as `POSITION`, `NORMAL`,
#! `TEXCOORD_0`, or `COLOR_0`, and the accessor holding it.
pub struct attribute {
pub var name: string;
pub var accessor: u64;
}
#! A part of a mesh drawn at once: its vertices' attributes, the indices of
#! them it draws, or none to draw them in order, and its material.
pub struct primitive {
pub var attributes: vector<attribute>;
pub var indices: maybe<u64>;
#! Its material, or none for glTF's default: white, not metallic, rough.
pub var material: maybe<u64>;
pub var mode := topology::triangles;
#! Its morph targets, each the attributes it moves.
pub var targets: vector<vector<attribute>>;
}
#! The accessor of an attribute of a primitive, by its name, where it has it.
pub def primitive::find(&this, name: strview): maybe<u64> {
for i in 0..this.attributes.length {
return this.attributes[i].accessor if this.attributes[i].name.view() == name;
}
return nothing{};
}
#! A mesh: its primitives, each drawn with its own material.
pub struct mesh {
pub var name: string;
pub var primitives: vector<primitive>;
#! The weights of its morph targets, where it gives them.
pub var weights: vector<f32>;
}
#! A texture as a material samples it: which, by which of its primitives'
#! `TEXCOORD_n`, and, of a normal map, its scale, or of occlusion, its strength.
pub struct texture_ref {
pub var texture: u64;
pub var set: u64;
pub var scale: f32 = 1;
}
#! How a material's alpha is taken.
pub enum alpha_mode: u8 {
#! Not at all: it's opaque.
opaque,
#! As a cutout: opaque where alpha is at least its cutoff, and not drawn where
#! it's below.
mask,
#! Blended over what's behind it.
blend,
}
#! A material, of glTF's metallic and rough model. Its colors are linear, as
#! glTF's factors are, and its textures of color are sRGB, as glTF's images are.
pub struct material {
pub var name: string;
#! The color its base color texture is multiplied by, and alpha.
pub var base_color: f32[4] = [1, 1, 1, 1];
pub var base_color_texture: maybe<texture_ref>;
pub var metallic: f32 = 1;
pub var roughness: f32 = 1;
#! Its roughness in green and metalness in blue.
pub var metallic_roughness_texture: maybe<texture_ref>;
#! Its normal map: which way each texel faces, across the surface's tangent
#! and the way up its texture, as OpenGL's normal maps hold it.
pub var normal_texture: maybe<texture_ref>;
#! How much light reaches it, in red.
pub var occlusion_texture: maybe<texture_ref>;
#! The light it gives, by `KHR_materials_emissive_strength` where it says.
pub var emissive: f32[3];
pub var emissive_texture: maybe<texture_ref>;
pub var alpha_mode := alpha_mode::opaque;
pub var alpha_cutoff: f32 = 0.5;
#! Whether its faces are seen from behind too.
pub var double_sided: bool;
#! Whether it's drawn as its colors are, unlit, by `KHR_materials_unlit`.
pub var unlit: bool;
}
#! A texture: an image, sampled by a sampler, or by repeating and blending
#! where it names none.
pub struct texture {
pub var name: string;
pub var sampler: maybe<u64>;
pub var source: maybe<u64>;
}
#! How a sampler picks between texels, where it says.
pub enum filter: u8 { unset, nearest, linear }
#! What a sampler reads past a texture's edge.
pub enum wrap: u8 { repeat, clamp, mirror }
#! How a texture is sampled.
pub struct sampler {
pub var name: string;
pub var mag_filter: filter;
pub var min_filter: filter;
#! Between mip levels, where the minifying filter uses them; unset where it
#! doesn't.
pub var mip_filter: filter;
pub var wrap_s := wrap::repeat;
pub var wrap_t := wrap::repeat;
}
#! An image, encoded as its file is, PNG or JPEG: its bytes, read from its file,
#! a `data:` URI, or a buffer view.
pub struct image {
pub var name: string;
#! Its URI, as the JSON writes it, or empty where it's in a buffer view.
pub var uri: string;
#! Its buffer view, where it's in one.
pub var view: maybe<u64>;
#! Its type, as `image/png`, where the JSON or its `data:` URI says.
pub var mime_type: string;
pub var bytes: vector<u8>;
}
#! How a camera projects.
pub enum camera_kind: u8 { perspective, orthographic }
#! A camera, looking down its node's -z.
pub struct camera {
pub var name: string;
pub var kind := camera_kind::perspective;
#! Of a perspective: how far it sees up and down, in radians, and its width
#! by its height, where it says.
pub var fov_y: f32;
pub var aspect: maybe<f32>;
#! Of an orthographic one: half its width and half its height.
pub var x_mag: f32;
pub var y_mag: f32;
pub var near: f32;
#! The furthest it draws, or none, of a perspective, for no end.
pub var far: maybe<f32>;
}
#! A skin: the nodes of its skeleton, its joints, and the inverses of where
#! each was as the mesh was bound to them.
pub struct skin {
pub var name: string;
pub var joints: vector<u64>;
#! An accessor of a matrix for each joint, or none for none but the identity.
pub var inverse_binds: maybe<u64>;
#! The skeleton's root, where it says.
pub var skeleton: maybe<u64>;
}
#! What an animation's channel moves.
pub enum target_path: u8 { translation, rotation, scale, weights }
#! How an animation's values change between its keys.
pub enum interpolation: u8 { linear, step, cubic_spline }
#! A channel of an animation: what it moves of a node, by which of its samplers.
pub struct channel {
pub var sampler: u64;
#! The node, or none where an extension names what it moves.
pub var node: maybe<u64>;
pub var path: target_path;
}
#! The keys of an animation: the accessor of their times, in seconds, and of
#! their values.
pub struct animation_sampler {
pub var input: u64;
pub var output: u64;
pub var interpolation := interpolation::linear;
}
#! An animation: channels, each moving a node by a sampler's keys.
pub struct animation {
pub var name: string;
pub var channels: vector<channel>;
pub var samplers: vector<animation_sampler>;
}
#! What a light is, of `KHR_lights_punctual`.
pub enum light_kind: u8 {
#! Shining down its node's -z, everywhere.
directional,
#! Shining every way from its node.
point,
#! Shining down its node's -z in a cone.
spot,
}
#! A light, of `KHR_lights_punctual`: its color, linear, and its intensity, in
#! lux for a directional light and in candela for the others.
pub struct light {
pub var name: string;
pub var kind := light_kind::point;
pub var color: f32[3] = [1, 1, 1];
pub var intensity: f32 = 1;
#! How far it reaches, or none where it reaches as far as its intensity does.
pub var range: maybe<f32>;
#! Of a spot light: the angles from its middle where it begins to dim, and
#! where it's dark, in radians.
pub var inner_cone: f32;
pub var outer_cone: f32 = 0.7853982;
}