Initial Commit

This commit is contained in:
SoraKatadzuma committed 2026-11-12 19:27:17 -06:00
commit ed1188f440
36 files changed
+8436

No files matched your search

+541
View File
@@ -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);
}
}