Initial Commit
This commit is contained in:
36 files changed
+8436
No files matched your search
@@ -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 malunal::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.span, 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,
|
||||
};
|
||||
}
|
||||
@@ -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 malunal::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.".span) 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}.".span) 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.".span) if comma == uri.length;
|
||||
val head := uri.substr(5, comma - 5);
|
||||
return failed(failure::unsupported, $"{whose}: its data URI isn't base64.".span) 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.".span);
|
||||
};
|
||||
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.".span);
|
||||
}
|
||||
break if uri[i] == '/';
|
||||
}
|
||||
val named := percent_decoded(uri) else { return failed(failure::malformed, $"{whose}: {uri} isn't percent-encoded right.".span); };
|
||||
val at := folder.length == 0 ? string::from(named.span, nothing{}) : $"{folder}/{named.span}";
|
||||
val file := path::parse(at.span) else (_) { return failed(failure::unreadable, $"{whose}: {at.span} isn't a path.".span); };
|
||||
val text := io::read_file(&file) else (_) { return failed(failure::unreadable, $"{whose}: {at.span} couldn't be read.".span); };
|
||||
var made := vector::<u8>::new();
|
||||
made.extend(text.span);
|
||||
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{};
|
||||
}
|
||||
@@ -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 malunal::linear;
|
||||
module malunal::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.span} couldn't be read.".span); };
|
||||
var folder := path::new();
|
||||
if at.parent() is some(&above) {
|
||||
folder = path::copy_of(&above);
|
||||
}
|
||||
return decode(bytes.span, folder.span);
|
||||
}
|
||||
|
||||
#! 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.".span); };
|
||||
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);
|
||||
}
|
||||
@@ -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 malunal::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}.".span);
|
||||
}
|
||||
|
||||
# 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".span) 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".span) 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".span); };
|
||||
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".span); };
|
||||
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".span); };
|
||||
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}".span) 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".span) 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}".span); };
|
||||
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".span); };
|
||||
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".span); };
|
||||
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}".span) 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".span); };
|
||||
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".span); };
|
||||
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".span); };
|
||||
return wrong(site, $"its {key} names {n}, of the {count} {list} there are".span) 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;
|
||||
}
|
||||
@@ -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 malunal::linear;
|
||||
module malunal::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.span) else (e) { return e; };
|
||||
var read := node{};
|
||||
read.name = text_member(&each, "name", site.span) else (e) { return e; };
|
||||
read.children = indices_member(&each, "children", site.span, n.nodes, "nodes") else (e) { return e; };
|
||||
read.mesh = index_member(&each, "mesh", site.span, n.meshes, "meshes") else (e) { return e; };
|
||||
read.camera = index_member(&each, "camera", site.span, n.cameras, "cameras") else (e) { return e; };
|
||||
read.skin = index_member(&each, "skin", site.span, n.skins, "skins") else (e) { return e; };
|
||||
read.weights = floats_member(&each, "weights", site.span, 0) else (e) { return e; };
|
||||
val extensions := object_member(&each, "extensions", site.span) 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.span, n.lights, "lights") else (e) { return e; };
|
||||
}
|
||||
}
|
||||
place_node(&mut read, &each, site.span) 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.".span) 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}.".span);
|
||||
}
|
||||
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.".span) 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;
|
||||
}
|
||||
@@ -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 malunal::linear;
|
||||
module malunal::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.span}".span);
|
||||
};
|
||||
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.span}, not 2.".span) if !made.version.span.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.".span) 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.span) else (e) { return e; };
|
||||
var read := buffer{};
|
||||
read.name = text_member(&each, "name", site.span) else (e) { return e; };
|
||||
read.uri = text_member(&each, "uri", site.span) else (e) { return e; };
|
||||
read.length = needed_count(&each, "byteLength", site.span) else (e) { return e; };
|
||||
if read.uri.length != 0 {
|
||||
var mime := string::new(nothing{});
|
||||
read.bytes = bytes_of_uri(read.uri.span, folder, site.span, &mut mime) else (e) { return e; };
|
||||
} else if i == 0 && has_bin {
|
||||
read.bytes.extend(bin);
|
||||
} else {
|
||||
return wrong(site.span, "it has no URI, and isn't a .glb file's binary chunk");
|
||||
}
|
||||
return wrong(site.span, $"it says it's {read.length} bytes, but it's {read.bytes.length}".span) 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.span) else (e) { return e; };
|
||||
var read := buffer_view{};
|
||||
read.name = text_member(&each, "name", site.span) else (e) { return e; };
|
||||
read.buffer = needed_index(&each, "buffer", site.span, n.buffers, "buffers") else (e) { return e; };
|
||||
read.offset = count_member(&each, "byteOffset", site.span, 0) else (e) { return e; };
|
||||
read.length = needed_count(&each, "byteLength", site.span) else (e) { return e; };
|
||||
read.stride = count_member(&each, "byteStride", site.span, 0) else (e) { return e; };
|
||||
val held := made.buffers[read.buffer].length;
|
||||
return wrong(site.span, $"it reaches byte {read.offset + read.length} of its buffer's {held}".span) if read.offset > held || read.length > held - read.offset;
|
||||
return wrong(site.span, $"its byteStride is {read.stride}, not a multiple of 4 from 4 to 252".span)
|
||||
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.span) else (e) { return e; };
|
||||
var read := accessor{};
|
||||
read.name = text_member(&each, "name", site.span) else (e) { return e; };
|
||||
read.view = index_member(&each, "bufferView", site.span, n.views, "bufferViews") else (e) { return e; };
|
||||
read.offset = count_member(&each, "byteOffset", site.span, 0) else (e) { return e; };
|
||||
val code := needed_count(&each, "componentType", site.span) else (e) { return e; };
|
||||
read.component_type = component_of(code) else { return wrong(site.span, $"its componentType {code} is none of glTF's".span); };
|
||||
read.normalized = bool_member(&each, "normalized", site.span, false) else (e) { return e; };
|
||||
read.count = needed_count(&each, "count", site.span) else (e) { return e; };
|
||||
return wrong(site.span, "its count is 0") if read.count == 0;
|
||||
val kind := text_member(&each, "type", site.span) else (e) { return e; };
|
||||
read.kind = element_of(kind.span) else { return wrong(site.span, $"its type {kind.span} is none of glTF's".span); };
|
||||
read.min = reals_member(&each, "min", site.span) else (e) { return e; };
|
||||
read.max = reals_member(&each, "max", site.span) else (e) { return e; };
|
||||
if read.view is some(v) {
|
||||
val view := &made.views[v];
|
||||
val size := read.element_bytes();
|
||||
return wrong(site.span, $"its bufferView's byteStride, {view.stride}, is less than an element's {size} bytes".span)
|
||||
if view.stride != 0 && view.stride < size;
|
||||
val stride := view.stride != 0 ? view.stride : size;
|
||||
return wrong(site.span, $"its {read.count} elements reach past its bufferView's {view.length} bytes".span)
|
||||
if read.offset > view.length || (read.count - 1) * stride + size > view.length - read.offset;
|
||||
}
|
||||
val holds_sparse := object_member(&each, "sparse", site.span) else (e) { return e; };
|
||||
if holds_sparse is some(s) {
|
||||
read.sparse = read_sparse(made, &s, &read, $"{site.span}.sparse".span, 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}".span) 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".span); };
|
||||
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.span;
|
||||
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".span) 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.span) else (e) { return e; };
|
||||
var read := image{};
|
||||
read.name = text_member(&each, "name", site.span) else (e) { return e; };
|
||||
read.uri = text_member(&each, "uri", site.span) else (e) { return e; };
|
||||
read.mime_type = text_member(&each, "mimeType", site.span) else (e) { return e; };
|
||||
read.view = index_member(&each, "bufferView", site.span, n.views, "bufferViews") else (e) { return e; };
|
||||
if read.uri.length != 0 {
|
||||
var mime := string::new(nothing{});
|
||||
read.bytes = bytes_of_uri(read.uri.span, folder, site.span, &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.span[view.offset:view.length]);
|
||||
} else {
|
||||
return wrong(site.span, "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.span) else (e) { return e; };
|
||||
var read := sampler{};
|
||||
read.name = text_member(&each, "name", site.span) else (e) { return e; };
|
||||
val mag := count_member(&each, "magFilter", site.span, 0) else (e) { return e; };
|
||||
val min := count_member(&each, "minFilter", site.span, 0) else (e) { return e; };
|
||||
val s := count_member(&each, "wrapS", site.span, 10497) else (e) { return e; };
|
||||
val t := count_member(&each, "wrapT", site.span, 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.span, $"its wrapS {s} is none of glTF's".span); };
|
||||
read.wrap_t = wrap_of(t) else { return wrong(site.span, $"its wrapT {t} is none of glTF's".span); };
|
||||
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.span) else (e) { return e; };
|
||||
var read := texture{};
|
||||
read.name = text_member(&each, "name", site.span) else (e) { return e; };
|
||||
read.sampler = index_member(&each, "sampler", site.span, n.samplers, "samplers") else (e) { return e; };
|
||||
read.source = index_member(&each, "source", site.span, 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.span, n.textures, "textures") else (e) { return e; };
|
||||
made.set = count_member(&info, "texCoord", inner.span, 0) else (e) { return e; };
|
||||
if scale_key.length != 0 {
|
||||
made.scale = float_member(&info, scale_key, inner.span, 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.span) else (e) { return e; };
|
||||
var read := material{};
|
||||
read.name = text_member(&each, "name", site.span) else (e) { return e; };
|
||||
val pbr_found := object_member(&each, "pbrMetallicRoughness", site.span) else (e) { return e; };
|
||||
if pbr_found is some(pbr) {
|
||||
val inner := $"{site.span}.pbrMetallicRoughness";
|
||||
val color := floats_member(&pbr, "baseColorFactor", inner.span, 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.span, n, "") else (e) { return e; };
|
||||
read.metallic = float_member(&pbr, "metallicFactor", inner.span, 1) else (e) { return e; };
|
||||
read.roughness = float_member(&pbr, "roughnessFactor", inner.span, 1) else (e) { return e; };
|
||||
read.metallic_roughness_texture = texture_member(&pbr, "metallicRoughnessTexture", inner.span, n, "") else (e) { return e; };
|
||||
}
|
||||
read.normal_texture = texture_member(&each, "normalTexture", site.span, n, "scale") else (e) { return e; };
|
||||
read.occlusion_texture = texture_member(&each, "occlusionTexture", site.span, n, "strength") else (e) { return e; };
|
||||
read.emissive_texture = texture_member(&each, "emissiveTexture", site.span, n, "") else (e) { return e; };
|
||||
val emissive := floats_member(&each, "emissiveFactor", site.span, 3) else (e) { return e; };
|
||||
if emissive.length == 3 {
|
||||
read.emissive = [emissive[0], emissive[1], emissive[2]];
|
||||
}
|
||||
val mode := text_member(&each, "alphaMode", site.span) else (e) { return e; };
|
||||
if mode.span == "MASK" {
|
||||
read.alpha_mode = alpha_mode::mask;
|
||||
} else if mode.span == "BLEND" {
|
||||
read.alpha_mode = alpha_mode::blend;
|
||||
} else if mode.length != 0 && mode.span != "OPAQUE" {
|
||||
return wrong(site.span, $"its alphaMode {mode.span} is none of glTF's".span);
|
||||
}
|
||||
read.alpha_cutoff = float_member(&each, "alphaCutoff", site.span, 0.5) else (e) { return e; };
|
||||
read.double_sided = bool_member(&each, "doubleSided", site.span, false) else (e) { return e; };
|
||||
val extensions := object_member(&each, "extensions", site.span) 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.span, 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".span); };
|
||||
return wrong(site, $"its {each.key} is {index}, of the {n.accessors} accessors there are".span) 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.span) else (e) { return e; };
|
||||
var read := mesh{};
|
||||
read.name = text_member(&each, "name", site.span) else (e) { return e; };
|
||||
read.weights = floats_member(&each, "weights", site.span, 0) else (e) { return e; };
|
||||
val parts_found := array_member(&each, "primitives", site.span) else (e) { return e; };
|
||||
val parts := parts_found else { return wrong(site.span, "it has no primitives"); };
|
||||
return wrong(site.span, "it has no primitives") if parts.length == 0;
|
||||
for k in 0..parts.length {
|
||||
val inner := $"{site.span}.primitives[{k}]";
|
||||
val part := object_at(&parts, k, inner.span) else (e) { return e; };
|
||||
var drawn := read_primitive(made, &part, inner.span, 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".span) 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.span) else (e) { return e; };
|
||||
var moved := attributes_of(&target, inner.span, 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.span} has {count} elements, of the other attributes' {vertices}".span)
|
||||
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".span) 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.span) else (e) { return e; };
|
||||
var read := camera{};
|
||||
read.name = text_member(&each, "name", site.span) else (e) { return e; };
|
||||
val kind := text_member(&each, "type", site.span) else (e) { return e; };
|
||||
if kind.span == "perspective" {
|
||||
val held := object_member(&each, "perspective", site.span) else (e) { return e; };
|
||||
val p := held else { return wrong(site.span, "it's a perspective but says none"); };
|
||||
read.fov_y = float_member(&p, "yfov", site.span, 0) else (e) { return e; };
|
||||
read.aspect = maybe_number(&p, "aspectRatio", site.span) else (e) { return e; };
|
||||
read.near = float_member(&p, "znear", site.span, 0) else (e) { return e; };
|
||||
read.far = maybe_number(&p, "zfar", site.span) else (e) { return e; };
|
||||
} else if kind.span == "orthographic" {
|
||||
read.kind = camera_kind::orthographic;
|
||||
val held := object_member(&each, "orthographic", site.span) else (e) { return e; };
|
||||
val o := held else { return wrong(site.span, "it's orthographic but says nothing of it"); };
|
||||
read.x_mag = float_member(&o, "xmag", site.span, 1) else (e) { return e; };
|
||||
read.y_mag = float_member(&o, "ymag", site.span, 1) else (e) { return e; };
|
||||
read.near = float_member(&o, "znear", site.span, 0) else (e) { return e; };
|
||||
read.far = maybe_number(&o, "zfar", site.span) else (e) { return e; };
|
||||
} else {
|
||||
return wrong(site.span, $"its type {kind.span} is none of glTF's".span);
|
||||
}
|
||||
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.span) else (e) { return e; };
|
||||
var read := light{};
|
||||
read.name = text_member(&each, "name", site.span) else (e) { return e; };
|
||||
val kind := text_member(&each, "type", site.span) else (e) { return e; };
|
||||
if kind.span == "directional" {
|
||||
read.kind = light_kind::directional;
|
||||
} else if kind.span == "spot" {
|
||||
read.kind = light_kind::spot;
|
||||
} else if kind.span != "point" {
|
||||
return wrong(site.span, $"its type {kind.span} is none of the extension's".span);
|
||||
}
|
||||
val color := floats_member(&each, "color", site.span, 3) else (e) { return e; };
|
||||
if color.length == 3 {
|
||||
read.color = [color[0], color[1], color[2]];
|
||||
}
|
||||
read.intensity = float_member(&each, "intensity", site.span, 1) else (e) { return e; };
|
||||
read.range = maybe_number(&each, "range", site.span) else (e) { return e; };
|
||||
val cone := object_member(&each, "spot", site.span) else (e) { return e; };
|
||||
if cone is some(s) {
|
||||
read.inner_cone = float_member(&s, "innerConeAngle", site.span, 0) else (e) { return e; };
|
||||
read.outer_cone = float_member(&s, "outerConeAngle", site.span, 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.span) else (e) { return e; };
|
||||
var read := skin{};
|
||||
read.name = text_member(&each, "name", site.span) else (e) { return e; };
|
||||
read.joints = indices_member(&each, "joints", site.span, n.nodes, "nodes") else (e) { return e; };
|
||||
return wrong(site.span, "it has no joints") if read.joints.length == 0;
|
||||
read.inverse_binds = index_member(&each, "inverseBindMatrices", site.span, n.accessors, "accessors") else (e) { return e; };
|
||||
read.skeleton = index_member(&each, "skeleton", site.span, n.nodes, "nodes") else (e) { return e; };
|
||||
if read.inverse_binds is some(at) {
|
||||
val binds := &made.accessors[at];
|
||||
return wrong(site.span, "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.span) else (e) { return e; };
|
||||
var read := scene{};
|
||||
read.name = text_member(&each, "name", site.span) else (e) { return e; };
|
||||
read.nodes = indices_member(&each, "nodes", site.span, n.nodes, "nodes") else (e) { return e; };
|
||||
for k in 0..read.nodes.length {
|
||||
return wrong(site.span, $"its node {read.nodes[k]} is another's child, not a root".span) 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.span) else (e) { return e; };
|
||||
var read := animation{};
|
||||
read.name = text_member(&each, "name", site.span) else (e) { return e; };
|
||||
val samplers_found := array_member(&each, "samplers", site.span) else (e) { return e; };
|
||||
val samplers := samplers_found else { return wrong(site.span, "it has no samplers"); };
|
||||
for k in 0..samplers.length {
|
||||
val inner := $"{site.span}.samplers[{k}]";
|
||||
val s := object_at(&samplers, k, inner.span) else (e) { return e; };
|
||||
var keys := animation_sampler{};
|
||||
keys.input = needed_index(&s, "input", inner.span, n.accessors, "accessors") else (e) { return e; };
|
||||
keys.output = needed_index(&s, "output", inner.span, n.accessors, "accessors") else (e) { return e; };
|
||||
val how := text_member(&s, "interpolation", inner.span) else (e) { return e; };
|
||||
if how.span == "STEP" {
|
||||
keys.interpolation = interpolation::step;
|
||||
} else if how.span == "CUBICSPLINE" {
|
||||
keys.interpolation = interpolation::cubic_spline;
|
||||
} else if how.length != 0 && how.span != "LINEAR" {
|
||||
return wrong(inner.span, $"its interpolation {how.span} is none of glTF's".span);
|
||||
}
|
||||
val times := &made.accessors[keys.input];
|
||||
return wrong(inner.span, "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.span) else (e) { return e; };
|
||||
val channels := channels_found else { return wrong(site.span, "it has no channels"); };
|
||||
for k in 0..channels.length {
|
||||
val inner := $"{site.span}.channels[{k}]";
|
||||
val c := object_at(&channels, k, inner.span) else (e) { return e; };
|
||||
var moved := channel{};
|
||||
moved.sampler = needed_index(&c, "sampler", inner.span, read.samplers.length, "samplers") else (e) { return e; };
|
||||
val target_found := object_member(&c, "target", inner.span) else (e) { return e; };
|
||||
val target := target_found else { return wrong(inner.span, "it has no target"); };
|
||||
moved.node = index_member(&target, "node", inner.span, n.nodes, "nodes") else (e) { return e; };
|
||||
val path := text_member(&target, "path", inner.span) else (e) { return e; };
|
||||
if path.span == "translation" {
|
||||
moved.path = target_path::translation;
|
||||
} else if path.span == "rotation" {
|
||||
moved.path = target_path::rotation;
|
||||
} else if path.span == "scale" {
|
||||
moved.path = target_path::scale;
|
||||
} else if path.span == "weights" {
|
||||
moved.path = target_path::weights;
|
||||
} else {
|
||||
return wrong(inner.span, $"its path {path.span} is none of glTF's".span);
|
||||
}
|
||||
read.channels.append(moved);
|
||||
}
|
||||
made.animations.append(move(read));
|
||||
}
|
||||
return;
|
||||
}
|
||||
@@ -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 malunal::linear;
|
||||
module malunal::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.span == 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;
|
||||
}
|
||||
@@ -0,0 +1,964 @@
|
||||
#! Contains writing an asset as glTF 2.0: its parts as JSON, each member glTF
|
||||
#! gives a default left out where it's that default, and its buffers' bytes, as
|
||||
#! a `.glb` file's binary chunk, `data:` URIs, or files beside it; and what an
|
||||
#! asset is built of by hand: bytes of its first buffer, views of them, and
|
||||
#! accessors of numbers, with their least and most, and images.
|
||||
#!
|
||||
#! What's read is written as it was read, so an asset read and written reads
|
||||
#! back the same, but for the extensions it used that aren't read, which it
|
||||
#! no longer holds, and a node's matrix, which glTF holds is no more than its
|
||||
#! translation, rotation, and scale, which are written in its place.
|
||||
|
||||
import std::io;
|
||||
import std::json;
|
||||
import std::math;
|
||||
import malunal::linear;
|
||||
module malunal::gltf;
|
||||
|
||||
#! An asset of nothing yet, of glTF 2.0, saying what wrote it.
|
||||
#! @param generator What wrote it, as its JSON says.
|
||||
pub def asset::new(generator: strview = "malunal gltf"): asset {
|
||||
var made := asset{};
|
||||
made.version = string::from("2.0", nothing{});
|
||||
made.generator = string::from(generator, nothing{});
|
||||
return made;
|
||||
}
|
||||
|
||||
#! Adds bytes to the asset's first buffer, which it's given where it has none,
|
||||
#! and a view of them, begun at a multiple of 4 bytes, as accessors need. A
|
||||
#! `.glb` file writes that buffer as its binary chunk, and a `.gltf` file as a
|
||||
#! `data:` URI.
|
||||
#! @param this The asset.
|
||||
#! @param bytes The bytes.
|
||||
#! @param name The view's name, or none.
|
||||
#! @returns The view, by its place among the asset's.
|
||||
pub def asset::add_view(&mut this, bytes: span<u8>, name: strview = ""): u64 {
|
||||
if this.buffers.length == 0 {
|
||||
this.buffers.append(buffer{});
|
||||
}
|
||||
val held := &mut this.buffers.at(0);
|
||||
while held.bytes.length % 4 != 0 {
|
||||
held.bytes.append(0);
|
||||
}
|
||||
val offset := held.bytes.length;
|
||||
held.bytes.extend(bytes);
|
||||
held.length = held.bytes.length;
|
||||
this.views.append(buffer_view{ name = string::from(name, nothing{}), buffer = 0, offset = offset, length = bytes.length });
|
||||
return this.views.length - 1;
|
||||
}
|
||||
|
||||
#! Adds an accessor of floats, of their own view, with the least and the most
|
||||
#! of each of their numbers, as glTF asks of a position's.
|
||||
#! @param this The asset.
|
||||
#! @param values The numbers, each element's in turn.
|
||||
#! @param kind What each element is, of how many of them.
|
||||
#! @param name The accessor's name, or none.
|
||||
#! @returns The accessor, by its place among the asset's.
|
||||
pub def asset::add_floats(&mut this, values: span<f32>, kind: element, name: strview = ""): u64 {
|
||||
val width := kind.components;
|
||||
var bytes := vector::<u8>::new();
|
||||
for i in 0..values.length {
|
||||
put_word(&mut bytes, math::bits_of(values[i]));
|
||||
}
|
||||
val view := this.add_view(bytes.span);
|
||||
var made := accessor{ name = string::from(name, nothing{}), view = view, kind = kind, count = values.length / width };
|
||||
for k in 0..width {
|
||||
var least := math::infinity::<f64>();
|
||||
var most := -math::infinity::<f64>();
|
||||
var i := k;
|
||||
while i < values.length {
|
||||
least = math::min(least, values[i] as f64);
|
||||
most = math::max(most, values[i] as f64);
|
||||
i += width;
|
||||
}
|
||||
made.min.append(least);
|
||||
made.max.append(most);
|
||||
}
|
||||
this.accessors.append(move(made));
|
||||
return this.accessors.length - 1;
|
||||
}
|
||||
|
||||
#! Adds an accessor of indices, as a primitive draws its vertices by: unsigned
|
||||
#! shorts where each is less than 65535, and unsigned ints otherwise.
|
||||
#! @param this The asset.
|
||||
#! @param values The indices.
|
||||
#! @param name The accessor's name, or none.
|
||||
#! @returns The accessor, by its place among the asset's.
|
||||
pub def asset::add_indices(&mut this, values: span<u32>, name: strview = ""): u64 {
|
||||
var most: u32 = 0;
|
||||
for i in 0..values.length {
|
||||
most = math::max(most, values[i]);
|
||||
}
|
||||
val short := most < 65535;
|
||||
var bytes := vector::<u8>::new();
|
||||
for i in 0..values.length {
|
||||
if short {
|
||||
bytes.append((values[i] & 0xFF) as u8);
|
||||
bytes.append((values[i] >> 8) as u8);
|
||||
} else {
|
||||
put_word(&mut bytes, values[i]);
|
||||
}
|
||||
}
|
||||
val view := this.add_view(bytes.span);
|
||||
this.accessors.append(accessor{
|
||||
name = string::from(name, nothing{}), view = view, count = values.length,
|
||||
component_type = short ? component::unsigned_short : component::unsigned_int,
|
||||
});
|
||||
return this.accessors.length - 1;
|
||||
}
|
||||
|
||||
#! Adds an image, of its file's bytes, as encoded, in a view of the first
|
||||
#! buffer.
|
||||
#! @param this The asset.
|
||||
#! @param bytes The file's bytes: PNG or JPEG.
|
||||
#! @param mime Its type, as `image/png`, or none, for what its first bytes say.
|
||||
#! @param name Its name, or none.
|
||||
#! @returns The image, by its place among the asset's.
|
||||
pub def asset::add_image(&mut this, bytes: span<u8>, mime: strview = "", name: strview = ""): u64 {
|
||||
val view := this.add_view(bytes);
|
||||
var made := image{ name = string::from(name, nothing{}), view = view };
|
||||
made.mime_type = string::from(mime.length != 0 ? mime : mime_of(bytes), nothing{});
|
||||
made.bytes.extend(bytes);
|
||||
this.images.append(move(made));
|
||||
return this.images.length - 1;
|
||||
}
|
||||
|
||||
# The type of an image's bytes, by its first: PNG's or JPEG's, or PNG's where
|
||||
# it's neither.
|
||||
def mime_of(bytes: span<u8>): strview {
|
||||
return "image/jpeg" if bytes.length >= 2 && bytes[0] == 0xFF && bytes[1] == 0xD8;
|
||||
return "image/png";
|
||||
}
|
||||
|
||||
#! Writes an asset as glTF: a `.glb` file, its JSON and its first buffer as its
|
||||
#! binary chunk where that names no file, or a `.gltf` file's JSON. Each other
|
||||
#! buffer, and an image of neither a view nor a file, is a `data:` URI; one
|
||||
#! naming a file names it still, which `save` writes, and this leaves to whoever
|
||||
#! writes it.
|
||||
#! @param made The asset.
|
||||
#! @param binary Whether it's a `.glb` file.
|
||||
#! @returns The file's bytes, or why it couldn't be written: `malformed` where a
|
||||
#! number is infinite or NaN, or a name isn't UTF-8.
|
||||
pub def encode(made: &asset, binary: bool = true): result<vector<u8>, gltf_error> {
|
||||
val chunked := binary && made.buffers.length != 0 && !names_file(made.buffers[0].uri.span);
|
||||
var w := json::writer::new();
|
||||
write_asset(&mut w, made, chunked);
|
||||
val text := w.finish() else (_) {
|
||||
return failed(failure::malformed, "A number of it is infinite or NaN, or a name of it isn't UTF-8.");
|
||||
};
|
||||
var out := vector::<u8>::new();
|
||||
if !binary {
|
||||
out.extend(text);
|
||||
return out;
|
||||
}
|
||||
# The header, then the JSON padded with spaces, then the binary chunk
|
||||
# padded with zeros, each chunk a multiple of 4 bytes.
|
||||
var json_bytes := vector::<u8>::new();
|
||||
json_bytes.extend(text);
|
||||
while json_bytes.length % 4 != 0 {
|
||||
json_bytes.append(' ');
|
||||
}
|
||||
var bin := vector::<u8>::new();
|
||||
if chunked {
|
||||
bin.extend(made.buffers[0].bytes.span);
|
||||
while bin.length % 4 != 0 {
|
||||
bin.append(0);
|
||||
}
|
||||
}
|
||||
var total := 12 + 8 + json_bytes.length;
|
||||
if chunked {
|
||||
total += 8 + bin.length;
|
||||
}
|
||||
put_word(&mut out, glb_magic);
|
||||
put_word(&mut out, 2);
|
||||
put_word(&mut out, total as u32);
|
||||
put_word(&mut out, json_bytes.length as u32);
|
||||
put_word(&mut out, json_chunk);
|
||||
out.extend(json_bytes.span);
|
||||
if chunked {
|
||||
put_word(&mut out, bin.length as u32);
|
||||
put_word(&mut out, bin_chunk);
|
||||
out.extend(bin.span);
|
||||
}
|
||||
return out;
|
||||
}
|
||||
|
||||
#! Writes an asset to a file: `.glb` where its name ends so, and `.gltf`
|
||||
#! otherwise, as `encode` writes it; and the files its buffers and images name,
|
||||
#! beside it, of their bytes, its folder made where it isn't.
|
||||
#! @param made The asset.
|
||||
#! @param at The file's path.
|
||||
#! @returns Nothing, or why it couldn't be written: `unreadable` where a file
|
||||
#! couldn't be written, as a file is read.
|
||||
pub def save(made: &asset, at: &path): result<void, gltf_error> {
|
||||
val binary := at.span.ends_with(".glb") || at.span.ends_with(".GLB");
|
||||
var folder := string::new(nothing{});
|
||||
if at.parent() is some(&above) {
|
||||
folder.append(above.span);
|
||||
_ = io::create_directories(above);
|
||||
}
|
||||
for i in 0..made.buffers.length {
|
||||
val uri := made.buffers[i].uri.span;
|
||||
continue if !names_file(uri);
|
||||
write_beside(folder.span, uri, made.buffers[i].bytes.span) else (e) { return e; };
|
||||
}
|
||||
for i in 0..made.images.length {
|
||||
val uri := made.images[i].uri.span;
|
||||
continue if made.images[i].view is some(_) || !names_file(uri);
|
||||
write_beside(folder.span, uri, made.images[i].bytes.span) else (e) { return e; };
|
||||
}
|
||||
val bytes := encode(made, binary) else (e) { return e; };
|
||||
io::write_file(at, bytes.span) else (_) { return failed(failure::unreadable, $"{at.span} couldn't be written.".span); };
|
||||
return;
|
||||
}
|
||||
|
||||
#! Writes an asset to a file named by text, as `save` does.
|
||||
pub def save(made: &asset, at: strview): result<void, gltf_error> {
|
||||
val named := path::parse(at) else (_) { return failed(failure::unreadable, $"{at} isn't a path.".span); };
|
||||
return save(made, &named);
|
||||
}
|
||||
|
||||
# Whether a URI names a file, rather than nothing or data.
|
||||
def names_file(uri: strview): bool {
|
||||
return uri.length != 0 && !uri.starts_with("data:");
|
||||
}
|
||||
|
||||
# Writes the bytes of a file a URI names, beside the asset's.
|
||||
def write_beside(folder: strview, uri: strview, bytes: span<u8>): result<void, gltf_error> {
|
||||
val named := percent_decoded(uri) else { return failed(failure::malformed, $"{uri} isn't percent-encoded right.".span); };
|
||||
val at := folder.length == 0 ? string::from(named.span, nothing{}) : $"{folder}/{named.span}";
|
||||
val file := path::parse(at.span) else (_) { return failed(failure::unreadable, $"{at.span} isn't a path.".span); };
|
||||
if file.parent() is some(&above) {
|
||||
_ = io::create_directories(above);
|
||||
}
|
||||
io::write_file(&file, bytes) else (_) { return failed(failure::unreadable, $"{at.span} couldn't be written.".span); };
|
||||
return;
|
||||
}
|
||||
|
||||
# A little-endian `u32`, added to bytes.
|
||||
def put_word(bytes: &mut vector<u8>, value: u32): void {
|
||||
for i in 0..4u {
|
||||
bytes.append(((value >> (8 * i)) & 0xFF) as u8);
|
||||
}
|
||||
}
|
||||
|
||||
# Bytes as base64, padded.
|
||||
def base64_text(bytes: span<u8>): string {
|
||||
val digits: strview = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";
|
||||
var made := string::new(nothing{});
|
||||
var i: u64 = 0;
|
||||
while i < bytes.length {
|
||||
val left := bytes.length - i;
|
||||
val a := bytes[i] as u32;
|
||||
val b: u32 = left > 1 ? bytes[i + 1] as u32 : 0;
|
||||
val c: u32 = left > 2 ? bytes[i + 2] as u32 : 0;
|
||||
val all := (a << 16) | (b << 8) | c;
|
||||
made.push(digits[((all >> 18) & 63) as u64]);
|
||||
made.push(digits[((all >> 12) & 63) as u64]);
|
||||
made.push(left > 1 ? digits[((all >> 6) & 63) as u64] : '=');
|
||||
made.push(left > 2 ? digits[(all & 63) as u64] : '=');
|
||||
i += 3;
|
||||
}
|
||||
return made;
|
||||
}
|
||||
|
||||
# A `data:` URI of bytes of a type.
|
||||
def data_uri_of(mime: strview, bytes: span<u8>): string {
|
||||
val digits := base64_text(bytes);
|
||||
return $"data:{mime};base64,{digits.span}";
|
||||
}
|
||||
|
||||
# A float, as the shortest text that reads back as it, or `null` where it's
|
||||
# infinite or NaN, which the writer keeps as its failure.
|
||||
def put_float(w: &mut json::writer, value: f32): void {
|
||||
if !(value - value == 0) {
|
||||
w.real(value as f64);
|
||||
return;
|
||||
}
|
||||
val text := $"{value}";
|
||||
w.raw(text.span);
|
||||
}
|
||||
|
||||
# A least or most of an accessor, as a float's text where it's a float's.
|
||||
def put_real(w: &mut json::writer, value: f64): void {
|
||||
if (value as f32) as f64 == value {
|
||||
put_float(w, value as f32);
|
||||
} else {
|
||||
w.real(value);
|
||||
}
|
||||
}
|
||||
|
||||
# A member of text, where it's given.
|
||||
def put_text(w: &mut json::writer, key: strview, value: &string): void {
|
||||
return if value.length == 0;
|
||||
w.member(key);
|
||||
w.text(value.span);
|
||||
}
|
||||
|
||||
# A member of a whole number.
|
||||
def put_count(w: &mut json::writer, key: strview, value: u64): void {
|
||||
w.member(key);
|
||||
w.unsigned(value);
|
||||
}
|
||||
|
||||
# A member of an index, where it's given.
|
||||
def put_index(w: &mut json::writer, key: strview, value: maybe<u64>): void {
|
||||
if value is some(at) {
|
||||
put_count(w, key, at);
|
||||
}
|
||||
}
|
||||
|
||||
# A member of indices, where there are any.
|
||||
def put_indices(w: &mut json::writer, key: strview, values: &vector<u64>): void {
|
||||
return if values.length == 0;
|
||||
w.member(key);
|
||||
w.begin_array();
|
||||
for i in 0..values.length {
|
||||
w.unsigned(values[i]);
|
||||
}
|
||||
w.end_array();
|
||||
}
|
||||
|
||||
# A member of floats.
|
||||
def put_floats(w: &mut json::writer, key: strview, values: span<f32>): void {
|
||||
w.member(key);
|
||||
w.begin_array();
|
||||
for i in 0..values.length {
|
||||
put_float(w, values[i]);
|
||||
}
|
||||
w.end_array();
|
||||
}
|
||||
|
||||
# A member of a float, where it isn't its default.
|
||||
def put_number(w: &mut json::writer, key: strview, value: f32, given: f32): void {
|
||||
return if value == given;
|
||||
w.member(key);
|
||||
put_float(w, value);
|
||||
}
|
||||
|
||||
# Writes an asset's JSON, its first buffer the binary chunk where `chunked`.
|
||||
def write_asset(w: &mut json::writer, made: &asset, chunked: bool): void {
|
||||
w.begin_object();
|
||||
w.member("asset");
|
||||
w.begin_object();
|
||||
w.member("version");
|
||||
w.text(made.version.length != 0 ? made.version.span : "2.0");
|
||||
put_text(w, "generator", &made.generator);
|
||||
w.end_object();
|
||||
|
||||
# The extensions it uses, of those written.
|
||||
var used := vector::<strview>::new();
|
||||
var required := vector::<strview>::new();
|
||||
if made.lights.length != 0 {
|
||||
used.append("KHR_lights_punctual");
|
||||
}
|
||||
var unlit := false;
|
||||
var strong := false;
|
||||
for i in 0..made.materials.length {
|
||||
unlit = unlit || made.materials[i].unlit;
|
||||
strong = strong || brightest(&made.materials[i]) > 1;
|
||||
}
|
||||
if unlit {
|
||||
used.append("KHR_materials_unlit");
|
||||
}
|
||||
if strong {
|
||||
used.append("KHR_materials_emissive_strength");
|
||||
}
|
||||
for i in 0..made.extensions.length {
|
||||
if made.extensions[i].span == "KHR_mesh_quantization" {
|
||||
used.append("KHR_mesh_quantization");
|
||||
required.append("KHR_mesh_quantization");
|
||||
}
|
||||
}
|
||||
if used.length != 0 {
|
||||
w.member("extensionsUsed");
|
||||
w.begin_array();
|
||||
for i in 0..used.length {
|
||||
w.text(used[i]);
|
||||
}
|
||||
w.end_array();
|
||||
}
|
||||
if required.length != 0 {
|
||||
w.member("extensionsRequired");
|
||||
w.begin_array();
|
||||
for i in 0..required.length {
|
||||
w.text(required[i]);
|
||||
}
|
||||
w.end_array();
|
||||
}
|
||||
|
||||
put_index(w, "scene", made.scene);
|
||||
write_scenes(w, made);
|
||||
write_nodes(w, made);
|
||||
write_meshes(w, made);
|
||||
write_materials(w, made);
|
||||
write_textures(w, made);
|
||||
write_images(w, made);
|
||||
write_accessors(w, made);
|
||||
write_views(w, made);
|
||||
write_buffers(w, made, chunked);
|
||||
write_cameras(w, made);
|
||||
write_skins(w, made);
|
||||
write_animations(w, made);
|
||||
if made.lights.length != 0 {
|
||||
w.member("extensions");
|
||||
w.begin_object();
|
||||
w.member("KHR_lights_punctual");
|
||||
w.begin_object();
|
||||
write_lights(w, made);
|
||||
w.end_object();
|
||||
w.end_object();
|
||||
}
|
||||
w.end_object();
|
||||
}
|
||||
|
||||
# The most of a material's emission, which more than 1 of is its strength.
|
||||
def brightest(m: &material): f32 {
|
||||
return math::max(m.emissive[0], math::max(m.emissive[1], m.emissive[2]));
|
||||
}
|
||||
|
||||
def write_scenes(w: &mut json::writer, made: &asset): void {
|
||||
return if made.scenes.length == 0;
|
||||
w.member("scenes");
|
||||
w.begin_array();
|
||||
for i in 0..made.scenes.length {
|
||||
val each := &made.scenes[i];
|
||||
w.begin_object();
|
||||
put_text(w, "name", &each.name);
|
||||
put_indices(w, "nodes", &each.nodes);
|
||||
w.end_object();
|
||||
}
|
||||
w.end_array();
|
||||
}
|
||||
|
||||
def write_nodes(w: &mut json::writer, made: &asset): void {
|
||||
return if made.nodes.length == 0;
|
||||
w.member("nodes");
|
||||
w.begin_array();
|
||||
for i in 0..made.nodes.length {
|
||||
val each := &made.nodes[i];
|
||||
w.begin_object();
|
||||
put_text(w, "name", &each.name);
|
||||
put_indices(w, "children", &each.children);
|
||||
put_index(w, "mesh", each.mesh);
|
||||
put_index(w, "camera", each.camera);
|
||||
put_index(w, "skin", each.skin);
|
||||
if each.weights.length != 0 {
|
||||
put_floats(w, "weights", each.weights.span);
|
||||
}
|
||||
val t := each.translation;
|
||||
if t.x != 0 || t.y != 0 || t.z != 0 {
|
||||
val numbers: f32[3] = [t.x, t.y, t.z];
|
||||
put_floats(w, "translation", numbers[:]);
|
||||
}
|
||||
val r := each.rotation;
|
||||
if r.x != 0 || r.y != 0 || r.z != 0 || r.w != 1 {
|
||||
val numbers: f32[4] = [r.x, r.y, r.z, r.w];
|
||||
put_floats(w, "rotation", numbers[:]);
|
||||
}
|
||||
val s := each.scale;
|
||||
if s.x != 1 || s.y != 1 || s.z != 1 {
|
||||
val numbers: f32[3] = [s.x, s.y, s.z];
|
||||
put_floats(w, "scale", numbers[:]);
|
||||
}
|
||||
if each.light is some(lit) {
|
||||
w.member("extensions");
|
||||
w.begin_object();
|
||||
w.member("KHR_lights_punctual");
|
||||
w.begin_object();
|
||||
put_count(w, "light", lit);
|
||||
w.end_object();
|
||||
w.end_object();
|
||||
}
|
||||
w.end_object();
|
||||
}
|
||||
w.end_array();
|
||||
}
|
||||
|
||||
# A primitive's attributes, or a morph target's, as an object of each's name.
|
||||
def write_attributes(w: &mut json::writer, list: &vector<attribute>): void {
|
||||
w.begin_object();
|
||||
for i in 0..list.length {
|
||||
put_count(w, list[i].name.span, list[i].accessor);
|
||||
}
|
||||
w.end_object();
|
||||
}
|
||||
|
||||
def write_meshes(w: &mut json::writer, made: &asset): void {
|
||||
return if made.meshes.length == 0;
|
||||
w.member("meshes");
|
||||
w.begin_array();
|
||||
for i in 0..made.meshes.length {
|
||||
val each := &made.meshes[i];
|
||||
w.begin_object();
|
||||
put_text(w, "name", &each.name);
|
||||
w.member("primitives");
|
||||
w.begin_array();
|
||||
for k in 0..each.primitives.length {
|
||||
val part := &each.primitives[k];
|
||||
w.begin_object();
|
||||
w.member("attributes");
|
||||
write_attributes(w, &part.attributes);
|
||||
put_index(w, "indices", part.indices);
|
||||
put_index(w, "material", part.material);
|
||||
if part.mode != topology::triangles {
|
||||
put_count(w, "mode", part.mode as u64);
|
||||
}
|
||||
if part.targets.length != 0 {
|
||||
w.member("targets");
|
||||
w.begin_array();
|
||||
for t in 0..part.targets.length {
|
||||
write_attributes(w, &part.targets[t]);
|
||||
}
|
||||
w.end_array();
|
||||
}
|
||||
w.end_object();
|
||||
}
|
||||
w.end_array();
|
||||
if each.weights.length != 0 {
|
||||
put_floats(w, "weights", each.weights.span);
|
||||
}
|
||||
w.end_object();
|
||||
}
|
||||
w.end_array();
|
||||
}
|
||||
|
||||
# A texture a material names, with its scale or strength where it has one.
|
||||
def write_texture_ref(w: &mut json::writer, key: strview, held: maybe<texture_ref>, scale_key: strview): void {
|
||||
val used := held else { return; };
|
||||
w.member(key);
|
||||
w.begin_object();
|
||||
put_count(w, "index", used.texture);
|
||||
if used.set != 0 {
|
||||
put_count(w, "texCoord", used.set);
|
||||
}
|
||||
if scale_key.length != 0 {
|
||||
put_number(w, scale_key, used.scale, 1);
|
||||
}
|
||||
w.end_object();
|
||||
}
|
||||
|
||||
def write_materials(w: &mut json::writer, made: &asset): void {
|
||||
return if made.materials.length == 0;
|
||||
w.member("materials");
|
||||
w.begin_array();
|
||||
for i in 0..made.materials.length {
|
||||
val each := &made.materials[i];
|
||||
w.begin_object();
|
||||
put_text(w, "name", &each.name);
|
||||
w.member("pbrMetallicRoughness");
|
||||
w.begin_object();
|
||||
val c := each.base_color;
|
||||
if c[0] != 1 || c[1] != 1 || c[2] != 1 || c[3] != 1 {
|
||||
put_floats(w, "baseColorFactor", c[:]);
|
||||
}
|
||||
write_texture_ref(w, "baseColorTexture", each.base_color_texture, "");
|
||||
put_number(w, "metallicFactor", each.metallic, 1);
|
||||
put_number(w, "roughnessFactor", each.roughness, 1);
|
||||
write_texture_ref(w, "metallicRoughnessTexture", each.metallic_roughness_texture, "");
|
||||
w.end_object();
|
||||
write_texture_ref(w, "normalTexture", each.normal_texture, "scale");
|
||||
write_texture_ref(w, "occlusionTexture", each.occlusion_texture, "strength");
|
||||
write_texture_ref(w, "emissiveTexture", each.emissive_texture, "");
|
||||
# Emission past 1 is written as its strength, by the extension.
|
||||
val strength := brightest(each);
|
||||
val by: f32 = strength > 1 ? strength : 1;
|
||||
if each.emissive[0] != 0 || each.emissive[1] != 0 || each.emissive[2] != 0 {
|
||||
val numbers: f32[3] = [each.emissive[0] / by, each.emissive[1] / by, each.emissive[2] / by];
|
||||
put_floats(w, "emissiveFactor", numbers[:]);
|
||||
}
|
||||
if each.alpha_mode == alpha_mode::mask {
|
||||
w.member("alphaMode");
|
||||
w.text("MASK");
|
||||
put_number(w, "alphaCutoff", each.alpha_cutoff, 0.5);
|
||||
} else if each.alpha_mode == alpha_mode::blend {
|
||||
w.member("alphaMode");
|
||||
w.text("BLEND");
|
||||
}
|
||||
if each.double_sided {
|
||||
w.member("doubleSided");
|
||||
w.boolean(true);
|
||||
}
|
||||
if each.unlit || strength > 1 {
|
||||
w.member("extensions");
|
||||
w.begin_object();
|
||||
if each.unlit {
|
||||
w.member("KHR_materials_unlit");
|
||||
w.begin_object();
|
||||
w.end_object();
|
||||
}
|
||||
if strength > 1 {
|
||||
w.member("KHR_materials_emissive_strength");
|
||||
w.begin_object();
|
||||
w.member("emissiveStrength");
|
||||
put_float(w, strength);
|
||||
w.end_object();
|
||||
}
|
||||
w.end_object();
|
||||
}
|
||||
w.end_object();
|
||||
}
|
||||
w.end_array();
|
||||
}
|
||||
|
||||
# glTF's code of a filter, or 0 for one unset.
|
||||
def filter_code(f: filter): u64 {
|
||||
return match f {
|
||||
unset => 0,
|
||||
nearest => 9728,
|
||||
linear => 9729,
|
||||
};
|
||||
}
|
||||
|
||||
# glTF's code of a minifying filter, between mip levels as it says.
|
||||
def min_filter_code(min: filter, mip: filter): u64 {
|
||||
return filter_code(min) if mip == filter::unset;
|
||||
return 0 if min == filter::unset;
|
||||
val linear := min == filter::linear;
|
||||
if mip == filter::nearest {
|
||||
return linear ? 9985 : 9984;
|
||||
}
|
||||
return linear ? 9987 : 9986;
|
||||
}
|
||||
|
||||
def wrap_code(how: wrap): u64 {
|
||||
return match how {
|
||||
repeat => 10497,
|
||||
clamp => 33071,
|
||||
mirror => 33648,
|
||||
};
|
||||
}
|
||||
|
||||
def write_textures(w: &mut json::writer, made: &asset): void {
|
||||
if made.textures.length != 0 {
|
||||
w.member("textures");
|
||||
w.begin_array();
|
||||
for i in 0..made.textures.length {
|
||||
val each := &made.textures[i];
|
||||
w.begin_object();
|
||||
put_text(w, "name", &each.name);
|
||||
put_index(w, "sampler", each.sampler);
|
||||
put_index(w, "source", each.source);
|
||||
w.end_object();
|
||||
}
|
||||
w.end_array();
|
||||
}
|
||||
return if made.samplers.length == 0;
|
||||
w.member("samplers");
|
||||
w.begin_array();
|
||||
for i in 0..made.samplers.length {
|
||||
val each := &made.samplers[i];
|
||||
w.begin_object();
|
||||
put_text(w, "name", &each.name);
|
||||
val mag := filter_code(each.mag_filter);
|
||||
if mag != 0 {
|
||||
put_count(w, "magFilter", mag);
|
||||
}
|
||||
val min := min_filter_code(each.min_filter, each.mip_filter);
|
||||
if min != 0 {
|
||||
put_count(w, "minFilter", min);
|
||||
}
|
||||
if each.wrap_s != wrap::repeat {
|
||||
put_count(w, "wrapS", wrap_code(each.wrap_s));
|
||||
}
|
||||
if each.wrap_t != wrap::repeat {
|
||||
put_count(w, "wrapT", wrap_code(each.wrap_t));
|
||||
}
|
||||
w.end_object();
|
||||
}
|
||||
w.end_array();
|
||||
}
|
||||
|
||||
def write_images(w: &mut json::writer, made: &asset): void {
|
||||
return if made.images.length == 0;
|
||||
w.member("images");
|
||||
w.begin_array();
|
||||
for i in 0..made.images.length {
|
||||
val each := &made.images[i];
|
||||
w.begin_object();
|
||||
put_text(w, "name", &each.name);
|
||||
if each.view is some(v) {
|
||||
put_count(w, "bufferView", v);
|
||||
w.member("mimeType");
|
||||
w.text(each.mime_type.length != 0 ? each.mime_type.span : mime_of(each.bytes.span));
|
||||
} else if names_file(each.uri.span) {
|
||||
w.member("uri");
|
||||
w.text(each.uri.span);
|
||||
put_text(w, "mimeType", &each.mime_type);
|
||||
} else {
|
||||
val mime := each.mime_type.length != 0 ? each.mime_type.span : mime_of(each.bytes.span);
|
||||
val uri := data_uri_of(mime, each.bytes.span);
|
||||
w.member("uri");
|
||||
w.text(uri.span);
|
||||
}
|
||||
w.end_object();
|
||||
}
|
||||
w.end_array();
|
||||
}
|
||||
|
||||
# glTF's code of the type of an accessor's numbers.
|
||||
def component_code(c: component): u64 {
|
||||
return match c {
|
||||
byte => 5120,
|
||||
unsigned_byte => 5121,
|
||||
short => 5122,
|
||||
unsigned_short => 5123,
|
||||
unsigned_int => 5125,
|
||||
float => 5126,
|
||||
};
|
||||
}
|
||||
|
||||
# glTF's name of what an accessor's elements are.
|
||||
def element_name(e: element): strview {
|
||||
return match e {
|
||||
scalar => "SCALAR",
|
||||
vec2 => "VEC2",
|
||||
vec3 => "VEC3",
|
||||
vec4 => "VEC4",
|
||||
mat2 => "MAT2",
|
||||
mat3 => "MAT3",
|
||||
mat4 => "MAT4",
|
||||
};
|
||||
}
|
||||
|
||||
# A member of an accessor's least or most, where it has them.
|
||||
def put_bounds(w: &mut json::writer, key: strview, values: &vector<f64>): void {
|
||||
return if values.length == 0;
|
||||
w.member(key);
|
||||
w.begin_array();
|
||||
for i in 0..values.length {
|
||||
put_real(w, values[i]);
|
||||
}
|
||||
w.end_array();
|
||||
}
|
||||
|
||||
def write_accessors(w: &mut json::writer, made: &asset): void {
|
||||
return if made.accessors.length == 0;
|
||||
w.member("accessors");
|
||||
w.begin_array();
|
||||
for i in 0..made.accessors.length {
|
||||
val each := &made.accessors[i];
|
||||
w.begin_object();
|
||||
put_text(w, "name", &each.name);
|
||||
put_index(w, "bufferView", each.view);
|
||||
if each.offset != 0 {
|
||||
put_count(w, "byteOffset", each.offset);
|
||||
}
|
||||
put_count(w, "componentType", component_code(each.component_type));
|
||||
if each.normalized {
|
||||
w.member("normalized");
|
||||
w.boolean(true);
|
||||
}
|
||||
put_count(w, "count", each.count);
|
||||
w.member("type");
|
||||
w.text(element_name(each.kind));
|
||||
put_bounds(w, "min", &each.min);
|
||||
put_bounds(w, "max", &each.max);
|
||||
if each.sparse is some(s) {
|
||||
w.member("sparse");
|
||||
w.begin_object();
|
||||
put_count(w, "count", s.count);
|
||||
w.member("indices");
|
||||
w.begin_object();
|
||||
put_count(w, "bufferView", s.indices_view);
|
||||
if s.indices_offset != 0 {
|
||||
put_count(w, "byteOffset", s.indices_offset);
|
||||
}
|
||||
put_count(w, "componentType", component_code(s.indices_type));
|
||||
w.end_object();
|
||||
w.member("values");
|
||||
w.begin_object();
|
||||
put_count(w, "bufferView", s.values_view);
|
||||
if s.values_offset != 0 {
|
||||
put_count(w, "byteOffset", s.values_offset);
|
||||
}
|
||||
w.end_object();
|
||||
w.end_object();
|
||||
}
|
||||
w.end_object();
|
||||
}
|
||||
w.end_array();
|
||||
}
|
||||
|
||||
def write_views(w: &mut json::writer, made: &asset): void {
|
||||
return if made.views.length == 0;
|
||||
w.member("bufferViews");
|
||||
w.begin_array();
|
||||
for i in 0..made.views.length {
|
||||
val each := &made.views[i];
|
||||
w.begin_object();
|
||||
put_text(w, "name", &each.name);
|
||||
put_count(w, "buffer", each.buffer);
|
||||
if each.offset != 0 {
|
||||
put_count(w, "byteOffset", each.offset);
|
||||
}
|
||||
put_count(w, "byteLength", each.length);
|
||||
if each.stride != 0 {
|
||||
put_count(w, "byteStride", each.stride);
|
||||
}
|
||||
w.end_object();
|
||||
}
|
||||
w.end_array();
|
||||
}
|
||||
|
||||
def write_buffers(w: &mut json::writer, made: &asset, chunked: bool): void {
|
||||
return if made.buffers.length == 0;
|
||||
w.member("buffers");
|
||||
w.begin_array();
|
||||
for i in 0..made.buffers.length {
|
||||
val each := &made.buffers[i];
|
||||
w.begin_object();
|
||||
put_text(w, "name", &each.name);
|
||||
put_count(w, "byteLength", each.bytes.length);
|
||||
if names_file(each.uri.span) {
|
||||
w.member("uri");
|
||||
w.text(each.uri.span);
|
||||
} else if !(chunked && i == 0) {
|
||||
val uri := data_uri_of("application/octet-stream", each.bytes.span);
|
||||
w.member("uri");
|
||||
w.text(uri.span);
|
||||
}
|
||||
w.end_object();
|
||||
}
|
||||
w.end_array();
|
||||
}
|
||||
|
||||
def write_cameras(w: &mut json::writer, made: &asset): void {
|
||||
return if made.cameras.length == 0;
|
||||
w.member("cameras");
|
||||
w.begin_array();
|
||||
for i in 0..made.cameras.length {
|
||||
val each := &made.cameras[i];
|
||||
w.begin_object();
|
||||
put_text(w, "name", &each.name);
|
||||
if each.kind == camera_kind::perspective {
|
||||
w.member("type");
|
||||
w.text("perspective");
|
||||
w.member("perspective");
|
||||
w.begin_object();
|
||||
w.member("yfov");
|
||||
put_float(w, each.fov_y);
|
||||
if each.aspect is some(aspect) {
|
||||
w.member("aspectRatio");
|
||||
put_float(w, aspect);
|
||||
}
|
||||
} else {
|
||||
w.member("type");
|
||||
w.text("orthographic");
|
||||
w.member("orthographic");
|
||||
w.begin_object();
|
||||
w.member("xmag");
|
||||
put_float(w, each.x_mag);
|
||||
w.member("ymag");
|
||||
put_float(w, each.y_mag);
|
||||
}
|
||||
w.member("znear");
|
||||
put_float(w, each.near);
|
||||
if each.far is some(far) {
|
||||
w.member("zfar");
|
||||
put_float(w, far);
|
||||
}
|
||||
w.end_object();
|
||||
w.end_object();
|
||||
}
|
||||
w.end_array();
|
||||
}
|
||||
|
||||
def write_skins(w: &mut json::writer, made: &asset): void {
|
||||
return if made.skins.length == 0;
|
||||
w.member("skins");
|
||||
w.begin_array();
|
||||
for i in 0..made.skins.length {
|
||||
val each := &made.skins[i];
|
||||
w.begin_object();
|
||||
put_text(w, "name", &each.name);
|
||||
put_indices(w, "joints", &each.joints);
|
||||
put_index(w, "inverseBindMatrices", each.inverse_binds);
|
||||
put_index(w, "skeleton", each.skeleton);
|
||||
w.end_object();
|
||||
}
|
||||
w.end_array();
|
||||
}
|
||||
|
||||
def write_animations(w: &mut json::writer, made: &asset): void {
|
||||
return if made.animations.length == 0;
|
||||
w.member("animations");
|
||||
w.begin_array();
|
||||
for i in 0..made.animations.length {
|
||||
val each := &made.animations[i];
|
||||
w.begin_object();
|
||||
put_text(w, "name", &each.name);
|
||||
w.member("samplers");
|
||||
w.begin_array();
|
||||
for k in 0..each.samplers.length {
|
||||
val keys := &each.samplers[k];
|
||||
w.begin_object();
|
||||
put_count(w, "input", keys.input);
|
||||
put_count(w, "output", keys.output);
|
||||
if keys.interpolation == interpolation::step {
|
||||
w.member("interpolation");
|
||||
w.text("STEP");
|
||||
} else if keys.interpolation == interpolation::cubic_spline {
|
||||
w.member("interpolation");
|
||||
w.text("CUBICSPLINE");
|
||||
}
|
||||
w.end_object();
|
||||
}
|
||||
w.end_array();
|
||||
w.member("channels");
|
||||
w.begin_array();
|
||||
for k in 0..each.channels.length {
|
||||
val moved := &each.channels[k];
|
||||
w.begin_object();
|
||||
put_count(w, "sampler", moved.sampler);
|
||||
w.member("target");
|
||||
w.begin_object();
|
||||
put_index(w, "node", moved.node);
|
||||
w.member("path");
|
||||
w.text(match moved.path {
|
||||
translation => "translation",
|
||||
rotation => "rotation",
|
||||
scale => "scale",
|
||||
weights => "weights",
|
||||
});
|
||||
w.end_object();
|
||||
w.end_object();
|
||||
}
|
||||
w.end_array();
|
||||
w.end_object();
|
||||
}
|
||||
w.end_array();
|
||||
}
|
||||
|
||||
def write_lights(w: &mut json::writer, made: &asset): void {
|
||||
w.member("lights");
|
||||
w.begin_array();
|
||||
for i in 0..made.lights.length {
|
||||
val each := &made.lights[i];
|
||||
w.begin_object();
|
||||
put_text(w, "name", &each.name);
|
||||
w.member("type");
|
||||
w.text(match each.kind {
|
||||
directional => "directional",
|
||||
point => "point",
|
||||
spot => "spot",
|
||||
});
|
||||
if each.color[0] != 1 || each.color[1] != 1 || each.color[2] != 1 {
|
||||
put_floats(w, "color", each.color[:]);
|
||||
}
|
||||
put_number(w, "intensity", each.intensity, 1);
|
||||
if each.range is some(far) {
|
||||
w.member("range");
|
||||
put_float(w, far);
|
||||
}
|
||||
if each.kind == light_kind::spot {
|
||||
w.member("spot");
|
||||
w.begin_object();
|
||||
put_number(w, "innerConeAngle", each.inner_cone, 0);
|
||||
put_number(w, "outerConeAngle", each.outer_cone, 0.7853982);
|
||||
w.end_object();
|
||||
}
|
||||
w.end_object();
|
||||
}
|
||||
w.end_array();
|
||||
}
|
||||
Reference in new issue
Block a user