Initial Commit
This commit is contained in:
36 files changed
+8436
No files matched your search
@@ -0,0 +1,148 @@
|
||||
#! Contains reading animations: a stack's time, a curve node's channels and the
|
||||
#! values they hold where no curve is given, and a curve's keys, each a time
|
||||
#! in FBX's ticks, 46,186,158,000 a second, read as seconds, and a value. How a
|
||||
#! key goes on to the next is given by attributes, each of flags and four
|
||||
#! numbers, a cubic's slopes first, each holding for as many keys in turn as
|
||||
#! its count says.
|
||||
|
||||
module malunal::fbx;
|
||||
|
||||
# Reads a stack: the time it spans.
|
||||
def scene::read_stack(&mut this, object: u32, id: i64, name: strview): u64 {
|
||||
var made := animation_stack{ id = id, name = string::from(name, nothing{}), node = object };
|
||||
made.start = this.number_of(object, "LocalStart", this.number_of(object, "ReferenceStart", 0)) / ticks_per_second;
|
||||
made.stop = this.number_of(object, "LocalStop", this.number_of(object, "ReferenceStop", 0)) / ticks_per_second;
|
||||
this.stacks.append(move(made));
|
||||
return this.stacks.length - 1;
|
||||
}
|
||||
|
||||
# Reads a curve node: a channel of each of its `d|` properties, of its value.
|
||||
def scene::read_curve_node(&mut this, object: u32, id: i64, name: strview): u64 {
|
||||
var made := curve_node{ id = id, name = string::from(name, nothing{}), node = object };
|
||||
if this.document.child(object, "Properties70") is some(properties) {
|
||||
val list := &this.document.nodes[properties as u64].children;
|
||||
for i in 0..list.length {
|
||||
val each := &this.document.nodes[list[i] as u64];
|
||||
continue if each.name.span != "P" || each.properties.length < 5;
|
||||
val named := each.properties[0].text();
|
||||
continue if !named.starts_with("d|");
|
||||
made.channels.append(curve_channel{ name = string::from(named.substr(2, named.length - 2), nothing{}), value = each.properties[4].number() as f32 });
|
||||
}
|
||||
}
|
||||
this.curve_nodes.append(move(made));
|
||||
return this.curve_nodes.length - 1;
|
||||
}
|
||||
|
||||
# Gives a curve node's channel of a connection's property, as `d|X`, its
|
||||
# curve, adding the channel where it hasn't one.
|
||||
def scene::attach_curve(&mut this, node: u64, curve: u32, property: strview): void {
|
||||
val name := property.starts_with("d|") ? property.substr(2, property.length - 2) : property;
|
||||
val value := this.curves[curve as u64].value;
|
||||
val held := &mut this.curve_nodes[node];
|
||||
for i in 0..held.channels.length {
|
||||
if held.channels[i].name.span == name {
|
||||
held.channels[i].curve = curve;
|
||||
return;
|
||||
}
|
||||
}
|
||||
held.channels.append(curve_channel{ name = string::from(name, nothing{}), value = value, curve = curve });
|
||||
}
|
||||
|
||||
# Reads a curve: its keys, and how each goes on to the next.
|
||||
def scene::read_curve(&mut this, object: u32, id: i64, name: strview): u64 {
|
||||
var made := curve{ id = id, name = string::from(name, nothing{}), node = object };
|
||||
made.value = this.document.number_of(object, "Default", 0) as f32;
|
||||
if this.document.child(object, "KeyTime") is some(times) {
|
||||
val values := this.document.integers(times);
|
||||
made.times.reserve(values.length);
|
||||
for i in 0..values.length {
|
||||
made.times.append(values[i] as f64 / ticks_per_second);
|
||||
}
|
||||
}
|
||||
if this.document.child(object, "KeyValueFloat") is some(values_node) {
|
||||
val values := this.document.reals(values_node);
|
||||
made.values.reserve(values.length);
|
||||
for i in 0..values.length {
|
||||
made.values.append(values[i] as f32);
|
||||
}
|
||||
}
|
||||
val keys := made.times.length < made.values.length ? made.times.length : made.values.length;
|
||||
var flags := vector::<i64>::new();
|
||||
var data := vector::<f64>::new();
|
||||
var counts := vector::<i64>::new();
|
||||
if this.document.child(object, "KeyAttrFlags") is some(found) {
|
||||
flags = this.document.integers(found);
|
||||
}
|
||||
if this.document.child(object, "KeyAttrDataFloat") is some(found) {
|
||||
data = this.document.reals(found);
|
||||
}
|
||||
if this.document.child(object, "KeyAttrRefCount") is some(found) {
|
||||
counts = this.document.integers(found);
|
||||
}
|
||||
var key: u64 = 0;
|
||||
for a in 0..flags.length {
|
||||
break if key >= keys;
|
||||
var held := keys - key;
|
||||
if a < counts.length && counts[a] >= 0 {
|
||||
held = counts[a] as u64;
|
||||
}
|
||||
val bits := flags[a];
|
||||
var how := key_interpolation::linear;
|
||||
if (bits & 0x2) != 0 {
|
||||
how = key_interpolation::constant;
|
||||
} else if (bits & 0x8) != 0 {
|
||||
how = key_interpolation::cubic;
|
||||
}
|
||||
val right: f32 = a * 4 + 1 < data.length ? data[a * 4] as f32 : 0;
|
||||
val next_left: f32 = a * 4 + 1 < data.length ? data[a * 4 + 1] as f32 : 0;
|
||||
var taken: u64 = 0;
|
||||
while taken < held && key < keys {
|
||||
made.interpolations.append(how);
|
||||
made.right_slopes.append(right);
|
||||
made.next_left_slopes.append(next_left);
|
||||
key++;
|
||||
taken++;
|
||||
}
|
||||
}
|
||||
while key < keys {
|
||||
made.interpolations.append(key_interpolation::linear);
|
||||
made.right_slopes.append(0);
|
||||
made.next_left_slopes.append(0);
|
||||
key++;
|
||||
}
|
||||
this.curves.append(move(made));
|
||||
return this.curves.length - 1;
|
||||
}
|
||||
|
||||
#! The value of a curve at a time: of its keys, held where they're constant,
|
||||
#! between them linearly, or along a cubic of their slopes; its first before
|
||||
#! its first key and its last after its last; its value where it has none.
|
||||
pub def curve::at(&this, time: f64): f32 {
|
||||
val keys := this.times.length < this.values.length ? this.times.length : this.values.length;
|
||||
return this.value if keys == 0;
|
||||
return this.values[0] if time <= this.times[0];
|
||||
return this.values[keys - 1] if time >= this.times[keys - 1];
|
||||
var k: u64 = 0;
|
||||
while k + 1 < keys && this.times[k + 1] <= time {
|
||||
k++;
|
||||
}
|
||||
val a := this.values[k];
|
||||
val b := this.values[k + 1];
|
||||
val span_of := this.times[k + 1] - this.times[k];
|
||||
return a if span_of <= 0;
|
||||
val t := ((time - this.times[k]) / span_of) as f32;
|
||||
val how := k < this.interpolations.length ? this.interpolations[k] : key_interpolation::linear;
|
||||
if how == key_interpolation::constant {
|
||||
return a;
|
||||
}
|
||||
if how == key_interpolation::cubic {
|
||||
# Hermite's, the slopes per second scaled to the span between the keys.
|
||||
val d := span_of as f32;
|
||||
val m0 := this.right_slopes[k] * d;
|
||||
val m1 := this.next_left_slopes[k] * d;
|
||||
val t2 := t * t;
|
||||
val t3 := t2 * t;
|
||||
return (2 * t3 - 3 * t2 + 1) * a + (t3 - 2 * t2 + t) * m0 + (-2 * t3 + 3 * t2) * b + (t3 - t2) * m1;
|
||||
}
|
||||
return a + (b - a) * t;
|
||||
}
|
||||
@@ -0,0 +1,253 @@
|
||||
#! Contains reading ASCII FBX: lines of `Name: property, property`, a node's
|
||||
#! children within `{` and `}` after its properties, comments from `;` to the
|
||||
#! line's end. A property is a number, text in quotes, a bare word, as `T`, or
|
||||
#! an array, `*count { a: number, number }`. Properties go on past a line's end
|
||||
#! after a comma. Numbers written with a point or an exponent are read as
|
||||
#! floats, others as integers, and an array of both as floats.
|
||||
|
||||
module malunal::fbx;
|
||||
|
||||
# Reads ASCII FBX's nodes.
|
||||
struct ascii_reader {
|
||||
var text: strview;
|
||||
var at: u64;
|
||||
var line: u64 = 1;
|
||||
}
|
||||
|
||||
# Reads ASCII FBX.
|
||||
def read_ascii(text: strview): result<document, fbx_error> {
|
||||
var made := document{ binary = false, version = 0 };
|
||||
var r := ascii_reader{ text = text };
|
||||
r.read_list(&mut made, absent) else (e) { return e; };
|
||||
if made.child(absent, "FBXHeaderExtension") is some(header) {
|
||||
if made.child(header, "FBXVersion") is some(version) && made.property(version, 0) is some(&given) {
|
||||
made.version = given.whole() as u32;
|
||||
}
|
||||
}
|
||||
return failed(failure::malformed, "It's neither binary FBX nor ASCII FBX of a header and objects.") if made.version == 0 && made.child(absent, "Objects") is none;
|
||||
return failed(failure::unsupported, $"It's FBX {made.version}, of before 7.0, which names its objects rather than numbering them.".span) if made.version != 0 && made.version < 7000;
|
||||
if made.version == 0 {
|
||||
made.version = 7400;
|
||||
}
|
||||
return made;
|
||||
}
|
||||
|
||||
# An error at the line it's reading.
|
||||
def ascii_reader::wrong(&this, why: strview): fbx_error {
|
||||
return failed(failure::malformed, $"line {this.line}: {why}".span);
|
||||
}
|
||||
|
||||
# Passes over spaces, lines' ends, and comments.
|
||||
def ascii_reader::skip_blank(&mut this): void {
|
||||
while this.at < this.text.length {
|
||||
val c := this.text[this.at];
|
||||
if c == '\n' {
|
||||
this.line++;
|
||||
} else if c == ';' {
|
||||
while this.at < this.text.length && this.text[this.at] != '\n' {
|
||||
this.at++;
|
||||
}
|
||||
continue;
|
||||
} else if c != ' ' && c != '\t' && c != '\r' {
|
||||
return;
|
||||
}
|
||||
this.at++;
|
||||
}
|
||||
}
|
||||
|
||||
# Passes over spaces, but not a line's end.
|
||||
def ascii_reader::skip_spaces(&mut this): void {
|
||||
while this.at < this.text.length && (this.text[this.at] == ' ' || this.text[this.at] == '\t' || this.text[this.at] == '\r') {
|
||||
this.at++;
|
||||
}
|
||||
}
|
||||
|
||||
# Reads nodes, beneath a parent, to the `}` closing it, or the text's end at the
|
||||
# root.
|
||||
def ascii_reader::read_list(&mut this, made: &mut document, parent: u32): result<void, fbx_error> {
|
||||
while true {
|
||||
this.skip_blank();
|
||||
if this.at >= this.text.length {
|
||||
return this.wrong("A `{` isn't closed.") if parent != absent;
|
||||
return;
|
||||
}
|
||||
if this.text[this.at] == '}' {
|
||||
return this.wrong("A `}` closes nothing.") if parent == absent;
|
||||
this.at++;
|
||||
return;
|
||||
}
|
||||
val begun := this.at;
|
||||
while this.at < this.text.length && this.text[this.at] != ':' && this.text[this.at] != '\n' && this.text[this.at] != '{' && this.text[this.at] != '}' {
|
||||
this.at++;
|
||||
}
|
||||
if this.at >= this.text.length || this.text[this.at] != ':' {
|
||||
return this.wrong("A node's name isn't followed by `:`.");
|
||||
}
|
||||
val name := trimmed(this.text.substr(begun, this.at - begun));
|
||||
this.at++;
|
||||
val index := made.add(parent, name);
|
||||
this.read_properties(made, index) else (e) { return e; };
|
||||
}
|
||||
return;
|
||||
}
|
||||
|
||||
# Reads a node's properties, to its line's end, and its children, where it has
|
||||
# them.
|
||||
def ascii_reader::read_properties(&mut this, made: &mut document, index: u32): result<void, fbx_error> {
|
||||
while true {
|
||||
this.skip_spaces();
|
||||
return if this.at >= this.text.length;
|
||||
val c := this.text[this.at];
|
||||
return if c == '\n' || c == '}';
|
||||
if c == ';' {
|
||||
while this.at < this.text.length && this.text[this.at] != '\n' {
|
||||
this.at++;
|
||||
}
|
||||
return;
|
||||
}
|
||||
if c == '{' {
|
||||
this.at++;
|
||||
return this.read_list(made, index);
|
||||
}
|
||||
if c == ',' {
|
||||
this.at++;
|
||||
this.skip_blank();
|
||||
continue;
|
||||
}
|
||||
if c == '*' {
|
||||
this.at++;
|
||||
var held := this.read_array() else (e) { return e; };
|
||||
made.nodes[index as u64].properties.append(move(held));
|
||||
continue;
|
||||
}
|
||||
if c == '"' {
|
||||
this.at++;
|
||||
val begun := this.at;
|
||||
while this.at < this.text.length && this.text[this.at] != '"' {
|
||||
if this.text[this.at] == '\n' {
|
||||
this.line++;
|
||||
}
|
||||
this.at++;
|
||||
}
|
||||
return this.wrong("Text isn't closed by `\"`.") if this.at >= this.text.length;
|
||||
var held := property{ kind = property_kind::text };
|
||||
held.bytes.extend(this.text.substr(begun, this.at - begun));
|
||||
this.at++;
|
||||
made.nodes[index as u64].properties.append(move(held));
|
||||
continue;
|
||||
}
|
||||
val word := this.read_word();
|
||||
return this.wrong($"`{c}` begins no property.".span) if word.length == 0;
|
||||
var held := word_property(word);
|
||||
made.nodes[index as u64].properties.append(move(held));
|
||||
}
|
||||
return;
|
||||
}
|
||||
|
||||
# Reads a word: a number, or a bare word, to the next comma, space, or brace.
|
||||
def ascii_reader::read_word(&mut this): strview {
|
||||
val begun := this.at;
|
||||
while this.at < this.text.length {
|
||||
val c := this.text[this.at];
|
||||
break if c == ',' || c == ' ' || c == '\t' || c == '\r' || c == '\n' || c == '{' || c == '}' || c == ';';
|
||||
this.at++;
|
||||
}
|
||||
return this.text.substr(begun, this.at - begun);
|
||||
}
|
||||
|
||||
# A word as a property: an integer, a float, or text.
|
||||
def word_property(word: strview): property {
|
||||
if is_whole(word) && integer::parse::<i64>(word) is value(n) {
|
||||
return property{ kind = property_kind::int64, integer = n };
|
||||
}
|
||||
if real::parse::<f64>(word) is value(x) {
|
||||
return property{ kind = property_kind::float64, real = x };
|
||||
}
|
||||
var made := property{ kind = property_kind::text };
|
||||
made.bytes.extend(word);
|
||||
return made;
|
||||
}
|
||||
|
||||
# Whether a word is written as a whole number: digits, after a sign.
|
||||
def is_whole(word: strview): bool {
|
||||
return false if word.length == 0;
|
||||
var from: u64 = word[0] == '-' || word[0] == '+' ? 1 : 0;
|
||||
return false if from >= word.length;
|
||||
for i in from..word.length {
|
||||
return false if word[i] < '0' || word[i] > '9';
|
||||
}
|
||||
return true;
|
||||
}
|
||||
|
||||
# Reads an array, after its `*`: its count, then `{ a: ` and its numbers, to
|
||||
# its `}`.
|
||||
def ascii_reader::read_array(&mut this): result<property, fbx_error> {
|
||||
val count_word := this.read_word();
|
||||
val count := integer::parse::<i64>(count_word) else (_) { return this.wrong($"`*{count_word}` isn't an array's count.".span); };
|
||||
this.skip_blank();
|
||||
return this.wrong("An array's count isn't followed by `{`.") if this.at >= this.text.length || this.text[this.at] != '{';
|
||||
this.at++;
|
||||
this.skip_blank();
|
||||
if this.at < this.text.length && this.text[this.at] == 'a' {
|
||||
this.at++;
|
||||
this.skip_spaces();
|
||||
return this.wrong("An array's `a` isn't followed by `:`.") if this.at >= this.text.length || this.text[this.at] != ':';
|
||||
this.at++;
|
||||
}
|
||||
var integers := vector::<i64>::new();
|
||||
var reals := vector::<f64>::new();
|
||||
var floating := false;
|
||||
while true {
|
||||
this.skip_blank();
|
||||
return this.wrong("An array isn't closed by `}`.") if this.at >= this.text.length;
|
||||
val c := this.text[this.at];
|
||||
if c == '}' {
|
||||
this.at++;
|
||||
break;
|
||||
}
|
||||
if c == ',' {
|
||||
this.at++;
|
||||
continue;
|
||||
}
|
||||
val word := this.read_word();
|
||||
return this.wrong($"`{c}` isn't a number of an array.".span) if word.length == 0;
|
||||
if !floating && is_whole(word) {
|
||||
val n := integer::parse::<i64>(word) else (_) { return this.wrong($"`{word}` isn't a number.".span); };
|
||||
integers.append(n);
|
||||
continue;
|
||||
}
|
||||
val x := real::parse::<f64>(word) else (_) { return this.wrong($"`{word}` isn't a number.".span); };
|
||||
if !floating {
|
||||
floating = true;
|
||||
for i in 0..integers.length {
|
||||
reals.append(integers[i] as f64);
|
||||
}
|
||||
integers.clear();
|
||||
}
|
||||
reals.append(x);
|
||||
}
|
||||
val read := floating ? reals.length : integers.length;
|
||||
return this.wrong($"An array says it holds {count} numbers, but holds {read}.".span) if read != count as u64;
|
||||
var made := property{};
|
||||
if floating {
|
||||
made.kind = property_kind::float64s;
|
||||
made.reals = move(reals);
|
||||
} else {
|
||||
made.kind = property_kind::int64s;
|
||||
made.integers = move(integers);
|
||||
}
|
||||
return made;
|
||||
}
|
||||
|
||||
# Text with the spaces about it taken away.
|
||||
def trimmed(text: strview): strview {
|
||||
var first: u64 = 0;
|
||||
var end := text.length;
|
||||
while first < end && (text[first] == ' ' || text[first] == '\t' || text[first] == '\r' || text[first] == '\n') {
|
||||
first++;
|
||||
}
|
||||
while end > first && (text[end - 1] == ' ' || text[end - 1] == '\t' || text[end - 1] == '\r' || text[end - 1] == '\n') {
|
||||
end--;
|
||||
}
|
||||
return text.substr(first, end - first);
|
||||
}
|
||||
@@ -0,0 +1,199 @@
|
||||
#! Contains reading binary FBX: a header and its version, then the nodes at the
|
||||
#! root, each its end, how many properties it has and how long they are, its
|
||||
#! name, its properties, and its children, ended by a record of zeros. From
|
||||
#! 7.5, the first three are 64 bits wide, not 32. An array's elements may be
|
||||
#! compressed by zlib, which `inflate` undoes.
|
||||
|
||||
import std::math;
|
||||
module malunal::fbx;
|
||||
|
||||
# The bytes binary FBX begins with, before its version.
|
||||
const binary_magic: strview = "Kaydara FBX Binary ";
|
||||
|
||||
# Whether bytes are of binary FBX.
|
||||
def is_binary(bytes: span<u8>): bool {
|
||||
return false if bytes.length < 27;
|
||||
for i in 0..18u {
|
||||
return false if bytes[i] != binary_magic[i];
|
||||
}
|
||||
return true;
|
||||
}
|
||||
|
||||
# A little-endian number of bytes, at a place.
|
||||
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);
|
||||
}
|
||||
|
||||
def long_at(bytes: span<u8>, at: u64): u64 {
|
||||
return word_at(bytes, at) as u64 | ((word_at(bytes, at + 4) as u64) << 32);
|
||||
}
|
||||
|
||||
# Reads binary FBX's nodes.
|
||||
struct binary_reader {
|
||||
var bytes: span<u8>;
|
||||
var at: u64;
|
||||
#! Whether a node's end and counts are 64 bits wide, as from 7.5.
|
||||
var wide: bool;
|
||||
}
|
||||
|
||||
# Reads binary FBX.
|
||||
def read_binary(bytes: span<u8>): result<document, fbx_error> {
|
||||
var made := document{ binary = true };
|
||||
made.version = word_at(bytes, 23);
|
||||
return failed(failure::unsupported, $"It's FBX {made.version}, of before 7.0, which names its objects rather than numbering them.".span) if made.version < 7000;
|
||||
var r := binary_reader{ bytes = bytes, at = 27, wide = made.version >= 7500 };
|
||||
while r.at < bytes.length {
|
||||
val more := r.read_node(&mut made, absent) else (e) { return e; };
|
||||
break if !more;
|
||||
}
|
||||
return made;
|
||||
}
|
||||
|
||||
# Whether as many bytes are left, from where it's reading.
|
||||
def binary_reader::holds(&this, count: u64): bool {
|
||||
return this.at <= this.bytes.length && count <= this.bytes.length - this.at;
|
||||
}
|
||||
|
||||
def binary_reader::byte(&mut this): u8 {
|
||||
val made := this.bytes[this.at];
|
||||
this.at++;
|
||||
return made;
|
||||
}
|
||||
|
||||
def binary_reader::word(&mut this): u32 {
|
||||
val made := word_at(this.bytes, this.at);
|
||||
this.at += 4;
|
||||
return made;
|
||||
}
|
||||
|
||||
def binary_reader::long(&mut this): u64 {
|
||||
val made := long_at(this.bytes, this.at);
|
||||
this.at += 8;
|
||||
return made;
|
||||
}
|
||||
|
||||
# Reads a node and its children, beneath a parent.
|
||||
# @returns Whether it was one, rather than the record of zeros ending a list.
|
||||
def binary_reader::read_node(&mut this, made: &mut document, parent: u32): result<bool, fbx_error> {
|
||||
val header: u64 = this.wide ? 25 : 13;
|
||||
if !this.holds(header) {
|
||||
# A list at the root may end with the file, before its record of zeros.
|
||||
return false if parent == absent;
|
||||
return failed(failure::malformed, $"A node's header at byte {this.at} is past the file's end.".span);
|
||||
}
|
||||
val begun := this.at;
|
||||
val end := this.wide ? this.long() : this.word() as u64;
|
||||
val count := this.wide ? this.long() : this.word() as u64;
|
||||
val length := this.wide ? this.long() : this.word() as u64;
|
||||
val name_length := this.byte() as u64;
|
||||
return false if end == 0;
|
||||
if end <= begun || end > this.bytes.length || !this.holds(name_length) {
|
||||
return failed(failure::malformed, $"The node at byte {begun} ends past the file's end, or before it begins.".span);
|
||||
}
|
||||
val name := strview::over(this.bytes.data + this.at, name_length);
|
||||
this.at += name_length;
|
||||
val index := made.add(parent, name);
|
||||
val properties_end := this.at + length;
|
||||
if properties_end > end {
|
||||
return failed(failure::malformed, $"{name}: its properties run past its end.".span);
|
||||
}
|
||||
made.nodes[index as u64].properties.reserve(count);
|
||||
for _ in 0..count {
|
||||
var held := this.read_property(name) else (e) { return e; };
|
||||
made.nodes[index as u64].properties.append(move(held));
|
||||
}
|
||||
if this.at != properties_end {
|
||||
return failed(failure::malformed, $"{name}: its properties aren't as long as it says.".span);
|
||||
}
|
||||
while this.at < end {
|
||||
val more := this.read_node(made, index) else (e) { return e; };
|
||||
break if !more;
|
||||
}
|
||||
this.at = end;
|
||||
return true;
|
||||
}
|
||||
|
||||
# Reads a property: its type's letter, then its value.
|
||||
def binary_reader::read_property(&mut this, name: strview): result<property, fbx_error> {
|
||||
return failed(failure::malformed, $"{name}: a property is past the file's end.".span) if !this.holds(1);
|
||||
val code := this.byte();
|
||||
var made := property{};
|
||||
if code == 'C' || code == 'Y' || code == 'I' || code == 'L' || code == 'F' || code == 'D' {
|
||||
val size: u64 = code == 'C' ? 1 : (code == 'Y' ? 2 : (code == 'I' || code == 'F' ? 4 : 8));
|
||||
return failed(failure::malformed, $"{name}: a property is past the file's end.".span) if !this.holds(size);
|
||||
if code == 'C' {
|
||||
made.kind = property_kind::boolean;
|
||||
made.integer = this.byte() as i64;
|
||||
} else if code == 'Y' {
|
||||
made.kind = property_kind::int16;
|
||||
val low := this.byte() as u16;
|
||||
val high := this.byte() as u16;
|
||||
made.integer = (low | (high << 8)) as i16 as i64;
|
||||
} else if code == 'I' {
|
||||
made.kind = property_kind::int32;
|
||||
made.integer = this.word() as i32 as i64;
|
||||
} else if code == 'L' {
|
||||
made.kind = property_kind::int64;
|
||||
made.integer = this.long() as i64;
|
||||
} else if code == 'F' {
|
||||
made.kind = property_kind::float32;
|
||||
made.real = math::real_of_bits(this.word()) as f64;
|
||||
} else {
|
||||
made.kind = property_kind::float64;
|
||||
made.real = math::real_of_bits(this.long());
|
||||
}
|
||||
return made;
|
||||
}
|
||||
if code == 'S' || code == 'R' {
|
||||
return failed(failure::malformed, $"{name}: a property is past the file's end.".span) if !this.holds(4);
|
||||
val length := this.word() as u64;
|
||||
return failed(failure::malformed, $"{name}: its text runs past the file's end.".span) if !this.holds(length);
|
||||
made.kind = code == 'S' ? property_kind::text : property_kind::raw;
|
||||
made.bytes.extend(span::<u8>::over(this.bytes.data + this.at, length));
|
||||
this.at += length;
|
||||
return made;
|
||||
}
|
||||
if code == 'b' || code == 'i' || code == 'l' || code == 'f' || code == 'd' {
|
||||
return failed(failure::malformed, $"{name}: a property is past the file's end.".span) if !this.holds(12);
|
||||
val count := this.word() as u64;
|
||||
val encoding := this.word();
|
||||
val stored := this.word() as u64;
|
||||
return failed(failure::malformed, $"{name}: an array runs past the file's end.".span) if !this.holds(stored);
|
||||
val size: u64 = code == 'b' ? 1 : (code == 'i' || code == 'f' ? 4 : 8);
|
||||
val data := span::<u8>::over(this.bytes.data + this.at, stored);
|
||||
this.at += stored;
|
||||
var inflated := vector::<u8>::new();
|
||||
var raw := data;
|
||||
if encoding == 1 {
|
||||
inflated.resize(count * size);
|
||||
val length := inflate(data, inflated.slice) else { return failed(failure::malformed, $"{name}: an array's data won't inflate.".span); };
|
||||
return failed(failure::malformed, $"{name}: an array's data inflates to {length} bytes, not {count * size}.".span) if length != count * size;
|
||||
raw = inflated.span;
|
||||
} else if encoding != 0 {
|
||||
return failed(failure::malformed, $"{name}: an array's encoding is {encoding}, of 0 and 1.".span);
|
||||
} else if stored != count * size {
|
||||
return failed(failure::malformed, $"{name}: an array is {stored} bytes, not {count * size}.".span);
|
||||
}
|
||||
if code == 'f' || code == 'd' {
|
||||
made.kind = code == 'f' ? property_kind::float32s : property_kind::float64s;
|
||||
made.reals.resize(count);
|
||||
for i in 0..count {
|
||||
made.reals[i] = code == 'f' ? math::real_of_bits(word_at(raw, i * 4)) as f64 : math::real_of_bits(long_at(raw, i * 8));
|
||||
}
|
||||
} else {
|
||||
made.kind = code == 'b' ? property_kind::booleans : (code == 'i' ? property_kind::int32s : property_kind::int64s);
|
||||
made.integers.resize(count);
|
||||
for i in 0..count {
|
||||
if code == 'b' {
|
||||
made.integers[i] = raw[i] as i64;
|
||||
} else if code == 'i' {
|
||||
made.integers[i] = word_at(raw, i * 4) as i32 as i64;
|
||||
} else {
|
||||
made.integers[i] = long_at(raw, i * 8) as i64;
|
||||
}
|
||||
}
|
||||
}
|
||||
return made;
|
||||
}
|
||||
return failed(failure::malformed, $"{name}: a property is of type `{code}`, which isn't FBX's.".span);
|
||||
}
|
||||
+253
@@ -0,0 +1,253 @@
|
||||
#! Contains `document`, an FBX file as it's written: a tree of nodes, each a
|
||||
#! name and properties, numbers, text, bytes, or arrays of numbers; why one
|
||||
#! couldn't be read; and reading one, binary or ASCII, from a file or from
|
||||
#! bytes.
|
||||
#!
|
||||
#! FBX is Autodesk's, and undocumented: what's read here is what Blender's
|
||||
#! importer and others have found it to be. A binary file is a header, then
|
||||
#! nodes, each its end, its properties, and its children; arrays may be
|
||||
#! compressed by zlib. An ASCII file is the same tree written as text, as
|
||||
#! `Name: 1, "text" { ... }`. Either is read into the same `document`, whose
|
||||
#! nodes are kept in one list, by index, each with its parent and children.
|
||||
#! `scene::of` reads what a document's nodes mean: models, meshes, materials,
|
||||
#! skins, and animations.
|
||||
|
||||
import std::io;
|
||||
module malunal::fbx;
|
||||
|
||||
#! What kind of thing kept a file from being read or written.
|
||||
pub enum failure: u8 {
|
||||
unreadable, #! A file couldn't be read, or written.
|
||||
malformed, #! The data breaks FBX: a node past the file's end, a property of an unknown type, compressed data that won't inflate, text that isn't of nodes.
|
||||
unsupported, #! It's well formed, but of what isn't read: an FBX older than 7.0, whose objects are named rather than numbered.
|
||||
}
|
||||
|
||||
#! Why a file couldn't be read, or written: the kind of thing, and what, as
|
||||
#! `Objects/Geometry: an array's data won't inflate`. It holds its text itself,
|
||||
#! its first 240 bytes, so it's plain data, as std's errors are.
|
||||
pub struct fbx_error {
|
||||
pub var kind: failure;
|
||||
var text: u8[240];
|
||||
var length: u64;
|
||||
}
|
||||
|
||||
#! What was wrong, and where.
|
||||
pub def fbx_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): fbx_error {
|
||||
var made := fbx_error{ kind = kind };
|
||||
made.length = why.length < 240 ? why.length : 240;
|
||||
for i in 0..made.length {
|
||||
made.text[i] = why[i];
|
||||
}
|
||||
return made;
|
||||
}
|
||||
|
||||
#! What an index names where it names nothing: a node's parent at the root,
|
||||
#! or a model's mesh where it has none.
|
||||
pub const absent: u32 = 0xFFFFFFFF;
|
||||
|
||||
#! The type of a property's value, by the letter binary FBX gives it.
|
||||
pub enum property_kind: u8 {
|
||||
boolean, #! `C`, a byte: 0 or 1, or a letter, as `T` or `Y`.
|
||||
int16, #! `Y`
|
||||
int32, #! `I`
|
||||
int64, #! `L`
|
||||
float32, #! `F`
|
||||
float64, #! `D`
|
||||
text, #! `S`
|
||||
raw, #! `R`, bytes, as an embedded file's.
|
||||
booleans, #! `b`, an array, as are those after it.
|
||||
int32s, #! `i`
|
||||
int64s, #! `l`
|
||||
float32s, #! `f`
|
||||
float64s, #! `d`
|
||||
}
|
||||
|
||||
#! A property of a node: a number, text, bytes, or an array of numbers, each
|
||||
#! held as the widest of its kind.
|
||||
pub struct property {
|
||||
pub var kind: property_kind;
|
||||
#! A boolean's, or an integer's.
|
||||
pub var integer: i64;
|
||||
#! A float's.
|
||||
pub var real: f64;
|
||||
#! Text's, or raw bytes.
|
||||
pub var bytes: vector<u8>;
|
||||
#! An array of booleans' or integers'.
|
||||
pub var integers: vector<i64>;
|
||||
#! An array of floats'.
|
||||
pub var reals: vector<f64>;
|
||||
}
|
||||
|
||||
#! Whether it's an array.
|
||||
pub def property::is_array(&this): bool {
|
||||
return this.kind as u8 >= property_kind::booleans as u8;
|
||||
}
|
||||
|
||||
#! It as a number: a float's, or an integer's, or 0 of text, bytes, or an
|
||||
#! array.
|
||||
pub def property::number(&this): f64 {
|
||||
if this.kind == property_kind::float32 || this.kind == property_kind::float64 {
|
||||
return this.real;
|
||||
}
|
||||
return this.is_array() || this.kind == property_kind::text || this.kind == property_kind::raw ? 0 : this.integer as f64;
|
||||
}
|
||||
|
||||
#! It as a whole number: an integer's, or a float's, cut.
|
||||
pub def property::whole(&this): i64 {
|
||||
if this.kind == property_kind::float32 || this.kind == property_kind::float64 {
|
||||
return this.real as i64;
|
||||
}
|
||||
return this.integer;
|
||||
}
|
||||
|
||||
#! Its text, or its bytes as text; empty of a number.
|
||||
pub def property::text(&this): strview {
|
||||
return strview::over(this.bytes.data, this.bytes.length);
|
||||
}
|
||||
|
||||
#! How many numbers its array holds.
|
||||
pub def property::count(&this): u64 {
|
||||
return this.kind == property_kind::float32s || this.kind == property_kind::float64s ? this.reals.length : this.integers.length;
|
||||
}
|
||||
|
||||
#! A number of its array, as a float, whichever its kind.
|
||||
pub def property::real_at(&this, at: u64): f64 {
|
||||
if this.kind == property_kind::float32s || this.kind == property_kind::float64s {
|
||||
return this.reals[at];
|
||||
}
|
||||
return this.integers[at] as f64;
|
||||
}
|
||||
|
||||
#! A number of its array, as an integer, whichever its kind.
|
||||
pub def property::integer_at(&this, at: u64): i64 {
|
||||
if this.kind == property_kind::float32s || this.kind == property_kind::float64s {
|
||||
return this.reals[at] as i64;
|
||||
}
|
||||
return this.integers[at];
|
||||
}
|
||||
|
||||
#! A node of the tree: its name, its properties, and its children and parent,
|
||||
#! by their indices in the document's nodes.
|
||||
pub struct node {
|
||||
pub var name: string;
|
||||
pub var properties: vector<property>;
|
||||
pub var children: vector<u32>;
|
||||
pub var parent: u32 = absent;
|
||||
}
|
||||
|
||||
#! An FBX file as it's written: its version, as 7400 for 7.4, whether it was
|
||||
#! binary, and its tree of nodes, all of them in one list, those at the root
|
||||
#! named in `roots`.
|
||||
pub struct document {
|
||||
pub var version: u32 = 7400;
|
||||
pub var binary: bool = true;
|
||||
pub var nodes: vector<node>;
|
||||
pub var roots: vector<u32>;
|
||||
}
|
||||
|
||||
#! Adds a node, after its parent's other children.
|
||||
#! @param parent Its parent, or `absent` at the root.
|
||||
#! @param name Its name.
|
||||
#! @returns Its index.
|
||||
pub def document::add(&mut this, parent: u32, name: strview): u32 {
|
||||
val index := this.nodes.length as u32;
|
||||
this.nodes.append(node{ name = string::from(name, nothing{}), parent = parent });
|
||||
if parent == absent {
|
||||
this.roots.append(index);
|
||||
} else {
|
||||
this.nodes[parent as u64].children.append(index);
|
||||
}
|
||||
return index;
|
||||
}
|
||||
|
||||
#! The first child of a node of a name, or of the root where it's `absent`.
|
||||
pub def document::child(&this, of: u32, name: strview): maybe<u32> {
|
||||
val list := of == absent ? this.roots.span : this.nodes[of as u64].children.span;
|
||||
for i in 0..list.length {
|
||||
return list[i] if this.nodes[list[i] as u64].name.span == name;
|
||||
}
|
||||
return nothing{};
|
||||
}
|
||||
|
||||
#! The children of a node of a name, or of the root where it's `absent`.
|
||||
pub def document::children_named(&this, of: u32, name: strview): vector<u32> {
|
||||
var made := vector::<u32>::new();
|
||||
val list := of == absent ? this.roots.span : this.nodes[of as u64].children.span;
|
||||
for i in 0..list.length {
|
||||
if this.nodes[list[i] as u64].name.span == name {
|
||||
made.append(list[i]);
|
||||
}
|
||||
}
|
||||
return made;
|
||||
}
|
||||
|
||||
#! A property of a node, where it has that many.
|
||||
pub def document::property(&this, of: u32, which: u64): maybe<&property> {
|
||||
val held := &this.nodes[of as u64];
|
||||
return nothing{} if which >= held.properties.length;
|
||||
return &held.properties[which];
|
||||
}
|
||||
|
||||
#! The numbers of a node: its first property's, where that's an array, or its
|
||||
#! properties' in turn, as an ASCII file before 7.0 writes them, as floats.
|
||||
pub def document::reals(&this, of: u32): vector<f64> {
|
||||
var made := vector::<f64>::new();
|
||||
val held := &this.nodes[of as u64];
|
||||
if held.properties.length != 0 && held.properties[0].is_array() {
|
||||
val first := &held.properties[0];
|
||||
made.reserve(first.count());
|
||||
for i in 0..first.count() {
|
||||
made.append(first.real_at(i));
|
||||
}
|
||||
return made;
|
||||
}
|
||||
for i in 0..held.properties.length {
|
||||
made.append(held.properties[i].number());
|
||||
}
|
||||
return made;
|
||||
}
|
||||
|
||||
#! The numbers of a node, as `reals` gives them, as integers.
|
||||
pub def document::integers(&this, of: u32): vector<i64> {
|
||||
var made := vector::<i64>::new();
|
||||
val held := &this.nodes[of as u64];
|
||||
if held.properties.length != 0 && held.properties[0].is_array() {
|
||||
val first := &held.properties[0];
|
||||
made.reserve(first.count());
|
||||
for i in 0..first.count() {
|
||||
made.append(first.integer_at(i));
|
||||
}
|
||||
return made;
|
||||
}
|
||||
for i in 0..held.properties.length {
|
||||
made.append(held.properties[i].whole());
|
||||
}
|
||||
return made;
|
||||
}
|
||||
|
||||
#! Reads a document from a file: binary or ASCII, whichever its first bytes
|
||||
#! say.
|
||||
#! @param at The file's path.
|
||||
#! @returns The document, or why it couldn't be read.
|
||||
pub def load(at: &path): result<document, fbx_error> {
|
||||
val bytes := io::read_file(at) else (_) { return failed(failure::unreadable, $"{at.span} couldn't be read.".span); };
|
||||
return decode(bytes.span);
|
||||
}
|
||||
|
||||
#! Reads a document from a file named by text, as `load` does.
|
||||
pub def load(at: strview): result<document, fbx_error> {
|
||||
val named := path::parse(at) else (_) { return failed(failure::unreadable, $"{at} isn't a path.".span); };
|
||||
return load(&named);
|
||||
}
|
||||
|
||||
#! Reads a document from bytes: a binary file's, which begin
|
||||
#! `Kaydara FBX Binary`, or else an ASCII file's text.
|
||||
pub def decode(bytes: span<u8>): result<document, fbx_error> {
|
||||
return read_binary(bytes) if is_binary(bytes);
|
||||
return read_ascii(strview::over(bytes.data, bytes.length));
|
||||
}
|
||||
@@ -0,0 +1,168 @@
|
||||
#! Contains reading a mesh's geometry: its points, `Vertices`; its polygons,
|
||||
#! `PolygonVertexIndex`, the last corner of each written as its point's bits
|
||||
#! turned over, so negative; and its layers, normals, places on textures,
|
||||
#! colors, and materials, each given by polygon corner, by point, by polygon,
|
||||
#! or once for all, directly or through indices, spread here to one for each
|
||||
#! corner, or each polygon of materials. And a blend shape's shapes: the
|
||||
#! points they move and how far.
|
||||
|
||||
import malunal::linear;
|
||||
module malunal::fbx;
|
||||
|
||||
# Reads a mesh.
|
||||
def scene::read_mesh(&mut this, object: u32, id: i64, name: strview): result<u64, fbx_error> {
|
||||
var made := mesh{ id = id, name = string::from(name, nothing{}), node = object };
|
||||
if this.document.child(object, "Vertices") is some(vertices) {
|
||||
val values := this.document.reals(vertices);
|
||||
made.positions.reserve(values.length / 3);
|
||||
for i in 0..values.length / 3 {
|
||||
made.positions.append(vec3{ values[i * 3] as f32, values[i * 3 + 1] as f32, values[i * 3 + 2] as f32 });
|
||||
}
|
||||
}
|
||||
if this.document.child(object, "PolygonVertexIndex") is some(indices) {
|
||||
val values := this.document.integers(indices);
|
||||
made.corners.reserve(values.length);
|
||||
var first: u64 = 0;
|
||||
for i in 0..values.length {
|
||||
var point := values[i];
|
||||
val ends := point < 0;
|
||||
if ends {
|
||||
point = -point - 1;
|
||||
}
|
||||
if point as u64 >= made.positions.length {
|
||||
return failed(failure::malformed, $"{name}: a polygon names point {point}, of the {made.positions.length} it has.".span);
|
||||
}
|
||||
made.corners.append(point as u32);
|
||||
if ends {
|
||||
made.polygons.append(polygon{ first = first, count = (i + 1 - first) as u32 });
|
||||
first = i + 1;
|
||||
}
|
||||
}
|
||||
if first < values.length {
|
||||
made.polygons.append(polygon{ first = first, count = (values.length - first) as u32 });
|
||||
}
|
||||
}
|
||||
# The polygon of each corner, which layers given by polygon need.
|
||||
var polygon_of := vector::<u32>::new();
|
||||
polygon_of.reserve(made.corners.length);
|
||||
for p in 0..made.polygons.length {
|
||||
for _ in 0..made.polygons[p].count as u64 {
|
||||
polygon_of.append(p as u32);
|
||||
}
|
||||
}
|
||||
val count := this.document.nodes[object as u64].children.length;
|
||||
for i in 0..count {
|
||||
val layer := this.document.nodes[object as u64].children[i];
|
||||
var kind := string::from(this.document.nodes[layer as u64].name.span, nothing{});
|
||||
if kind.span == "LayerElementNormal" && made.normals.length == 0 {
|
||||
val values := this.layer_values(layer, "Normals", "NormalsIndex", 3, &made.corners, &polygon_of);
|
||||
for c in 0..values.length / 3 {
|
||||
made.normals.append(vec3{ values[c * 3] as f32, values[c * 3 + 1] as f32, values[c * 3 + 2] as f32 });
|
||||
}
|
||||
} else if kind.span == "LayerElementUV" {
|
||||
val values := this.layer_values(layer, "UV", "UVIndex", 2, &made.corners, &polygon_of);
|
||||
continue if values.length == 0 && made.corners.length != 0;
|
||||
var set := uv_set{ name = string::from(this.document.text_of(layer, "Name"), nothing{}) };
|
||||
set.uvs.reserve(values.length / 2);
|
||||
for c in 0..values.length / 2 {
|
||||
set.uvs.append(vec2{ values[c * 2] as f32, values[c * 2 + 1] as f32 });
|
||||
}
|
||||
made.uv_sets.append(move(set));
|
||||
} else if kind.span == "LayerElementColor" && made.colors.length == 0 {
|
||||
val values := this.layer_values(layer, "Colors", "ColorIndex", 4, &made.corners, &polygon_of);
|
||||
for c in 0..values.length / 4 {
|
||||
made.colors.append(vec4{ values[c * 4] as f32, values[c * 4 + 1] as f32, values[c * 4 + 2] as f32, values[c * 4 + 3] as f32 });
|
||||
}
|
||||
} else if kind.span == "LayerElementMaterial" && made.materials.length == 0 {
|
||||
made.materials = this.layer_materials(layer, made.polygons.length);
|
||||
}
|
||||
}
|
||||
this.meshes.append(move(made));
|
||||
return this.meshes.length - 1;
|
||||
}
|
||||
|
||||
# A layer's values, one for each corner, `width` numbers each: by how it maps
|
||||
# them, `MappingInformationType`, and whether through indices,
|
||||
# `ReferenceInformationType`. A corner whose index names nothing is zeros. It's
|
||||
# empty where the layer maps them by edge, which isn't read.
|
||||
def scene::layer_values(&this, layer: u32, data_name: strview, index_name: strview, width: u64, corners: &vector<u32>, polygon_of: &vector<u32>): vector<f64> {
|
||||
var made := vector::<f64>::new();
|
||||
val data_node := this.document.child(layer, data_name) else { return made; };
|
||||
val data := this.document.reals(data_node);
|
||||
val mapping := this.document.text_of(layer, "MappingInformationType");
|
||||
val reference := this.document.text_of(layer, "ReferenceInformationType");
|
||||
val indexed := reference == "IndexToDirect" || reference == "Index";
|
||||
var indices := vector::<i64>::new();
|
||||
if indexed {
|
||||
if this.document.child(layer, index_name) is some(found) {
|
||||
indices = this.document.integers(found);
|
||||
}
|
||||
}
|
||||
val by_corner := mapping == "ByPolygonVertex";
|
||||
val by_point := mapping == "ByVertice" || mapping == "ByVertex" || mapping == "ByControlPoint";
|
||||
val by_polygon := mapping == "ByPolygon";
|
||||
val all_same := mapping == "AllSame";
|
||||
return made if !(by_corner || by_point || by_polygon || all_same);
|
||||
val count := data.length / width;
|
||||
made.resize(corners.length * width, 0);
|
||||
for c in 0..corners.length {
|
||||
var element: u64 = 0;
|
||||
if by_corner {
|
||||
element = c;
|
||||
} else if by_point {
|
||||
element = corners[c] as u64;
|
||||
} else if by_polygon {
|
||||
element = polygon_of[c] as u64;
|
||||
}
|
||||
var value := element;
|
||||
if indexed {
|
||||
continue if element >= indices.length || indices[element] < 0;
|
||||
value = indices[element] as u64;
|
||||
}
|
||||
continue if value >= count;
|
||||
for k in 0..width {
|
||||
made[c * width + k] = data[value * width + k];
|
||||
}
|
||||
}
|
||||
return made;
|
||||
}
|
||||
|
||||
# A layer's materials, one for each polygon, by polygon or once for all.
|
||||
def scene::layer_materials(&this, layer: u32, polygons: u64): vector<u32> {
|
||||
var made := vector::<u32>::new();
|
||||
val data_node := this.document.child(layer, "Materials") else { return made; };
|
||||
val values := this.document.integers(data_node);
|
||||
return made if values.length == 0;
|
||||
val all_same := this.document.text_of(layer, "MappingInformationType") == "AllSame";
|
||||
made.reserve(polygons);
|
||||
for p in 0..polygons {
|
||||
val value := all_same || p >= values.length ? values[0] : values[p];
|
||||
made.append(value < 0 ? 0 : value as u32);
|
||||
}
|
||||
return made;
|
||||
}
|
||||
|
||||
# Reads a shape a blend shape channel blends toward.
|
||||
def scene::read_shape(&mut this, object: u32, id: i64, name: strview): u64 {
|
||||
var made := shape{ id = id, name = string::from(name, nothing{}), node = object };
|
||||
if this.document.child(object, "Indexes") is some(indexes) {
|
||||
val values := this.document.integers(indexes);
|
||||
for i in 0..values.length {
|
||||
made.points.append(values[i] as u32);
|
||||
}
|
||||
}
|
||||
if this.document.child(object, "Vertices") is some(vertices) {
|
||||
val values := this.document.reals(vertices);
|
||||
for i in 0..values.length / 3 {
|
||||
made.offsets.append(vec3{ values[i * 3] as f32, values[i * 3 + 1] as f32, values[i * 3 + 2] as f32 });
|
||||
}
|
||||
}
|
||||
if this.document.child(object, "Normals") is some(normals) {
|
||||
val values := this.document.reals(normals);
|
||||
for i in 0..values.length / 3 {
|
||||
made.normals.append(vec3{ values[i * 3] as f32, values[i * 3 + 1] as f32, values[i * 3 + 2] as f32 });
|
||||
}
|
||||
}
|
||||
this.shapes.append(move(made));
|
||||
return this.shapes.length - 1;
|
||||
}
|
||||
@@ -0,0 +1,394 @@
|
||||
#! Contains inflate, which undoes the compression of binary FBX's arrays:
|
||||
#! DEFLATE, as RFC 1951 writes it, within zlib's wrapping, as RFC 1950 writes
|
||||
#! it. It's `image`'s, of its PNG reader, copied, so `models` needs no more
|
||||
#! than `physics`: Huffman codes read as stb_image reads them, by a table of
|
||||
#! codes up to 9 bits long and longer ones by where each length's codes end.
|
||||
|
||||
module malunal::fbx;
|
||||
|
||||
# How many bits the fast table reads at once.
|
||||
const fast_bits: u64 = 9;
|
||||
|
||||
# The lengths and distances of runs: the least of each symbol's, and how many
|
||||
# bits more it reads.
|
||||
const length_base: u32[29] = [3, 4, 5, 6, 7, 8, 9, 10, 11, 13, 15, 17, 19, 23, 27, 31, 35, 43, 51, 59, 67, 83, 99, 115, 131, 163, 195, 227, 258];
|
||||
const length_extra: u32[29] = [0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 2, 2, 2, 2, 3, 3, 3, 3, 4, 4, 4, 4, 5, 5, 5, 5, 0];
|
||||
const distance_base: u32[30] = [1, 2, 3, 4, 5, 7, 9, 13, 17, 25, 33, 49, 65, 97, 129, 193, 257, 385, 513, 769, 1025, 1537, 2049, 3073, 4097, 6145, 8193, 12289, 16385, 24577];
|
||||
const distance_extra: u32[30] = [0, 0, 0, 0, 1, 1, 2, 2, 3, 3, 4, 4, 5, 5, 6, 6, 7, 7, 8, 8, 9, 9, 10, 10, 11, 11, 12, 12, 13, 13];
|
||||
|
||||
# The order a dynamic block gives the lengths of the code its lengths are in.
|
||||
const length_order: u64[19] = [16, 17, 18, 0, 8, 7, 9, 6, 10, 5, 11, 4, 12, 3, 13, 2, 14, 1, 15];
|
||||
|
||||
# A Huffman code: each symbol's code, as the lengths of all of them give it.
|
||||
struct huffman {
|
||||
var fast: u16[512]; #! `length << 9 | symbol` by a code's first 9 bits, read reversed, or 0 for a longer one.
|
||||
var first_code: u32[16];
|
||||
var first_symbol: u32[16];
|
||||
var max_code: u32[17]; #! Just past the last code of each length, shifted to be 16 bits long.
|
||||
var size: u8[288];
|
||||
var value: u16[288];
|
||||
}
|
||||
|
||||
# Builds a code from each symbol's length, which may leave codes unused, but not
|
||||
# give more than there are.
|
||||
def huffman::build(&mut this, lengths: span<u8>): bool {
|
||||
var counts: u32[17];
|
||||
for length in lengths {
|
||||
counts[length as u64]++;
|
||||
}
|
||||
counts[0] = 0;
|
||||
for bits in 1u..16u {
|
||||
if counts[bits] as u64 > (1u << bits) {
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
var next: u32[16];
|
||||
var code: u32 = 0;
|
||||
var symbols: u32 = 0;
|
||||
for bits in 1u..16u {
|
||||
next[bits] = code;
|
||||
this.first_code[bits] = code;
|
||||
this.first_symbol[bits] = symbols;
|
||||
code += counts[bits];
|
||||
if counts[bits] != 0 && (code - 1) as u64 >= (1u << bits) {
|
||||
return false;
|
||||
}
|
||||
this.max_code[bits] = code << (16 - bits) as u32;
|
||||
code <<= 1;
|
||||
symbols += counts[bits];
|
||||
}
|
||||
this.max_code[16] = 0x10000;
|
||||
|
||||
for symbol, length in lengths {
|
||||
if length == 0 {
|
||||
continue;
|
||||
}
|
||||
val bits := length as u64;
|
||||
val slot := (next[bits] - this.first_code[bits] + this.first_symbol[bits]) as u64;
|
||||
this.size[slot] = length;
|
||||
this.value[slot] = symbol as u16;
|
||||
if bits <= fast_bits {
|
||||
var at := reversed_bits(next[bits], bits) as u64;
|
||||
while at < 512 {
|
||||
this.fast[at] = ((bits << 9) | symbol) as u16;
|
||||
at += 1u << bits;
|
||||
}
|
||||
}
|
||||
next[bits]++;
|
||||
}
|
||||
return true;
|
||||
}
|
||||
|
||||
# The lowest bits of a number, in the opposite order.
|
||||
def reversed_bits(code: u32, bits: u64): u32 {
|
||||
var from := code;
|
||||
var made: u32 = 0;
|
||||
for _ in 0..bits {
|
||||
made = (made << 1) | (from & 1);
|
||||
from >>= 1;
|
||||
}
|
||||
return made;
|
||||
}
|
||||
|
||||
# The 16 lowest bits of a number, in the opposite order.
|
||||
def reversed16(code: u32): u32 {
|
||||
var made := code;
|
||||
made = ((made & 0xAAAA) >> 1) | ((made & 0x5555) << 1);
|
||||
made = ((made & 0xCCCC) >> 2) | ((made & 0x3333) << 2);
|
||||
made = ((made & 0xF0F0) >> 4) | ((made & 0x0F0F) << 4);
|
||||
return ((made & 0xFF00) >> 8) | ((made & 0x00FF) << 8);
|
||||
}
|
||||
|
||||
# The Adler-32 of bytes, as zlib checks them by.
|
||||
def adler32(data: span<u8>): u32 {
|
||||
var low: u32 = 1;
|
||||
var high: u32 = 0;
|
||||
var at: u64 = 0;
|
||||
while at < data.length {
|
||||
# 5552 bytes is the most that can be summed before either could pass 32 bits.
|
||||
val end := at + 5552 < data.length ? at + 5552 : data.length;
|
||||
while at < end {
|
||||
low += data[at];
|
||||
high += low;
|
||||
at++;
|
||||
}
|
||||
low %= 65521;
|
||||
high %= 65521;
|
||||
}
|
||||
return (high << 16) | low;
|
||||
}
|
||||
|
||||
# Reads DEFLATE's bits, least significant first, into the bytes made.
|
||||
struct inflater {
|
||||
var data: span<u8>;
|
||||
var at: u64; #! The next byte to read, which runs past the end where bits read past it.
|
||||
var buffer: u64;
|
||||
var count: u64; #! How many bits the buffer holds.
|
||||
var out: slice<u8>;
|
||||
var written: u64;
|
||||
}
|
||||
|
||||
# Inflates zlib's data into memory exactly as long as it should be, which it must
|
||||
# not go past, checking its Adler-32.
|
||||
# @returns How many bytes it inflated to, or `nothing` where it's broken.
|
||||
def inflate(data: span<u8>, out: slice<u8>): maybe<u64> {
|
||||
if data.length < 6 {
|
||||
return nothing {};
|
||||
}
|
||||
val method := data[0];
|
||||
val flags := data[1];
|
||||
if (method & 0x0F) != 8 || (method >> 4) > 7 || (flags & 0x20) != 0 || ((method as u32) * 256 + flags as u32) % 31 != 0 {
|
||||
return nothing {};
|
||||
}
|
||||
|
||||
var z := inflater { data = data, at = 2, out = out };
|
||||
var last := false;
|
||||
while !last {
|
||||
last = z.take(1) == 1;
|
||||
val kind := z.take(2);
|
||||
var read := false;
|
||||
if kind == 0 {
|
||||
read = z.stored();
|
||||
} else if kind == 1 {
|
||||
read = z.fixed();
|
||||
} else if kind == 2 {
|
||||
read = z.dynamic();
|
||||
}
|
||||
if !read || z.overran() {
|
||||
return nothing {};
|
||||
}
|
||||
}
|
||||
|
||||
# The checksum is in the next whole bytes, the most significant first.
|
||||
z.align();
|
||||
var expected: u32 = 0;
|
||||
for _ in 0..4 {
|
||||
expected = (expected << 8) | z.take(8);
|
||||
}
|
||||
if z.overran() || adler32(z.out[0:z.written]) != expected {
|
||||
return nothing {};
|
||||
}
|
||||
return z.written;
|
||||
}
|
||||
|
||||
# Copies a stored block, whose length follows from the next whole byte.
|
||||
def inflater::stored(&mut this): bool {
|
||||
this.align();
|
||||
val length := this.take(16);
|
||||
if (length ^ 0xFFFF) != this.take(16) {
|
||||
return false;
|
||||
}
|
||||
|
||||
# What the buffer holds first, then the rest straight from the data.
|
||||
var left := length as u64;
|
||||
while left > 0 && this.count > 0 {
|
||||
if !this.put(this.take(8) as u8) {
|
||||
return false;
|
||||
}
|
||||
left--;
|
||||
}
|
||||
if this.at + left > this.data.length || this.written + left > this.out.length {
|
||||
return false;
|
||||
}
|
||||
for index in 0..left {
|
||||
this.out[this.written + index] = this.data[this.at + index];
|
||||
}
|
||||
this.at += left;
|
||||
this.written += left;
|
||||
return true;
|
||||
}
|
||||
|
||||
# Inflates a block of the fixed codes RFC 1951 gives.
|
||||
def inflater::fixed(&mut this): bool {
|
||||
var lengths: u8[288];
|
||||
for symbol in 0u..288u {
|
||||
lengths[symbol] = symbol < 144 ? 8 : (symbol < 256 ? 9 : (symbol < 280 ? 7 : 8));
|
||||
}
|
||||
var distances: u8[30];
|
||||
for symbol in 0u..30u {
|
||||
distances[symbol] = 5;
|
||||
}
|
||||
var literal_code := huffman {};
|
||||
var distance_code := huffman {};
|
||||
_ = literal_code.build(lengths[:]);
|
||||
_ = distance_code.build(distances[:]);
|
||||
return this.codes(&literal_code, &distance_code);
|
||||
}
|
||||
|
||||
# Inflates a block of codes of its own, whose lengths it gives first, in a code of
|
||||
# their own.
|
||||
def inflater::dynamic(&mut this): bool {
|
||||
val literals := this.take(5) as u64 + 257;
|
||||
val distances := this.take(5) as u64 + 1;
|
||||
val count := this.take(4) as u64 + 4;
|
||||
|
||||
var length_lengths: u8[19];
|
||||
for index in 0..count {
|
||||
length_lengths[length_order[index]] = this.take(3) as u8;
|
||||
}
|
||||
var length_code := huffman {};
|
||||
if !length_code.build(length_lengths[:]) {
|
||||
return false;
|
||||
}
|
||||
|
||||
# The lengths, where 16 repeats the last, and 17 and 18 give runs of zeros.
|
||||
var lengths: u8[320];
|
||||
val total := literals + distances;
|
||||
var read: u64 = 0;
|
||||
while read < total {
|
||||
val symbol := this.decode(&length_code);
|
||||
if symbol < 0 {
|
||||
return false;
|
||||
}
|
||||
var length: u8 = 0;
|
||||
var repeat: u64 = 1;
|
||||
if symbol < 16 {
|
||||
length = symbol as u8;
|
||||
} else if symbol == 16 {
|
||||
if read == 0 {
|
||||
return false;
|
||||
}
|
||||
length = lengths[read - 1];
|
||||
repeat = 3 + this.take(2) as u64;
|
||||
} else if symbol == 17 {
|
||||
repeat = 3 + this.take(3) as u64;
|
||||
} else {
|
||||
repeat = 11 + this.take(7) as u64;
|
||||
}
|
||||
if read + repeat > total {
|
||||
return false;
|
||||
}
|
||||
for _ in 0..repeat {
|
||||
lengths[read] = length;
|
||||
read++;
|
||||
}
|
||||
}
|
||||
if lengths[256] == 0 {
|
||||
return false;
|
||||
}
|
||||
|
||||
var literal_code := huffman {};
|
||||
var distance_code := huffman {};
|
||||
if !literal_code.build(lengths[0:literals]) || !distance_code.build(lengths[literals:distances]) {
|
||||
return false;
|
||||
}
|
||||
return this.codes(&literal_code, &distance_code);
|
||||
}
|
||||
|
||||
# Inflates a block's symbols: bytes, then runs of what came before, to its end.
|
||||
def inflater::codes(&mut this, literals: &huffman, distances: &huffman): bool {
|
||||
while true {
|
||||
val symbol := this.decode(literals);
|
||||
if symbol < 0 {
|
||||
return false;
|
||||
}
|
||||
if symbol < 256 {
|
||||
if !this.put(symbol as u8) {
|
||||
return false;
|
||||
}
|
||||
continue;
|
||||
}
|
||||
if symbol == 256 {
|
||||
return true;
|
||||
}
|
||||
|
||||
val index := (symbol - 257) as u64;
|
||||
if index >= 29 {
|
||||
return false;
|
||||
}
|
||||
val length := (length_base[index] + this.take(length_extra[index] as u64)) as u64;
|
||||
val which := this.decode(distances);
|
||||
if which < 0 || which >= 30 {
|
||||
return false;
|
||||
}
|
||||
val distance := (distance_base[which as u64] + this.take(distance_extra[which as u64] as u64)) as u64;
|
||||
if distance > this.written || this.written + length > this.out.length || this.overran() {
|
||||
return false;
|
||||
}
|
||||
# A run may overlap itself, repeating what it copies, so it goes a byte at a time.
|
||||
var from := this.written - distance;
|
||||
for _ in 0..length {
|
||||
this.out[this.written] = this.out[from];
|
||||
this.written++;
|
||||
from++;
|
||||
}
|
||||
}
|
||||
return true;
|
||||
}
|
||||
|
||||
# Decodes a symbol of a code.
|
||||
# @returns The symbol, or -1 where the bits are no code's.
|
||||
def inflater::decode(&mut this, code: &huffman): i32 {
|
||||
if this.count < 16 {
|
||||
this.fill();
|
||||
}
|
||||
val entry := code.fast[this.buffer & 511];
|
||||
if entry != 0 {
|
||||
val length := (entry >> 9) as u64;
|
||||
this.buffer >>= length;
|
||||
this.count -= length;
|
||||
return (entry & 511) as i32;
|
||||
}
|
||||
|
||||
# Longer than the table reads: the code's length is the first whose codes end
|
||||
# past the bits, read most significant first.
|
||||
val bits := reversed16((this.buffer & 0xFFFF) as u32);
|
||||
var length: u64 = fast_bits + 1;
|
||||
while bits >= code.max_code[length] {
|
||||
length++;
|
||||
}
|
||||
if length >= 16 {
|
||||
return -1;
|
||||
}
|
||||
val slot := ((bits >> (16 - length) as u32) - code.first_code[length] + code.first_symbol[length]) as u64;
|
||||
if slot >= 288 || code.size[slot] as u64 != length {
|
||||
return -1;
|
||||
}
|
||||
this.buffer >>= length;
|
||||
this.count -= length;
|
||||
return code.value[slot] as i32;
|
||||
}
|
||||
|
||||
# Reads a number of bits, up to 16, the first the least significant.
|
||||
def inflater::take(&mut this, bits: u64): u32 {
|
||||
if this.count < bits {
|
||||
this.fill();
|
||||
}
|
||||
val made := (this.buffer & ((1u << bits) - 1)) as u32;
|
||||
this.buffer >>= bits;
|
||||
this.count -= bits;
|
||||
return made;
|
||||
}
|
||||
|
||||
# Fills the buffer, with zeros past the end of the data, which `overran` tells.
|
||||
def inflater::fill(&mut this): void {
|
||||
while this.count <= 56 {
|
||||
if this.at < this.data.length {
|
||||
this.buffer |= (this.data[this.at] as u64) << this.count;
|
||||
}
|
||||
this.at++;
|
||||
this.count += 8;
|
||||
}
|
||||
}
|
||||
|
||||
# Drops the bits up to the next whole byte.
|
||||
def inflater::align(&mut this): void {
|
||||
val extra := this.count % 8;
|
||||
this.buffer >>= extra;
|
||||
this.count -= extra;
|
||||
}
|
||||
|
||||
# Whether more bits have been read than the data holds.
|
||||
def inflater::overran(&this): bool {
|
||||
return this.at * 8 - this.count > this.data.length * 8;
|
||||
}
|
||||
|
||||
def inflater::put(&mut this, byte: u8): bool {
|
||||
if this.written >= this.out.length {
|
||||
return false;
|
||||
}
|
||||
this.out[this.written] = byte;
|
||||
this.written++;
|
||||
return true;
|
||||
}
|
||||
@@ -0,0 +1,541 @@
|
||||
#! Contains reading a scene of a document: its settings, each object of
|
||||
#! `Objects` read into the list of its kind, then `Connections`, which say
|
||||
#! what's whose: a model's parent, mesh, materials, camera, and light, a
|
||||
#! material's textures, a skin's clusters and each cluster's bone, a blend
|
||||
#! shape's channels and their shapes, an animation's layers and curves and what
|
||||
#! they animate.
|
||||
|
||||
import std::containers;
|
||||
import malunal::linear;
|
||||
module malunal::fbx;
|
||||
|
||||
# What kind of object an id names, as `Objects` gives them.
|
||||
enum object_kind: u8 { model, mesh, shape, material, texture, video, camera, light, skin, cluster, blend_shape, channel, stack, layer, curve_node, curve, pose }
|
||||
|
||||
# FBX's ticks a second.
|
||||
const ticks_per_second: f64 = 46186158000;
|
||||
|
||||
#! Reads what a document's objects mean.
|
||||
#! @param made The document, which the scene keeps.
|
||||
#! @returns The scene, or why it couldn't be read: `malformed` where a mesh's
|
||||
#! polygon names a point it hasn't.
|
||||
pub def scene::of(made: document): result<scene, fbx_error> {
|
||||
var held := move(made);
|
||||
var built := scene{ document = move(held) };
|
||||
built.read_templates();
|
||||
built.read_settings();
|
||||
var ids := dict::<i64, u64>::new();
|
||||
if built.document.child(absent, "Objects") is some(objects) {
|
||||
val count := built.document.nodes[objects as u64].children.length;
|
||||
for i in 0..count {
|
||||
val object := built.document.nodes[objects as u64].children[i];
|
||||
val read := built.read_object(object) else (e) { return e; };
|
||||
if read is some(found) {
|
||||
ids.set(built.id_of(object), found);
|
||||
}
|
||||
}
|
||||
}
|
||||
if built.document.child(absent, "Connections") is some(connections) {
|
||||
val count := built.document.nodes[connections as u64].children.length;
|
||||
for i in 0..count {
|
||||
val link := built.document.nodes[connections as u64].children[i];
|
||||
val node := &built.document.nodes[link as u64];
|
||||
continue if node.name.span != "C" || node.properties.length < 3;
|
||||
val child := node.properties[1].whole();
|
||||
val parent := node.properties[2].whole();
|
||||
var property := string::new(nothing{});
|
||||
if node.properties.length > 3 {
|
||||
property.append(node.properties[3].text());
|
||||
}
|
||||
built.connect(&ids, child, parent, property.span);
|
||||
}
|
||||
}
|
||||
for i in 0..built.models.length {
|
||||
if built.models[i].parent == absent {
|
||||
built.roots.append(i as u32);
|
||||
}
|
||||
}
|
||||
built.place_poses(&ids);
|
||||
return built;
|
||||
}
|
||||
|
||||
#! Reads a scene of a file, as `load` and `scene::of` read them.
|
||||
pub def load_scene(at: strview): result<scene, fbx_error> {
|
||||
var made := load(at) else (e) { return e; };
|
||||
return scene::of(move(made));
|
||||
}
|
||||
|
||||
#! Reads a scene of bytes, as `decode` and `scene::of` read them.
|
||||
pub def decode_scene(bytes: span<u8>): result<scene, fbx_error> {
|
||||
var made := decode(bytes) else (e) { return e; };
|
||||
return scene::of(move(made));
|
||||
}
|
||||
|
||||
# An object's id, its first property.
|
||||
def scene::id_of(&this, object: u32): i64 {
|
||||
val held := &this.document.nodes[object as u64];
|
||||
return held.properties.length == 0 ? 0 : held.properties[0].whole();
|
||||
}
|
||||
|
||||
# An object's name, its second property: binary FBX's `name\0\1Class`, or
|
||||
# ASCII's `Class::name`, as the name alone.
|
||||
def scene::name_of(&this, object: u32): strview {
|
||||
val held := &this.document.nodes[object as u64];
|
||||
return "" if held.properties.length < 2;
|
||||
val text := held.properties[1].text();
|
||||
if this.document.binary {
|
||||
for i in 0..text.length {
|
||||
return text.substr(0, i) if text[i] == 0 && i + 1 < text.length && text[i + 1] == 1;
|
||||
}
|
||||
return text;
|
||||
}
|
||||
if text.find("::") is some(at) {
|
||||
return text.substr(at + 2, text.length - at - 2);
|
||||
}
|
||||
return text;
|
||||
}
|
||||
|
||||
# An object's class, its third property, as `Mesh` or `LimbNode`.
|
||||
def scene::class_of(&this, object: u32): strview {
|
||||
val held := &this.document.nodes[object as u64];
|
||||
return "" if held.properties.length < 3;
|
||||
return held.properties[2].text();
|
||||
}
|
||||
|
||||
# A kind and an index, as one number.
|
||||
def packed(kind: object_kind, index: u64): u64 {
|
||||
return ((kind as u64) << 40) | index;
|
||||
}
|
||||
|
||||
def kind_of(packed: u64): u8 {
|
||||
return (packed >> 40) as u8;
|
||||
}
|
||||
|
||||
def index_of(packed: u64): u64 {
|
||||
return packed & 0xFFFFFFFFFF;
|
||||
}
|
||||
|
||||
# Reads an object into the list of its kind.
|
||||
# @returns Its kind and index, packed, or nothing where it's of a kind not
|
||||
# read.
|
||||
def scene::read_object(&mut this, object: u32): result<maybe<u64>, fbx_error> {
|
||||
val skipped: maybe<u64> = nothing{};
|
||||
var kind := string::from(this.document.nodes[object as u64].name.span, nothing{});
|
||||
var subclass := string::from(this.class_of(object), nothing{});
|
||||
var name := string::from(this.name_of(object), nothing{});
|
||||
val id := this.id_of(object);
|
||||
val k := kind.span;
|
||||
val c := subclass.span;
|
||||
if k == "Model" {
|
||||
val at := this.read_model(object, id, name.span, c);
|
||||
val made: maybe<u64> = packed(object_kind::model, at);
|
||||
return made;
|
||||
}
|
||||
if k == "Geometry" && c == "Mesh" {
|
||||
val at := this.read_mesh(object, id, name.span) else (e) { return e; };
|
||||
val made: maybe<u64> = packed(object_kind::mesh, at);
|
||||
return made;
|
||||
}
|
||||
if k == "Geometry" && c == "Shape" {
|
||||
val made: maybe<u64> = packed(object_kind::shape, this.read_shape(object, id, name.span));
|
||||
return made;
|
||||
}
|
||||
if k == "Material" {
|
||||
val made: maybe<u64> = packed(object_kind::material, this.read_material(object, id, name.span));
|
||||
return made;
|
||||
}
|
||||
if k == "Texture" {
|
||||
val made: maybe<u64> = packed(object_kind::texture, this.read_texture(object, id, name.span));
|
||||
return made;
|
||||
}
|
||||
if k == "Video" {
|
||||
val made: maybe<u64> = packed(object_kind::video, this.read_video(object, id, name.span));
|
||||
return made;
|
||||
}
|
||||
if k == "NodeAttribute" && c == "Camera" {
|
||||
val made: maybe<u64> = packed(object_kind::camera, this.read_camera(object, id, name.span));
|
||||
return made;
|
||||
}
|
||||
if k == "NodeAttribute" && c == "Light" {
|
||||
val made: maybe<u64> = packed(object_kind::light, this.read_light(object, id, name.span));
|
||||
return made;
|
||||
}
|
||||
if k == "Deformer" && c == "Skin" {
|
||||
this.skins.append(skin{ id = id, name = string::from(name.span, nothing{}), node = object });
|
||||
val made: maybe<u64> = packed(object_kind::skin, this.skins.length - 1);
|
||||
return made;
|
||||
}
|
||||
if k == "Deformer" && c == "Cluster" {
|
||||
val made: maybe<u64> = packed(object_kind::cluster, this.read_cluster(object, id, name.span));
|
||||
return made;
|
||||
}
|
||||
if k == "Deformer" && c == "BlendShape" {
|
||||
this.blend_shapes.append(blend_shape{ id = id, name = string::from(name.span, nothing{}), node = object });
|
||||
val made: maybe<u64> = packed(object_kind::blend_shape, this.blend_shapes.length - 1);
|
||||
return made;
|
||||
}
|
||||
if k == "Deformer" && c == "BlendShapeChannel" {
|
||||
val made: maybe<u64> = packed(object_kind::channel, this.read_channel(object, id, name.span));
|
||||
return made;
|
||||
}
|
||||
if k == "Pose" {
|
||||
val made: maybe<u64> = packed(object_kind::pose, this.read_pose(object, id, name.span, c));
|
||||
return made;
|
||||
}
|
||||
if k == "AnimationStack" {
|
||||
val made: maybe<u64> = packed(object_kind::stack, this.read_stack(object, id, name.span));
|
||||
return made;
|
||||
}
|
||||
if k == "AnimationLayer" {
|
||||
val weight := this.number_of(object, "Weight", 100) as f32;
|
||||
this.layers.append(animation_layer{ id = id, name = string::from(name.span, nothing{}), node = object, weight = weight });
|
||||
val made: maybe<u64> = packed(object_kind::layer, this.layers.length - 1);
|
||||
return made;
|
||||
}
|
||||
if k == "AnimationCurveNode" {
|
||||
val made: maybe<u64> = packed(object_kind::curve_node, this.read_curve_node(object, id, name.span));
|
||||
return made;
|
||||
}
|
||||
if k == "AnimationCurve" {
|
||||
val made: maybe<u64> = packed(object_kind::curve, this.read_curve(object, id, name.span));
|
||||
return made;
|
||||
}
|
||||
return skipped;
|
||||
}
|
||||
|
||||
# Reads the settings of `GlobalSettings`.
|
||||
def scene::read_settings(&mut this): void {
|
||||
val global := this.document.child(absent, "GlobalSettings") else { return; };
|
||||
var s := settings{};
|
||||
s.up_axis = this.number_of(global, "UpAxis", 1) as u32;
|
||||
s.up_sign = this.number_of(global, "UpAxisSign", 1) as i32;
|
||||
s.front_axis = this.number_of(global, "FrontAxis", 2) as u32;
|
||||
s.front_sign = this.number_of(global, "FrontAxisSign", 1) as i32;
|
||||
s.coord_axis = this.number_of(global, "CoordAxis", 0) as u32;
|
||||
s.coord_sign = this.number_of(global, "CoordAxisSign", 1) as i32;
|
||||
s.unit_scale = this.number_of(global, "UnitScaleFactor", 1);
|
||||
s.original_unit_scale = this.number_of(global, "OriginalUnitScaleFactor", s.unit_scale);
|
||||
val mode := this.number_of(global, "TimeMode", 0) as u64;
|
||||
val rates: f64[19] = [30, 120, 100, 60, 50, 48, 30, 30, 29.97, 29.97, 25, 24, 1000, 23.976, 0, 96, 72, 59.94, 119.88];
|
||||
s.frame_rate = mode < 19 ? rates[mode] : 30;
|
||||
if mode == 14 {
|
||||
s.frame_rate = this.number_of(global, "CustomFrameRate", 30);
|
||||
}
|
||||
s.start = this.number_of(global, "TimeSpanStart", 0) / ticks_per_second;
|
||||
s.stop = this.number_of(global, "TimeSpanStop", 0) / ticks_per_second;
|
||||
s.ambient = this.vector_of(global, "AmbientColor", vec3::zero);
|
||||
this.settings = s;
|
||||
}
|
||||
|
||||
# Reads a model, where it's placed and how.
|
||||
def scene::read_model(&mut this, object: u32, id: i64, name: strview, kind: strview): u64 {
|
||||
var made := model{ id = id, name = string::from(name, nothing{}), kind = string::from(kind, nothing{}), node = object };
|
||||
made.translation = this.vector_of(object, "Lcl Translation", vec3::zero);
|
||||
made.rotation = this.vector_of(object, "Lcl Rotation", vec3::zero);
|
||||
made.scale = this.vector_of(object, "Lcl Scaling", vec3::one);
|
||||
made.pre_rotation = this.vector_of(object, "PreRotation", vec3::zero);
|
||||
made.post_rotation = this.vector_of(object, "PostRotation", vec3::zero);
|
||||
val order := this.number_of(object, "RotationOrder", 0) as u64;
|
||||
val orders: rotation_order[7] = [rotation_order::xyz, rotation_order::xzy, rotation_order::yzx, rotation_order::yxz, rotation_order::zxy, rotation_order::zyx, rotation_order::spheric_xyz];
|
||||
made.order = order < 7 ? orders[order] : rotation_order::xyz;
|
||||
made.rotation_active = this.flag_of(object, "RotationActive", false);
|
||||
made.rotation_offset = this.vector_of(object, "RotationOffset", vec3::zero);
|
||||
made.rotation_pivot = this.vector_of(object, "RotationPivot", vec3::zero);
|
||||
made.scaling_offset = this.vector_of(object, "ScalingOffset", vec3::zero);
|
||||
made.scaling_pivot = this.vector_of(object, "ScalingPivot", vec3::zero);
|
||||
made.geometric_translation = this.vector_of(object, "GeometricTranslation", vec3::zero);
|
||||
made.geometric_rotation = this.vector_of(object, "GeometricRotation", vec3::zero);
|
||||
made.geometric_scale = this.vector_of(object, "GeometricScaling", vec3::one);
|
||||
made.inherit = this.number_of(object, "InheritType", 1) as u32;
|
||||
made.visible = this.number_of(object, "Visibility", 1) != 0;
|
||||
this.models.append(move(made));
|
||||
return this.models.length - 1;
|
||||
}
|
||||
|
||||
# Reads a material: its shading model, colors, and factors.
|
||||
def scene::read_material(&mut this, object: u32, id: i64, name: strview): u64 {
|
||||
var made := material{ id = id, name = string::from(name, nothing{}), node = object };
|
||||
made.shading = string::from(this.document.text_of(object, "ShadingModel"), nothing{});
|
||||
made.diffuse = this.vector_of(object, "DiffuseColor", this.vector_of(object, "Diffuse", made.diffuse));
|
||||
made.diffuse_factor = this.number_of(object, "DiffuseFactor", 1) as f32;
|
||||
made.ambient = this.vector_of(object, "AmbientColor", made.ambient);
|
||||
made.ambient_factor = this.number_of(object, "AmbientFactor", 1) as f32;
|
||||
made.specular = this.vector_of(object, "SpecularColor", made.specular);
|
||||
made.specular_factor = this.number_of(object, "SpecularFactor", 1) as f32;
|
||||
made.shininess = this.number_of(object, "ShininessExponent", this.number_of(object, "Shininess", 20)) as f32;
|
||||
made.emissive = this.vector_of(object, "EmissiveColor", vec3::zero);
|
||||
made.emissive_factor = this.number_of(object, "EmissiveFactor", 1) as f32;
|
||||
made.transparency = this.number_of(object, "TransparencyFactor", 0) as f32;
|
||||
made.opacity = this.number_of(object, "Opacity", 1) as f32;
|
||||
made.reflection_factor = this.number_of(object, "ReflectionFactor", 1) as f32;
|
||||
made.bump_factor = this.number_of(object, "BumpFactor", 1) as f32;
|
||||
this.materials.append(move(made));
|
||||
return this.materials.length - 1;
|
||||
}
|
||||
|
||||
# Reads a texture: the file it names, and how it's placed.
|
||||
def scene::read_texture(&mut this, object: u32, id: i64, name: strview): u64 {
|
||||
var made := texture{ id = id, name = string::from(name, nothing{}), node = object };
|
||||
var file := this.document.text_of(object, "FileName");
|
||||
if file.length == 0 {
|
||||
file = this.document.text_of(object, "Filename");
|
||||
}
|
||||
made.file = string::from(file, nothing{});
|
||||
made.relative = string::from(this.document.text_of(object, "RelativeFilename"), nothing{});
|
||||
made.uv_set = string::from(this.text_of(object, "UVSet"), nothing{});
|
||||
made.translation = this.vector_of(object, "Translation", vec3::zero);
|
||||
made.rotation = this.vector_of(object, "Rotation", vec3::zero);
|
||||
made.scale = this.vector_of(object, "Scaling", vec3::one);
|
||||
made.wrap_u = this.number_of(object, "WrapModeU", 0) as u32;
|
||||
made.wrap_v = this.number_of(object, "WrapModeV", 0) as u32;
|
||||
this.textures.append(move(made));
|
||||
return this.textures.length - 1;
|
||||
}
|
||||
|
||||
# Reads a video: the file it names, and its bytes, where they're embedded, as
|
||||
# binary's raw bytes or ASCII's base64.
|
||||
def scene::read_video(&mut this, object: u32, id: i64, name: strview): u64 {
|
||||
var made := video{ id = id, name = string::from(name, nothing{}), node = object };
|
||||
var file := this.document.text_of(object, "FileName");
|
||||
if file.length == 0 {
|
||||
file = this.document.text_of(object, "Filename");
|
||||
}
|
||||
if file.length == 0 {
|
||||
file = this.text_of(object, "Path");
|
||||
}
|
||||
made.file = string::from(file, nothing{});
|
||||
made.relative = string::from(this.document.text_of(object, "RelativeFilename"), nothing{});
|
||||
if this.document.child(object, "Content") is some(content) {
|
||||
val held := &this.document.nodes[content as u64];
|
||||
var text := string::new(nothing{});
|
||||
for i in 0..held.properties.length {
|
||||
if held.properties[i].kind == property_kind::raw {
|
||||
made.content.extend(held.properties[i].bytes.span);
|
||||
} else if held.properties[i].kind == property_kind::text {
|
||||
text.append(held.properties[i].text());
|
||||
}
|
||||
}
|
||||
if made.content.length == 0 && text.length != 0 {
|
||||
made.content = base64_bytes(text.span);
|
||||
}
|
||||
}
|
||||
this.videos.append(move(made));
|
||||
return this.videos.length - 1;
|
||||
}
|
||||
|
||||
# The bytes of base64, its spaces and padding passed over.
|
||||
def base64_bytes(text: strview): vector<u8> {
|
||||
var made := vector::<u8>::new();
|
||||
var bits: u32 = 0;
|
||||
var count: u32 = 0;
|
||||
for i in 0..text.length {
|
||||
val c := text[i];
|
||||
var value: u32 = 64;
|
||||
if c >= 'A' && c <= 'Z' {
|
||||
value = (c - 'A') as u32;
|
||||
} else if c >= 'a' && c <= 'z' {
|
||||
value = (c - 'a') as u32 + 26;
|
||||
} else if c >= '0' && c <= '9' {
|
||||
value = (c - '0') as u32 + 52;
|
||||
} else if c == '+' {
|
||||
value = 62;
|
||||
} else if c == '/' {
|
||||
value = 63;
|
||||
}
|
||||
continue if value == 64;
|
||||
bits = (bits << 6) | value;
|
||||
count += 6;
|
||||
if count >= 8 {
|
||||
count -= 8;
|
||||
made.append(((bits >> count) & 0xFF) as u8);
|
||||
}
|
||||
}
|
||||
return made;
|
||||
}
|
||||
|
||||
# Reads a camera.
|
||||
def scene::read_camera(&mut this, object: u32, id: i64, name: strview): u64 {
|
||||
var made := camera{ id = id, name = string::from(name, nothing{}), node = object };
|
||||
made.orthographic = this.number_of(object, "CameraProjectionType", 0) == 1;
|
||||
made.field_of_view = this.number_of(object, "FieldOfView", 40) as f32;
|
||||
made.field_of_view_x = this.number_of(object, "FieldOfViewX", made.field_of_view as f64) as f32;
|
||||
made.field_of_view_y = this.number_of(object, "FieldOfViewY", made.field_of_view as f64) as f32;
|
||||
made.focal_length = this.number_of(object, "FocalLength", 34.89) as f32;
|
||||
made.near = this.number_of(object, "NearPlane", 10) as f32;
|
||||
made.far = this.number_of(object, "FarPlane", 4000) as f32;
|
||||
made.aspect_width = this.number_of(object, "AspectWidth", 320) as f32;
|
||||
made.aspect_height = this.number_of(object, "AspectHeight", 200) as f32;
|
||||
made.ortho_zoom = this.number_of(object, "OrthoZoom", 1) as f32;
|
||||
this.cameras.append(move(made));
|
||||
return this.cameras.length - 1;
|
||||
}
|
||||
|
||||
# Reads a light.
|
||||
def scene::read_light(&mut this, object: u32, id: i64, name: strview): u64 {
|
||||
var made := light{ id = id, name = string::from(name, nothing{}), node = object };
|
||||
val kind := this.number_of(object, "LightType", 0) as u64;
|
||||
val kinds: light_kind[5] = [light_kind::point, light_kind::directional, light_kind::spot, light_kind::area, light_kind::volume];
|
||||
made.kind = kind < 5 ? kinds[kind] : light_kind::point;
|
||||
made.color = this.vector_of(object, "Color", vec3::one);
|
||||
made.intensity = this.number_of(object, "Intensity", 100) as f32;
|
||||
made.inner_angle = this.number_of(object, "InnerAngle", 0) as f32;
|
||||
made.outer_angle = this.number_of(object, "OuterAngle", 45) as f32;
|
||||
made.decay = this.number_of(object, "DecayType", 0) as u32;
|
||||
made.decay_start = this.number_of(object, "DecayStart", 0) as f32;
|
||||
made.casts_shadows = this.flag_of(object, "CastShadows", false);
|
||||
this.lights.append(move(made));
|
||||
return this.lights.length - 1;
|
||||
}
|
||||
|
||||
# Reads a cluster: the points its bone moves, how much, and the matrices it
|
||||
# was bound by.
|
||||
def scene::read_cluster(&mut this, object: u32, id: i64, name: strview): u64 {
|
||||
var made := cluster{ id = id, name = string::from(name, nothing{}), node = object };
|
||||
if this.document.child(object, "Indexes") is some(indexes) {
|
||||
val values := this.document.integers(indexes);
|
||||
made.points.reserve(values.length);
|
||||
for i in 0..values.length {
|
||||
made.points.append(values[i] as u32);
|
||||
}
|
||||
}
|
||||
if this.document.child(object, "Weights") is some(weights) {
|
||||
val values := this.document.reals(weights);
|
||||
made.weights.reserve(values.length);
|
||||
for i in 0..values.length {
|
||||
made.weights.append(values[i] as f32);
|
||||
}
|
||||
}
|
||||
if this.document.child(object, "Transform") is some(transform) {
|
||||
made.transform = matrix_of(this.document.reals(transform).span);
|
||||
}
|
||||
if this.document.child(object, "TransformLink") is some(link) {
|
||||
made.transform_link = matrix_of(this.document.reals(link).span);
|
||||
}
|
||||
this.clusters.append(move(made));
|
||||
return this.clusters.length - 1;
|
||||
}
|
||||
|
||||
# A matrix of 16 numbers, column after column, as FBX writes them; the
|
||||
# identity where there aren't 16.
|
||||
def matrix_of(values: span<f64>): mat4 {
|
||||
var made := mat4::identity;
|
||||
return made if values.length != 16;
|
||||
for i in 0..16u {
|
||||
made.m[i] = values[i] as f32;
|
||||
}
|
||||
return made;
|
||||
}
|
||||
|
||||
# Reads a blend shape channel: how far it blends, and its shapes' weights.
|
||||
def scene::read_channel(&mut this, object: u32, id: i64, name: strview): u64 {
|
||||
var made := blend_channel{ id = id, name = string::from(name, nothing{}), node = object };
|
||||
made.weight = this.document.number_of(object, "DeformPercent", this.number_of(object, "DeformPercent", 0)) as f32;
|
||||
if this.document.child(object, "FullWeights") is some(full) {
|
||||
val values := this.document.reals(full);
|
||||
for i in 0..values.length {
|
||||
made.full_weights.append(values[i] as f32);
|
||||
}
|
||||
}
|
||||
this.channels.append(move(made));
|
||||
return this.channels.length - 1;
|
||||
}
|
||||
|
||||
# Reads a pose: each model's matrix, by its id, which `place_poses` finds the
|
||||
# model of once all are read.
|
||||
def scene::read_pose(&mut this, object: u32, id: i64, name: strview, subclass: strview): u64 {
|
||||
var made := pose{ id = id, name = string::from(name, nothing{}), node = object, bind = subclass == "BindPose" };
|
||||
val entries := this.document.children_named(object, "PoseNode");
|
||||
for i in 0..entries.length {
|
||||
var entry := pose_entry{};
|
||||
if this.document.child(entries[i], "Node") is some(named) && this.document.property(named, 0) is some(&given) {
|
||||
entry.id = given.whole();
|
||||
}
|
||||
if this.document.child(entries[i], "Matrix") is some(matrix) {
|
||||
entry.matrix = matrix_of(this.document.reals(matrix).span);
|
||||
}
|
||||
made.entries.append(entry);
|
||||
}
|
||||
this.poses.append(move(made));
|
||||
return this.poses.length - 1;
|
||||
}
|
||||
|
||||
# Finds the model of each pose's entry, by its id.
|
||||
def scene::place_poses(&mut this, ids: &dict<i64, u64>): void {
|
||||
for p in 0..this.poses.length {
|
||||
for e in 0..this.poses[p].entries.length {
|
||||
val found := ids.get_or(&this.poses[p].entries[e].id, 0xFFFFFFFFFFFFFFFF);
|
||||
if found != 0xFFFFFFFFFFFFFFFF && kind_of(found) == object_kind::model as u8 {
|
||||
this.poses[p].entries[e].model = index_of(found) as u32;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
# Joins what a connection says is whose.
|
||||
def scene::connect(&mut this, ids: &dict<i64, u64>, child_id: i64, parent_id: i64, property: strview): void {
|
||||
val unknown: u64 = 0xFFFFFFFFFFFFFFFF;
|
||||
val child := ids.get_or(&child_id, unknown);
|
||||
return if child == unknown;
|
||||
val ck := kind_of(child);
|
||||
val ci := index_of(child);
|
||||
val parent := parent_id == 0 ? unknown : ids.get_or(&parent_id, unknown);
|
||||
return if parent == unknown;
|
||||
val pk := kind_of(parent);
|
||||
val pi := index_of(parent);
|
||||
val model_kind := object_kind::model as u8;
|
||||
if ck == model_kind && pk == model_kind {
|
||||
this.models[ci].parent = pi as u32;
|
||||
this.models[pi].children.append(ci as u32);
|
||||
} else if ck == object_kind::mesh as u8 && pk == model_kind {
|
||||
this.models[pi].mesh = ci as u32;
|
||||
} else if ck == object_kind::material as u8 && pk == model_kind {
|
||||
this.models[pi].materials.append(ci as u32);
|
||||
} else if ck == object_kind::camera as u8 && pk == model_kind {
|
||||
this.models[pi].camera = ci as u32;
|
||||
} else if ck == object_kind::light as u8 && pk == model_kind {
|
||||
this.models[pi].light = ci as u32;
|
||||
} else if ck == object_kind::texture as u8 && pk == object_kind::material as u8 {
|
||||
this.materials[pi].maps.append(material_map{ property = string::from(property, nothing{}), texture = ci as u32 });
|
||||
} else if ck == object_kind::video as u8 && pk == object_kind::texture as u8 {
|
||||
this.textures[pi].video = ci as u32;
|
||||
} else if ck == object_kind::skin as u8 && pk == object_kind::mesh as u8 {
|
||||
this.meshes[pi].skin = ci as u32;
|
||||
this.skins[ci].mesh = pi as u32;
|
||||
} else if ck == object_kind::cluster as u8 && pk == object_kind::skin as u8 {
|
||||
this.skins[pi].clusters.append(ci as u32);
|
||||
this.clusters[ci].skin = pi as u32;
|
||||
} else if ck == model_kind && pk == object_kind::cluster as u8 {
|
||||
this.clusters[pi].bone = ci as u32;
|
||||
} else if ck == object_kind::blend_shape as u8 && pk == object_kind::mesh as u8 {
|
||||
this.meshes[pi].blend_shapes.append(ci as u32);
|
||||
this.blend_shapes[ci].mesh = pi as u32;
|
||||
} else if ck == object_kind::channel as u8 && pk == object_kind::blend_shape as u8 {
|
||||
this.blend_shapes[pi].channels.append(ci as u32);
|
||||
} else if ck == object_kind::shape as u8 && pk == object_kind::channel as u8 {
|
||||
this.channels[pi].shapes.append(ci as u32);
|
||||
} else if ck == object_kind::layer as u8 && pk == object_kind::stack as u8 {
|
||||
this.stacks[pi].layers.append(ci as u32);
|
||||
this.layers[ci].stack = pi as u32;
|
||||
} else if ck == object_kind::curve_node as u8 && pk == object_kind::layer as u8 {
|
||||
this.layers[pi].curve_nodes.append(ci as u32);
|
||||
this.curve_nodes[ci].layer = pi as u32;
|
||||
} else if ck == object_kind::curve_node as u8 {
|
||||
this.curve_nodes[ci].target = pi as u32;
|
||||
this.curve_nodes[ci].property = string::from(property, nothing{});
|
||||
if pk == model_kind {
|
||||
this.curve_nodes[ci].target_kind = part_kind::model;
|
||||
} else if pk == object_kind::channel as u8 {
|
||||
this.curve_nodes[ci].target_kind = part_kind::channel;
|
||||
} else if pk == object_kind::material as u8 {
|
||||
this.curve_nodes[ci].target_kind = part_kind::material;
|
||||
} else if pk == object_kind::camera as u8 {
|
||||
this.curve_nodes[ci].target_kind = part_kind::camera;
|
||||
} else if pk == object_kind::light as u8 {
|
||||
this.curve_nodes[ci].target_kind = part_kind::light;
|
||||
} else {
|
||||
this.curve_nodes[ci].target_kind = part_kind::other;
|
||||
}
|
||||
} else if ck == object_kind::curve as u8 && pk == object_kind::curve_node as u8 {
|
||||
this.attach_curve(pi, ci as u32, property);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,107 @@
|
||||
#! Contains reading an object's properties as `Properties70` holds them: each a
|
||||
#! `P` node of its name, its type, its label, and its flags, then its values.
|
||||
#! Where an object leaves one out, the template of its kind, of the document's
|
||||
#! `Definitions`, gives it, as FBX's SDK reads them. And reading the children
|
||||
#! a node holds a value in, as a texture's `FileName`.
|
||||
|
||||
import malunal::linear;
|
||||
module malunal::fbx;
|
||||
|
||||
#! The text of a node's first child of a name, its first property's, or empty
|
||||
#! where it has none.
|
||||
pub def document::text_of(&this, of: u32, name: strview): strview {
|
||||
val found := this.child(of, name) else { return ""; };
|
||||
val held := &this.nodes[found as u64];
|
||||
return "" if held.properties.length == 0;
|
||||
return held.properties[0].text();
|
||||
}
|
||||
|
||||
#! The number of a node's first child of a name, its first property's, or a
|
||||
#! given one where it has none.
|
||||
pub def document::number_of(&this, of: u32, name: strview, given: f64): f64 {
|
||||
val found := this.child(of, name) else { return given; };
|
||||
val held := &this.nodes[found as u64];
|
||||
return given if held.properties.length == 0;
|
||||
return held.properties[0].number();
|
||||
}
|
||||
|
||||
# Notes the templates of the document's definitions.
|
||||
def scene::read_templates(&mut this): void {
|
||||
val definitions := this.document.child(absent, "Definitions") else { return; };
|
||||
val kinds := this.document.children_named(definitions, "ObjectType");
|
||||
for k in 0..kinds.length {
|
||||
var kind := string::new(nothing{});
|
||||
if this.document.property(kinds[k], 0) is some(&named) {
|
||||
kind.append(named.text());
|
||||
}
|
||||
val templates := this.document.children_named(kinds[k], "PropertyTemplate");
|
||||
for t in 0..templates.length {
|
||||
if this.document.child(templates[t], "Properties70") is some(properties) {
|
||||
this.templates.append(template{ kind = string::from(kind.span, nothing{}), properties = properties });
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
# The `P` node of a name among a `Properties70` node's.
|
||||
def entry_in(made: &document, properties: u32, name: strview): maybe<u32> {
|
||||
val list := made.nodes[properties as u64].children.span;
|
||||
for i in 0..list.length {
|
||||
val each := &made.nodes[list[i] as u64];
|
||||
continue if each.properties.length == 0 || each.name.span != "P";
|
||||
return list[i] if each.properties[0].text() == name;
|
||||
}
|
||||
return nothing{};
|
||||
}
|
||||
|
||||
#! An object's property of a name: the `P` node of it, of its own
|
||||
#! `Properties70`, or of its kind's template, where neither has it, nothing.
|
||||
#! A `P` node's properties are its name, type, label, and flags, then its
|
||||
#! values.
|
||||
#! @param object The object's node, or any node holding `Properties70`, as
|
||||
#! `GlobalSettings`.
|
||||
pub def scene::entry(&this, object: u32, name: strview): maybe<u32> {
|
||||
if this.document.child(object, "Properties70") is some(own) {
|
||||
if entry_in(&this.document, own, name) is some(found) {
|
||||
return found;
|
||||
}
|
||||
}
|
||||
val kind := this.document.nodes[object as u64].name.span;
|
||||
for i in 0..this.templates.length {
|
||||
continue if this.templates[i].kind.span != kind;
|
||||
if entry_in(&this.document, this.templates[i].properties, name) is some(found) {
|
||||
return found;
|
||||
}
|
||||
}
|
||||
return nothing{};
|
||||
}
|
||||
|
||||
#! An object's property of a number, or a given one where it has none.
|
||||
pub def scene::number_of(&this, object: u32, name: strview, given: f64): f64 {
|
||||
val found := this.entry(object, name) else { return given; };
|
||||
val held := &this.document.nodes[found as u64];
|
||||
return given if held.properties.length < 5;
|
||||
return held.properties[4].number();
|
||||
}
|
||||
|
||||
#! An object's property of three numbers, as a color or a translation, or a
|
||||
#! given one where it has none.
|
||||
pub def scene::vector_of(&this, object: u32, name: strview, given: vec3): vec3 {
|
||||
val found := this.entry(object, name) else { return given; };
|
||||
val held := &this.document.nodes[found as u64];
|
||||
return given if held.properties.length < 7;
|
||||
return vec3{ held.properties[4].number() as f32, held.properties[5].number() as f32, held.properties[6].number() as f32 };
|
||||
}
|
||||
|
||||
#! An object's property of text, or empty where it has none.
|
||||
pub def scene::text_of(&this, object: u32, name: strview): strview {
|
||||
val found := this.entry(object, name) else { return ""; };
|
||||
val held := &this.document.nodes[found as u64];
|
||||
return "" if held.properties.length < 5;
|
||||
return held.properties[4].text();
|
||||
}
|
||||
|
||||
#! An object's property of a boolean, or a given one where it has none.
|
||||
pub def scene::flag_of(&this, object: u32, name: strview, given: bool): bool {
|
||||
return this.number_of(object, name, given ? 1 : 0) != 0;
|
||||
}
|
||||
@@ -0,0 +1,400 @@
|
||||
#! Contains `scene`, what a document's objects mean, as FBX's SDK reads them:
|
||||
#! its settings; models, the tree of nodes, each placed by FBX's chain of
|
||||
#! translations, pivots, rotations, and scales; meshes, of polygons of any
|
||||
#! number of corners, their normals, places on textures, colors, and
|
||||
#! materials given for each corner; materials, textures, and the files they
|
||||
#! embed; cameras and lights; skins, of clusters binding a mesh's points to
|
||||
#! bones; blend shapes; bind poses; and animations, of stacks, layers, curve
|
||||
#! nodes, and curves. Each part keeps its id, its name, and its node in the
|
||||
#! document, whose other properties `scene::entry` and those after it read.
|
||||
#! Indices between parts are `u32`s, into the scene's lists, `absent` where
|
||||
#! they name nothing.
|
||||
|
||||
import malunal::linear;
|
||||
module malunal::fbx;
|
||||
|
||||
#! The order a model's rotation turns about its axes, the first named turning
|
||||
#! first.
|
||||
pub enum rotation_order: u8 { xyz, xzy, yzx, yxz, zxy, zyx, spheric_xyz }
|
||||
|
||||
#! What a scene's settings say of the whole of it.
|
||||
pub struct settings {
|
||||
#! The axis up, the axis to the front, and the axis across, each 0, 1, or 2
|
||||
#! for x, y, or z, and its sign, 1 or -1.
|
||||
pub var up_axis: u32 = 1;
|
||||
pub var up_sign: i32 = 1;
|
||||
pub var front_axis: u32 = 2;
|
||||
pub var front_sign: i32 = 1;
|
||||
pub var coord_axis: u32;
|
||||
pub var coord_sign: i32 = 1;
|
||||
#! How many centimeters a unit is, as 100 of a file in meters; and what it
|
||||
#! was before the tool that wrote it scaled it.
|
||||
pub var unit_scale: f64 = 1;
|
||||
pub var original_unit_scale: f64 = 1;
|
||||
#! Frames a second, and the time it spans, in seconds.
|
||||
pub var frame_rate: f64 = 30;
|
||||
pub var start: f64;
|
||||
pub var stop: f64;
|
||||
pub var ambient := vec3::zero;
|
||||
}
|
||||
|
||||
#! A model: a node of the tree, and what's there, a mesh, a camera, a light,
|
||||
#! or a bone, as `kind` says, as `Mesh`, `LimbNode`, or `Null`.
|
||||
pub struct model {
|
||||
pub var id: i64;
|
||||
pub var name: string;
|
||||
pub var kind: string;
|
||||
pub var node: u32;
|
||||
pub var parent: u32 = absent;
|
||||
pub var children: vector<u32>;
|
||||
pub var mesh: u32 = absent;
|
||||
#! Its materials, in the order they're connected, which a mesh's polygons'
|
||||
#! materials index.
|
||||
pub var materials: vector<u32>;
|
||||
pub var camera: u32 = absent;
|
||||
pub var light: u32 = absent;
|
||||
#! Where it is within its parent: `Lcl Translation`, `Lcl Rotation` in
|
||||
#! degrees, and `Lcl Scaling`.
|
||||
pub var translation := vec3::zero;
|
||||
pub var rotation := vec3::zero;
|
||||
pub var scale := vec3::one;
|
||||
#! Rotations before and after its own, in degrees, and the order its own
|
||||
#! turns in, which hold only where `rotation_active` is.
|
||||
pub var pre_rotation := vec3::zero;
|
||||
pub var post_rotation := vec3::zero;
|
||||
pub var order := rotation_order::xyz;
|
||||
pub var rotation_active: bool;
|
||||
#! The pivots it's turned and scaled about, and their offsets.
|
||||
pub var rotation_offset := vec3::zero;
|
||||
pub var rotation_pivot := vec3::zero;
|
||||
pub var scaling_offset := vec3::zero;
|
||||
pub var scaling_pivot := vec3::zero;
|
||||
#! Where its mesh is within it, its children not: `GeometricTranslation`,
|
||||
#! `GeometricRotation` in degrees, and `GeometricScaling`.
|
||||
pub var geometric_translation := vec3::zero;
|
||||
pub var geometric_rotation := vec3::zero;
|
||||
pub var geometric_scale := vec3::one;
|
||||
#! `InheritType`: how its parent's scale passes to it; 1, the default, as
|
||||
#! matrices multiply.
|
||||
pub var inherit: u32 = 1;
|
||||
pub var visible := true;
|
||||
}
|
||||
|
||||
#! A run of a mesh's corners.
|
||||
pub struct polygon {
|
||||
pub var first: u64;
|
||||
pub var count: u32;
|
||||
}
|
||||
|
||||
#! A set of places on a texture, one for each corner, of a name.
|
||||
pub struct uv_set {
|
||||
pub var name: string;
|
||||
pub var uvs: vector<vec2>;
|
||||
}
|
||||
|
||||
#! A mesh: points, and polygons of them; what's given of each corner, its
|
||||
#! normal, its places on textures, and its color, each list as long as the
|
||||
#! corners, where it's given; and each polygon's material.
|
||||
pub struct mesh {
|
||||
pub var id: i64;
|
||||
pub var name: string;
|
||||
pub var node: u32;
|
||||
pub var positions: vector<vec3>;
|
||||
pub var polygons: vector<polygon>;
|
||||
#! The points of each polygon's corners, in turn.
|
||||
pub var corners: vector<u32>;
|
||||
pub var normals: vector<vec3>;
|
||||
pub var uv_sets: vector<uv_set>;
|
||||
pub var colors: vector<vec4>;
|
||||
#! Each polygon's material, an index into its model's; empty where none's
|
||||
#! given, as all of the first.
|
||||
pub var materials: vector<u32>;
|
||||
pub var skin: u32 = absent;
|
||||
pub var blend_shapes: vector<u32>;
|
||||
}
|
||||
|
||||
#! A shape a blend shape channel blends a mesh toward: how far each of the
|
||||
#! points it names moves, and its normal turns.
|
||||
pub struct shape {
|
||||
pub var id: i64;
|
||||
pub var name: string;
|
||||
pub var node: u32;
|
||||
pub var points: vector<u32>;
|
||||
pub var offsets: vector<vec3>;
|
||||
pub var normals: vector<vec3>;
|
||||
}
|
||||
|
||||
#! A blend shape: the channels blending a mesh.
|
||||
pub struct blend_shape {
|
||||
pub var id: i64;
|
||||
pub var name: string;
|
||||
pub var node: u32;
|
||||
pub var mesh: u32 = absent;
|
||||
pub var channels: vector<u32>;
|
||||
}
|
||||
|
||||
#! A channel of a blend shape: how far, from 0 to 100, it blends toward its
|
||||
#! shapes, and the weight at which each is whole, where it has more than one.
|
||||
pub struct blend_channel {
|
||||
pub var id: i64;
|
||||
pub var name: string;
|
||||
pub var node: u32;
|
||||
pub var weight: f32;
|
||||
pub var full_weights: vector<f32>;
|
||||
pub var shapes: vector<u32>;
|
||||
}
|
||||
|
||||
#! A skin: the clusters binding a mesh's points to bones.
|
||||
pub struct skin {
|
||||
pub var id: i64;
|
||||
pub var name: string;
|
||||
pub var node: u32;
|
||||
pub var mesh: u32 = absent;
|
||||
pub var clusters: vector<u32>;
|
||||
}
|
||||
|
||||
#! A cluster: the points a bone moves, and how much; the mesh's place when it
|
||||
#! was bound, `transform`, and the bone's, `transform_link`.
|
||||
pub struct cluster {
|
||||
pub var id: i64;
|
||||
pub var name: string;
|
||||
pub var node: u32;
|
||||
pub var skin: u32 = absent;
|
||||
#! The model that's its bone.
|
||||
pub var bone: u32 = absent;
|
||||
pub var points: vector<u32>;
|
||||
pub var weights: vector<f32>;
|
||||
pub var transform := mat4::identity;
|
||||
pub var transform_link := mat4::identity;
|
||||
}
|
||||
|
||||
#! A texture a material maps, and the property it's mapped to, as
|
||||
#! `DiffuseColor` or `NormalMap`.
|
||||
pub struct material_map {
|
||||
pub var property: string;
|
||||
pub var texture: u32;
|
||||
}
|
||||
|
||||
#! A material: its shading model, `phong` or `lambert`, its colors and
|
||||
#! factors, of the defaults FBX's SDK gives where it leaves them out, and the
|
||||
#! textures it maps.
|
||||
pub struct material {
|
||||
pub var id: i64;
|
||||
pub var name: string;
|
||||
pub var node: u32;
|
||||
pub var shading: string;
|
||||
pub var diffuse := vec3{ 0.8, 0.8, 0.8 };
|
||||
pub var diffuse_factor: f32 = 1;
|
||||
pub var ambient := vec3{ 0.2, 0.2, 0.2 };
|
||||
pub var ambient_factor: f32 = 1;
|
||||
pub var specular := vec3{ 0.2, 0.2, 0.2 };
|
||||
pub var specular_factor: f32 = 1;
|
||||
pub var shininess: f32 = 20;
|
||||
pub var emissive := vec3::zero;
|
||||
pub var emissive_factor: f32 = 1;
|
||||
#! `TransparencyFactor`, and `Opacity`, where it's given, which some tools
|
||||
#! write and others don't.
|
||||
pub var transparency: f32;
|
||||
pub var opacity: f32 = 1;
|
||||
pub var reflection_factor: f32 = 1;
|
||||
pub var bump_factor: f32 = 1;
|
||||
pub var maps: vector<material_map>;
|
||||
}
|
||||
|
||||
#! The texture it maps to a property, where it maps one.
|
||||
pub def material::map(&this, property: strview): maybe<u32> {
|
||||
for i in 0..this.maps.length {
|
||||
return this.maps[i].texture if this.maps[i].property.span == property;
|
||||
}
|
||||
return nothing{};
|
||||
}
|
||||
|
||||
#! A texture: the file it names, as written, and relative to the FBX file; the
|
||||
#! set of places it's drawn by, where it names one; how it's placed; and the
|
||||
#! video embedding its file, where one does.
|
||||
pub struct texture {
|
||||
pub var id: i64;
|
||||
pub var name: string;
|
||||
pub var node: u32;
|
||||
pub var file: string;
|
||||
pub var relative: string;
|
||||
pub var uv_set: string;
|
||||
pub var translation := vec3::zero;
|
||||
pub var rotation := vec3::zero;
|
||||
pub var scale := vec3::one;
|
||||
#! 0 where it repeats, 1 where it's clamped.
|
||||
pub var wrap_u: u32;
|
||||
pub var wrap_v: u32;
|
||||
pub var video: u32 = absent;
|
||||
}
|
||||
|
||||
#! A video, as FBX calls an image: the file it names, and its bytes, where the
|
||||
#! FBX file embeds them.
|
||||
pub struct video {
|
||||
pub var id: i64;
|
||||
pub var name: string;
|
||||
pub var node: u32;
|
||||
pub var file: string;
|
||||
pub var relative: string;
|
||||
pub var content: vector<u8>;
|
||||
}
|
||||
|
||||
#! A camera, as its node attribute gives it: distances and angles in the
|
||||
#! file's units and degrees.
|
||||
pub struct camera {
|
||||
pub var id: i64;
|
||||
pub var name: string;
|
||||
pub var node: u32;
|
||||
pub var orthographic: bool;
|
||||
pub var field_of_view: f32 = 40;
|
||||
pub var field_of_view_x: f32 = 40;
|
||||
pub var field_of_view_y: f32 = 40;
|
||||
pub var focal_length: f32 = 34.89;
|
||||
pub var near: f32 = 10;
|
||||
pub var far: f32 = 4000;
|
||||
pub var aspect_width: f32 = 320;
|
||||
pub var aspect_height: f32 = 200;
|
||||
pub var ortho_zoom: f32 = 1;
|
||||
}
|
||||
|
||||
#! What kind of light it is.
|
||||
pub enum light_kind: u8 { point, directional, spot, area, volume }
|
||||
|
||||
#! A light, as its node attribute gives it: its intensity as a percent, 100
|
||||
#! the whole of its color, and a spot's cone's angles in degrees.
|
||||
pub struct light {
|
||||
pub var id: i64;
|
||||
pub var name: string;
|
||||
pub var node: u32;
|
||||
pub var kind: light_kind;
|
||||
pub var color := vec3::one;
|
||||
pub var intensity: f32 = 100;
|
||||
pub var inner_angle: f32;
|
||||
pub var outer_angle: f32 = 45;
|
||||
#! 0 where it doesn't decay, 1 linearly, 2 quadratically, 3 cubically.
|
||||
pub var decay: u32;
|
||||
pub var decay_start: f32;
|
||||
pub var casts_shadows: bool;
|
||||
}
|
||||
|
||||
#! A model's place in a pose: its matrix, of its place in the world, where
|
||||
#! the pose is a bind pose.
|
||||
pub struct pose_entry {
|
||||
pub var model: u32 = absent;
|
||||
pub var id: i64;
|
||||
pub var matrix := mat4::identity;
|
||||
}
|
||||
|
||||
#! A pose: each model's matrix, as when a skin was bound, where it's a bind
|
||||
#! pose.
|
||||
pub struct pose {
|
||||
pub var id: i64;
|
||||
pub var name: string;
|
||||
pub var node: u32;
|
||||
pub var bind: bool;
|
||||
pub var entries: vector<pose_entry>;
|
||||
}
|
||||
|
||||
#! An animation: its layers, and the time it spans, in seconds.
|
||||
pub struct animation_stack {
|
||||
pub var id: i64;
|
||||
pub var name: string;
|
||||
pub var node: u32;
|
||||
pub var start: f64;
|
||||
pub var stop: f64;
|
||||
pub var layers: vector<u32>;
|
||||
}
|
||||
|
||||
#! A layer of an animation: its curve nodes, and how much it weighs, from 0 to
|
||||
#! 100.
|
||||
pub struct animation_layer {
|
||||
pub var id: i64;
|
||||
pub var name: string;
|
||||
pub var node: u32;
|
||||
pub var stack: u32 = absent;
|
||||
pub var weight: f32 = 100;
|
||||
pub var curve_nodes: vector<u32>;
|
||||
}
|
||||
|
||||
#! What kind of part a curve node animates.
|
||||
pub enum part_kind: u8 { none, model, channel, material, camera, light, other }
|
||||
|
||||
#! A channel of a curve node: its name, as `X` of `d|X`, its value where no
|
||||
#! curve's given, and its curve, where one is.
|
||||
pub struct curve_channel {
|
||||
pub var name: string;
|
||||
pub var value: f32;
|
||||
pub var curve: u32 = absent;
|
||||
}
|
||||
|
||||
#! A curve node: the property of a part it animates, as a model's
|
||||
#! `Lcl Translation` or a blend channel's `DeformPercent`, and its channels.
|
||||
pub struct curve_node {
|
||||
pub var id: i64;
|
||||
pub var name: string;
|
||||
pub var node: u32;
|
||||
pub var layer: u32 = absent;
|
||||
pub var target_kind: part_kind;
|
||||
pub var target: u32 = absent;
|
||||
pub var property: string;
|
||||
pub var channels: vector<curve_channel>;
|
||||
}
|
||||
|
||||
#! The channel of a name, as `X`, where it has one.
|
||||
pub def curve_node::channel(&this, name: strview): maybe<&curve_channel> {
|
||||
for i in 0..this.channels.length {
|
||||
return &this.channels[i] if this.channels[i].name.span == name;
|
||||
}
|
||||
return nothing{};
|
||||
}
|
||||
|
||||
#! How a curve goes from a key to the next.
|
||||
pub enum key_interpolation: u8 { constant, linear, cubic }
|
||||
|
||||
#! A curve: its keys, each a time in seconds and a value, how it goes on to the
|
||||
#! next, and a cubic's slopes, to its right and to the next key's left.
|
||||
pub struct curve {
|
||||
pub var id: i64;
|
||||
pub var name: string;
|
||||
pub var node: u32;
|
||||
pub var value: f32;
|
||||
pub var times: vector<f64>;
|
||||
pub var values: vector<f32>;
|
||||
pub var interpolations: vector<key_interpolation>;
|
||||
pub var right_slopes: vector<f32>;
|
||||
pub var next_left_slopes: vector<f32>;
|
||||
}
|
||||
|
||||
#! A property template of the document's definitions, which gives the values
|
||||
#! its objects of a kind leave out.
|
||||
struct template {
|
||||
var kind: string;
|
||||
var properties: u32;
|
||||
}
|
||||
|
||||
#! A scene: the document it's of, and what its objects mean, each kind in a
|
||||
#! list of its own.
|
||||
pub struct scene {
|
||||
pub var document: document;
|
||||
pub var settings: settings;
|
||||
pub var models: vector<model>;
|
||||
pub var meshes: vector<mesh>;
|
||||
pub var shapes: vector<shape>;
|
||||
pub var blend_shapes: vector<blend_shape>;
|
||||
pub var channels: vector<blend_channel>;
|
||||
pub var skins: vector<skin>;
|
||||
pub var clusters: vector<cluster>;
|
||||
pub var materials: vector<material>;
|
||||
pub var textures: vector<texture>;
|
||||
pub var videos: vector<video>;
|
||||
pub var cameras: vector<camera>;
|
||||
pub var lights: vector<light>;
|
||||
pub var poses: vector<pose>;
|
||||
pub var stacks: vector<animation_stack>;
|
||||
pub var layers: vector<animation_layer>;
|
||||
pub var curve_nodes: vector<curve_node>;
|
||||
pub var curves: vector<curve>;
|
||||
#! The models at the root.
|
||||
pub var roots: vector<u32>;
|
||||
var templates: vector<template>;
|
||||
}
|
||||
@@ -0,0 +1,103 @@
|
||||
#! Contains where models are: a model's matrix within its parent, by FBX's
|
||||
#! chain of translation, rotation offset and pivot, pre-rotation, rotation,
|
||||
#! post-rotation, and scaling offset and pivot, as its SDK puts them together;
|
||||
#! its mesh's within it; and its matrix in the world, through its parents. And
|
||||
#! turning a scene's axes and units into y up, z to the front, and meters.
|
||||
|
||||
import std::math;
|
||||
import malunal::linear;
|
||||
module malunal::fbx;
|
||||
|
||||
# A rotation of angles in degrees about x, y, and z, turning in an order.
|
||||
def euler_matrix(degrees: vec3, order: rotation_order): mat4 {
|
||||
val k := (math::pi / 180) as f32;
|
||||
val x := mat4::rotation(quat::axis_angle(vec3::right, degrees.x * k));
|
||||
val y := mat4::rotation(quat::axis_angle(vec3::up, degrees.y * k));
|
||||
val z := mat4::rotation(quat::axis_angle(vec3::back, degrees.z * k));
|
||||
# The axis turning first is the rightmost, nearest what's turned.
|
||||
if order == rotation_order::xzy {
|
||||
return y.mul(&z).mul(&x);
|
||||
}
|
||||
if order == rotation_order::yzx {
|
||||
return x.mul(&z).mul(&y);
|
||||
}
|
||||
if order == rotation_order::yxz {
|
||||
return z.mul(&x).mul(&y);
|
||||
}
|
||||
if order == rotation_order::zxy {
|
||||
return y.mul(&x).mul(&z);
|
||||
}
|
||||
if order == rotation_order::zyx {
|
||||
return x.mul(&y).mul(&z);
|
||||
}
|
||||
return z.mul(&y).mul(&x);
|
||||
}
|
||||
|
||||
#! Its matrix within its parent: its translation, rotation offset, rotation
|
||||
#! pivot, pre-rotation, rotation, post-rotation turned back, the pivot taken
|
||||
#! away, then its scaling offset and pivot, scale, and the pivot taken away,
|
||||
#! as `T * Roff * Rp * Rpre * R * Rpost⁻¹ * Rp⁻¹ * Soff * Sp * S * Sp⁻¹`.
|
||||
#! Where its rotation isn't active, its pre- and post-rotations and order are
|
||||
#! taken as none and `xyz`.
|
||||
pub def model::local_matrix(&this): mat4 {
|
||||
val active := this.rotation_active;
|
||||
val order := active ? this.order : rotation_order::xyz;
|
||||
val pre := active ? euler_matrix(this.pre_rotation, rotation_order::xyz) : mat4::identity;
|
||||
val post := active ? euler_matrix(this.post_rotation, rotation_order::xyz).transposed() : mat4::identity;
|
||||
val turned := euler_matrix(this.rotation, order);
|
||||
var made := mat4::translation(this.translation);
|
||||
made = made.mul(&mat4::translation(this.rotation_offset));
|
||||
made = made.mul(&mat4::translation(this.rotation_pivot));
|
||||
made = made.mul(&pre).mul(&turned).mul(&post);
|
||||
made = made.mul(&mat4::translation(this.rotation_pivot.negate()));
|
||||
made = made.mul(&mat4::translation(this.scaling_offset));
|
||||
made = made.mul(&mat4::translation(this.scaling_pivot));
|
||||
made = made.mul(&mat4::scaling(this.scale));
|
||||
made = made.mul(&mat4::translation(this.scaling_pivot.negate()));
|
||||
return made;
|
||||
}
|
||||
|
||||
#! Its mesh's matrix within it, which its children don't follow:
|
||||
#! `GeometricTranslation`, `GeometricRotation`, and `GeometricScaling`.
|
||||
pub def model::geometry_matrix(&this): mat4 {
|
||||
val turned := euler_matrix(this.geometric_rotation, rotation_order::xyz);
|
||||
return mat4::translation(this.geometric_translation).mul(&turned).mul(&mat4::scaling(this.geometric_scale));
|
||||
}
|
||||
|
||||
#! A model's matrix in the world: its parents', each's within its own, then
|
||||
#! its own, multiplied as matrices are, as FBX's default way of inheriting
|
||||
#! does.
|
||||
pub def scene::world_matrix(&this, of: u32): mat4 {
|
||||
var made := this.models[of as u64].local_matrix();
|
||||
var above := this.models[of as u64].parent;
|
||||
var steps: u64 = 0;
|
||||
while above != absent && steps < this.models.length {
|
||||
made = this.models[above as u64].local_matrix().mul(&made);
|
||||
above = this.models[above as u64].parent;
|
||||
steps++;
|
||||
}
|
||||
return made;
|
||||
}
|
||||
|
||||
#! The matrix turning the scene's axes into x across, y up, and z to the
|
||||
#! front, as glTF's are, mirroring where they're left-handed.
|
||||
pub def settings::axes(&this): mat4 {
|
||||
var made := mat4{};
|
||||
made.m[15] = 1;
|
||||
made.m[(this.coord_axis % 3) as u64 * 4] = this.coord_sign < 0 ? -1 : 1;
|
||||
made.m[(this.up_axis % 3) as u64 * 4 + 1] = this.up_sign < 0 ? -1 : 1;
|
||||
made.m[(this.front_axis % 3) as u64 * 4 + 2] = this.front_sign < 0 ? -1 : 1;
|
||||
return made;
|
||||
}
|
||||
|
||||
#! How many meters a unit is.
|
||||
pub def settings::meters_per_unit(&this): f32 {
|
||||
return (this.unit_scale / 100) as f32;
|
||||
}
|
||||
|
||||
#! The matrix turning the scene into meters, with x across, y up, and z to the
|
||||
#! front: its axes, scaled.
|
||||
pub def settings::conversion(&this): mat4 {
|
||||
val k := this.meters_per_unit();
|
||||
return mat4::scaling(vec3{ k, k, k }).mul(&this.axes());
|
||||
}
|
||||
@@ -0,0 +1,240 @@
|
||||
#! Contains writing a document as binary FBX, `encode` and `save`, and making
|
||||
#! properties to build one by hand. Arrays are written as they are, not
|
||||
#! compressed, which FBX allows; nodes end with a record of zeros where they
|
||||
#! have children, and where Blender's writer finds Autodesk's reader wants one,
|
||||
#! and the file with the footer Autodesk's writer gives.
|
||||
|
||||
import std::io;
|
||||
import std::math;
|
||||
module malunal::fbx;
|
||||
|
||||
#! A property of a boolean.
|
||||
pub def property::of_bool(value: bool): property {
|
||||
return property{ kind = property_kind::boolean, integer = value ? 1 : 0 };
|
||||
}
|
||||
|
||||
#! A property of a 32-bit integer.
|
||||
pub def property::of_int32(value: i32): property {
|
||||
return property{ kind = property_kind::int32, integer = value as i64 };
|
||||
}
|
||||
|
||||
#! A property of a 64-bit integer, as an object's id.
|
||||
pub def property::of_int64(value: i64): property {
|
||||
return property{ kind = property_kind::int64, integer = value };
|
||||
}
|
||||
|
||||
#! A property of a 32-bit float.
|
||||
pub def property::of_float32(value: f32): property {
|
||||
return property{ kind = property_kind::float32, real = value as f64 };
|
||||
}
|
||||
|
||||
#! A property of a 64-bit float.
|
||||
pub def property::of_float64(value: f64): property {
|
||||
return property{ kind = property_kind::float64, real = value };
|
||||
}
|
||||
|
||||
#! A property of text.
|
||||
pub def property::of_text(value: strview): property {
|
||||
var made := property{ kind = property_kind::text };
|
||||
made.bytes.extend(value);
|
||||
return made;
|
||||
}
|
||||
|
||||
#! A property of bytes, as an embedded file's.
|
||||
pub def property::of_bytes(value: span<u8>): property {
|
||||
var made := property{ kind = property_kind::raw };
|
||||
made.bytes.extend(value);
|
||||
return made;
|
||||
}
|
||||
|
||||
#! A property of an array of integers, of a kind: `booleans`, `int32s`, or
|
||||
#! `int64s`.
|
||||
pub def property::of_integers(kind: property_kind, values: span<i64>): property {
|
||||
var made := property{ kind = kind };
|
||||
made.integers.extend(values);
|
||||
return made;
|
||||
}
|
||||
|
||||
#! A property of an array of floats, of a kind: `float32s` or `float64s`.
|
||||
pub def property::of_reals(kind: property_kind, values: span<f64>): property {
|
||||
var made := property{ kind = kind };
|
||||
made.reals.extend(values);
|
||||
return made;
|
||||
}
|
||||
|
||||
# The footer's first 16 bytes, and its last, as Autodesk's writer gives them.
|
||||
const footer_id: u8[16] = [0xFA, 0xBC, 0xAB, 0x09, 0xD0, 0xC8, 0xD4, 0x66, 0xB1, 0x76, 0xFB, 0x83, 0x1C, 0xF7, 0x26, 0x7E];
|
||||
const footer_magic: u8[16] = [0xF8, 0x5A, 0x8C, 0x6A, 0xDE, 0xF5, 0xD9, 0x7E, 0xEC, 0xE9, 0x0C, 0xE3, 0x75, 0x8F, 0x29, 0x0B];
|
||||
|
||||
#! Writes a document as binary FBX, of its version, or 7.4 where it's of
|
||||
#! before 7.0.
|
||||
#! @param made The document.
|
||||
#! @returns The file's bytes, or why it couldn't be written: `malformed` where a
|
||||
#! node's name is longer than 255 bytes, or a file of 7.4 or before
|
||||
#! would pass 4 GB.
|
||||
pub def encode(made: &document): result<vector<u8>, fbx_error> {
|
||||
val version: u32 = made.version >= 7000 ? made.version : 7400;
|
||||
val wide := version >= 7500;
|
||||
var out := vector::<u8>::new();
|
||||
out.extend(binary_magic);
|
||||
out.append(0);
|
||||
out.append(0x1A);
|
||||
out.append(0);
|
||||
put_u32(&mut out, version);
|
||||
# An ASCII document's objects are named as `Class::name`, which binary FBX
|
||||
# writes as `name\0\1Class`.
|
||||
var renamed: u32 = absent;
|
||||
if !made.binary {
|
||||
if made.child(absent, "Objects") is some(objects) {
|
||||
renamed = objects;
|
||||
}
|
||||
}
|
||||
for k in 0..made.roots.length {
|
||||
write_node(&mut out, made, made.roots[k], k + 1 == made.roots.length, wide, renamed) else (e) { return e; };
|
||||
}
|
||||
put_zeros(&mut out, wide ? 25 : 13);
|
||||
out.extend(footer_id[:]);
|
||||
put_zeros(&mut out, 4);
|
||||
val past := out.length % 16;
|
||||
put_zeros(&mut out, past == 0 ? 16 : 16 - past);
|
||||
put_u32(&mut out, version);
|
||||
put_zeros(&mut out, 120);
|
||||
out.extend(footer_magic[:]);
|
||||
return out;
|
||||
}
|
||||
|
||||
#! Writes a document to a file, as `encode` writes it, its folder made where it
|
||||
#! isn't.
|
||||
#! @returns Nothing, or why it couldn't be written: `unreadable` where the file
|
||||
#! couldn't be.
|
||||
pub def save(made: &document, at: &path): result<void, fbx_error> {
|
||||
val bytes := encode(made) else (e) { return e; };
|
||||
if at.parent() is some(&above) {
|
||||
_ = io::create_directories(above);
|
||||
}
|
||||
io::write_file(at, bytes.span) else (_) { return failed(failure::unreadable, $"{at.span} couldn't be written.".span); };
|
||||
return;
|
||||
}
|
||||
|
||||
#! Writes a document to a file named by text, as `save` does.
|
||||
pub def save(made: &document, at: strview): result<void, fbx_error> {
|
||||
val named := path::parse(at) else (_) { return failed(failure::unreadable, $"{at} isn't a path.".span); };
|
||||
return save(made, &named);
|
||||
}
|
||||
|
||||
def put_u32(out: &mut vector<u8>, value: u32): void {
|
||||
for i in 0..4u {
|
||||
out.append(((value >> (8 * i)) & 0xFF) as u8);
|
||||
}
|
||||
}
|
||||
|
||||
def put_u64(out: &mut vector<u8>, value: u64): void {
|
||||
for i in 0..8u {
|
||||
out.append(((value >> (8 * i)) & 0xFF) as u8);
|
||||
}
|
||||
}
|
||||
|
||||
def put_zeros(out: &mut vector<u8>, count: u64): void {
|
||||
for _ in 0..count {
|
||||
out.append(0);
|
||||
}
|
||||
}
|
||||
|
||||
# Writes a number at a place written before, 32 or 64 bits wide.
|
||||
def patch(out: &mut vector<u8>, at: u64, value: u64, wide: bool): void {
|
||||
val bytes: u64 = wide ? 8 : 4;
|
||||
for i in 0..bytes {
|
||||
out[at + i] = ((value >> (8 * i)) & 0xFF) as u8;
|
||||
}
|
||||
}
|
||||
|
||||
# Writes a node: its header, its properties, its children, and the record of
|
||||
# zeros ending them, where it needs one.
|
||||
def write_node(out: &mut vector<u8>, made: &document, index: u32, last: bool, wide: bool, renamed: u32): result<void, fbx_error> {
|
||||
val held := &made.nodes[index as u64];
|
||||
return failed(failure::malformed, $"A node's name is {held.name.length} bytes, past the 255 there may be.".span) if held.name.length > 255;
|
||||
val begun := out.length;
|
||||
put_zeros(out, wide ? 24 : 12);
|
||||
out.append(held.name.length as u8);
|
||||
out.extend(held.name.span);
|
||||
val properties_begun := out.length;
|
||||
for i in 0..held.properties.length {
|
||||
val name := held.properties[i].text();
|
||||
if i == 1 && renamed != absent && held.parent == renamed && held.properties[i].kind == property_kind::text && name.find("::") is some(at) {
|
||||
var turned := string::from(name.substr(at + 2, name.length - at - 2), nothing{});
|
||||
turned.push(0);
|
||||
turned.push(1);
|
||||
turned.append(name.substr(0, at));
|
||||
write_property(out, &property::of_text(turned.span));
|
||||
continue;
|
||||
}
|
||||
write_property(out, &held.properties[i]);
|
||||
}
|
||||
val properties_length := out.length - properties_begun;
|
||||
for k in 0..held.children.length {
|
||||
write_node(out, made, held.children[k], k + 1 == held.children.length, wide, renamed) else (e) { return e; };
|
||||
}
|
||||
val always := held.name.span == "AnimationStack" || held.name.span == "AnimationLayer";
|
||||
if held.children.length != 0 || (held.properties.length == 0 && !last) || always {
|
||||
put_zeros(out, wide ? 25 : 13);
|
||||
}
|
||||
val end := out.length as u64;
|
||||
return failed(failure::malformed, "It would pass 4 GB, which FBX of 7.4 and before can't.") if !wide && end > 0xFFFFFFFF;
|
||||
val step: u64 = wide ? 8 : 4;
|
||||
patch(out, begun, end, wide);
|
||||
patch(out, begun + step, held.properties.length as u64, wide);
|
||||
patch(out, begun + 2 * step, properties_length as u64, wide);
|
||||
return;
|
||||
}
|
||||
|
||||
# Writes a property: its type's letter, then its value.
|
||||
def write_property(out: &mut vector<u8>, held: &property): void {
|
||||
val kind := held.kind;
|
||||
if kind == property_kind::boolean {
|
||||
out.append('C');
|
||||
out.append(held.integer as u8);
|
||||
} else if kind == property_kind::int16 {
|
||||
out.append('Y');
|
||||
val v := held.integer as u64;
|
||||
out.append((v & 0xFF) as u8);
|
||||
out.append(((v >> 8) & 0xFF) as u8);
|
||||
} else if kind == property_kind::int32 {
|
||||
out.append('I');
|
||||
put_u32(out, held.integer as u64 as u32);
|
||||
} else if kind == property_kind::int64 {
|
||||
out.append('L');
|
||||
put_u64(out, held.integer as u64);
|
||||
} else if kind == property_kind::float32 {
|
||||
out.append('F');
|
||||
put_u32(out, math::bits_of(held.real as f32));
|
||||
} else if kind == property_kind::float64 {
|
||||
out.append('D');
|
||||
put_u64(out, math::bits_of(held.real));
|
||||
} else if kind == property_kind::text || kind == property_kind::raw {
|
||||
out.append(kind == property_kind::text ? 'S' : 'R');
|
||||
put_u32(out, held.bytes.length as u32);
|
||||
out.extend(held.bytes.span);
|
||||
} else {
|
||||
val codes: u8[5] = ['b', 'i', 'l', 'f', 'd'];
|
||||
val sizes: u64[5] = [1, 4, 8, 4, 8];
|
||||
val which := (kind as u8 - property_kind::booleans as u8) as u64;
|
||||
val count := held.count();
|
||||
out.append(codes[which]);
|
||||
put_u32(out, count as u32);
|
||||
put_u32(out, 0);
|
||||
put_u32(out, (count * sizes[which]) as u32);
|
||||
for i in 0..count {
|
||||
if which == 0 {
|
||||
out.append(held.integers[i] as u8);
|
||||
} else if which == 1 {
|
||||
put_u32(out, held.integers[i] as u64 as u32);
|
||||
} else if which == 2 {
|
||||
put_u64(out, held.integers[i] as u64);
|
||||
} else if which == 3 {
|
||||
put_u32(out, math::bits_of(held.reals[i] as f32));
|
||||
} else {
|
||||
put_u64(out, math::bits_of(held.reals[i]));
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
Reference in new issue
Block a user