Files
models/README.md
T

158 lines
23 KiB
Markdown
Raw Normal View History

2026-10-30 12:04:54 -05:00
# 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.