commit ed1188f4407fe2cd1f9925a4ebddb6395bc1efbd Author: SoraKatadzuma Date: Fri Oct 30 12:04:54 2026 -0500 Initial Commit diff --git a/.editorconfig b/.editorconfig new file mode 100644 index 0000000..c6c8b36 --- /dev/null +++ b/.editorconfig @@ -0,0 +1,9 @@ +root = true + +[*] +indent_style = space +indent_size = 2 +end_of_line = lf +charset = utf-8 +trim_trailing_whitespace = true +insert_final_newline = true diff --git a/.gitignore b/.gitignore new file mode 100644 index 0000000..cfecb95 --- /dev/null +++ b/.gitignore @@ -0,0 +1 @@ +.blossom diff --git a/README.md b/README.md new file mode 100644 index 0000000..28c9ce4 --- /dev/null +++ b/README.md @@ -0,0 +1,158 @@ +# models +Models read and written, of three formats, each a library of its own: `gltf`, glTF 2.0, read whole and checked and written; `obj`, Wavefront's OBJ and the MTL files of its materials, read and written; and `fbx`, Autodesk's FBX, binary or ASCII, read as its tree of nodes and as a scene of what they mean, the tree written as binary. It's Sakura's, built with [blossom](https://git.malunal.studio/sakura/blossom), reads std's `containers`, `io`, `json`, and `math`, and places what it reads by the vectors, rotations, and matrices of `linear`, of the [physics](https://git.malunal.studio/malunal/physics) package. It was `gltf` until 2026-11-12, when it learned OBJ and FBX. + +A project reads them by requiring this folder, or its remote, and naming the libraries it uses among a target's `deps`, each `malunal.NAME`, whose module is `malunal::NAME`: + +```yaml +requires: +- https://git.malunal.studio/malunal/models@v1.0.0 +targets: +- name: game + type: program + deps: [malunal.gltf, malunal.obj, malunal.fbx] +``` + +| Library | Holds | +|---|---| +| `malunal.gltf` | glTF 2.0: `.gltf` and the files it names, or `.glb`; every part, checked as it's read, each accessor's numbers read as floats or integers; and written, as either, of what was read or built by hand | +| `malunal.obj` | Wavefront's OBJ: positions, their colors, places on textures, and normals; faces of any number of corners, lines, and points; objects, groups, and smoothing groups; and the materials of its MTL files, of every map and option; read, and written as OBJ and MTL | +| `malunal.fbx` | Autodesk's FBX, 7.0 and after: binary, its arrays compressed by zlib or not, and ASCII, read into one tree of nodes; a scene of it, its models placed by FBX's chain of pivots and rotations, meshes, materials, textures and the images they embed, cameras, lights, skins, blend shapes, bind poses, and animations; and the tree written as binary | + +## gltf +```sakura +import malunal::gltf; + +val tree := gltf::load("models/tree.glb") else (e) { io::println(e.describe().span); ... }; +for &part in tree.meshes[0].primitives { + val places := tree.floats(part.find("POSITION").expect("...")); # x, y, z of each vertex + val indices := tree.integers(part.indices.expect("...")); # three a triangle + val look := &tree.materials[part.material.expect("...")]; # base color, textures, alpha +} +val placed := tree.world_matrix(2); # a node, through its parents +``` +`gltf::decode(bytes, folder)` reads bytes already in memory, the files they name found in the folder. An image is given as the bytes of its file, PNG or JPEG, as [image](https://git.malunal.studio/malunal/image) reads them, which `gltf` doesn't decode itself. + +```sakura +var quad := gltf::asset::new("my tool"); +val p := quad.add_floats(places.span, gltf::element::vec3); # its least and most worked out +val i := quad.add_indices(indices.span); # shorts where they fit +var part := gltf::primitive{ indices = i }; +part.attributes.append(gltf::attribute{ name = string::from("POSITION", nothing{}), accessor = p }); +... # meshes, nodes, a scene +gltf::save(&quad, "models/quad.glb") else (e) { ... }; # or .gltf, by the name +``` +`gltf::encode(&asset, binary)` gives the bytes of either. Writing is what reading reads, so an asset read and written reads back the same. + +### What's read +- **Files**: `.gltf`, its buffers and images named as files beside it, their URIs percent-decoded, or as `data:` URIs of base64; and `.glb`, its JSON and binary chunks, other chunks passed over. A URI naming another place, as `https:`, isn't fetched, and is `unsupported`. +- **Every part of glTF 2.0**: scenes, and the scene shown at first; nodes, each with its children and parent, its mesh, camera, skin, and light, its morph weights, and where it is, as a matrix, taken apart into a translation, rotation, and scale, x's negative where it mirrors, or those, put together into a matrix; meshes, their primitives' attributes, indices, material, mode, and morph targets; materials of the metallic-rough model, each texture they name with its `TEXCOORD` set, a normal map's scale and occlusion's strength, emission, and alpha opaque, cut out, or blended, and double sided; textures, samplers, and images; cameras, perspective or orthographic; skins; and animations, their channels and samplers, linear, step, or cubic spline. +- **Accessors** of every component type and element, normalized or not, interleaved by a view's stride, a matrix's columns each begun at a multiple of 4 bytes, and sparse, over a view's elements or over zeros. `floats` makes integers floats, and normalized ones fractions, as glTF says, -1 at the least for a signed one; `integers` reads indices and joints as they are. +- **Extensions**: `KHR_lights_punctual`'s directional, point, and spot lights; `KHR_materials_unlit`; `KHR_materials_emissive_strength`, multiplying emission; and `KHR_mesh_quantization`, whose accessors of integers `floats` reads anyway. An asset requiring another is `unsupported`, naming it. One using another without requiring it is read without what it adds, and names it in `extensions`. +- **What's checked**: the version is 2; every index names a part there is; each buffer view lies within its buffer, of a stride from 4 to 252, a multiple of 4; each accessor lies within its view, its stride no less than an element; each sparse index names an element; a primitive's attributes are of one count, and its indices name vertices it has; a skin's inverse binds are a matrix of floats for each joint; an animation's times are floats; each node has one parent at most, following parents up ends, and a scene's nodes are roots. What breaks it is `malformed`, saying what and where, as `meshes[2].primitives[0]: its index 9 is past its 8 vertices.` + +A `gltf_error` holds the first 240 bytes of why, so it's plain data, as std's errors are; `obj_error` and `fbx_error` are the same. + +### What's written +- **Files**: `.glb`, the first buffer its binary chunk where it names no file; or `.gltf`. A buffer of no URI, or a `data:` one, is written as a `data:` URI of its bytes, but the `.glb` file's chunk; one naming a file names it still, and `save` writes its bytes beside the model, as it does an image's that names a file, the folders made. An image in a view is written so; one of neither a view nor a file, as a `data:` URI of its type, PNG where it's none. +- **Every part read**, each member left out where it's glTF's default, as a node of no translation, a material's factors of 1, or a sampler that repeats. A node is written by its translation, rotation, and scale, which glTF holds its matrix is no more than. A material's emission brighter than 1 is written as its color and its strength, by `KHR_materials_emissive_strength`; a material unlit, by `KHR_materials_unlit`; lights, by `KHR_lights_punctual`. `KHR_mesh_quantization`, where it was read, is used and required still; an extension used that isn't read isn't written, as its data is gone. +- **Numbers**: floats as the shortest text that reads back as them; an accessor's least and most as floats where they're a float's. `add_floats` works them out, as glTF asks of positions; `add_indices` writes unsigned shorts where every index is less than 65535, and unsigned ints otherwise; `add_view` begins each view of the first buffer at a multiple of 4 bytes. +- **What fails**: a number infinite or NaN, or a name that isn't UTF-8, `malformed`; a file that can't be written, `unreadable`, as one read is. + +## obj +```sakura +import malunal::obj; + +val crate := obj::load("models/crate.obj") else (e) { ... }; # its MTL files read from beside it +for &face in crate.faces { + for corner in crate.corners_of(&face) { # three or more + val at := crate.positions[corner.position]; + if corner.uv != obj::absent { val uv := crate.uvs[corner.uv]; } + } + val look := &crate.materials[face.material]; # where it isn't `absent` +} +obj::save(&crate, "out/crate.obj") else (e) { ... }; # and out/crate.mtl +``` +`obj::decode(text, folder)` reads text already in memory, its MTL files from the folder; `obj::decode_materials(text)` reads an MTL file's alone, and `obj::encode` and `obj::encode_materials` give the text of each. + +### What's read +- **Statements**: `v`, its weight passed over and its color kept where it gives `x y z r g b`; `vt`; `vn`; `f` and `fo`, of `v`, `v/vt`, `v//vn`, or `v/vt/vn`, each index counted from 1, or back from the last given where it's negative, and naming a position given after it where it does; `l`, `p`, `o`, `g`, `s` of a number or `off`, `usemtl`, and `mtllib` of one file or more, or of one whose name has a space where that's the file beside it. A line ending with `\` goes on in the next; a comment begins a line, or a word, with `#`. Statements of curves and surfaces, and of display, are passed over. +- **A model**: its positions, colors, places on textures, and normals; its corners, and its faces, lines, and points, each a run of them, with its material, smoothing group, object, and group. Indices are counted from 0; `absent` is a corner's that names no place on a texture or no normal, and an element's of no material, object, or group. +- **Materials**: `newmtl`; `Ka`, `Kd`, `Ks`, `Ke`, and `Tf`, of three numbers or one, `xyz` passed over and `spectral` not read; `Ns`, `Ni`, `d` and `Tr`, `illum`, `sharpness`; the physically based `Pr`, `Pm`, `Ps`, `Pc`, `Pcr`, `aniso`, and `anisor`; and maps, `map_Ka`, `map_Kd`, `map_Ks`, `map_Ke`, `map_Ns`, `map_d`, `bump` and `map_bump`, `disp`, `decal`, `refl`, `norm`, `map_Pr`, `map_Pm`, and `map_Ps`, with their options, `-blendu`, `-blendv`, `-boost`, `-mm`, `-o`, `-s`, `-t`, `-texres`, `-clamp`, `-bm`, `-imfchan`, `-type`, and `-cc`, and the file after them, which may hold spaces. A model's materials are its MTL files', each name kept by the first that gives it, then one of each name `usemtl` gives that none of them has, of the defaults; an MTL file not found is named in `missing`, and the model read without it. +- **What's refused**, `malformed`, saying the line: a number that isn't one; a position of fewer than three; a face of fewer than three corners, a line of fewer than two; an index of 0, or counted back past the first; an index naming what there isn't; and a statement of an MTL file before its first `newmtl`. + +### What's written +An OBJ file of its positions, their colors where it has a color for each, places on textures, and normals, then its faces, lines, and points, each `o`, `g`, `usemtl`, and `s` written where what follows is of another; and an MTL file of its materials, beside it, named as the first it read from or as the OBJ file with `.mtl`, each map's options written where they aren't their defaults. Numbers are the shortest text that reads back as them, so a model read, written, and read again is the same. + +## fbx +```sakura +import malunal::fbx; + +val s := fbx::load_scene("models/hero.fbx") else (e) { ... }; +for i in 0..s.models.length { + val m := &s.models[i]; + val placed := s.world_matrix(i as u32); # FBX's chain, through its parents + if m.mesh != fbx::absent { + val mesh := &s.meshes[m.mesh]; # polygons, and each corner's normal and uvs + val within := m.geometry_matrix(); # where its mesh is within it + } +} +val to_meters := s.settings.conversion(); # y up, z to the front, in meters +val turned := s.curves[0].at(0.5); # a curve's value half a second in +``` +`fbx::load` and `fbx::decode` read the tree of nodes alone, a `document`, and `scene::of` what it means; the scene keeps the document, and `scene::entry`, `number_of`, `vector_of`, `text_of`, and `flag_of` read any property of an object, its own or its kind's template's. `fbx::encode` and `fbx::save` write a document as binary, and `property::of_int64`, `of_text`, `of_reals`, and the others make properties to build one by hand. + +FBX is Autodesk's, and undocumented: what's read here is what Blender's importer, and others, have found it to be. + +### What's read +- **Files**: binary, of 7.0 and after, 32 bits wide or, from 7.5, 64, each array raw or compressed by zlib, which the library inflates itself, as `image` does PNG's, so the package needs no more than `physics`; and ASCII, nodes of `Name: properties`, children within braces, `;` comments, arrays as `*count { a: ... }` or as numbers going on past a line's end, numbers with a point or an exponent read as floats and others as integers. Either is a `document`: its version, and its nodes in one list, each a name, properties, children, and a parent. FBX before 7.0, whose objects are named rather than numbered, is `unsupported`. +- **A scene**: `GlobalSettings`' axes, units, frame rate, and time; and the objects of `Objects`, joined by `Connections`. **Models**: their kind, as `Mesh`, `LimbNode`, or `Null`; their parent and children, mesh, materials in their order, camera, and light; and `Lcl Translation`, `Lcl Rotation`, `Lcl Scaling`, the pre- and post-rotations, the rotation order, the rotation and scaling offsets and pivots, and the geometric translation, rotation, and scaling. **Meshes**: points and polygons of any number of corners; normals, every set of places on textures, and colors, each spread to one for each corner, from by corner, by point, by polygon, or once for all, directly or through indices; and each polygon's material. **Materials**: shading model, diffuse, ambient, specular, and emissive colors and factors, shininess, transparency, opacity, reflection and bump factors, and the textures mapped to each property; **textures**: their file, as written and relative, set of places, placement, and wrapping; **videos**: their file and the bytes embedded, binary's raw or ASCII's base64. **Cameras** and **lights**, of their node attributes. **Skins**, of clusters, each its bone, points, weights, and matrices bound by; **blend shapes**, of channels, each's weight and shapes, each shape's points, offsets, and normals; **bind poses**; and **animations**, of stacks, layers, curve nodes, each the property of a part it animates and its channels' values, and curves, their keys' times in seconds, values, interpolation, constant, linear, or cubic, and a cubic's slopes. A value an object leaves out is its kind's template's, of `Definitions`, or else FBX's SDK's default. +- **Where models are**: `local_matrix` puts together `T * Roff * Rp * Rpre * R * Rpost⁻¹ * Rp⁻¹ * Soff * Sp * S * Sp⁻¹`, as FBX's SDK does, the pre- and post-rotations and order holding only where `RotationActive` does, as Blender's importer finds; `world_matrix` multiplies a model's parents' in turn; and `settings::conversion` turns a scene's axes and units to y up, z to the front, and meters, mirroring a scene of left-handed axes. +- **What's refused**, `malformed`, saying where: a node, property, or array past the file's end; properties not as long as their node says; a property of an unknown type; an array that won't inflate, or inflates to another length; ASCII of a node not followed by `:`, a brace not closed, or an array not holding as many numbers as it says; and a mesh's polygon naming a point it hasn't. + +### What's written +A document, as binary FBX of its version, or 7.4 where it's of before 7.0: each node, its properties, and its children, ended by a record of zeros where it has children, or none and no properties, or is an `AnimationStack` or `AnimationLayer`, as Blender's writer finds Autodesk's reader wants, and the file ended by Autodesk's footer; arrays as they are, not compressed. An ASCII document's object names, `Class::name`, are written as binary's `name\0\1Class`. A document read and written reads back the same. + +## Layout +`gltf/` is the module `malunal::gltf`, `obj/` is `malunal::obj`, and `fbx/` is `malunal::fbx`. + +| Path | Holds | +|---|---| +| `gltf/gltf.sakura` | `asset`, `gltf_error` and its `failure`, the extensions read, and `load` and `decode` | +| `gltf/parts.sakura` | The parts of an asset: scenes, nodes, meshes and their primitives, materials and the textures they name, textures, samplers, images, cameras, skins, animations, and lights | +| `gltf/accessors.sakura` | Buffers, their views, and accessors; reading an accessor's numbers, sparse ones among them | +| `gltf/nodes.sakura` | The tree of nodes: each placed by a matrix or a translation, rotation, and scale, each child's parent, and a node's world matrix | +| `gltf/parse.sakura` | Reading the JSON into the parts, in the order they need one another, each checked as it's read | +| `gltf/members.sakura` | Reading the JSON's members: each of its kind, with its default, an index checked against its list | +| `gltf/files.sakura` | A `.glb` file's chunks, and the bytes a URI names: a `data:` URI's base64, or a file beside the asset | +| `gltf/writing.sakura` | Writing an asset: `encode` and `save`, its JSON and its buffers, and building one by hand, `asset::new`, `add_view`, `add_floats`, `add_indices`, and `add_image` | +| `obj/obj.sakura` | `model`, its `corner`s and `element`s, `obj_error` and its `failure`, and `load`, `decode`, and `load_materials` | +| `obj/text.sakura` | Reading OBJ's and MTL's text: statements, a line ending with `\` joined to the next, and their words and numbers | +| `obj/reading.sakura` | Reading an OBJ file's statements into a model, its corners checked once all are read, and the materials of the MTL files it names | +| `obj/materials.sakura` | `material`, `texture_map` and its `map_slot`, and reading an MTL file, `decode_materials` | +| `obj/writing.sakura` | Writing a model as OBJ and its materials as MTL: `encode`, `encode_materials`, and `save` | +| `fbx/fbx.sakura` | `document`, its `node`s and their `property`s, `fbx_error` and its `failure`, and `load` and `decode` | +| `fbx/binary.sakura` | Reading binary FBX: its header, nodes, and properties, arrays raw or compressed | +| `fbx/ascii.sakura` | Reading ASCII FBX into the same tree | +| `fbx/inflate.sakura` | Inflating zlib's data, of DEFLATE's Huffman codes, `image`'s PNG reader's, copied | +| `fbx/writing.sakura` | Writing a document as binary FBX, `encode` and `save`, and making properties to build one by hand | +| `fbx/scene.sakura` | `scene` and its parts: settings, models, meshes, shapes, blend shapes and channels, skins and clusters, materials, textures, videos, cameras, lights, poses, and animations' stacks, layers, curve nodes, and curves | +| `fbx/properties.sakura` | Reading an object's `Properties70`, its own or its kind's template's, and the values its children hold | +| `fbx/objects.sakura` | Reading a scene: `scene::of`, the settings, each object into the list of its kind, and the connections joining them | +| `fbx/geometry.sakura` | Reading a mesh's points, polygons, and layers, spread to its corners, and blend shapes' shapes | +| `fbx/transforms.sakura` | A model's matrix within its parent by FBX's chain, its mesh's, and its world's; and a scene's axes and units turned | +| `fbx/animation.sakura` | Reading animations: stacks, curve nodes and their channels, and curves and their keys; and a curve's value at a time | + +## Speed +33 of Khronos's sample glTF models, 65 MB of them, from a box of 24 vertices to BrainStem's skin and MetalRoughSpheres' 3.5 million numbers, each read whole and every accessor's numbers read after, take 136 ms on a Ryzen 9 9950X3D, the files' own reading among it. An FBX of 11 MB, of 615 models, 4 skinned meshes of 304,143 corners, 430 clusters, and an animation of 3,069 curves and 383,319 keys, is read as a document in 104 ms, and as a scene in 139 ms; an OBJ of 4,452 faces, and its MTL file, in 23 ms. + +## Testing +`blossom test` runs `tests/`. Of `gltf`, it writes models of its own and reads them back: a quad from JSON with its buffer in a `data:` URI, from a `.glb` file, and from files beside it, one named with a space; an image in a buffer view; numbers of every size, interleaved, normalized, in a matrix's padded columns, and sparse; a matrix taken apart and a translation put together, through a parent; cameras, a spot light, a skin, and an animation; and what's refused, each with why. Then models written: a quad built by hand, as `.glb` and as JSON, read back; one read of every part, lights, cameras, a skin, an animation, a sampler, a material's textures, unlit, written as each and read again the same, an extension it didn't read left out; and models saved, a buffer named as a file beside them, of a name with a space. + +Of `obj`: a cube read with its MTL file, of every form of corner, some counted back from the last, colors, a comment after a statement, groups, smoothing on and off, maps with options, and a material no MTL file gives; lines and points, an MTL file that isn't there, and a line joined to the next; what's refused, each saying its line; and the cube written as OBJ and MTL and read back the same. Of `fbx`: an ASCII scene of every part, its settings, templates, a mesh's layers by point, by corner through indices, and by polygon, a model with a pre-rotation and a bone beneath it, materials, a texture whose video embeds bytes, a light, a skin, and an animation, read, then written as binary and read again the same; a document built by hand, written as binary 32 and 64 bits wide and read back node for node; an array compressed by zlib, and its checksum broken; models placed about pivots, in rotation orders, active and not, and a post-rotation, and a scene's axes turned; a curve's values held, linear, and cubic; and what's refused. + +What's read was checked further against files that aren't part of the repository. For glTF, Khronos's [glTF sample assets](https://github.com/KhronosGroup/glTF-Sample-Assets): 33 models, as `.glb`, embedded `.gltf`, and `.gltf` with files beside it, each read, every accessor its primitives, skins, and animations name read, and every position within the least and the most its accessor says. For FBX, four binary files of 7.2 and 7.4, from 1 MB to 11 MB, two rigged and one animated, each read, its scene's lists of the lengths their meshes say, written as binary and read again the same; the rigged one's every bone placed within 0.00001 of where its cluster says it was bound. For OBJ, four models that come with Max, two with MTL files, of 1,890 to 6,199 positions and of up to ten objects. + +## Not yet +- **gltf**: URIs fetched from the network; a buffer's bytes written as a view's target; sparse accessors built by hand, though those read are written; `KHR_texture_transform`, `KHR_draco_mesh_compression`, `EXT_meshopt_compression`, and `KHR_texture_basisu`; and extensions' `extras`. +- **obj**: curves and surfaces, `vp`, `curv`, `surf`, and those of them; `maplib` and `usemap`; spectral colors read; and a face's triangles, which its users cut themselves. +- **fbx**: FBX before 7.0; a scene written as FBX, rather than its tree, and ASCII written; arrays written compressed; layers by edge, smoothing groups, tangents and binormals, and creases; inheriting a parent's scale but by multiplying matrices, `InheritType` 0 and 2; NURBS and lines; constraints; and animation layers blended, which a scene's user does from its curves. diff --git a/blossomfile b/blossomfile new file mode 100644 index 0000000..726928d --- /dev/null +++ b/blossomfile @@ -0,0 +1,83 @@ +name: models +gpid: malunal +semv: 1.0.0 + +options: + level: 2 + +requires: +- https://git.malunal.studio/sakura/std@v1.0.0 +# Vectors, rotations, and matrices, which nodes are placed by: +# `malunal::linear`, of the `physics` package. +- https://git.malunal.studio/malunal/physics@v1.0.0 + +targets: +# glTF 2.0, read and written. +- name: malunal.gltf + type: library + root: ./gltf + deps: + - malunal.linear + - std.containers + - std.io + - std.json + - std.math + +# Wavefront's OBJ, and the MTL files of its materials, read and written. +- name: malunal.obj + type: library + root: ./obj + deps: + - malunal.linear + - std.containers + - std.io + - std.math + +# Autodesk's FBX, binary or ASCII, read as its tree of nodes and as a scene +# of what they mean; the tree written as binary. +- name: malunal.fbx + type: library + root: ./fbx + deps: + - malunal.linear + - std.containers + - std.io + - std.math + +tests: +# They write and read models of their own, under `.blossom/gltf tests/`. +- name: malunal.gltf.tests + type: program + deps: [malunal.gltf, malunal.linear, std.io, std.math, std.testing] + srcs: + - tests/main.sakura + - tests/support.sakura + - tests/reading.sakura + - tests/accessors.sakura + - tests/nodes.sakura + - tests/writing.sakura + +# They write and read models of their own, under `.blossom/obj tests/`. +- name: malunal.obj.tests + type: program + deps: [malunal.obj, malunal.linear, std.io, std.math, std.testing] + srcs: + - tests/main.sakura + - tests/obj.sakura + +# They build documents and scenes of their own, in memory. +- name: malunal.fbx.tests + type: program + deps: [malunal.fbx, malunal.linear, std.math, std.testing] + srcs: + - tests/main.sakura + - tests/fbx.sakura + +exports: +- malunal.gltf +- malunal.obj +- malunal.fbx + +package: + desc: Models read and written. glTF 2.0, as .gltf and its files or .glb, whole and checked, with what their accessors hold read as numbers; Wavefront's OBJ, its faces of any number of corners, and the MTL files of its materials. + auth: John Christman diff --git a/fbx/animation.sakura b/fbx/animation.sakura new file mode 100644 index 0000000..2742bfd --- /dev/null +++ b/fbx/animation.sakura @@ -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::::new(); + var data := vector::::new(); + var counts := vector::::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; +} diff --git a/fbx/ascii.sakura b/fbx/ascii.sakura new file mode 100644 index 0000000..748b693 --- /dev/null +++ b/fbx/ascii.sakura @@ -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 { + 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 { + 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 { + 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::(word) is value(n) { + return property{ kind = property_kind::int64, integer = n }; + } + if real::parse::(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 { + val count_word := this.read_word(); + val count := integer::parse::(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::::new(); + var reals := vector::::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::(word) else (_) { return this.wrong($"`{word}` isn't a number.".span); }; + integers.append(n); + continue; + } + val x := real::parse::(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); +} diff --git a/fbx/binary.sakura b/fbx/binary.sakura new file mode 100644 index 0000000..da0961c --- /dev/null +++ b/fbx/binary.sakura @@ -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): 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, 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, 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; + 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): result { + 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 { + 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 { + 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::::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::::over(this.bytes.data + this.at, stored); + this.at += stored; + var inflated := vector::::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); +} diff --git a/fbx/fbx.sakura b/fbx/fbx.sakura new file mode 100644 index 0000000..314bfde --- /dev/null +++ b/fbx/fbx.sakura @@ -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; + #! An array of booleans' or integers'. + pub var integers: vector; + #! An array of floats'. + pub var reals: vector; +} + +#! 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; + pub var children: vector; + 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; + pub var roots: vector; +} + +#! 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 { + 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 { + var made := vector::::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 { + var made := vector::::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 { + var made := vector::::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 { + 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 { + 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): result { + return read_binary(bytes) if is_binary(bytes); + return read_ascii(strview::over(bytes.data, bytes.length)); +} diff --git a/fbx/geometry.sakura b/fbx/geometry.sakura new file mode 100644 index 0000000..a88952c --- /dev/null +++ b/fbx/geometry.sakura @@ -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 { + 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::::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, polygon_of: &vector): vector { + var made := vector::::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::::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 { + var made := vector::::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; +} diff --git a/fbx/inflate.sakura b/fbx/inflate.sakura new file mode 100644 index 0000000..74b7f59 --- /dev/null +++ b/fbx/inflate.sakura @@ -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): 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): 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; + 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; + 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, out: slice): maybe { + 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; +} diff --git a/fbx/objects.sakura b/fbx/objects.sakura new file mode 100644 index 0000000..cea59c2 --- /dev/null +++ b/fbx/objects.sakura @@ -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 { + var held := move(made); + var built := scene{ document = move(held) }; + built.read_templates(); + built.read_settings(); + var ids := dict::::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 { + 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): result { + 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, fbx_error> { + val skipped: maybe = 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 = 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 = packed(object_kind::mesh, at); + return made; + } + if k == "Geometry" && c == "Shape" { + val made: maybe = packed(object_kind::shape, this.read_shape(object, id, name.span)); + return made; + } + if k == "Material" { + val made: maybe = packed(object_kind::material, this.read_material(object, id, name.span)); + return made; + } + if k == "Texture" { + val made: maybe = packed(object_kind::texture, this.read_texture(object, id, name.span)); + return made; + } + if k == "Video" { + val made: maybe = packed(object_kind::video, this.read_video(object, id, name.span)); + return made; + } + if k == "NodeAttribute" && c == "Camera" { + val made: maybe = packed(object_kind::camera, this.read_camera(object, id, name.span)); + return made; + } + if k == "NodeAttribute" && c == "Light" { + val made: maybe = 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 = packed(object_kind::skin, this.skins.length - 1); + return made; + } + if k == "Deformer" && c == "Cluster" { + val made: maybe = 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 = packed(object_kind::blend_shape, this.blend_shapes.length - 1); + return made; + } + if k == "Deformer" && c == "BlendShapeChannel" { + val made: maybe = packed(object_kind::channel, this.read_channel(object, id, name.span)); + return made; + } + if k == "Pose" { + val made: maybe = packed(object_kind::pose, this.read_pose(object, id, name.span, c)); + return made; + } + if k == "AnimationStack" { + val made: maybe = 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 = packed(object_kind::layer, this.layers.length - 1); + return made; + } + if k == "AnimationCurveNode" { + val made: maybe = packed(object_kind::curve_node, this.read_curve_node(object, id, name.span)); + return made; + } + if k == "AnimationCurve" { + val made: maybe = 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 { + var made := vector::::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): 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): 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, 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); + } +} diff --git a/fbx/properties.sakura b/fbx/properties.sakura new file mode 100644 index 0000000..18fe7a9 --- /dev/null +++ b/fbx/properties.sakura @@ -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 { + 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 { + 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; +} diff --git a/fbx/scene.sakura b/fbx/scene.sakura new file mode 100644 index 0000000..ccded9e --- /dev/null +++ b/fbx/scene.sakura @@ -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; + pub var mesh: u32 = absent; + #! Its materials, in the order they're connected, which a mesh's polygons' + #! materials index. + pub var materials: vector; + 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; +} + +#! 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; + pub var polygons: vector; + #! The points of each polygon's corners, in turn. + pub var corners: vector; + pub var normals: vector; + pub var uv_sets: vector; + pub var colors: vector; + #! Each polygon's material, an index into its model's; empty where none's + #! given, as all of the first. + pub var materials: vector; + pub var skin: u32 = absent; + pub var blend_shapes: vector; +} + +#! 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; + pub var offsets: vector; + pub var normals: vector; +} + +#! 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; +} + +#! 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; + pub var shapes: vector; +} + +#! 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; +} + +#! 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; + pub var weights: vector; + 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; +} + +#! The texture it maps to a property, where it maps one. +pub def material::map(&this, property: strview): maybe { + 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; +} + +#! 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; +} + +#! 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; +} + +#! 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; +} + +#! 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; +} + +#! 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; + pub var values: vector; + pub var interpolations: vector; + pub var right_slopes: vector; + pub var next_left_slopes: vector; +} + +#! 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; + pub var meshes: vector; + pub var shapes: vector; + pub var blend_shapes: vector; + pub var channels: vector; + pub var skins: vector; + pub var clusters: vector; + pub var materials: vector; + pub var textures: vector; + pub var videos: vector