Initial Commit
This commit is contained in:
36 files changed
+8436
No files matched your search
@@ -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
|
||||||
@@ -0,0 +1 @@
|
|||||||
|
.blossom
|
||||||
@@ -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.
|
||||||
+83
@@ -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 <sorakatadzuma@gmail.com>
|
||||||
@@ -0,0 +1,148 @@
|
|||||||
|
#! Contains reading animations: a stack's time, a curve node's channels and the
|
||||||
|
#! values they hold where no curve is given, and a curve's keys, each a time
|
||||||
|
#! in FBX's ticks, 46,186,158,000 a second, read as seconds, and a value. How a
|
||||||
|
#! key goes on to the next is given by attributes, each of flags and four
|
||||||
|
#! numbers, a cubic's slopes first, each holding for as many keys in turn as
|
||||||
|
#! its count says.
|
||||||
|
|
||||||
|
module malunal::fbx;
|
||||||
|
|
||||||
|
# Reads a stack: the time it spans.
|
||||||
|
def scene::read_stack(&mut this, object: u32, id: i64, name: strview): u64 {
|
||||||
|
var made := animation_stack{ id = id, name = string::from(name, nothing{}), node = object };
|
||||||
|
made.start = this.number_of(object, "LocalStart", this.number_of(object, "ReferenceStart", 0)) / ticks_per_second;
|
||||||
|
made.stop = this.number_of(object, "LocalStop", this.number_of(object, "ReferenceStop", 0)) / ticks_per_second;
|
||||||
|
this.stacks.append(move(made));
|
||||||
|
return this.stacks.length - 1;
|
||||||
|
}
|
||||||
|
|
||||||
|
# Reads a curve node: a channel of each of its `d|` properties, of its value.
|
||||||
|
def scene::read_curve_node(&mut this, object: u32, id: i64, name: strview): u64 {
|
||||||
|
var made := curve_node{ id = id, name = string::from(name, nothing{}), node = object };
|
||||||
|
if this.document.child(object, "Properties70") is some(properties) {
|
||||||
|
val list := &this.document.nodes[properties as u64].children;
|
||||||
|
for i in 0..list.length {
|
||||||
|
val each := &this.document.nodes[list[i] as u64];
|
||||||
|
continue if each.name.span != "P" || each.properties.length < 5;
|
||||||
|
val named := each.properties[0].text();
|
||||||
|
continue if !named.starts_with("d|");
|
||||||
|
made.channels.append(curve_channel{ name = string::from(named.substr(2, named.length - 2), nothing{}), value = each.properties[4].number() as f32 });
|
||||||
|
}
|
||||||
|
}
|
||||||
|
this.curve_nodes.append(move(made));
|
||||||
|
return this.curve_nodes.length - 1;
|
||||||
|
}
|
||||||
|
|
||||||
|
# Gives a curve node's channel of a connection's property, as `d|X`, its
|
||||||
|
# curve, adding the channel where it hasn't one.
|
||||||
|
def scene::attach_curve(&mut this, node: u64, curve: u32, property: strview): void {
|
||||||
|
val name := property.starts_with("d|") ? property.substr(2, property.length - 2) : property;
|
||||||
|
val value := this.curves[curve as u64].value;
|
||||||
|
val held := &mut this.curve_nodes[node];
|
||||||
|
for i in 0..held.channels.length {
|
||||||
|
if held.channels[i].name.span == name {
|
||||||
|
held.channels[i].curve = curve;
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
held.channels.append(curve_channel{ name = string::from(name, nothing{}), value = value, curve = curve });
|
||||||
|
}
|
||||||
|
|
||||||
|
# Reads a curve: its keys, and how each goes on to the next.
|
||||||
|
def scene::read_curve(&mut this, object: u32, id: i64, name: strview): u64 {
|
||||||
|
var made := curve{ id = id, name = string::from(name, nothing{}), node = object };
|
||||||
|
made.value = this.document.number_of(object, "Default", 0) as f32;
|
||||||
|
if this.document.child(object, "KeyTime") is some(times) {
|
||||||
|
val values := this.document.integers(times);
|
||||||
|
made.times.reserve(values.length);
|
||||||
|
for i in 0..values.length {
|
||||||
|
made.times.append(values[i] as f64 / ticks_per_second);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if this.document.child(object, "KeyValueFloat") is some(values_node) {
|
||||||
|
val values := this.document.reals(values_node);
|
||||||
|
made.values.reserve(values.length);
|
||||||
|
for i in 0..values.length {
|
||||||
|
made.values.append(values[i] as f32);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
val keys := made.times.length < made.values.length ? made.times.length : made.values.length;
|
||||||
|
var flags := vector::<i64>::new();
|
||||||
|
var data := vector::<f64>::new();
|
||||||
|
var counts := vector::<i64>::new();
|
||||||
|
if this.document.child(object, "KeyAttrFlags") is some(found) {
|
||||||
|
flags = this.document.integers(found);
|
||||||
|
}
|
||||||
|
if this.document.child(object, "KeyAttrDataFloat") is some(found) {
|
||||||
|
data = this.document.reals(found);
|
||||||
|
}
|
||||||
|
if this.document.child(object, "KeyAttrRefCount") is some(found) {
|
||||||
|
counts = this.document.integers(found);
|
||||||
|
}
|
||||||
|
var key: u64 = 0;
|
||||||
|
for a in 0..flags.length {
|
||||||
|
break if key >= keys;
|
||||||
|
var held := keys - key;
|
||||||
|
if a < counts.length && counts[a] >= 0 {
|
||||||
|
held = counts[a] as u64;
|
||||||
|
}
|
||||||
|
val bits := flags[a];
|
||||||
|
var how := key_interpolation::linear;
|
||||||
|
if (bits & 0x2) != 0 {
|
||||||
|
how = key_interpolation::constant;
|
||||||
|
} else if (bits & 0x8) != 0 {
|
||||||
|
how = key_interpolation::cubic;
|
||||||
|
}
|
||||||
|
val right: f32 = a * 4 + 1 < data.length ? data[a * 4] as f32 : 0;
|
||||||
|
val next_left: f32 = a * 4 + 1 < data.length ? data[a * 4 + 1] as f32 : 0;
|
||||||
|
var taken: u64 = 0;
|
||||||
|
while taken < held && key < keys {
|
||||||
|
made.interpolations.append(how);
|
||||||
|
made.right_slopes.append(right);
|
||||||
|
made.next_left_slopes.append(next_left);
|
||||||
|
key++;
|
||||||
|
taken++;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
while key < keys {
|
||||||
|
made.interpolations.append(key_interpolation::linear);
|
||||||
|
made.right_slopes.append(0);
|
||||||
|
made.next_left_slopes.append(0);
|
||||||
|
key++;
|
||||||
|
}
|
||||||
|
this.curves.append(move(made));
|
||||||
|
return this.curves.length - 1;
|
||||||
|
}
|
||||||
|
|
||||||
|
#! The value of a curve at a time: of its keys, held where they're constant,
|
||||||
|
#! between them linearly, or along a cubic of their slopes; its first before
|
||||||
|
#! its first key and its last after its last; its value where it has none.
|
||||||
|
pub def curve::at(&this, time: f64): f32 {
|
||||||
|
val keys := this.times.length < this.values.length ? this.times.length : this.values.length;
|
||||||
|
return this.value if keys == 0;
|
||||||
|
return this.values[0] if time <= this.times[0];
|
||||||
|
return this.values[keys - 1] if time >= this.times[keys - 1];
|
||||||
|
var k: u64 = 0;
|
||||||
|
while k + 1 < keys && this.times[k + 1] <= time {
|
||||||
|
k++;
|
||||||
|
}
|
||||||
|
val a := this.values[k];
|
||||||
|
val b := this.values[k + 1];
|
||||||
|
val span_of := this.times[k + 1] - this.times[k];
|
||||||
|
return a if span_of <= 0;
|
||||||
|
val t := ((time - this.times[k]) / span_of) as f32;
|
||||||
|
val how := k < this.interpolations.length ? this.interpolations[k] : key_interpolation::linear;
|
||||||
|
if how == key_interpolation::constant {
|
||||||
|
return a;
|
||||||
|
}
|
||||||
|
if how == key_interpolation::cubic {
|
||||||
|
# Hermite's, the slopes per second scaled to the span between the keys.
|
||||||
|
val d := span_of as f32;
|
||||||
|
val m0 := this.right_slopes[k] * d;
|
||||||
|
val m1 := this.next_left_slopes[k] * d;
|
||||||
|
val t2 := t * t;
|
||||||
|
val t3 := t2 * t;
|
||||||
|
return (2 * t3 - 3 * t2 + 1) * a + (t3 - 2 * t2 + t) * m0 + (-2 * t3 + 3 * t2) * b + (t3 - t2) * m1;
|
||||||
|
}
|
||||||
|
return a + (b - a) * t;
|
||||||
|
}
|
||||||
@@ -0,0 +1,253 @@
|
|||||||
|
#! Contains reading ASCII FBX: lines of `Name: property, property`, a node's
|
||||||
|
#! children within `{` and `}` after its properties, comments from `;` to the
|
||||||
|
#! line's end. A property is a number, text in quotes, a bare word, as `T`, or
|
||||||
|
#! an array, `*count { a: number, number }`. Properties go on past a line's end
|
||||||
|
#! after a comma. Numbers written with a point or an exponent are read as
|
||||||
|
#! floats, others as integers, and an array of both as floats.
|
||||||
|
|
||||||
|
module malunal::fbx;
|
||||||
|
|
||||||
|
# Reads ASCII FBX's nodes.
|
||||||
|
struct ascii_reader {
|
||||||
|
var text: strview;
|
||||||
|
var at: u64;
|
||||||
|
var line: u64 = 1;
|
||||||
|
}
|
||||||
|
|
||||||
|
# Reads ASCII FBX.
|
||||||
|
def read_ascii(text: strview): result<document, fbx_error> {
|
||||||
|
var made := document{ binary = false, version = 0 };
|
||||||
|
var r := ascii_reader{ text = text };
|
||||||
|
r.read_list(&mut made, absent) else (e) { return e; };
|
||||||
|
if made.child(absent, "FBXHeaderExtension") is some(header) {
|
||||||
|
if made.child(header, "FBXVersion") is some(version) && made.property(version, 0) is some(&given) {
|
||||||
|
made.version = given.whole() as u32;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return failed(failure::malformed, "It's neither binary FBX nor ASCII FBX of a header and objects.") if made.version == 0 && made.child(absent, "Objects") is none;
|
||||||
|
return failed(failure::unsupported, $"It's FBX {made.version}, of before 7.0, which names its objects rather than numbering them.".span) if made.version != 0 && made.version < 7000;
|
||||||
|
if made.version == 0 {
|
||||||
|
made.version = 7400;
|
||||||
|
}
|
||||||
|
return made;
|
||||||
|
}
|
||||||
|
|
||||||
|
# An error at the line it's reading.
|
||||||
|
def ascii_reader::wrong(&this, why: strview): fbx_error {
|
||||||
|
return failed(failure::malformed, $"line {this.line}: {why}".span);
|
||||||
|
}
|
||||||
|
|
||||||
|
# Passes over spaces, lines' ends, and comments.
|
||||||
|
def ascii_reader::skip_blank(&mut this): void {
|
||||||
|
while this.at < this.text.length {
|
||||||
|
val c := this.text[this.at];
|
||||||
|
if c == '\n' {
|
||||||
|
this.line++;
|
||||||
|
} else if c == ';' {
|
||||||
|
while this.at < this.text.length && this.text[this.at] != '\n' {
|
||||||
|
this.at++;
|
||||||
|
}
|
||||||
|
continue;
|
||||||
|
} else if c != ' ' && c != '\t' && c != '\r' {
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
this.at++;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
# Passes over spaces, but not a line's end.
|
||||||
|
def ascii_reader::skip_spaces(&mut this): void {
|
||||||
|
while this.at < this.text.length && (this.text[this.at] == ' ' || this.text[this.at] == '\t' || this.text[this.at] == '\r') {
|
||||||
|
this.at++;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
# Reads nodes, beneath a parent, to the `}` closing it, or the text's end at the
|
||||||
|
# root.
|
||||||
|
def ascii_reader::read_list(&mut this, made: &mut document, parent: u32): result<void, fbx_error> {
|
||||||
|
while true {
|
||||||
|
this.skip_blank();
|
||||||
|
if this.at >= this.text.length {
|
||||||
|
return this.wrong("A `{` isn't closed.") if parent != absent;
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
if this.text[this.at] == '}' {
|
||||||
|
return this.wrong("A `}` closes nothing.") if parent == absent;
|
||||||
|
this.at++;
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
val begun := this.at;
|
||||||
|
while this.at < this.text.length && this.text[this.at] != ':' && this.text[this.at] != '\n' && this.text[this.at] != '{' && this.text[this.at] != '}' {
|
||||||
|
this.at++;
|
||||||
|
}
|
||||||
|
if this.at >= this.text.length || this.text[this.at] != ':' {
|
||||||
|
return this.wrong("A node's name isn't followed by `:`.");
|
||||||
|
}
|
||||||
|
val name := trimmed(this.text.substr(begun, this.at - begun));
|
||||||
|
this.at++;
|
||||||
|
val index := made.add(parent, name);
|
||||||
|
this.read_properties(made, index) else (e) { return e; };
|
||||||
|
}
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
# Reads a node's properties, to its line's end, and its children, where it has
|
||||||
|
# them.
|
||||||
|
def ascii_reader::read_properties(&mut this, made: &mut document, index: u32): result<void, fbx_error> {
|
||||||
|
while true {
|
||||||
|
this.skip_spaces();
|
||||||
|
return if this.at >= this.text.length;
|
||||||
|
val c := this.text[this.at];
|
||||||
|
return if c == '\n' || c == '}';
|
||||||
|
if c == ';' {
|
||||||
|
while this.at < this.text.length && this.text[this.at] != '\n' {
|
||||||
|
this.at++;
|
||||||
|
}
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
if c == '{' {
|
||||||
|
this.at++;
|
||||||
|
return this.read_list(made, index);
|
||||||
|
}
|
||||||
|
if c == ',' {
|
||||||
|
this.at++;
|
||||||
|
this.skip_blank();
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
if c == '*' {
|
||||||
|
this.at++;
|
||||||
|
var held := this.read_array() else (e) { return e; };
|
||||||
|
made.nodes[index as u64].properties.append(move(held));
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
if c == '"' {
|
||||||
|
this.at++;
|
||||||
|
val begun := this.at;
|
||||||
|
while this.at < this.text.length && this.text[this.at] != '"' {
|
||||||
|
if this.text[this.at] == '\n' {
|
||||||
|
this.line++;
|
||||||
|
}
|
||||||
|
this.at++;
|
||||||
|
}
|
||||||
|
return this.wrong("Text isn't closed by `\"`.") if this.at >= this.text.length;
|
||||||
|
var held := property{ kind = property_kind::text };
|
||||||
|
held.bytes.extend(this.text.substr(begun, this.at - begun));
|
||||||
|
this.at++;
|
||||||
|
made.nodes[index as u64].properties.append(move(held));
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
val word := this.read_word();
|
||||||
|
return this.wrong($"`{c}` begins no property.".span) if word.length == 0;
|
||||||
|
var held := word_property(word);
|
||||||
|
made.nodes[index as u64].properties.append(move(held));
|
||||||
|
}
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
# Reads a word: a number, or a bare word, to the next comma, space, or brace.
|
||||||
|
def ascii_reader::read_word(&mut this): strview {
|
||||||
|
val begun := this.at;
|
||||||
|
while this.at < this.text.length {
|
||||||
|
val c := this.text[this.at];
|
||||||
|
break if c == ',' || c == ' ' || c == '\t' || c == '\r' || c == '\n' || c == '{' || c == '}' || c == ';';
|
||||||
|
this.at++;
|
||||||
|
}
|
||||||
|
return this.text.substr(begun, this.at - begun);
|
||||||
|
}
|
||||||
|
|
||||||
|
# A word as a property: an integer, a float, or text.
|
||||||
|
def word_property(word: strview): property {
|
||||||
|
if is_whole(word) && integer::parse::<i64>(word) is value(n) {
|
||||||
|
return property{ kind = property_kind::int64, integer = n };
|
||||||
|
}
|
||||||
|
if real::parse::<f64>(word) is value(x) {
|
||||||
|
return property{ kind = property_kind::float64, real = x };
|
||||||
|
}
|
||||||
|
var made := property{ kind = property_kind::text };
|
||||||
|
made.bytes.extend(word);
|
||||||
|
return made;
|
||||||
|
}
|
||||||
|
|
||||||
|
# Whether a word is written as a whole number: digits, after a sign.
|
||||||
|
def is_whole(word: strview): bool {
|
||||||
|
return false if word.length == 0;
|
||||||
|
var from: u64 = word[0] == '-' || word[0] == '+' ? 1 : 0;
|
||||||
|
return false if from >= word.length;
|
||||||
|
for i in from..word.length {
|
||||||
|
return false if word[i] < '0' || word[i] > '9';
|
||||||
|
}
|
||||||
|
return true;
|
||||||
|
}
|
||||||
|
|
||||||
|
# Reads an array, after its `*`: its count, then `{ a: ` and its numbers, to
|
||||||
|
# its `}`.
|
||||||
|
def ascii_reader::read_array(&mut this): result<property, fbx_error> {
|
||||||
|
val count_word := this.read_word();
|
||||||
|
val count := integer::parse::<i64>(count_word) else (_) { return this.wrong($"`*{count_word}` isn't an array's count.".span); };
|
||||||
|
this.skip_blank();
|
||||||
|
return this.wrong("An array's count isn't followed by `{`.") if this.at >= this.text.length || this.text[this.at] != '{';
|
||||||
|
this.at++;
|
||||||
|
this.skip_blank();
|
||||||
|
if this.at < this.text.length && this.text[this.at] == 'a' {
|
||||||
|
this.at++;
|
||||||
|
this.skip_spaces();
|
||||||
|
return this.wrong("An array's `a` isn't followed by `:`.") if this.at >= this.text.length || this.text[this.at] != ':';
|
||||||
|
this.at++;
|
||||||
|
}
|
||||||
|
var integers := vector::<i64>::new();
|
||||||
|
var reals := vector::<f64>::new();
|
||||||
|
var floating := false;
|
||||||
|
while true {
|
||||||
|
this.skip_blank();
|
||||||
|
return this.wrong("An array isn't closed by `}`.") if this.at >= this.text.length;
|
||||||
|
val c := this.text[this.at];
|
||||||
|
if c == '}' {
|
||||||
|
this.at++;
|
||||||
|
break;
|
||||||
|
}
|
||||||
|
if c == ',' {
|
||||||
|
this.at++;
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
val word := this.read_word();
|
||||||
|
return this.wrong($"`{c}` isn't a number of an array.".span) if word.length == 0;
|
||||||
|
if !floating && is_whole(word) {
|
||||||
|
val n := integer::parse::<i64>(word) else (_) { return this.wrong($"`{word}` isn't a number.".span); };
|
||||||
|
integers.append(n);
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
val x := real::parse::<f64>(word) else (_) { return this.wrong($"`{word}` isn't a number.".span); };
|
||||||
|
if !floating {
|
||||||
|
floating = true;
|
||||||
|
for i in 0..integers.length {
|
||||||
|
reals.append(integers[i] as f64);
|
||||||
|
}
|
||||||
|
integers.clear();
|
||||||
|
}
|
||||||
|
reals.append(x);
|
||||||
|
}
|
||||||
|
val read := floating ? reals.length : integers.length;
|
||||||
|
return this.wrong($"An array says it holds {count} numbers, but holds {read}.".span) if read != count as u64;
|
||||||
|
var made := property{};
|
||||||
|
if floating {
|
||||||
|
made.kind = property_kind::float64s;
|
||||||
|
made.reals = move(reals);
|
||||||
|
} else {
|
||||||
|
made.kind = property_kind::int64s;
|
||||||
|
made.integers = move(integers);
|
||||||
|
}
|
||||||
|
return made;
|
||||||
|
}
|
||||||
|
|
||||||
|
# Text with the spaces about it taken away.
|
||||||
|
def trimmed(text: strview): strview {
|
||||||
|
var first: u64 = 0;
|
||||||
|
var end := text.length;
|
||||||
|
while first < end && (text[first] == ' ' || text[first] == '\t' || text[first] == '\r' || text[first] == '\n') {
|
||||||
|
first++;
|
||||||
|
}
|
||||||
|
while end > first && (text[end - 1] == ' ' || text[end - 1] == '\t' || text[end - 1] == '\r' || text[end - 1] == '\n') {
|
||||||
|
end--;
|
||||||
|
}
|
||||||
|
return text.substr(first, end - first);
|
||||||
|
}
|
||||||
@@ -0,0 +1,199 @@
|
|||||||
|
#! Contains reading binary FBX: a header and its version, then the nodes at the
|
||||||
|
#! root, each its end, how many properties it has and how long they are, its
|
||||||
|
#! name, its properties, and its children, ended by a record of zeros. From
|
||||||
|
#! 7.5, the first three are 64 bits wide, not 32. An array's elements may be
|
||||||
|
#! compressed by zlib, which `inflate` undoes.
|
||||||
|
|
||||||
|
import std::math;
|
||||||
|
module malunal::fbx;
|
||||||
|
|
||||||
|
# The bytes binary FBX begins with, before its version.
|
||||||
|
const binary_magic: strview = "Kaydara FBX Binary ";
|
||||||
|
|
||||||
|
# Whether bytes are of binary FBX.
|
||||||
|
def is_binary(bytes: span<u8>): bool {
|
||||||
|
return false if bytes.length < 27;
|
||||||
|
for i in 0..18u {
|
||||||
|
return false if bytes[i] != binary_magic[i];
|
||||||
|
}
|
||||||
|
return true;
|
||||||
|
}
|
||||||
|
|
||||||
|
# A little-endian number of bytes, at a place.
|
||||||
|
def word_at(bytes: span<u8>, at: u64): u32 {
|
||||||
|
return bytes[at] as u32 | ((bytes[at + 1] as u32) << 8) | ((bytes[at + 2] as u32) << 16) | ((bytes[at + 3] as u32) << 24);
|
||||||
|
}
|
||||||
|
|
||||||
|
def long_at(bytes: span<u8>, at: u64): u64 {
|
||||||
|
return word_at(bytes, at) as u64 | ((word_at(bytes, at + 4) as u64) << 32);
|
||||||
|
}
|
||||||
|
|
||||||
|
# Reads binary FBX's nodes.
|
||||||
|
struct binary_reader {
|
||||||
|
var bytes: span<u8>;
|
||||||
|
var at: u64;
|
||||||
|
#! Whether a node's end and counts are 64 bits wide, as from 7.5.
|
||||||
|
var wide: bool;
|
||||||
|
}
|
||||||
|
|
||||||
|
# Reads binary FBX.
|
||||||
|
def read_binary(bytes: span<u8>): result<document, fbx_error> {
|
||||||
|
var made := document{ binary = true };
|
||||||
|
made.version = word_at(bytes, 23);
|
||||||
|
return failed(failure::unsupported, $"It's FBX {made.version}, of before 7.0, which names its objects rather than numbering them.".span) if made.version < 7000;
|
||||||
|
var r := binary_reader{ bytes = bytes, at = 27, wide = made.version >= 7500 };
|
||||||
|
while r.at < bytes.length {
|
||||||
|
val more := r.read_node(&mut made, absent) else (e) { return e; };
|
||||||
|
break if !more;
|
||||||
|
}
|
||||||
|
return made;
|
||||||
|
}
|
||||||
|
|
||||||
|
# Whether as many bytes are left, from where it's reading.
|
||||||
|
def binary_reader::holds(&this, count: u64): bool {
|
||||||
|
return this.at <= this.bytes.length && count <= this.bytes.length - this.at;
|
||||||
|
}
|
||||||
|
|
||||||
|
def binary_reader::byte(&mut this): u8 {
|
||||||
|
val made := this.bytes[this.at];
|
||||||
|
this.at++;
|
||||||
|
return made;
|
||||||
|
}
|
||||||
|
|
||||||
|
def binary_reader::word(&mut this): u32 {
|
||||||
|
val made := word_at(this.bytes, this.at);
|
||||||
|
this.at += 4;
|
||||||
|
return made;
|
||||||
|
}
|
||||||
|
|
||||||
|
def binary_reader::long(&mut this): u64 {
|
||||||
|
val made := long_at(this.bytes, this.at);
|
||||||
|
this.at += 8;
|
||||||
|
return made;
|
||||||
|
}
|
||||||
|
|
||||||
|
# Reads a node and its children, beneath a parent.
|
||||||
|
# @returns Whether it was one, rather than the record of zeros ending a list.
|
||||||
|
def binary_reader::read_node(&mut this, made: &mut document, parent: u32): result<bool, fbx_error> {
|
||||||
|
val header: u64 = this.wide ? 25 : 13;
|
||||||
|
if !this.holds(header) {
|
||||||
|
# A list at the root may end with the file, before its record of zeros.
|
||||||
|
return false if parent == absent;
|
||||||
|
return failed(failure::malformed, $"A node's header at byte {this.at} is past the file's end.".span);
|
||||||
|
}
|
||||||
|
val begun := this.at;
|
||||||
|
val end := this.wide ? this.long() : this.word() as u64;
|
||||||
|
val count := this.wide ? this.long() : this.word() as u64;
|
||||||
|
val length := this.wide ? this.long() : this.word() as u64;
|
||||||
|
val name_length := this.byte() as u64;
|
||||||
|
return false if end == 0;
|
||||||
|
if end <= begun || end > this.bytes.length || !this.holds(name_length) {
|
||||||
|
return failed(failure::malformed, $"The node at byte {begun} ends past the file's end, or before it begins.".span);
|
||||||
|
}
|
||||||
|
val name := strview::over(this.bytes.data + this.at, name_length);
|
||||||
|
this.at += name_length;
|
||||||
|
val index := made.add(parent, name);
|
||||||
|
val properties_end := this.at + length;
|
||||||
|
if properties_end > end {
|
||||||
|
return failed(failure::malformed, $"{name}: its properties run past its end.".span);
|
||||||
|
}
|
||||||
|
made.nodes[index as u64].properties.reserve(count);
|
||||||
|
for _ in 0..count {
|
||||||
|
var held := this.read_property(name) else (e) { return e; };
|
||||||
|
made.nodes[index as u64].properties.append(move(held));
|
||||||
|
}
|
||||||
|
if this.at != properties_end {
|
||||||
|
return failed(failure::malformed, $"{name}: its properties aren't as long as it says.".span);
|
||||||
|
}
|
||||||
|
while this.at < end {
|
||||||
|
val more := this.read_node(made, index) else (e) { return e; };
|
||||||
|
break if !more;
|
||||||
|
}
|
||||||
|
this.at = end;
|
||||||
|
return true;
|
||||||
|
}
|
||||||
|
|
||||||
|
# Reads a property: its type's letter, then its value.
|
||||||
|
def binary_reader::read_property(&mut this, name: strview): result<property, fbx_error> {
|
||||||
|
return failed(failure::malformed, $"{name}: a property is past the file's end.".span) if !this.holds(1);
|
||||||
|
val code := this.byte();
|
||||||
|
var made := property{};
|
||||||
|
if code == 'C' || code == 'Y' || code == 'I' || code == 'L' || code == 'F' || code == 'D' {
|
||||||
|
val size: u64 = code == 'C' ? 1 : (code == 'Y' ? 2 : (code == 'I' || code == 'F' ? 4 : 8));
|
||||||
|
return failed(failure::malformed, $"{name}: a property is past the file's end.".span) if !this.holds(size);
|
||||||
|
if code == 'C' {
|
||||||
|
made.kind = property_kind::boolean;
|
||||||
|
made.integer = this.byte() as i64;
|
||||||
|
} else if code == 'Y' {
|
||||||
|
made.kind = property_kind::int16;
|
||||||
|
val low := this.byte() as u16;
|
||||||
|
val high := this.byte() as u16;
|
||||||
|
made.integer = (low | (high << 8)) as i16 as i64;
|
||||||
|
} else if code == 'I' {
|
||||||
|
made.kind = property_kind::int32;
|
||||||
|
made.integer = this.word() as i32 as i64;
|
||||||
|
} else if code == 'L' {
|
||||||
|
made.kind = property_kind::int64;
|
||||||
|
made.integer = this.long() as i64;
|
||||||
|
} else if code == 'F' {
|
||||||
|
made.kind = property_kind::float32;
|
||||||
|
made.real = math::real_of_bits(this.word()) as f64;
|
||||||
|
} else {
|
||||||
|
made.kind = property_kind::float64;
|
||||||
|
made.real = math::real_of_bits(this.long());
|
||||||
|
}
|
||||||
|
return made;
|
||||||
|
}
|
||||||
|
if code == 'S' || code == 'R' {
|
||||||
|
return failed(failure::malformed, $"{name}: a property is past the file's end.".span) if !this.holds(4);
|
||||||
|
val length := this.word() as u64;
|
||||||
|
return failed(failure::malformed, $"{name}: its text runs past the file's end.".span) if !this.holds(length);
|
||||||
|
made.kind = code == 'S' ? property_kind::text : property_kind::raw;
|
||||||
|
made.bytes.extend(span::<u8>::over(this.bytes.data + this.at, length));
|
||||||
|
this.at += length;
|
||||||
|
return made;
|
||||||
|
}
|
||||||
|
if code == 'b' || code == 'i' || code == 'l' || code == 'f' || code == 'd' {
|
||||||
|
return failed(failure::malformed, $"{name}: a property is past the file's end.".span) if !this.holds(12);
|
||||||
|
val count := this.word() as u64;
|
||||||
|
val encoding := this.word();
|
||||||
|
val stored := this.word() as u64;
|
||||||
|
return failed(failure::malformed, $"{name}: an array runs past the file's end.".span) if !this.holds(stored);
|
||||||
|
val size: u64 = code == 'b' ? 1 : (code == 'i' || code == 'f' ? 4 : 8);
|
||||||
|
val data := span::<u8>::over(this.bytes.data + this.at, stored);
|
||||||
|
this.at += stored;
|
||||||
|
var inflated := vector::<u8>::new();
|
||||||
|
var raw := data;
|
||||||
|
if encoding == 1 {
|
||||||
|
inflated.resize(count * size);
|
||||||
|
val length := inflate(data, inflated.slice) else { return failed(failure::malformed, $"{name}: an array's data won't inflate.".span); };
|
||||||
|
return failed(failure::malformed, $"{name}: an array's data inflates to {length} bytes, not {count * size}.".span) if length != count * size;
|
||||||
|
raw = inflated.span;
|
||||||
|
} else if encoding != 0 {
|
||||||
|
return failed(failure::malformed, $"{name}: an array's encoding is {encoding}, of 0 and 1.".span);
|
||||||
|
} else if stored != count * size {
|
||||||
|
return failed(failure::malformed, $"{name}: an array is {stored} bytes, not {count * size}.".span);
|
||||||
|
}
|
||||||
|
if code == 'f' || code == 'd' {
|
||||||
|
made.kind = code == 'f' ? property_kind::float32s : property_kind::float64s;
|
||||||
|
made.reals.resize(count);
|
||||||
|
for i in 0..count {
|
||||||
|
made.reals[i] = code == 'f' ? math::real_of_bits(word_at(raw, i * 4)) as f64 : math::real_of_bits(long_at(raw, i * 8));
|
||||||
|
}
|
||||||
|
} else {
|
||||||
|
made.kind = code == 'b' ? property_kind::booleans : (code == 'i' ? property_kind::int32s : property_kind::int64s);
|
||||||
|
made.integers.resize(count);
|
||||||
|
for i in 0..count {
|
||||||
|
if code == 'b' {
|
||||||
|
made.integers[i] = raw[i] as i64;
|
||||||
|
} else if code == 'i' {
|
||||||
|
made.integers[i] = word_at(raw, i * 4) as i32 as i64;
|
||||||
|
} else {
|
||||||
|
made.integers[i] = long_at(raw, i * 8) as i64;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return made;
|
||||||
|
}
|
||||||
|
return failed(failure::malformed, $"{name}: a property is of type `{code}`, which isn't FBX's.".span);
|
||||||
|
}
|
||||||
+253
@@ -0,0 +1,253 @@
|
|||||||
|
#! Contains `document`, an FBX file as it's written: a tree of nodes, each a
|
||||||
|
#! name and properties, numbers, text, bytes, or arrays of numbers; why one
|
||||||
|
#! couldn't be read; and reading one, binary or ASCII, from a file or from
|
||||||
|
#! bytes.
|
||||||
|
#!
|
||||||
|
#! FBX is Autodesk's, and undocumented: what's read here is what Blender's
|
||||||
|
#! importer and others have found it to be. A binary file is a header, then
|
||||||
|
#! nodes, each its end, its properties, and its children; arrays may be
|
||||||
|
#! compressed by zlib. An ASCII file is the same tree written as text, as
|
||||||
|
#! `Name: 1, "text" { ... }`. Either is read into the same `document`, whose
|
||||||
|
#! nodes are kept in one list, by index, each with its parent and children.
|
||||||
|
#! `scene::of` reads what a document's nodes mean: models, meshes, materials,
|
||||||
|
#! skins, and animations.
|
||||||
|
|
||||||
|
import std::io;
|
||||||
|
module malunal::fbx;
|
||||||
|
|
||||||
|
#! What kind of thing kept a file from being read or written.
|
||||||
|
pub enum failure: u8 {
|
||||||
|
unreadable, #! A file couldn't be read, or written.
|
||||||
|
malformed, #! The data breaks FBX: a node past the file's end, a property of an unknown type, compressed data that won't inflate, text that isn't of nodes.
|
||||||
|
unsupported, #! It's well formed, but of what isn't read: an FBX older than 7.0, whose objects are named rather than numbered.
|
||||||
|
}
|
||||||
|
|
||||||
|
#! Why a file couldn't be read, or written: the kind of thing, and what, as
|
||||||
|
#! `Objects/Geometry: an array's data won't inflate`. It holds its text itself,
|
||||||
|
#! its first 240 bytes, so it's plain data, as std's errors are.
|
||||||
|
pub struct fbx_error {
|
||||||
|
pub var kind: failure;
|
||||||
|
var text: u8[240];
|
||||||
|
var length: u64;
|
||||||
|
}
|
||||||
|
|
||||||
|
#! What was wrong, and where.
|
||||||
|
pub def fbx_error::describe(&this): string {
|
||||||
|
return string::from(strview::over(&this.text[0] as *u8, this.length), nothing{});
|
||||||
|
}
|
||||||
|
|
||||||
|
# An error of a kind, saying why.
|
||||||
|
def failed(kind: failure, why: strview): fbx_error {
|
||||||
|
var made := fbx_error{ kind = kind };
|
||||||
|
made.length = why.length < 240 ? why.length : 240;
|
||||||
|
for i in 0..made.length {
|
||||||
|
made.text[i] = why[i];
|
||||||
|
}
|
||||||
|
return made;
|
||||||
|
}
|
||||||
|
|
||||||
|
#! What an index names where it names nothing: a node's parent at the root,
|
||||||
|
#! or a model's mesh where it has none.
|
||||||
|
pub const absent: u32 = 0xFFFFFFFF;
|
||||||
|
|
||||||
|
#! The type of a property's value, by the letter binary FBX gives it.
|
||||||
|
pub enum property_kind: u8 {
|
||||||
|
boolean, #! `C`, a byte: 0 or 1, or a letter, as `T` or `Y`.
|
||||||
|
int16, #! `Y`
|
||||||
|
int32, #! `I`
|
||||||
|
int64, #! `L`
|
||||||
|
float32, #! `F`
|
||||||
|
float64, #! `D`
|
||||||
|
text, #! `S`
|
||||||
|
raw, #! `R`, bytes, as an embedded file's.
|
||||||
|
booleans, #! `b`, an array, as are those after it.
|
||||||
|
int32s, #! `i`
|
||||||
|
int64s, #! `l`
|
||||||
|
float32s, #! `f`
|
||||||
|
float64s, #! `d`
|
||||||
|
}
|
||||||
|
|
||||||
|
#! A property of a node: a number, text, bytes, or an array of numbers, each
|
||||||
|
#! held as the widest of its kind.
|
||||||
|
pub struct property {
|
||||||
|
pub var kind: property_kind;
|
||||||
|
#! A boolean's, or an integer's.
|
||||||
|
pub var integer: i64;
|
||||||
|
#! A float's.
|
||||||
|
pub var real: f64;
|
||||||
|
#! Text's, or raw bytes.
|
||||||
|
pub var bytes: vector<u8>;
|
||||||
|
#! An array of booleans' or integers'.
|
||||||
|
pub var integers: vector<i64>;
|
||||||
|
#! An array of floats'.
|
||||||
|
pub var reals: vector<f64>;
|
||||||
|
}
|
||||||
|
|
||||||
|
#! Whether it's an array.
|
||||||
|
pub def property::is_array(&this): bool {
|
||||||
|
return this.kind as u8 >= property_kind::booleans as u8;
|
||||||
|
}
|
||||||
|
|
||||||
|
#! It as a number: a float's, or an integer's, or 0 of text, bytes, or an
|
||||||
|
#! array.
|
||||||
|
pub def property::number(&this): f64 {
|
||||||
|
if this.kind == property_kind::float32 || this.kind == property_kind::float64 {
|
||||||
|
return this.real;
|
||||||
|
}
|
||||||
|
return this.is_array() || this.kind == property_kind::text || this.kind == property_kind::raw ? 0 : this.integer as f64;
|
||||||
|
}
|
||||||
|
|
||||||
|
#! It as a whole number: an integer's, or a float's, cut.
|
||||||
|
pub def property::whole(&this): i64 {
|
||||||
|
if this.kind == property_kind::float32 || this.kind == property_kind::float64 {
|
||||||
|
return this.real as i64;
|
||||||
|
}
|
||||||
|
return this.integer;
|
||||||
|
}
|
||||||
|
|
||||||
|
#! Its text, or its bytes as text; empty of a number.
|
||||||
|
pub def property::text(&this): strview {
|
||||||
|
return strview::over(this.bytes.data, this.bytes.length);
|
||||||
|
}
|
||||||
|
|
||||||
|
#! How many numbers its array holds.
|
||||||
|
pub def property::count(&this): u64 {
|
||||||
|
return this.kind == property_kind::float32s || this.kind == property_kind::float64s ? this.reals.length : this.integers.length;
|
||||||
|
}
|
||||||
|
|
||||||
|
#! A number of its array, as a float, whichever its kind.
|
||||||
|
pub def property::real_at(&this, at: u64): f64 {
|
||||||
|
if this.kind == property_kind::float32s || this.kind == property_kind::float64s {
|
||||||
|
return this.reals[at];
|
||||||
|
}
|
||||||
|
return this.integers[at] as f64;
|
||||||
|
}
|
||||||
|
|
||||||
|
#! A number of its array, as an integer, whichever its kind.
|
||||||
|
pub def property::integer_at(&this, at: u64): i64 {
|
||||||
|
if this.kind == property_kind::float32s || this.kind == property_kind::float64s {
|
||||||
|
return this.reals[at] as i64;
|
||||||
|
}
|
||||||
|
return this.integers[at];
|
||||||
|
}
|
||||||
|
|
||||||
|
#! A node of the tree: its name, its properties, and its children and parent,
|
||||||
|
#! by their indices in the document's nodes.
|
||||||
|
pub struct node {
|
||||||
|
pub var name: string;
|
||||||
|
pub var properties: vector<property>;
|
||||||
|
pub var children: vector<u32>;
|
||||||
|
pub var parent: u32 = absent;
|
||||||
|
}
|
||||||
|
|
||||||
|
#! An FBX file as it's written: its version, as 7400 for 7.4, whether it was
|
||||||
|
#! binary, and its tree of nodes, all of them in one list, those at the root
|
||||||
|
#! named in `roots`.
|
||||||
|
pub struct document {
|
||||||
|
pub var version: u32 = 7400;
|
||||||
|
pub var binary: bool = true;
|
||||||
|
pub var nodes: vector<node>;
|
||||||
|
pub var roots: vector<u32>;
|
||||||
|
}
|
||||||
|
|
||||||
|
#! Adds a node, after its parent's other children.
|
||||||
|
#! @param parent Its parent, or `absent` at the root.
|
||||||
|
#! @param name Its name.
|
||||||
|
#! @returns Its index.
|
||||||
|
pub def document::add(&mut this, parent: u32, name: strview): u32 {
|
||||||
|
val index := this.nodes.length as u32;
|
||||||
|
this.nodes.append(node{ name = string::from(name, nothing{}), parent = parent });
|
||||||
|
if parent == absent {
|
||||||
|
this.roots.append(index);
|
||||||
|
} else {
|
||||||
|
this.nodes[parent as u64].children.append(index);
|
||||||
|
}
|
||||||
|
return index;
|
||||||
|
}
|
||||||
|
|
||||||
|
#! The first child of a node of a name, or of the root where it's `absent`.
|
||||||
|
pub def document::child(&this, of: u32, name: strview): maybe<u32> {
|
||||||
|
val list := of == absent ? this.roots.span : this.nodes[of as u64].children.span;
|
||||||
|
for i in 0..list.length {
|
||||||
|
return list[i] if this.nodes[list[i] as u64].name.span == name;
|
||||||
|
}
|
||||||
|
return nothing{};
|
||||||
|
}
|
||||||
|
|
||||||
|
#! The children of a node of a name, or of the root where it's `absent`.
|
||||||
|
pub def document::children_named(&this, of: u32, name: strview): vector<u32> {
|
||||||
|
var made := vector::<u32>::new();
|
||||||
|
val list := of == absent ? this.roots.span : this.nodes[of as u64].children.span;
|
||||||
|
for i in 0..list.length {
|
||||||
|
if this.nodes[list[i] as u64].name.span == name {
|
||||||
|
made.append(list[i]);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return made;
|
||||||
|
}
|
||||||
|
|
||||||
|
#! A property of a node, where it has that many.
|
||||||
|
pub def document::property(&this, of: u32, which: u64): maybe<&property> {
|
||||||
|
val held := &this.nodes[of as u64];
|
||||||
|
return nothing{} if which >= held.properties.length;
|
||||||
|
return &held.properties[which];
|
||||||
|
}
|
||||||
|
|
||||||
|
#! The numbers of a node: its first property's, where that's an array, or its
|
||||||
|
#! properties' in turn, as an ASCII file before 7.0 writes them, as floats.
|
||||||
|
pub def document::reals(&this, of: u32): vector<f64> {
|
||||||
|
var made := vector::<f64>::new();
|
||||||
|
val held := &this.nodes[of as u64];
|
||||||
|
if held.properties.length != 0 && held.properties[0].is_array() {
|
||||||
|
val first := &held.properties[0];
|
||||||
|
made.reserve(first.count());
|
||||||
|
for i in 0..first.count() {
|
||||||
|
made.append(first.real_at(i));
|
||||||
|
}
|
||||||
|
return made;
|
||||||
|
}
|
||||||
|
for i in 0..held.properties.length {
|
||||||
|
made.append(held.properties[i].number());
|
||||||
|
}
|
||||||
|
return made;
|
||||||
|
}
|
||||||
|
|
||||||
|
#! The numbers of a node, as `reals` gives them, as integers.
|
||||||
|
pub def document::integers(&this, of: u32): vector<i64> {
|
||||||
|
var made := vector::<i64>::new();
|
||||||
|
val held := &this.nodes[of as u64];
|
||||||
|
if held.properties.length != 0 && held.properties[0].is_array() {
|
||||||
|
val first := &held.properties[0];
|
||||||
|
made.reserve(first.count());
|
||||||
|
for i in 0..first.count() {
|
||||||
|
made.append(first.integer_at(i));
|
||||||
|
}
|
||||||
|
return made;
|
||||||
|
}
|
||||||
|
for i in 0..held.properties.length {
|
||||||
|
made.append(held.properties[i].whole());
|
||||||
|
}
|
||||||
|
return made;
|
||||||
|
}
|
||||||
|
|
||||||
|
#! Reads a document from a file: binary or ASCII, whichever its first bytes
|
||||||
|
#! say.
|
||||||
|
#! @param at The file's path.
|
||||||
|
#! @returns The document, or why it couldn't be read.
|
||||||
|
pub def load(at: &path): result<document, fbx_error> {
|
||||||
|
val bytes := io::read_file(at) else (_) { return failed(failure::unreadable, $"{at.span} couldn't be read.".span); };
|
||||||
|
return decode(bytes.span);
|
||||||
|
}
|
||||||
|
|
||||||
|
#! Reads a document from a file named by text, as `load` does.
|
||||||
|
pub def load(at: strview): result<document, fbx_error> {
|
||||||
|
val named := path::parse(at) else (_) { return failed(failure::unreadable, $"{at} isn't a path.".span); };
|
||||||
|
return load(&named);
|
||||||
|
}
|
||||||
|
|
||||||
|
#! Reads a document from bytes: a binary file's, which begin
|
||||||
|
#! `Kaydara FBX Binary`, or else an ASCII file's text.
|
||||||
|
pub def decode(bytes: span<u8>): result<document, fbx_error> {
|
||||||
|
return read_binary(bytes) if is_binary(bytes);
|
||||||
|
return read_ascii(strview::over(bytes.data, bytes.length));
|
||||||
|
}
|
||||||
@@ -0,0 +1,168 @@
|
|||||||
|
#! Contains reading a mesh's geometry: its points, `Vertices`; its polygons,
|
||||||
|
#! `PolygonVertexIndex`, the last corner of each written as its point's bits
|
||||||
|
#! turned over, so negative; and its layers, normals, places on textures,
|
||||||
|
#! colors, and materials, each given by polygon corner, by point, by polygon,
|
||||||
|
#! or once for all, directly or through indices, spread here to one for each
|
||||||
|
#! corner, or each polygon of materials. And a blend shape's shapes: the
|
||||||
|
#! points they move and how far.
|
||||||
|
|
||||||
|
import malunal::linear;
|
||||||
|
module malunal::fbx;
|
||||||
|
|
||||||
|
# Reads a mesh.
|
||||||
|
def scene::read_mesh(&mut this, object: u32, id: i64, name: strview): result<u64, fbx_error> {
|
||||||
|
var made := mesh{ id = id, name = string::from(name, nothing{}), node = object };
|
||||||
|
if this.document.child(object, "Vertices") is some(vertices) {
|
||||||
|
val values := this.document.reals(vertices);
|
||||||
|
made.positions.reserve(values.length / 3);
|
||||||
|
for i in 0..values.length / 3 {
|
||||||
|
made.positions.append(vec3{ values[i * 3] as f32, values[i * 3 + 1] as f32, values[i * 3 + 2] as f32 });
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if this.document.child(object, "PolygonVertexIndex") is some(indices) {
|
||||||
|
val values := this.document.integers(indices);
|
||||||
|
made.corners.reserve(values.length);
|
||||||
|
var first: u64 = 0;
|
||||||
|
for i in 0..values.length {
|
||||||
|
var point := values[i];
|
||||||
|
val ends := point < 0;
|
||||||
|
if ends {
|
||||||
|
point = -point - 1;
|
||||||
|
}
|
||||||
|
if point as u64 >= made.positions.length {
|
||||||
|
return failed(failure::malformed, $"{name}: a polygon names point {point}, of the {made.positions.length} it has.".span);
|
||||||
|
}
|
||||||
|
made.corners.append(point as u32);
|
||||||
|
if ends {
|
||||||
|
made.polygons.append(polygon{ first = first, count = (i + 1 - first) as u32 });
|
||||||
|
first = i + 1;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if first < values.length {
|
||||||
|
made.polygons.append(polygon{ first = first, count = (values.length - first) as u32 });
|
||||||
|
}
|
||||||
|
}
|
||||||
|
# The polygon of each corner, which layers given by polygon need.
|
||||||
|
var polygon_of := vector::<u32>::new();
|
||||||
|
polygon_of.reserve(made.corners.length);
|
||||||
|
for p in 0..made.polygons.length {
|
||||||
|
for _ in 0..made.polygons[p].count as u64 {
|
||||||
|
polygon_of.append(p as u32);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
val count := this.document.nodes[object as u64].children.length;
|
||||||
|
for i in 0..count {
|
||||||
|
val layer := this.document.nodes[object as u64].children[i];
|
||||||
|
var kind := string::from(this.document.nodes[layer as u64].name.span, nothing{});
|
||||||
|
if kind.span == "LayerElementNormal" && made.normals.length == 0 {
|
||||||
|
val values := this.layer_values(layer, "Normals", "NormalsIndex", 3, &made.corners, &polygon_of);
|
||||||
|
for c in 0..values.length / 3 {
|
||||||
|
made.normals.append(vec3{ values[c * 3] as f32, values[c * 3 + 1] as f32, values[c * 3 + 2] as f32 });
|
||||||
|
}
|
||||||
|
} else if kind.span == "LayerElementUV" {
|
||||||
|
val values := this.layer_values(layer, "UV", "UVIndex", 2, &made.corners, &polygon_of);
|
||||||
|
continue if values.length == 0 && made.corners.length != 0;
|
||||||
|
var set := uv_set{ name = string::from(this.document.text_of(layer, "Name"), nothing{}) };
|
||||||
|
set.uvs.reserve(values.length / 2);
|
||||||
|
for c in 0..values.length / 2 {
|
||||||
|
set.uvs.append(vec2{ values[c * 2] as f32, values[c * 2 + 1] as f32 });
|
||||||
|
}
|
||||||
|
made.uv_sets.append(move(set));
|
||||||
|
} else if kind.span == "LayerElementColor" && made.colors.length == 0 {
|
||||||
|
val values := this.layer_values(layer, "Colors", "ColorIndex", 4, &made.corners, &polygon_of);
|
||||||
|
for c in 0..values.length / 4 {
|
||||||
|
made.colors.append(vec4{ values[c * 4] as f32, values[c * 4 + 1] as f32, values[c * 4 + 2] as f32, values[c * 4 + 3] as f32 });
|
||||||
|
}
|
||||||
|
} else if kind.span == "LayerElementMaterial" && made.materials.length == 0 {
|
||||||
|
made.materials = this.layer_materials(layer, made.polygons.length);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
this.meshes.append(move(made));
|
||||||
|
return this.meshes.length - 1;
|
||||||
|
}
|
||||||
|
|
||||||
|
# A layer's values, one for each corner, `width` numbers each: by how it maps
|
||||||
|
# them, `MappingInformationType`, and whether through indices,
|
||||||
|
# `ReferenceInformationType`. A corner whose index names nothing is zeros. It's
|
||||||
|
# empty where the layer maps them by edge, which isn't read.
|
||||||
|
def scene::layer_values(&this, layer: u32, data_name: strview, index_name: strview, width: u64, corners: &vector<u32>, polygon_of: &vector<u32>): vector<f64> {
|
||||||
|
var made := vector::<f64>::new();
|
||||||
|
val data_node := this.document.child(layer, data_name) else { return made; };
|
||||||
|
val data := this.document.reals(data_node);
|
||||||
|
val mapping := this.document.text_of(layer, "MappingInformationType");
|
||||||
|
val reference := this.document.text_of(layer, "ReferenceInformationType");
|
||||||
|
val indexed := reference == "IndexToDirect" || reference == "Index";
|
||||||
|
var indices := vector::<i64>::new();
|
||||||
|
if indexed {
|
||||||
|
if this.document.child(layer, index_name) is some(found) {
|
||||||
|
indices = this.document.integers(found);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
val by_corner := mapping == "ByPolygonVertex";
|
||||||
|
val by_point := mapping == "ByVertice" || mapping == "ByVertex" || mapping == "ByControlPoint";
|
||||||
|
val by_polygon := mapping == "ByPolygon";
|
||||||
|
val all_same := mapping == "AllSame";
|
||||||
|
return made if !(by_corner || by_point || by_polygon || all_same);
|
||||||
|
val count := data.length / width;
|
||||||
|
made.resize(corners.length * width, 0);
|
||||||
|
for c in 0..corners.length {
|
||||||
|
var element: u64 = 0;
|
||||||
|
if by_corner {
|
||||||
|
element = c;
|
||||||
|
} else if by_point {
|
||||||
|
element = corners[c] as u64;
|
||||||
|
} else if by_polygon {
|
||||||
|
element = polygon_of[c] as u64;
|
||||||
|
}
|
||||||
|
var value := element;
|
||||||
|
if indexed {
|
||||||
|
continue if element >= indices.length || indices[element] < 0;
|
||||||
|
value = indices[element] as u64;
|
||||||
|
}
|
||||||
|
continue if value >= count;
|
||||||
|
for k in 0..width {
|
||||||
|
made[c * width + k] = data[value * width + k];
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return made;
|
||||||
|
}
|
||||||
|
|
||||||
|
# A layer's materials, one for each polygon, by polygon or once for all.
|
||||||
|
def scene::layer_materials(&this, layer: u32, polygons: u64): vector<u32> {
|
||||||
|
var made := vector::<u32>::new();
|
||||||
|
val data_node := this.document.child(layer, "Materials") else { return made; };
|
||||||
|
val values := this.document.integers(data_node);
|
||||||
|
return made if values.length == 0;
|
||||||
|
val all_same := this.document.text_of(layer, "MappingInformationType") == "AllSame";
|
||||||
|
made.reserve(polygons);
|
||||||
|
for p in 0..polygons {
|
||||||
|
val value := all_same || p >= values.length ? values[0] : values[p];
|
||||||
|
made.append(value < 0 ? 0 : value as u32);
|
||||||
|
}
|
||||||
|
return made;
|
||||||
|
}
|
||||||
|
|
||||||
|
# Reads a shape a blend shape channel blends toward.
|
||||||
|
def scene::read_shape(&mut this, object: u32, id: i64, name: strview): u64 {
|
||||||
|
var made := shape{ id = id, name = string::from(name, nothing{}), node = object };
|
||||||
|
if this.document.child(object, "Indexes") is some(indexes) {
|
||||||
|
val values := this.document.integers(indexes);
|
||||||
|
for i in 0..values.length {
|
||||||
|
made.points.append(values[i] as u32);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if this.document.child(object, "Vertices") is some(vertices) {
|
||||||
|
val values := this.document.reals(vertices);
|
||||||
|
for i in 0..values.length / 3 {
|
||||||
|
made.offsets.append(vec3{ values[i * 3] as f32, values[i * 3 + 1] as f32, values[i * 3 + 2] as f32 });
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if this.document.child(object, "Normals") is some(normals) {
|
||||||
|
val values := this.document.reals(normals);
|
||||||
|
for i in 0..values.length / 3 {
|
||||||
|
made.normals.append(vec3{ values[i * 3] as f32, values[i * 3 + 1] as f32, values[i * 3 + 2] as f32 });
|
||||||
|
}
|
||||||
|
}
|
||||||
|
this.shapes.append(move(made));
|
||||||
|
return this.shapes.length - 1;
|
||||||
|
}
|
||||||
@@ -0,0 +1,394 @@
|
|||||||
|
#! Contains inflate, which undoes the compression of binary FBX's arrays:
|
||||||
|
#! DEFLATE, as RFC 1951 writes it, within zlib's wrapping, as RFC 1950 writes
|
||||||
|
#! it. It's `image`'s, of its PNG reader, copied, so `models` needs no more
|
||||||
|
#! than `physics`: Huffman codes read as stb_image reads them, by a table of
|
||||||
|
#! codes up to 9 bits long and longer ones by where each length's codes end.
|
||||||
|
|
||||||
|
module malunal::fbx;
|
||||||
|
|
||||||
|
# How many bits the fast table reads at once.
|
||||||
|
const fast_bits: u64 = 9;
|
||||||
|
|
||||||
|
# The lengths and distances of runs: the least of each symbol's, and how many
|
||||||
|
# bits more it reads.
|
||||||
|
const length_base: u32[29] = [3, 4, 5, 6, 7, 8, 9, 10, 11, 13, 15, 17, 19, 23, 27, 31, 35, 43, 51, 59, 67, 83, 99, 115, 131, 163, 195, 227, 258];
|
||||||
|
const length_extra: u32[29] = [0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 2, 2, 2, 2, 3, 3, 3, 3, 4, 4, 4, 4, 5, 5, 5, 5, 0];
|
||||||
|
const distance_base: u32[30] = [1, 2, 3, 4, 5, 7, 9, 13, 17, 25, 33, 49, 65, 97, 129, 193, 257, 385, 513, 769, 1025, 1537, 2049, 3073, 4097, 6145, 8193, 12289, 16385, 24577];
|
||||||
|
const distance_extra: u32[30] = [0, 0, 0, 0, 1, 1, 2, 2, 3, 3, 4, 4, 5, 5, 6, 6, 7, 7, 8, 8, 9, 9, 10, 10, 11, 11, 12, 12, 13, 13];
|
||||||
|
|
||||||
|
# The order a dynamic block gives the lengths of the code its lengths are in.
|
||||||
|
const length_order: u64[19] = [16, 17, 18, 0, 8, 7, 9, 6, 10, 5, 11, 4, 12, 3, 13, 2, 14, 1, 15];
|
||||||
|
|
||||||
|
# A Huffman code: each symbol's code, as the lengths of all of them give it.
|
||||||
|
struct huffman {
|
||||||
|
var fast: u16[512]; #! `length << 9 | symbol` by a code's first 9 bits, read reversed, or 0 for a longer one.
|
||||||
|
var first_code: u32[16];
|
||||||
|
var first_symbol: u32[16];
|
||||||
|
var max_code: u32[17]; #! Just past the last code of each length, shifted to be 16 bits long.
|
||||||
|
var size: u8[288];
|
||||||
|
var value: u16[288];
|
||||||
|
}
|
||||||
|
|
||||||
|
# Builds a code from each symbol's length, which may leave codes unused, but not
|
||||||
|
# give more than there are.
|
||||||
|
def huffman::build(&mut this, lengths: span<u8>): bool {
|
||||||
|
var counts: u32[17];
|
||||||
|
for length in lengths {
|
||||||
|
counts[length as u64]++;
|
||||||
|
}
|
||||||
|
counts[0] = 0;
|
||||||
|
for bits in 1u..16u {
|
||||||
|
if counts[bits] as u64 > (1u << bits) {
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
var next: u32[16];
|
||||||
|
var code: u32 = 0;
|
||||||
|
var symbols: u32 = 0;
|
||||||
|
for bits in 1u..16u {
|
||||||
|
next[bits] = code;
|
||||||
|
this.first_code[bits] = code;
|
||||||
|
this.first_symbol[bits] = symbols;
|
||||||
|
code += counts[bits];
|
||||||
|
if counts[bits] != 0 && (code - 1) as u64 >= (1u << bits) {
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
this.max_code[bits] = code << (16 - bits) as u32;
|
||||||
|
code <<= 1;
|
||||||
|
symbols += counts[bits];
|
||||||
|
}
|
||||||
|
this.max_code[16] = 0x10000;
|
||||||
|
|
||||||
|
for symbol, length in lengths {
|
||||||
|
if length == 0 {
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
val bits := length as u64;
|
||||||
|
val slot := (next[bits] - this.first_code[bits] + this.first_symbol[bits]) as u64;
|
||||||
|
this.size[slot] = length;
|
||||||
|
this.value[slot] = symbol as u16;
|
||||||
|
if bits <= fast_bits {
|
||||||
|
var at := reversed_bits(next[bits], bits) as u64;
|
||||||
|
while at < 512 {
|
||||||
|
this.fast[at] = ((bits << 9) | symbol) as u16;
|
||||||
|
at += 1u << bits;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
next[bits]++;
|
||||||
|
}
|
||||||
|
return true;
|
||||||
|
}
|
||||||
|
|
||||||
|
# The lowest bits of a number, in the opposite order.
|
||||||
|
def reversed_bits(code: u32, bits: u64): u32 {
|
||||||
|
var from := code;
|
||||||
|
var made: u32 = 0;
|
||||||
|
for _ in 0..bits {
|
||||||
|
made = (made << 1) | (from & 1);
|
||||||
|
from >>= 1;
|
||||||
|
}
|
||||||
|
return made;
|
||||||
|
}
|
||||||
|
|
||||||
|
# The 16 lowest bits of a number, in the opposite order.
|
||||||
|
def reversed16(code: u32): u32 {
|
||||||
|
var made := code;
|
||||||
|
made = ((made & 0xAAAA) >> 1) | ((made & 0x5555) << 1);
|
||||||
|
made = ((made & 0xCCCC) >> 2) | ((made & 0x3333) << 2);
|
||||||
|
made = ((made & 0xF0F0) >> 4) | ((made & 0x0F0F) << 4);
|
||||||
|
return ((made & 0xFF00) >> 8) | ((made & 0x00FF) << 8);
|
||||||
|
}
|
||||||
|
|
||||||
|
# The Adler-32 of bytes, as zlib checks them by.
|
||||||
|
def adler32(data: span<u8>): u32 {
|
||||||
|
var low: u32 = 1;
|
||||||
|
var high: u32 = 0;
|
||||||
|
var at: u64 = 0;
|
||||||
|
while at < data.length {
|
||||||
|
# 5552 bytes is the most that can be summed before either could pass 32 bits.
|
||||||
|
val end := at + 5552 < data.length ? at + 5552 : data.length;
|
||||||
|
while at < end {
|
||||||
|
low += data[at];
|
||||||
|
high += low;
|
||||||
|
at++;
|
||||||
|
}
|
||||||
|
low %= 65521;
|
||||||
|
high %= 65521;
|
||||||
|
}
|
||||||
|
return (high << 16) | low;
|
||||||
|
}
|
||||||
|
|
||||||
|
# Reads DEFLATE's bits, least significant first, into the bytes made.
|
||||||
|
struct inflater {
|
||||||
|
var data: span<u8>;
|
||||||
|
var at: u64; #! The next byte to read, which runs past the end where bits read past it.
|
||||||
|
var buffer: u64;
|
||||||
|
var count: u64; #! How many bits the buffer holds.
|
||||||
|
var out: slice<u8>;
|
||||||
|
var written: u64;
|
||||||
|
}
|
||||||
|
|
||||||
|
# Inflates zlib's data into memory exactly as long as it should be, which it must
|
||||||
|
# not go past, checking its Adler-32.
|
||||||
|
# @returns How many bytes it inflated to, or `nothing` where it's broken.
|
||||||
|
def inflate(data: span<u8>, out: slice<u8>): maybe<u64> {
|
||||||
|
if data.length < 6 {
|
||||||
|
return nothing {};
|
||||||
|
}
|
||||||
|
val method := data[0];
|
||||||
|
val flags := data[1];
|
||||||
|
if (method & 0x0F) != 8 || (method >> 4) > 7 || (flags & 0x20) != 0 || ((method as u32) * 256 + flags as u32) % 31 != 0 {
|
||||||
|
return nothing {};
|
||||||
|
}
|
||||||
|
|
||||||
|
var z := inflater { data = data, at = 2, out = out };
|
||||||
|
var last := false;
|
||||||
|
while !last {
|
||||||
|
last = z.take(1) == 1;
|
||||||
|
val kind := z.take(2);
|
||||||
|
var read := false;
|
||||||
|
if kind == 0 {
|
||||||
|
read = z.stored();
|
||||||
|
} else if kind == 1 {
|
||||||
|
read = z.fixed();
|
||||||
|
} else if kind == 2 {
|
||||||
|
read = z.dynamic();
|
||||||
|
}
|
||||||
|
if !read || z.overran() {
|
||||||
|
return nothing {};
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
# The checksum is in the next whole bytes, the most significant first.
|
||||||
|
z.align();
|
||||||
|
var expected: u32 = 0;
|
||||||
|
for _ in 0..4 {
|
||||||
|
expected = (expected << 8) | z.take(8);
|
||||||
|
}
|
||||||
|
if z.overran() || adler32(z.out[0:z.written]) != expected {
|
||||||
|
return nothing {};
|
||||||
|
}
|
||||||
|
return z.written;
|
||||||
|
}
|
||||||
|
|
||||||
|
# Copies a stored block, whose length follows from the next whole byte.
|
||||||
|
def inflater::stored(&mut this): bool {
|
||||||
|
this.align();
|
||||||
|
val length := this.take(16);
|
||||||
|
if (length ^ 0xFFFF) != this.take(16) {
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
|
||||||
|
# What the buffer holds first, then the rest straight from the data.
|
||||||
|
var left := length as u64;
|
||||||
|
while left > 0 && this.count > 0 {
|
||||||
|
if !this.put(this.take(8) as u8) {
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
left--;
|
||||||
|
}
|
||||||
|
if this.at + left > this.data.length || this.written + left > this.out.length {
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
for index in 0..left {
|
||||||
|
this.out[this.written + index] = this.data[this.at + index];
|
||||||
|
}
|
||||||
|
this.at += left;
|
||||||
|
this.written += left;
|
||||||
|
return true;
|
||||||
|
}
|
||||||
|
|
||||||
|
# Inflates a block of the fixed codes RFC 1951 gives.
|
||||||
|
def inflater::fixed(&mut this): bool {
|
||||||
|
var lengths: u8[288];
|
||||||
|
for symbol in 0u..288u {
|
||||||
|
lengths[symbol] = symbol < 144 ? 8 : (symbol < 256 ? 9 : (symbol < 280 ? 7 : 8));
|
||||||
|
}
|
||||||
|
var distances: u8[30];
|
||||||
|
for symbol in 0u..30u {
|
||||||
|
distances[symbol] = 5;
|
||||||
|
}
|
||||||
|
var literal_code := huffman {};
|
||||||
|
var distance_code := huffman {};
|
||||||
|
_ = literal_code.build(lengths[:]);
|
||||||
|
_ = distance_code.build(distances[:]);
|
||||||
|
return this.codes(&literal_code, &distance_code);
|
||||||
|
}
|
||||||
|
|
||||||
|
# Inflates a block of codes of its own, whose lengths it gives first, in a code of
|
||||||
|
# their own.
|
||||||
|
def inflater::dynamic(&mut this): bool {
|
||||||
|
val literals := this.take(5) as u64 + 257;
|
||||||
|
val distances := this.take(5) as u64 + 1;
|
||||||
|
val count := this.take(4) as u64 + 4;
|
||||||
|
|
||||||
|
var length_lengths: u8[19];
|
||||||
|
for index in 0..count {
|
||||||
|
length_lengths[length_order[index]] = this.take(3) as u8;
|
||||||
|
}
|
||||||
|
var length_code := huffman {};
|
||||||
|
if !length_code.build(length_lengths[:]) {
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
|
||||||
|
# The lengths, where 16 repeats the last, and 17 and 18 give runs of zeros.
|
||||||
|
var lengths: u8[320];
|
||||||
|
val total := literals + distances;
|
||||||
|
var read: u64 = 0;
|
||||||
|
while read < total {
|
||||||
|
val symbol := this.decode(&length_code);
|
||||||
|
if symbol < 0 {
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
var length: u8 = 0;
|
||||||
|
var repeat: u64 = 1;
|
||||||
|
if symbol < 16 {
|
||||||
|
length = symbol as u8;
|
||||||
|
} else if symbol == 16 {
|
||||||
|
if read == 0 {
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
length = lengths[read - 1];
|
||||||
|
repeat = 3 + this.take(2) as u64;
|
||||||
|
} else if symbol == 17 {
|
||||||
|
repeat = 3 + this.take(3) as u64;
|
||||||
|
} else {
|
||||||
|
repeat = 11 + this.take(7) as u64;
|
||||||
|
}
|
||||||
|
if read + repeat > total {
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
for _ in 0..repeat {
|
||||||
|
lengths[read] = length;
|
||||||
|
read++;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if lengths[256] == 0 {
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
|
||||||
|
var literal_code := huffman {};
|
||||||
|
var distance_code := huffman {};
|
||||||
|
if !literal_code.build(lengths[0:literals]) || !distance_code.build(lengths[literals:distances]) {
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
return this.codes(&literal_code, &distance_code);
|
||||||
|
}
|
||||||
|
|
||||||
|
# Inflates a block's symbols: bytes, then runs of what came before, to its end.
|
||||||
|
def inflater::codes(&mut this, literals: &huffman, distances: &huffman): bool {
|
||||||
|
while true {
|
||||||
|
val symbol := this.decode(literals);
|
||||||
|
if symbol < 0 {
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
if symbol < 256 {
|
||||||
|
if !this.put(symbol as u8) {
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
if symbol == 256 {
|
||||||
|
return true;
|
||||||
|
}
|
||||||
|
|
||||||
|
val index := (symbol - 257) as u64;
|
||||||
|
if index >= 29 {
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
val length := (length_base[index] + this.take(length_extra[index] as u64)) as u64;
|
||||||
|
val which := this.decode(distances);
|
||||||
|
if which < 0 || which >= 30 {
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
val distance := (distance_base[which as u64] + this.take(distance_extra[which as u64] as u64)) as u64;
|
||||||
|
if distance > this.written || this.written + length > this.out.length || this.overran() {
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
# A run may overlap itself, repeating what it copies, so it goes a byte at a time.
|
||||||
|
var from := this.written - distance;
|
||||||
|
for _ in 0..length {
|
||||||
|
this.out[this.written] = this.out[from];
|
||||||
|
this.written++;
|
||||||
|
from++;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return true;
|
||||||
|
}
|
||||||
|
|
||||||
|
# Decodes a symbol of a code.
|
||||||
|
# @returns The symbol, or -1 where the bits are no code's.
|
||||||
|
def inflater::decode(&mut this, code: &huffman): i32 {
|
||||||
|
if this.count < 16 {
|
||||||
|
this.fill();
|
||||||
|
}
|
||||||
|
val entry := code.fast[this.buffer & 511];
|
||||||
|
if entry != 0 {
|
||||||
|
val length := (entry >> 9) as u64;
|
||||||
|
this.buffer >>= length;
|
||||||
|
this.count -= length;
|
||||||
|
return (entry & 511) as i32;
|
||||||
|
}
|
||||||
|
|
||||||
|
# Longer than the table reads: the code's length is the first whose codes end
|
||||||
|
# past the bits, read most significant first.
|
||||||
|
val bits := reversed16((this.buffer & 0xFFFF) as u32);
|
||||||
|
var length: u64 = fast_bits + 1;
|
||||||
|
while bits >= code.max_code[length] {
|
||||||
|
length++;
|
||||||
|
}
|
||||||
|
if length >= 16 {
|
||||||
|
return -1;
|
||||||
|
}
|
||||||
|
val slot := ((bits >> (16 - length) as u32) - code.first_code[length] + code.first_symbol[length]) as u64;
|
||||||
|
if slot >= 288 || code.size[slot] as u64 != length {
|
||||||
|
return -1;
|
||||||
|
}
|
||||||
|
this.buffer >>= length;
|
||||||
|
this.count -= length;
|
||||||
|
return code.value[slot] as i32;
|
||||||
|
}
|
||||||
|
|
||||||
|
# Reads a number of bits, up to 16, the first the least significant.
|
||||||
|
def inflater::take(&mut this, bits: u64): u32 {
|
||||||
|
if this.count < bits {
|
||||||
|
this.fill();
|
||||||
|
}
|
||||||
|
val made := (this.buffer & ((1u << bits) - 1)) as u32;
|
||||||
|
this.buffer >>= bits;
|
||||||
|
this.count -= bits;
|
||||||
|
return made;
|
||||||
|
}
|
||||||
|
|
||||||
|
# Fills the buffer, with zeros past the end of the data, which `overran` tells.
|
||||||
|
def inflater::fill(&mut this): void {
|
||||||
|
while this.count <= 56 {
|
||||||
|
if this.at < this.data.length {
|
||||||
|
this.buffer |= (this.data[this.at] as u64) << this.count;
|
||||||
|
}
|
||||||
|
this.at++;
|
||||||
|
this.count += 8;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
# Drops the bits up to the next whole byte.
|
||||||
|
def inflater::align(&mut this): void {
|
||||||
|
val extra := this.count % 8;
|
||||||
|
this.buffer >>= extra;
|
||||||
|
this.count -= extra;
|
||||||
|
}
|
||||||
|
|
||||||
|
# Whether more bits have been read than the data holds.
|
||||||
|
def inflater::overran(&this): bool {
|
||||||
|
return this.at * 8 - this.count > this.data.length * 8;
|
||||||
|
}
|
||||||
|
|
||||||
|
def inflater::put(&mut this, byte: u8): bool {
|
||||||
|
if this.written >= this.out.length {
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
this.out[this.written] = byte;
|
||||||
|
this.written++;
|
||||||
|
return true;
|
||||||
|
}
|
||||||
@@ -0,0 +1,541 @@
|
|||||||
|
#! Contains reading a scene of a document: its settings, each object of
|
||||||
|
#! `Objects` read into the list of its kind, then `Connections`, which say
|
||||||
|
#! what's whose: a model's parent, mesh, materials, camera, and light, a
|
||||||
|
#! material's textures, a skin's clusters and each cluster's bone, a blend
|
||||||
|
#! shape's channels and their shapes, an animation's layers and curves and what
|
||||||
|
#! they animate.
|
||||||
|
|
||||||
|
import std::containers;
|
||||||
|
import malunal::linear;
|
||||||
|
module malunal::fbx;
|
||||||
|
|
||||||
|
# What kind of object an id names, as `Objects` gives them.
|
||||||
|
enum object_kind: u8 { model, mesh, shape, material, texture, video, camera, light, skin, cluster, blend_shape, channel, stack, layer, curve_node, curve, pose }
|
||||||
|
|
||||||
|
# FBX's ticks a second.
|
||||||
|
const ticks_per_second: f64 = 46186158000;
|
||||||
|
|
||||||
|
#! Reads what a document's objects mean.
|
||||||
|
#! @param made The document, which the scene keeps.
|
||||||
|
#! @returns The scene, or why it couldn't be read: `malformed` where a mesh's
|
||||||
|
#! polygon names a point it hasn't.
|
||||||
|
pub def scene::of(made: document): result<scene, fbx_error> {
|
||||||
|
var held := move(made);
|
||||||
|
var built := scene{ document = move(held) };
|
||||||
|
built.read_templates();
|
||||||
|
built.read_settings();
|
||||||
|
var ids := dict::<i64, u64>::new();
|
||||||
|
if built.document.child(absent, "Objects") is some(objects) {
|
||||||
|
val count := built.document.nodes[objects as u64].children.length;
|
||||||
|
for i in 0..count {
|
||||||
|
val object := built.document.nodes[objects as u64].children[i];
|
||||||
|
val read := built.read_object(object) else (e) { return e; };
|
||||||
|
if read is some(found) {
|
||||||
|
ids.set(built.id_of(object), found);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if built.document.child(absent, "Connections") is some(connections) {
|
||||||
|
val count := built.document.nodes[connections as u64].children.length;
|
||||||
|
for i in 0..count {
|
||||||
|
val link := built.document.nodes[connections as u64].children[i];
|
||||||
|
val node := &built.document.nodes[link as u64];
|
||||||
|
continue if node.name.span != "C" || node.properties.length < 3;
|
||||||
|
val child := node.properties[1].whole();
|
||||||
|
val parent := node.properties[2].whole();
|
||||||
|
var property := string::new(nothing{});
|
||||||
|
if node.properties.length > 3 {
|
||||||
|
property.append(node.properties[3].text());
|
||||||
|
}
|
||||||
|
built.connect(&ids, child, parent, property.span);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
for i in 0..built.models.length {
|
||||||
|
if built.models[i].parent == absent {
|
||||||
|
built.roots.append(i as u32);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
built.place_poses(&ids);
|
||||||
|
return built;
|
||||||
|
}
|
||||||
|
|
||||||
|
#! Reads a scene of a file, as `load` and `scene::of` read them.
|
||||||
|
pub def load_scene(at: strview): result<scene, fbx_error> {
|
||||||
|
var made := load(at) else (e) { return e; };
|
||||||
|
return scene::of(move(made));
|
||||||
|
}
|
||||||
|
|
||||||
|
#! Reads a scene of bytes, as `decode` and `scene::of` read them.
|
||||||
|
pub def decode_scene(bytes: span<u8>): result<scene, fbx_error> {
|
||||||
|
var made := decode(bytes) else (e) { return e; };
|
||||||
|
return scene::of(move(made));
|
||||||
|
}
|
||||||
|
|
||||||
|
# An object's id, its first property.
|
||||||
|
def scene::id_of(&this, object: u32): i64 {
|
||||||
|
val held := &this.document.nodes[object as u64];
|
||||||
|
return held.properties.length == 0 ? 0 : held.properties[0].whole();
|
||||||
|
}
|
||||||
|
|
||||||
|
# An object's name, its second property: binary FBX's `name\0\1Class`, or
|
||||||
|
# ASCII's `Class::name`, as the name alone.
|
||||||
|
def scene::name_of(&this, object: u32): strview {
|
||||||
|
val held := &this.document.nodes[object as u64];
|
||||||
|
return "" if held.properties.length < 2;
|
||||||
|
val text := held.properties[1].text();
|
||||||
|
if this.document.binary {
|
||||||
|
for i in 0..text.length {
|
||||||
|
return text.substr(0, i) if text[i] == 0 && i + 1 < text.length && text[i + 1] == 1;
|
||||||
|
}
|
||||||
|
return text;
|
||||||
|
}
|
||||||
|
if text.find("::") is some(at) {
|
||||||
|
return text.substr(at + 2, text.length - at - 2);
|
||||||
|
}
|
||||||
|
return text;
|
||||||
|
}
|
||||||
|
|
||||||
|
# An object's class, its third property, as `Mesh` or `LimbNode`.
|
||||||
|
def scene::class_of(&this, object: u32): strview {
|
||||||
|
val held := &this.document.nodes[object as u64];
|
||||||
|
return "" if held.properties.length < 3;
|
||||||
|
return held.properties[2].text();
|
||||||
|
}
|
||||||
|
|
||||||
|
# A kind and an index, as one number.
|
||||||
|
def packed(kind: object_kind, index: u64): u64 {
|
||||||
|
return ((kind as u64) << 40) | index;
|
||||||
|
}
|
||||||
|
|
||||||
|
def kind_of(packed: u64): u8 {
|
||||||
|
return (packed >> 40) as u8;
|
||||||
|
}
|
||||||
|
|
||||||
|
def index_of(packed: u64): u64 {
|
||||||
|
return packed & 0xFFFFFFFFFF;
|
||||||
|
}
|
||||||
|
|
||||||
|
# Reads an object into the list of its kind.
|
||||||
|
# @returns Its kind and index, packed, or nothing where it's of a kind not
|
||||||
|
# read.
|
||||||
|
def scene::read_object(&mut this, object: u32): result<maybe<u64>, fbx_error> {
|
||||||
|
val skipped: maybe<u64> = nothing{};
|
||||||
|
var kind := string::from(this.document.nodes[object as u64].name.span, nothing{});
|
||||||
|
var subclass := string::from(this.class_of(object), nothing{});
|
||||||
|
var name := string::from(this.name_of(object), nothing{});
|
||||||
|
val id := this.id_of(object);
|
||||||
|
val k := kind.span;
|
||||||
|
val c := subclass.span;
|
||||||
|
if k == "Model" {
|
||||||
|
val at := this.read_model(object, id, name.span, c);
|
||||||
|
val made: maybe<u64> = packed(object_kind::model, at);
|
||||||
|
return made;
|
||||||
|
}
|
||||||
|
if k == "Geometry" && c == "Mesh" {
|
||||||
|
val at := this.read_mesh(object, id, name.span) else (e) { return e; };
|
||||||
|
val made: maybe<u64> = packed(object_kind::mesh, at);
|
||||||
|
return made;
|
||||||
|
}
|
||||||
|
if k == "Geometry" && c == "Shape" {
|
||||||
|
val made: maybe<u64> = packed(object_kind::shape, this.read_shape(object, id, name.span));
|
||||||
|
return made;
|
||||||
|
}
|
||||||
|
if k == "Material" {
|
||||||
|
val made: maybe<u64> = packed(object_kind::material, this.read_material(object, id, name.span));
|
||||||
|
return made;
|
||||||
|
}
|
||||||
|
if k == "Texture" {
|
||||||
|
val made: maybe<u64> = packed(object_kind::texture, this.read_texture(object, id, name.span));
|
||||||
|
return made;
|
||||||
|
}
|
||||||
|
if k == "Video" {
|
||||||
|
val made: maybe<u64> = packed(object_kind::video, this.read_video(object, id, name.span));
|
||||||
|
return made;
|
||||||
|
}
|
||||||
|
if k == "NodeAttribute" && c == "Camera" {
|
||||||
|
val made: maybe<u64> = packed(object_kind::camera, this.read_camera(object, id, name.span));
|
||||||
|
return made;
|
||||||
|
}
|
||||||
|
if k == "NodeAttribute" && c == "Light" {
|
||||||
|
val made: maybe<u64> = packed(object_kind::light, this.read_light(object, id, name.span));
|
||||||
|
return made;
|
||||||
|
}
|
||||||
|
if k == "Deformer" && c == "Skin" {
|
||||||
|
this.skins.append(skin{ id = id, name = string::from(name.span, nothing{}), node = object });
|
||||||
|
val made: maybe<u64> = packed(object_kind::skin, this.skins.length - 1);
|
||||||
|
return made;
|
||||||
|
}
|
||||||
|
if k == "Deformer" && c == "Cluster" {
|
||||||
|
val made: maybe<u64> = packed(object_kind::cluster, this.read_cluster(object, id, name.span));
|
||||||
|
return made;
|
||||||
|
}
|
||||||
|
if k == "Deformer" && c == "BlendShape" {
|
||||||
|
this.blend_shapes.append(blend_shape{ id = id, name = string::from(name.span, nothing{}), node = object });
|
||||||
|
val made: maybe<u64> = packed(object_kind::blend_shape, this.blend_shapes.length - 1);
|
||||||
|
return made;
|
||||||
|
}
|
||||||
|
if k == "Deformer" && c == "BlendShapeChannel" {
|
||||||
|
val made: maybe<u64> = packed(object_kind::channel, this.read_channel(object, id, name.span));
|
||||||
|
return made;
|
||||||
|
}
|
||||||
|
if k == "Pose" {
|
||||||
|
val made: maybe<u64> = packed(object_kind::pose, this.read_pose(object, id, name.span, c));
|
||||||
|
return made;
|
||||||
|
}
|
||||||
|
if k == "AnimationStack" {
|
||||||
|
val made: maybe<u64> = packed(object_kind::stack, this.read_stack(object, id, name.span));
|
||||||
|
return made;
|
||||||
|
}
|
||||||
|
if k == "AnimationLayer" {
|
||||||
|
val weight := this.number_of(object, "Weight", 100) as f32;
|
||||||
|
this.layers.append(animation_layer{ id = id, name = string::from(name.span, nothing{}), node = object, weight = weight });
|
||||||
|
val made: maybe<u64> = packed(object_kind::layer, this.layers.length - 1);
|
||||||
|
return made;
|
||||||
|
}
|
||||||
|
if k == "AnimationCurveNode" {
|
||||||
|
val made: maybe<u64> = packed(object_kind::curve_node, this.read_curve_node(object, id, name.span));
|
||||||
|
return made;
|
||||||
|
}
|
||||||
|
if k == "AnimationCurve" {
|
||||||
|
val made: maybe<u64> = packed(object_kind::curve, this.read_curve(object, id, name.span));
|
||||||
|
return made;
|
||||||
|
}
|
||||||
|
return skipped;
|
||||||
|
}
|
||||||
|
|
||||||
|
# Reads the settings of `GlobalSettings`.
|
||||||
|
def scene::read_settings(&mut this): void {
|
||||||
|
val global := this.document.child(absent, "GlobalSettings") else { return; };
|
||||||
|
var s := settings{};
|
||||||
|
s.up_axis = this.number_of(global, "UpAxis", 1) as u32;
|
||||||
|
s.up_sign = this.number_of(global, "UpAxisSign", 1) as i32;
|
||||||
|
s.front_axis = this.number_of(global, "FrontAxis", 2) as u32;
|
||||||
|
s.front_sign = this.number_of(global, "FrontAxisSign", 1) as i32;
|
||||||
|
s.coord_axis = this.number_of(global, "CoordAxis", 0) as u32;
|
||||||
|
s.coord_sign = this.number_of(global, "CoordAxisSign", 1) as i32;
|
||||||
|
s.unit_scale = this.number_of(global, "UnitScaleFactor", 1);
|
||||||
|
s.original_unit_scale = this.number_of(global, "OriginalUnitScaleFactor", s.unit_scale);
|
||||||
|
val mode := this.number_of(global, "TimeMode", 0) as u64;
|
||||||
|
val rates: f64[19] = [30, 120, 100, 60, 50, 48, 30, 30, 29.97, 29.97, 25, 24, 1000, 23.976, 0, 96, 72, 59.94, 119.88];
|
||||||
|
s.frame_rate = mode < 19 ? rates[mode] : 30;
|
||||||
|
if mode == 14 {
|
||||||
|
s.frame_rate = this.number_of(global, "CustomFrameRate", 30);
|
||||||
|
}
|
||||||
|
s.start = this.number_of(global, "TimeSpanStart", 0) / ticks_per_second;
|
||||||
|
s.stop = this.number_of(global, "TimeSpanStop", 0) / ticks_per_second;
|
||||||
|
s.ambient = this.vector_of(global, "AmbientColor", vec3::zero);
|
||||||
|
this.settings = s;
|
||||||
|
}
|
||||||
|
|
||||||
|
# Reads a model, where it's placed and how.
|
||||||
|
def scene::read_model(&mut this, object: u32, id: i64, name: strview, kind: strview): u64 {
|
||||||
|
var made := model{ id = id, name = string::from(name, nothing{}), kind = string::from(kind, nothing{}), node = object };
|
||||||
|
made.translation = this.vector_of(object, "Lcl Translation", vec3::zero);
|
||||||
|
made.rotation = this.vector_of(object, "Lcl Rotation", vec3::zero);
|
||||||
|
made.scale = this.vector_of(object, "Lcl Scaling", vec3::one);
|
||||||
|
made.pre_rotation = this.vector_of(object, "PreRotation", vec3::zero);
|
||||||
|
made.post_rotation = this.vector_of(object, "PostRotation", vec3::zero);
|
||||||
|
val order := this.number_of(object, "RotationOrder", 0) as u64;
|
||||||
|
val orders: rotation_order[7] = [rotation_order::xyz, rotation_order::xzy, rotation_order::yzx, rotation_order::yxz, rotation_order::zxy, rotation_order::zyx, rotation_order::spheric_xyz];
|
||||||
|
made.order = order < 7 ? orders[order] : rotation_order::xyz;
|
||||||
|
made.rotation_active = this.flag_of(object, "RotationActive", false);
|
||||||
|
made.rotation_offset = this.vector_of(object, "RotationOffset", vec3::zero);
|
||||||
|
made.rotation_pivot = this.vector_of(object, "RotationPivot", vec3::zero);
|
||||||
|
made.scaling_offset = this.vector_of(object, "ScalingOffset", vec3::zero);
|
||||||
|
made.scaling_pivot = this.vector_of(object, "ScalingPivot", vec3::zero);
|
||||||
|
made.geometric_translation = this.vector_of(object, "GeometricTranslation", vec3::zero);
|
||||||
|
made.geometric_rotation = this.vector_of(object, "GeometricRotation", vec3::zero);
|
||||||
|
made.geometric_scale = this.vector_of(object, "GeometricScaling", vec3::one);
|
||||||
|
made.inherit = this.number_of(object, "InheritType", 1) as u32;
|
||||||
|
made.visible = this.number_of(object, "Visibility", 1) != 0;
|
||||||
|
this.models.append(move(made));
|
||||||
|
return this.models.length - 1;
|
||||||
|
}
|
||||||
|
|
||||||
|
# Reads a material: its shading model, colors, and factors.
|
||||||
|
def scene::read_material(&mut this, object: u32, id: i64, name: strview): u64 {
|
||||||
|
var made := material{ id = id, name = string::from(name, nothing{}), node = object };
|
||||||
|
made.shading = string::from(this.document.text_of(object, "ShadingModel"), nothing{});
|
||||||
|
made.diffuse = this.vector_of(object, "DiffuseColor", this.vector_of(object, "Diffuse", made.diffuse));
|
||||||
|
made.diffuse_factor = this.number_of(object, "DiffuseFactor", 1) as f32;
|
||||||
|
made.ambient = this.vector_of(object, "AmbientColor", made.ambient);
|
||||||
|
made.ambient_factor = this.number_of(object, "AmbientFactor", 1) as f32;
|
||||||
|
made.specular = this.vector_of(object, "SpecularColor", made.specular);
|
||||||
|
made.specular_factor = this.number_of(object, "SpecularFactor", 1) as f32;
|
||||||
|
made.shininess = this.number_of(object, "ShininessExponent", this.number_of(object, "Shininess", 20)) as f32;
|
||||||
|
made.emissive = this.vector_of(object, "EmissiveColor", vec3::zero);
|
||||||
|
made.emissive_factor = this.number_of(object, "EmissiveFactor", 1) as f32;
|
||||||
|
made.transparency = this.number_of(object, "TransparencyFactor", 0) as f32;
|
||||||
|
made.opacity = this.number_of(object, "Opacity", 1) as f32;
|
||||||
|
made.reflection_factor = this.number_of(object, "ReflectionFactor", 1) as f32;
|
||||||
|
made.bump_factor = this.number_of(object, "BumpFactor", 1) as f32;
|
||||||
|
this.materials.append(move(made));
|
||||||
|
return this.materials.length - 1;
|
||||||
|
}
|
||||||
|
|
||||||
|
# Reads a texture: the file it names, and how it's placed.
|
||||||
|
def scene::read_texture(&mut this, object: u32, id: i64, name: strview): u64 {
|
||||||
|
var made := texture{ id = id, name = string::from(name, nothing{}), node = object };
|
||||||
|
var file := this.document.text_of(object, "FileName");
|
||||||
|
if file.length == 0 {
|
||||||
|
file = this.document.text_of(object, "Filename");
|
||||||
|
}
|
||||||
|
made.file = string::from(file, nothing{});
|
||||||
|
made.relative = string::from(this.document.text_of(object, "RelativeFilename"), nothing{});
|
||||||
|
made.uv_set = string::from(this.text_of(object, "UVSet"), nothing{});
|
||||||
|
made.translation = this.vector_of(object, "Translation", vec3::zero);
|
||||||
|
made.rotation = this.vector_of(object, "Rotation", vec3::zero);
|
||||||
|
made.scale = this.vector_of(object, "Scaling", vec3::one);
|
||||||
|
made.wrap_u = this.number_of(object, "WrapModeU", 0) as u32;
|
||||||
|
made.wrap_v = this.number_of(object, "WrapModeV", 0) as u32;
|
||||||
|
this.textures.append(move(made));
|
||||||
|
return this.textures.length - 1;
|
||||||
|
}
|
||||||
|
|
||||||
|
# Reads a video: the file it names, and its bytes, where they're embedded, as
|
||||||
|
# binary's raw bytes or ASCII's base64.
|
||||||
|
def scene::read_video(&mut this, object: u32, id: i64, name: strview): u64 {
|
||||||
|
var made := video{ id = id, name = string::from(name, nothing{}), node = object };
|
||||||
|
var file := this.document.text_of(object, "FileName");
|
||||||
|
if file.length == 0 {
|
||||||
|
file = this.document.text_of(object, "Filename");
|
||||||
|
}
|
||||||
|
if file.length == 0 {
|
||||||
|
file = this.text_of(object, "Path");
|
||||||
|
}
|
||||||
|
made.file = string::from(file, nothing{});
|
||||||
|
made.relative = string::from(this.document.text_of(object, "RelativeFilename"), nothing{});
|
||||||
|
if this.document.child(object, "Content") is some(content) {
|
||||||
|
val held := &this.document.nodes[content as u64];
|
||||||
|
var text := string::new(nothing{});
|
||||||
|
for i in 0..held.properties.length {
|
||||||
|
if held.properties[i].kind == property_kind::raw {
|
||||||
|
made.content.extend(held.properties[i].bytes.span);
|
||||||
|
} else if held.properties[i].kind == property_kind::text {
|
||||||
|
text.append(held.properties[i].text());
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if made.content.length == 0 && text.length != 0 {
|
||||||
|
made.content = base64_bytes(text.span);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
this.videos.append(move(made));
|
||||||
|
return this.videos.length - 1;
|
||||||
|
}
|
||||||
|
|
||||||
|
# The bytes of base64, its spaces and padding passed over.
|
||||||
|
def base64_bytes(text: strview): vector<u8> {
|
||||||
|
var made := vector::<u8>::new();
|
||||||
|
var bits: u32 = 0;
|
||||||
|
var count: u32 = 0;
|
||||||
|
for i in 0..text.length {
|
||||||
|
val c := text[i];
|
||||||
|
var value: u32 = 64;
|
||||||
|
if c >= 'A' && c <= 'Z' {
|
||||||
|
value = (c - 'A') as u32;
|
||||||
|
} else if c >= 'a' && c <= 'z' {
|
||||||
|
value = (c - 'a') as u32 + 26;
|
||||||
|
} else if c >= '0' && c <= '9' {
|
||||||
|
value = (c - '0') as u32 + 52;
|
||||||
|
} else if c == '+' {
|
||||||
|
value = 62;
|
||||||
|
} else if c == '/' {
|
||||||
|
value = 63;
|
||||||
|
}
|
||||||
|
continue if value == 64;
|
||||||
|
bits = (bits << 6) | value;
|
||||||
|
count += 6;
|
||||||
|
if count >= 8 {
|
||||||
|
count -= 8;
|
||||||
|
made.append(((bits >> count) & 0xFF) as u8);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return made;
|
||||||
|
}
|
||||||
|
|
||||||
|
# Reads a camera.
|
||||||
|
def scene::read_camera(&mut this, object: u32, id: i64, name: strview): u64 {
|
||||||
|
var made := camera{ id = id, name = string::from(name, nothing{}), node = object };
|
||||||
|
made.orthographic = this.number_of(object, "CameraProjectionType", 0) == 1;
|
||||||
|
made.field_of_view = this.number_of(object, "FieldOfView", 40) as f32;
|
||||||
|
made.field_of_view_x = this.number_of(object, "FieldOfViewX", made.field_of_view as f64) as f32;
|
||||||
|
made.field_of_view_y = this.number_of(object, "FieldOfViewY", made.field_of_view as f64) as f32;
|
||||||
|
made.focal_length = this.number_of(object, "FocalLength", 34.89) as f32;
|
||||||
|
made.near = this.number_of(object, "NearPlane", 10) as f32;
|
||||||
|
made.far = this.number_of(object, "FarPlane", 4000) as f32;
|
||||||
|
made.aspect_width = this.number_of(object, "AspectWidth", 320) as f32;
|
||||||
|
made.aspect_height = this.number_of(object, "AspectHeight", 200) as f32;
|
||||||
|
made.ortho_zoom = this.number_of(object, "OrthoZoom", 1) as f32;
|
||||||
|
this.cameras.append(move(made));
|
||||||
|
return this.cameras.length - 1;
|
||||||
|
}
|
||||||
|
|
||||||
|
# Reads a light.
|
||||||
|
def scene::read_light(&mut this, object: u32, id: i64, name: strview): u64 {
|
||||||
|
var made := light{ id = id, name = string::from(name, nothing{}), node = object };
|
||||||
|
val kind := this.number_of(object, "LightType", 0) as u64;
|
||||||
|
val kinds: light_kind[5] = [light_kind::point, light_kind::directional, light_kind::spot, light_kind::area, light_kind::volume];
|
||||||
|
made.kind = kind < 5 ? kinds[kind] : light_kind::point;
|
||||||
|
made.color = this.vector_of(object, "Color", vec3::one);
|
||||||
|
made.intensity = this.number_of(object, "Intensity", 100) as f32;
|
||||||
|
made.inner_angle = this.number_of(object, "InnerAngle", 0) as f32;
|
||||||
|
made.outer_angle = this.number_of(object, "OuterAngle", 45) as f32;
|
||||||
|
made.decay = this.number_of(object, "DecayType", 0) as u32;
|
||||||
|
made.decay_start = this.number_of(object, "DecayStart", 0) as f32;
|
||||||
|
made.casts_shadows = this.flag_of(object, "CastShadows", false);
|
||||||
|
this.lights.append(move(made));
|
||||||
|
return this.lights.length - 1;
|
||||||
|
}
|
||||||
|
|
||||||
|
# Reads a cluster: the points its bone moves, how much, and the matrices it
|
||||||
|
# was bound by.
|
||||||
|
def scene::read_cluster(&mut this, object: u32, id: i64, name: strview): u64 {
|
||||||
|
var made := cluster{ id = id, name = string::from(name, nothing{}), node = object };
|
||||||
|
if this.document.child(object, "Indexes") is some(indexes) {
|
||||||
|
val values := this.document.integers(indexes);
|
||||||
|
made.points.reserve(values.length);
|
||||||
|
for i in 0..values.length {
|
||||||
|
made.points.append(values[i] as u32);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if this.document.child(object, "Weights") is some(weights) {
|
||||||
|
val values := this.document.reals(weights);
|
||||||
|
made.weights.reserve(values.length);
|
||||||
|
for i in 0..values.length {
|
||||||
|
made.weights.append(values[i] as f32);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if this.document.child(object, "Transform") is some(transform) {
|
||||||
|
made.transform = matrix_of(this.document.reals(transform).span);
|
||||||
|
}
|
||||||
|
if this.document.child(object, "TransformLink") is some(link) {
|
||||||
|
made.transform_link = matrix_of(this.document.reals(link).span);
|
||||||
|
}
|
||||||
|
this.clusters.append(move(made));
|
||||||
|
return this.clusters.length - 1;
|
||||||
|
}
|
||||||
|
|
||||||
|
# A matrix of 16 numbers, column after column, as FBX writes them; the
|
||||||
|
# identity where there aren't 16.
|
||||||
|
def matrix_of(values: span<f64>): mat4 {
|
||||||
|
var made := mat4::identity;
|
||||||
|
return made if values.length != 16;
|
||||||
|
for i in 0..16u {
|
||||||
|
made.m[i] = values[i] as f32;
|
||||||
|
}
|
||||||
|
return made;
|
||||||
|
}
|
||||||
|
|
||||||
|
# Reads a blend shape channel: how far it blends, and its shapes' weights.
|
||||||
|
def scene::read_channel(&mut this, object: u32, id: i64, name: strview): u64 {
|
||||||
|
var made := blend_channel{ id = id, name = string::from(name, nothing{}), node = object };
|
||||||
|
made.weight = this.document.number_of(object, "DeformPercent", this.number_of(object, "DeformPercent", 0)) as f32;
|
||||||
|
if this.document.child(object, "FullWeights") is some(full) {
|
||||||
|
val values := this.document.reals(full);
|
||||||
|
for i in 0..values.length {
|
||||||
|
made.full_weights.append(values[i] as f32);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
this.channels.append(move(made));
|
||||||
|
return this.channels.length - 1;
|
||||||
|
}
|
||||||
|
|
||||||
|
# Reads a pose: each model's matrix, by its id, which `place_poses` finds the
|
||||||
|
# model of once all are read.
|
||||||
|
def scene::read_pose(&mut this, object: u32, id: i64, name: strview, subclass: strview): u64 {
|
||||||
|
var made := pose{ id = id, name = string::from(name, nothing{}), node = object, bind = subclass == "BindPose" };
|
||||||
|
val entries := this.document.children_named(object, "PoseNode");
|
||||||
|
for i in 0..entries.length {
|
||||||
|
var entry := pose_entry{};
|
||||||
|
if this.document.child(entries[i], "Node") is some(named) && this.document.property(named, 0) is some(&given) {
|
||||||
|
entry.id = given.whole();
|
||||||
|
}
|
||||||
|
if this.document.child(entries[i], "Matrix") is some(matrix) {
|
||||||
|
entry.matrix = matrix_of(this.document.reals(matrix).span);
|
||||||
|
}
|
||||||
|
made.entries.append(entry);
|
||||||
|
}
|
||||||
|
this.poses.append(move(made));
|
||||||
|
return this.poses.length - 1;
|
||||||
|
}
|
||||||
|
|
||||||
|
# Finds the model of each pose's entry, by its id.
|
||||||
|
def scene::place_poses(&mut this, ids: &dict<i64, u64>): void {
|
||||||
|
for p in 0..this.poses.length {
|
||||||
|
for e in 0..this.poses[p].entries.length {
|
||||||
|
val found := ids.get_or(&this.poses[p].entries[e].id, 0xFFFFFFFFFFFFFFFF);
|
||||||
|
if found != 0xFFFFFFFFFFFFFFFF && kind_of(found) == object_kind::model as u8 {
|
||||||
|
this.poses[p].entries[e].model = index_of(found) as u32;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
# Joins what a connection says is whose.
|
||||||
|
def scene::connect(&mut this, ids: &dict<i64, u64>, child_id: i64, parent_id: i64, property: strview): void {
|
||||||
|
val unknown: u64 = 0xFFFFFFFFFFFFFFFF;
|
||||||
|
val child := ids.get_or(&child_id, unknown);
|
||||||
|
return if child == unknown;
|
||||||
|
val ck := kind_of(child);
|
||||||
|
val ci := index_of(child);
|
||||||
|
val parent := parent_id == 0 ? unknown : ids.get_or(&parent_id, unknown);
|
||||||
|
return if parent == unknown;
|
||||||
|
val pk := kind_of(parent);
|
||||||
|
val pi := index_of(parent);
|
||||||
|
val model_kind := object_kind::model as u8;
|
||||||
|
if ck == model_kind && pk == model_kind {
|
||||||
|
this.models[ci].parent = pi as u32;
|
||||||
|
this.models[pi].children.append(ci as u32);
|
||||||
|
} else if ck == object_kind::mesh as u8 && pk == model_kind {
|
||||||
|
this.models[pi].mesh = ci as u32;
|
||||||
|
} else if ck == object_kind::material as u8 && pk == model_kind {
|
||||||
|
this.models[pi].materials.append(ci as u32);
|
||||||
|
} else if ck == object_kind::camera as u8 && pk == model_kind {
|
||||||
|
this.models[pi].camera = ci as u32;
|
||||||
|
} else if ck == object_kind::light as u8 && pk == model_kind {
|
||||||
|
this.models[pi].light = ci as u32;
|
||||||
|
} else if ck == object_kind::texture as u8 && pk == object_kind::material as u8 {
|
||||||
|
this.materials[pi].maps.append(material_map{ property = string::from(property, nothing{}), texture = ci as u32 });
|
||||||
|
} else if ck == object_kind::video as u8 && pk == object_kind::texture as u8 {
|
||||||
|
this.textures[pi].video = ci as u32;
|
||||||
|
} else if ck == object_kind::skin as u8 && pk == object_kind::mesh as u8 {
|
||||||
|
this.meshes[pi].skin = ci as u32;
|
||||||
|
this.skins[ci].mesh = pi as u32;
|
||||||
|
} else if ck == object_kind::cluster as u8 && pk == object_kind::skin as u8 {
|
||||||
|
this.skins[pi].clusters.append(ci as u32);
|
||||||
|
this.clusters[ci].skin = pi as u32;
|
||||||
|
} else if ck == model_kind && pk == object_kind::cluster as u8 {
|
||||||
|
this.clusters[pi].bone = ci as u32;
|
||||||
|
} else if ck == object_kind::blend_shape as u8 && pk == object_kind::mesh as u8 {
|
||||||
|
this.meshes[pi].blend_shapes.append(ci as u32);
|
||||||
|
this.blend_shapes[ci].mesh = pi as u32;
|
||||||
|
} else if ck == object_kind::channel as u8 && pk == object_kind::blend_shape as u8 {
|
||||||
|
this.blend_shapes[pi].channels.append(ci as u32);
|
||||||
|
} else if ck == object_kind::shape as u8 && pk == object_kind::channel as u8 {
|
||||||
|
this.channels[pi].shapes.append(ci as u32);
|
||||||
|
} else if ck == object_kind::layer as u8 && pk == object_kind::stack as u8 {
|
||||||
|
this.stacks[pi].layers.append(ci as u32);
|
||||||
|
this.layers[ci].stack = pi as u32;
|
||||||
|
} else if ck == object_kind::curve_node as u8 && pk == object_kind::layer as u8 {
|
||||||
|
this.layers[pi].curve_nodes.append(ci as u32);
|
||||||
|
this.curve_nodes[ci].layer = pi as u32;
|
||||||
|
} else if ck == object_kind::curve_node as u8 {
|
||||||
|
this.curve_nodes[ci].target = pi as u32;
|
||||||
|
this.curve_nodes[ci].property = string::from(property, nothing{});
|
||||||
|
if pk == model_kind {
|
||||||
|
this.curve_nodes[ci].target_kind = part_kind::model;
|
||||||
|
} else if pk == object_kind::channel as u8 {
|
||||||
|
this.curve_nodes[ci].target_kind = part_kind::channel;
|
||||||
|
} else if pk == object_kind::material as u8 {
|
||||||
|
this.curve_nodes[ci].target_kind = part_kind::material;
|
||||||
|
} else if pk == object_kind::camera as u8 {
|
||||||
|
this.curve_nodes[ci].target_kind = part_kind::camera;
|
||||||
|
} else if pk == object_kind::light as u8 {
|
||||||
|
this.curve_nodes[ci].target_kind = part_kind::light;
|
||||||
|
} else {
|
||||||
|
this.curve_nodes[ci].target_kind = part_kind::other;
|
||||||
|
}
|
||||||
|
} else if ck == object_kind::curve as u8 && pk == object_kind::curve_node as u8 {
|
||||||
|
this.attach_curve(pi, ci as u32, property);
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,107 @@
|
|||||||
|
#! Contains reading an object's properties as `Properties70` holds them: each a
|
||||||
|
#! `P` node of its name, its type, its label, and its flags, then its values.
|
||||||
|
#! Where an object leaves one out, the template of its kind, of the document's
|
||||||
|
#! `Definitions`, gives it, as FBX's SDK reads them. And reading the children
|
||||||
|
#! a node holds a value in, as a texture's `FileName`.
|
||||||
|
|
||||||
|
import malunal::linear;
|
||||||
|
module malunal::fbx;
|
||||||
|
|
||||||
|
#! The text of a node's first child of a name, its first property's, or empty
|
||||||
|
#! where it has none.
|
||||||
|
pub def document::text_of(&this, of: u32, name: strview): strview {
|
||||||
|
val found := this.child(of, name) else { return ""; };
|
||||||
|
val held := &this.nodes[found as u64];
|
||||||
|
return "" if held.properties.length == 0;
|
||||||
|
return held.properties[0].text();
|
||||||
|
}
|
||||||
|
|
||||||
|
#! The number of a node's first child of a name, its first property's, or a
|
||||||
|
#! given one where it has none.
|
||||||
|
pub def document::number_of(&this, of: u32, name: strview, given: f64): f64 {
|
||||||
|
val found := this.child(of, name) else { return given; };
|
||||||
|
val held := &this.nodes[found as u64];
|
||||||
|
return given if held.properties.length == 0;
|
||||||
|
return held.properties[0].number();
|
||||||
|
}
|
||||||
|
|
||||||
|
# Notes the templates of the document's definitions.
|
||||||
|
def scene::read_templates(&mut this): void {
|
||||||
|
val definitions := this.document.child(absent, "Definitions") else { return; };
|
||||||
|
val kinds := this.document.children_named(definitions, "ObjectType");
|
||||||
|
for k in 0..kinds.length {
|
||||||
|
var kind := string::new(nothing{});
|
||||||
|
if this.document.property(kinds[k], 0) is some(&named) {
|
||||||
|
kind.append(named.text());
|
||||||
|
}
|
||||||
|
val templates := this.document.children_named(kinds[k], "PropertyTemplate");
|
||||||
|
for t in 0..templates.length {
|
||||||
|
if this.document.child(templates[t], "Properties70") is some(properties) {
|
||||||
|
this.templates.append(template{ kind = string::from(kind.span, nothing{}), properties = properties });
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
# The `P` node of a name among a `Properties70` node's.
|
||||||
|
def entry_in(made: &document, properties: u32, name: strview): maybe<u32> {
|
||||||
|
val list := made.nodes[properties as u64].children.span;
|
||||||
|
for i in 0..list.length {
|
||||||
|
val each := &made.nodes[list[i] as u64];
|
||||||
|
continue if each.properties.length == 0 || each.name.span != "P";
|
||||||
|
return list[i] if each.properties[0].text() == name;
|
||||||
|
}
|
||||||
|
return nothing{};
|
||||||
|
}
|
||||||
|
|
||||||
|
#! An object's property of a name: the `P` node of it, of its own
|
||||||
|
#! `Properties70`, or of its kind's template, where neither has it, nothing.
|
||||||
|
#! A `P` node's properties are its name, type, label, and flags, then its
|
||||||
|
#! values.
|
||||||
|
#! @param object The object's node, or any node holding `Properties70`, as
|
||||||
|
#! `GlobalSettings`.
|
||||||
|
pub def scene::entry(&this, object: u32, name: strview): maybe<u32> {
|
||||||
|
if this.document.child(object, "Properties70") is some(own) {
|
||||||
|
if entry_in(&this.document, own, name) is some(found) {
|
||||||
|
return found;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
val kind := this.document.nodes[object as u64].name.span;
|
||||||
|
for i in 0..this.templates.length {
|
||||||
|
continue if this.templates[i].kind.span != kind;
|
||||||
|
if entry_in(&this.document, this.templates[i].properties, name) is some(found) {
|
||||||
|
return found;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return nothing{};
|
||||||
|
}
|
||||||
|
|
||||||
|
#! An object's property of a number, or a given one where it has none.
|
||||||
|
pub def scene::number_of(&this, object: u32, name: strview, given: f64): f64 {
|
||||||
|
val found := this.entry(object, name) else { return given; };
|
||||||
|
val held := &this.document.nodes[found as u64];
|
||||||
|
return given if held.properties.length < 5;
|
||||||
|
return held.properties[4].number();
|
||||||
|
}
|
||||||
|
|
||||||
|
#! An object's property of three numbers, as a color or a translation, or a
|
||||||
|
#! given one where it has none.
|
||||||
|
pub def scene::vector_of(&this, object: u32, name: strview, given: vec3): vec3 {
|
||||||
|
val found := this.entry(object, name) else { return given; };
|
||||||
|
val held := &this.document.nodes[found as u64];
|
||||||
|
return given if held.properties.length < 7;
|
||||||
|
return vec3{ held.properties[4].number() as f32, held.properties[5].number() as f32, held.properties[6].number() as f32 };
|
||||||
|
}
|
||||||
|
|
||||||
|
#! An object's property of text, or empty where it has none.
|
||||||
|
pub def scene::text_of(&this, object: u32, name: strview): strview {
|
||||||
|
val found := this.entry(object, name) else { return ""; };
|
||||||
|
val held := &this.document.nodes[found as u64];
|
||||||
|
return "" if held.properties.length < 5;
|
||||||
|
return held.properties[4].text();
|
||||||
|
}
|
||||||
|
|
||||||
|
#! An object's property of a boolean, or a given one where it has none.
|
||||||
|
pub def scene::flag_of(&this, object: u32, name: strview, given: bool): bool {
|
||||||
|
return this.number_of(object, name, given ? 1 : 0) != 0;
|
||||||
|
}
|
||||||
@@ -0,0 +1,400 @@
|
|||||||
|
#! Contains `scene`, what a document's objects mean, as FBX's SDK reads them:
|
||||||
|
#! its settings; models, the tree of nodes, each placed by FBX's chain of
|
||||||
|
#! translations, pivots, rotations, and scales; meshes, of polygons of any
|
||||||
|
#! number of corners, their normals, places on textures, colors, and
|
||||||
|
#! materials given for each corner; materials, textures, and the files they
|
||||||
|
#! embed; cameras and lights; skins, of clusters binding a mesh's points to
|
||||||
|
#! bones; blend shapes; bind poses; and animations, of stacks, layers, curve
|
||||||
|
#! nodes, and curves. Each part keeps its id, its name, and its node in the
|
||||||
|
#! document, whose other properties `scene::entry` and those after it read.
|
||||||
|
#! Indices between parts are `u32`s, into the scene's lists, `absent` where
|
||||||
|
#! they name nothing.
|
||||||
|
|
||||||
|
import malunal::linear;
|
||||||
|
module malunal::fbx;
|
||||||
|
|
||||||
|
#! The order a model's rotation turns about its axes, the first named turning
|
||||||
|
#! first.
|
||||||
|
pub enum rotation_order: u8 { xyz, xzy, yzx, yxz, zxy, zyx, spheric_xyz }
|
||||||
|
|
||||||
|
#! What a scene's settings say of the whole of it.
|
||||||
|
pub struct settings {
|
||||||
|
#! The axis up, the axis to the front, and the axis across, each 0, 1, or 2
|
||||||
|
#! for x, y, or z, and its sign, 1 or -1.
|
||||||
|
pub var up_axis: u32 = 1;
|
||||||
|
pub var up_sign: i32 = 1;
|
||||||
|
pub var front_axis: u32 = 2;
|
||||||
|
pub var front_sign: i32 = 1;
|
||||||
|
pub var coord_axis: u32;
|
||||||
|
pub var coord_sign: i32 = 1;
|
||||||
|
#! How many centimeters a unit is, as 100 of a file in meters; and what it
|
||||||
|
#! was before the tool that wrote it scaled it.
|
||||||
|
pub var unit_scale: f64 = 1;
|
||||||
|
pub var original_unit_scale: f64 = 1;
|
||||||
|
#! Frames a second, and the time it spans, in seconds.
|
||||||
|
pub var frame_rate: f64 = 30;
|
||||||
|
pub var start: f64;
|
||||||
|
pub var stop: f64;
|
||||||
|
pub var ambient := vec3::zero;
|
||||||
|
}
|
||||||
|
|
||||||
|
#! A model: a node of the tree, and what's there, a mesh, a camera, a light,
|
||||||
|
#! or a bone, as `kind` says, as `Mesh`, `LimbNode`, or `Null`.
|
||||||
|
pub struct model {
|
||||||
|
pub var id: i64;
|
||||||
|
pub var name: string;
|
||||||
|
pub var kind: string;
|
||||||
|
pub var node: u32;
|
||||||
|
pub var parent: u32 = absent;
|
||||||
|
pub var children: vector<u32>;
|
||||||
|
pub var mesh: u32 = absent;
|
||||||
|
#! Its materials, in the order they're connected, which a mesh's polygons'
|
||||||
|
#! materials index.
|
||||||
|
pub var materials: vector<u32>;
|
||||||
|
pub var camera: u32 = absent;
|
||||||
|
pub var light: u32 = absent;
|
||||||
|
#! Where it is within its parent: `Lcl Translation`, `Lcl Rotation` in
|
||||||
|
#! degrees, and `Lcl Scaling`.
|
||||||
|
pub var translation := vec3::zero;
|
||||||
|
pub var rotation := vec3::zero;
|
||||||
|
pub var scale := vec3::one;
|
||||||
|
#! Rotations before and after its own, in degrees, and the order its own
|
||||||
|
#! turns in, which hold only where `rotation_active` is.
|
||||||
|
pub var pre_rotation := vec3::zero;
|
||||||
|
pub var post_rotation := vec3::zero;
|
||||||
|
pub var order := rotation_order::xyz;
|
||||||
|
pub var rotation_active: bool;
|
||||||
|
#! The pivots it's turned and scaled about, and their offsets.
|
||||||
|
pub var rotation_offset := vec3::zero;
|
||||||
|
pub var rotation_pivot := vec3::zero;
|
||||||
|
pub var scaling_offset := vec3::zero;
|
||||||
|
pub var scaling_pivot := vec3::zero;
|
||||||
|
#! Where its mesh is within it, its children not: `GeometricTranslation`,
|
||||||
|
#! `GeometricRotation` in degrees, and `GeometricScaling`.
|
||||||
|
pub var geometric_translation := vec3::zero;
|
||||||
|
pub var geometric_rotation := vec3::zero;
|
||||||
|
pub var geometric_scale := vec3::one;
|
||||||
|
#! `InheritType`: how its parent's scale passes to it; 1, the default, as
|
||||||
|
#! matrices multiply.
|
||||||
|
pub var inherit: u32 = 1;
|
||||||
|
pub var visible := true;
|
||||||
|
}
|
||||||
|
|
||||||
|
#! A run of a mesh's corners.
|
||||||
|
pub struct polygon {
|
||||||
|
pub var first: u64;
|
||||||
|
pub var count: u32;
|
||||||
|
}
|
||||||
|
|
||||||
|
#! A set of places on a texture, one for each corner, of a name.
|
||||||
|
pub struct uv_set {
|
||||||
|
pub var name: string;
|
||||||
|
pub var uvs: vector<vec2>;
|
||||||
|
}
|
||||||
|
|
||||||
|
#! A mesh: points, and polygons of them; what's given of each corner, its
|
||||||
|
#! normal, its places on textures, and its color, each list as long as the
|
||||||
|
#! corners, where it's given; and each polygon's material.
|
||||||
|
pub struct mesh {
|
||||||
|
pub var id: i64;
|
||||||
|
pub var name: string;
|
||||||
|
pub var node: u32;
|
||||||
|
pub var positions: vector<vec3>;
|
||||||
|
pub var polygons: vector<polygon>;
|
||||||
|
#! The points of each polygon's corners, in turn.
|
||||||
|
pub var corners: vector<u32>;
|
||||||
|
pub var normals: vector<vec3>;
|
||||||
|
pub var uv_sets: vector<uv_set>;
|
||||||
|
pub var colors: vector<vec4>;
|
||||||
|
#! Each polygon's material, an index into its model's; empty where none's
|
||||||
|
#! given, as all of the first.
|
||||||
|
pub var materials: vector<u32>;
|
||||||
|
pub var skin: u32 = absent;
|
||||||
|
pub var blend_shapes: vector<u32>;
|
||||||
|
}
|
||||||
|
|
||||||
|
#! A shape a blend shape channel blends a mesh toward: how far each of the
|
||||||
|
#! points it names moves, and its normal turns.
|
||||||
|
pub struct shape {
|
||||||
|
pub var id: i64;
|
||||||
|
pub var name: string;
|
||||||
|
pub var node: u32;
|
||||||
|
pub var points: vector<u32>;
|
||||||
|
pub var offsets: vector<vec3>;
|
||||||
|
pub var normals: vector<vec3>;
|
||||||
|
}
|
||||||
|
|
||||||
|
#! A blend shape: the channels blending a mesh.
|
||||||
|
pub struct blend_shape {
|
||||||
|
pub var id: i64;
|
||||||
|
pub var name: string;
|
||||||
|
pub var node: u32;
|
||||||
|
pub var mesh: u32 = absent;
|
||||||
|
pub var channels: vector<u32>;
|
||||||
|
}
|
||||||
|
|
||||||
|
#! A channel of a blend shape: how far, from 0 to 100, it blends toward its
|
||||||
|
#! shapes, and the weight at which each is whole, where it has more than one.
|
||||||
|
pub struct blend_channel {
|
||||||
|
pub var id: i64;
|
||||||
|
pub var name: string;
|
||||||
|
pub var node: u32;
|
||||||
|
pub var weight: f32;
|
||||||
|
pub var full_weights: vector<f32>;
|
||||||
|
pub var shapes: vector<u32>;
|
||||||
|
}
|
||||||
|
|
||||||
|
#! A skin: the clusters binding a mesh's points to bones.
|
||||||
|
pub struct skin {
|
||||||
|
pub var id: i64;
|
||||||
|
pub var name: string;
|
||||||
|
pub var node: u32;
|
||||||
|
pub var mesh: u32 = absent;
|
||||||
|
pub var clusters: vector<u32>;
|
||||||
|
}
|
||||||
|
|
||||||
|
#! A cluster: the points a bone moves, and how much; the mesh's place when it
|
||||||
|
#! was bound, `transform`, and the bone's, `transform_link`.
|
||||||
|
pub struct cluster {
|
||||||
|
pub var id: i64;
|
||||||
|
pub var name: string;
|
||||||
|
pub var node: u32;
|
||||||
|
pub var skin: u32 = absent;
|
||||||
|
#! The model that's its bone.
|
||||||
|
pub var bone: u32 = absent;
|
||||||
|
pub var points: vector<u32>;
|
||||||
|
pub var weights: vector<f32>;
|
||||||
|
pub var transform := mat4::identity;
|
||||||
|
pub var transform_link := mat4::identity;
|
||||||
|
}
|
||||||
|
|
||||||
|
#! A texture a material maps, and the property it's mapped to, as
|
||||||
|
#! `DiffuseColor` or `NormalMap`.
|
||||||
|
pub struct material_map {
|
||||||
|
pub var property: string;
|
||||||
|
pub var texture: u32;
|
||||||
|
}
|
||||||
|
|
||||||
|
#! A material: its shading model, `phong` or `lambert`, its colors and
|
||||||
|
#! factors, of the defaults FBX's SDK gives where it leaves them out, and the
|
||||||
|
#! textures it maps.
|
||||||
|
pub struct material {
|
||||||
|
pub var id: i64;
|
||||||
|
pub var name: string;
|
||||||
|
pub var node: u32;
|
||||||
|
pub var shading: string;
|
||||||
|
pub var diffuse := vec3{ 0.8, 0.8, 0.8 };
|
||||||
|
pub var diffuse_factor: f32 = 1;
|
||||||
|
pub var ambient := vec3{ 0.2, 0.2, 0.2 };
|
||||||
|
pub var ambient_factor: f32 = 1;
|
||||||
|
pub var specular := vec3{ 0.2, 0.2, 0.2 };
|
||||||
|
pub var specular_factor: f32 = 1;
|
||||||
|
pub var shininess: f32 = 20;
|
||||||
|
pub var emissive := vec3::zero;
|
||||||
|
pub var emissive_factor: f32 = 1;
|
||||||
|
#! `TransparencyFactor`, and `Opacity`, where it's given, which some tools
|
||||||
|
#! write and others don't.
|
||||||
|
pub var transparency: f32;
|
||||||
|
pub var opacity: f32 = 1;
|
||||||
|
pub var reflection_factor: f32 = 1;
|
||||||
|
pub var bump_factor: f32 = 1;
|
||||||
|
pub var maps: vector<material_map>;
|
||||||
|
}
|
||||||
|
|
||||||
|
#! The texture it maps to a property, where it maps one.
|
||||||
|
pub def material::map(&this, property: strview): maybe<u32> {
|
||||||
|
for i in 0..this.maps.length {
|
||||||
|
return this.maps[i].texture if this.maps[i].property.span == property;
|
||||||
|
}
|
||||||
|
return nothing{};
|
||||||
|
}
|
||||||
|
|
||||||
|
#! A texture: the file it names, as written, and relative to the FBX file; the
|
||||||
|
#! set of places it's drawn by, where it names one; how it's placed; and the
|
||||||
|
#! video embedding its file, where one does.
|
||||||
|
pub struct texture {
|
||||||
|
pub var id: i64;
|
||||||
|
pub var name: string;
|
||||||
|
pub var node: u32;
|
||||||
|
pub var file: string;
|
||||||
|
pub var relative: string;
|
||||||
|
pub var uv_set: string;
|
||||||
|
pub var translation := vec3::zero;
|
||||||
|
pub var rotation := vec3::zero;
|
||||||
|
pub var scale := vec3::one;
|
||||||
|
#! 0 where it repeats, 1 where it's clamped.
|
||||||
|
pub var wrap_u: u32;
|
||||||
|
pub var wrap_v: u32;
|
||||||
|
pub var video: u32 = absent;
|
||||||
|
}
|
||||||
|
|
||||||
|
#! A video, as FBX calls an image: the file it names, and its bytes, where the
|
||||||
|
#! FBX file embeds them.
|
||||||
|
pub struct video {
|
||||||
|
pub var id: i64;
|
||||||
|
pub var name: string;
|
||||||
|
pub var node: u32;
|
||||||
|
pub var file: string;
|
||||||
|
pub var relative: string;
|
||||||
|
pub var content: vector<u8>;
|
||||||
|
}
|
||||||
|
|
||||||
|
#! A camera, as its node attribute gives it: distances and angles in the
|
||||||
|
#! file's units and degrees.
|
||||||
|
pub struct camera {
|
||||||
|
pub var id: i64;
|
||||||
|
pub var name: string;
|
||||||
|
pub var node: u32;
|
||||||
|
pub var orthographic: bool;
|
||||||
|
pub var field_of_view: f32 = 40;
|
||||||
|
pub var field_of_view_x: f32 = 40;
|
||||||
|
pub var field_of_view_y: f32 = 40;
|
||||||
|
pub var focal_length: f32 = 34.89;
|
||||||
|
pub var near: f32 = 10;
|
||||||
|
pub var far: f32 = 4000;
|
||||||
|
pub var aspect_width: f32 = 320;
|
||||||
|
pub var aspect_height: f32 = 200;
|
||||||
|
pub var ortho_zoom: f32 = 1;
|
||||||
|
}
|
||||||
|
|
||||||
|
#! What kind of light it is.
|
||||||
|
pub enum light_kind: u8 { point, directional, spot, area, volume }
|
||||||
|
|
||||||
|
#! A light, as its node attribute gives it: its intensity as a percent, 100
|
||||||
|
#! the whole of its color, and a spot's cone's angles in degrees.
|
||||||
|
pub struct light {
|
||||||
|
pub var id: i64;
|
||||||
|
pub var name: string;
|
||||||
|
pub var node: u32;
|
||||||
|
pub var kind: light_kind;
|
||||||
|
pub var color := vec3::one;
|
||||||
|
pub var intensity: f32 = 100;
|
||||||
|
pub var inner_angle: f32;
|
||||||
|
pub var outer_angle: f32 = 45;
|
||||||
|
#! 0 where it doesn't decay, 1 linearly, 2 quadratically, 3 cubically.
|
||||||
|
pub var decay: u32;
|
||||||
|
pub var decay_start: f32;
|
||||||
|
pub var casts_shadows: bool;
|
||||||
|
}
|
||||||
|
|
||||||
|
#! A model's place in a pose: its matrix, of its place in the world, where
|
||||||
|
#! the pose is a bind pose.
|
||||||
|
pub struct pose_entry {
|
||||||
|
pub var model: u32 = absent;
|
||||||
|
pub var id: i64;
|
||||||
|
pub var matrix := mat4::identity;
|
||||||
|
}
|
||||||
|
|
||||||
|
#! A pose: each model's matrix, as when a skin was bound, where it's a bind
|
||||||
|
#! pose.
|
||||||
|
pub struct pose {
|
||||||
|
pub var id: i64;
|
||||||
|
pub var name: string;
|
||||||
|
pub var node: u32;
|
||||||
|
pub var bind: bool;
|
||||||
|
pub var entries: vector<pose_entry>;
|
||||||
|
}
|
||||||
|
|
||||||
|
#! An animation: its layers, and the time it spans, in seconds.
|
||||||
|
pub struct animation_stack {
|
||||||
|
pub var id: i64;
|
||||||
|
pub var name: string;
|
||||||
|
pub var node: u32;
|
||||||
|
pub var start: f64;
|
||||||
|
pub var stop: f64;
|
||||||
|
pub var layers: vector<u32>;
|
||||||
|
}
|
||||||
|
|
||||||
|
#! A layer of an animation: its curve nodes, and how much it weighs, from 0 to
|
||||||
|
#! 100.
|
||||||
|
pub struct animation_layer {
|
||||||
|
pub var id: i64;
|
||||||
|
pub var name: string;
|
||||||
|
pub var node: u32;
|
||||||
|
pub var stack: u32 = absent;
|
||||||
|
pub var weight: f32 = 100;
|
||||||
|
pub var curve_nodes: vector<u32>;
|
||||||
|
}
|
||||||
|
|
||||||
|
#! What kind of part a curve node animates.
|
||||||
|
pub enum part_kind: u8 { none, model, channel, material, camera, light, other }
|
||||||
|
|
||||||
|
#! A channel of a curve node: its name, as `X` of `d|X`, its value where no
|
||||||
|
#! curve's given, and its curve, where one is.
|
||||||
|
pub struct curve_channel {
|
||||||
|
pub var name: string;
|
||||||
|
pub var value: f32;
|
||||||
|
pub var curve: u32 = absent;
|
||||||
|
}
|
||||||
|
|
||||||
|
#! A curve node: the property of a part it animates, as a model's
|
||||||
|
#! `Lcl Translation` or a blend channel's `DeformPercent`, and its channels.
|
||||||
|
pub struct curve_node {
|
||||||
|
pub var id: i64;
|
||||||
|
pub var name: string;
|
||||||
|
pub var node: u32;
|
||||||
|
pub var layer: u32 = absent;
|
||||||
|
pub var target_kind: part_kind;
|
||||||
|
pub var target: u32 = absent;
|
||||||
|
pub var property: string;
|
||||||
|
pub var channels: vector<curve_channel>;
|
||||||
|
}
|
||||||
|
|
||||||
|
#! The channel of a name, as `X`, where it has one.
|
||||||
|
pub def curve_node::channel(&this, name: strview): maybe<&curve_channel> {
|
||||||
|
for i in 0..this.channels.length {
|
||||||
|
return &this.channels[i] if this.channels[i].name.span == name;
|
||||||
|
}
|
||||||
|
return nothing{};
|
||||||
|
}
|
||||||
|
|
||||||
|
#! How a curve goes from a key to the next.
|
||||||
|
pub enum key_interpolation: u8 { constant, linear, cubic }
|
||||||
|
|
||||||
|
#! A curve: its keys, each a time in seconds and a value, how it goes on to the
|
||||||
|
#! next, and a cubic's slopes, to its right and to the next key's left.
|
||||||
|
pub struct curve {
|
||||||
|
pub var id: i64;
|
||||||
|
pub var name: string;
|
||||||
|
pub var node: u32;
|
||||||
|
pub var value: f32;
|
||||||
|
pub var times: vector<f64>;
|
||||||
|
pub var values: vector<f32>;
|
||||||
|
pub var interpolations: vector<key_interpolation>;
|
||||||
|
pub var right_slopes: vector<f32>;
|
||||||
|
pub var next_left_slopes: vector<f32>;
|
||||||
|
}
|
||||||
|
|
||||||
|
#! A property template of the document's definitions, which gives the values
|
||||||
|
#! its objects of a kind leave out.
|
||||||
|
struct template {
|
||||||
|
var kind: string;
|
||||||
|
var properties: u32;
|
||||||
|
}
|
||||||
|
|
||||||
|
#! A scene: the document it's of, and what its objects mean, each kind in a
|
||||||
|
#! list of its own.
|
||||||
|
pub struct scene {
|
||||||
|
pub var document: document;
|
||||||
|
pub var settings: settings;
|
||||||
|
pub var models: vector<model>;
|
||||||
|
pub var meshes: vector<mesh>;
|
||||||
|
pub var shapes: vector<shape>;
|
||||||
|
pub var blend_shapes: vector<blend_shape>;
|
||||||
|
pub var channels: vector<blend_channel>;
|
||||||
|
pub var skins: vector<skin>;
|
||||||
|
pub var clusters: vector<cluster>;
|
||||||
|
pub var materials: vector<material>;
|
||||||
|
pub var textures: vector<texture>;
|
||||||
|
pub var videos: vector<video>;
|
||||||
|
pub var cameras: vector<camera>;
|
||||||
|
pub var lights: vector<light>;
|
||||||
|
pub var poses: vector<pose>;
|
||||||
|
pub var stacks: vector<animation_stack>;
|
||||||
|
pub var layers: vector<animation_layer>;
|
||||||
|
pub var curve_nodes: vector<curve_node>;
|
||||||
|
pub var curves: vector<curve>;
|
||||||
|
#! The models at the root.
|
||||||
|
pub var roots: vector<u32>;
|
||||||
|
var templates: vector<template>;
|
||||||
|
}
|
||||||
@@ -0,0 +1,103 @@
|
|||||||
|
#! Contains where models are: a model's matrix within its parent, by FBX's
|
||||||
|
#! chain of translation, rotation offset and pivot, pre-rotation, rotation,
|
||||||
|
#! post-rotation, and scaling offset and pivot, as its SDK puts them together;
|
||||||
|
#! its mesh's within it; and its matrix in the world, through its parents. And
|
||||||
|
#! turning a scene's axes and units into y up, z to the front, and meters.
|
||||||
|
|
||||||
|
import std::math;
|
||||||
|
import malunal::linear;
|
||||||
|
module malunal::fbx;
|
||||||
|
|
||||||
|
# A rotation of angles in degrees about x, y, and z, turning in an order.
|
||||||
|
def euler_matrix(degrees: vec3, order: rotation_order): mat4 {
|
||||||
|
val k := (math::pi / 180) as f32;
|
||||||
|
val x := mat4::rotation(quat::axis_angle(vec3::right, degrees.x * k));
|
||||||
|
val y := mat4::rotation(quat::axis_angle(vec3::up, degrees.y * k));
|
||||||
|
val z := mat4::rotation(quat::axis_angle(vec3::back, degrees.z * k));
|
||||||
|
# The axis turning first is the rightmost, nearest what's turned.
|
||||||
|
if order == rotation_order::xzy {
|
||||||
|
return y.mul(&z).mul(&x);
|
||||||
|
}
|
||||||
|
if order == rotation_order::yzx {
|
||||||
|
return x.mul(&z).mul(&y);
|
||||||
|
}
|
||||||
|
if order == rotation_order::yxz {
|
||||||
|
return z.mul(&x).mul(&y);
|
||||||
|
}
|
||||||
|
if order == rotation_order::zxy {
|
||||||
|
return y.mul(&x).mul(&z);
|
||||||
|
}
|
||||||
|
if order == rotation_order::zyx {
|
||||||
|
return x.mul(&y).mul(&z);
|
||||||
|
}
|
||||||
|
return z.mul(&y).mul(&x);
|
||||||
|
}
|
||||||
|
|
||||||
|
#! Its matrix within its parent: its translation, rotation offset, rotation
|
||||||
|
#! pivot, pre-rotation, rotation, post-rotation turned back, the pivot taken
|
||||||
|
#! away, then its scaling offset and pivot, scale, and the pivot taken away,
|
||||||
|
#! as `T * Roff * Rp * Rpre * R * Rpost⁻¹ * Rp⁻¹ * Soff * Sp * S * Sp⁻¹`.
|
||||||
|
#! Where its rotation isn't active, its pre- and post-rotations and order are
|
||||||
|
#! taken as none and `xyz`.
|
||||||
|
pub def model::local_matrix(&this): mat4 {
|
||||||
|
val active := this.rotation_active;
|
||||||
|
val order := active ? this.order : rotation_order::xyz;
|
||||||
|
val pre := active ? euler_matrix(this.pre_rotation, rotation_order::xyz) : mat4::identity;
|
||||||
|
val post := active ? euler_matrix(this.post_rotation, rotation_order::xyz).transposed() : mat4::identity;
|
||||||
|
val turned := euler_matrix(this.rotation, order);
|
||||||
|
var made := mat4::translation(this.translation);
|
||||||
|
made = made.mul(&mat4::translation(this.rotation_offset));
|
||||||
|
made = made.mul(&mat4::translation(this.rotation_pivot));
|
||||||
|
made = made.mul(&pre).mul(&turned).mul(&post);
|
||||||
|
made = made.mul(&mat4::translation(this.rotation_pivot.negate()));
|
||||||
|
made = made.mul(&mat4::translation(this.scaling_offset));
|
||||||
|
made = made.mul(&mat4::translation(this.scaling_pivot));
|
||||||
|
made = made.mul(&mat4::scaling(this.scale));
|
||||||
|
made = made.mul(&mat4::translation(this.scaling_pivot.negate()));
|
||||||
|
return made;
|
||||||
|
}
|
||||||
|
|
||||||
|
#! Its mesh's matrix within it, which its children don't follow:
|
||||||
|
#! `GeometricTranslation`, `GeometricRotation`, and `GeometricScaling`.
|
||||||
|
pub def model::geometry_matrix(&this): mat4 {
|
||||||
|
val turned := euler_matrix(this.geometric_rotation, rotation_order::xyz);
|
||||||
|
return mat4::translation(this.geometric_translation).mul(&turned).mul(&mat4::scaling(this.geometric_scale));
|
||||||
|
}
|
||||||
|
|
||||||
|
#! A model's matrix in the world: its parents', each's within its own, then
|
||||||
|
#! its own, multiplied as matrices are, as FBX's default way of inheriting
|
||||||
|
#! does.
|
||||||
|
pub def scene::world_matrix(&this, of: u32): mat4 {
|
||||||
|
var made := this.models[of as u64].local_matrix();
|
||||||
|
var above := this.models[of as u64].parent;
|
||||||
|
var steps: u64 = 0;
|
||||||
|
while above != absent && steps < this.models.length {
|
||||||
|
made = this.models[above as u64].local_matrix().mul(&made);
|
||||||
|
above = this.models[above as u64].parent;
|
||||||
|
steps++;
|
||||||
|
}
|
||||||
|
return made;
|
||||||
|
}
|
||||||
|
|
||||||
|
#! The matrix turning the scene's axes into x across, y up, and z to the
|
||||||
|
#! front, as glTF's are, mirroring where they're left-handed.
|
||||||
|
pub def settings::axes(&this): mat4 {
|
||||||
|
var made := mat4{};
|
||||||
|
made.m[15] = 1;
|
||||||
|
made.m[(this.coord_axis % 3) as u64 * 4] = this.coord_sign < 0 ? -1 : 1;
|
||||||
|
made.m[(this.up_axis % 3) as u64 * 4 + 1] = this.up_sign < 0 ? -1 : 1;
|
||||||
|
made.m[(this.front_axis % 3) as u64 * 4 + 2] = this.front_sign < 0 ? -1 : 1;
|
||||||
|
return made;
|
||||||
|
}
|
||||||
|
|
||||||
|
#! How many meters a unit is.
|
||||||
|
pub def settings::meters_per_unit(&this): f32 {
|
||||||
|
return (this.unit_scale / 100) as f32;
|
||||||
|
}
|
||||||
|
|
||||||
|
#! The matrix turning the scene into meters, with x across, y up, and z to the
|
||||||
|
#! front: its axes, scaled.
|
||||||
|
pub def settings::conversion(&this): mat4 {
|
||||||
|
val k := this.meters_per_unit();
|
||||||
|
return mat4::scaling(vec3{ k, k, k }).mul(&this.axes());
|
||||||
|
}
|
||||||
@@ -0,0 +1,240 @@
|
|||||||
|
#! Contains writing a document as binary FBX, `encode` and `save`, and making
|
||||||
|
#! properties to build one by hand. Arrays are written as they are, not
|
||||||
|
#! compressed, which FBX allows; nodes end with a record of zeros where they
|
||||||
|
#! have children, and where Blender's writer finds Autodesk's reader wants one,
|
||||||
|
#! and the file with the footer Autodesk's writer gives.
|
||||||
|
|
||||||
|
import std::io;
|
||||||
|
import std::math;
|
||||||
|
module malunal::fbx;
|
||||||
|
|
||||||
|
#! A property of a boolean.
|
||||||
|
pub def property::of_bool(value: bool): property {
|
||||||
|
return property{ kind = property_kind::boolean, integer = value ? 1 : 0 };
|
||||||
|
}
|
||||||
|
|
||||||
|
#! A property of a 32-bit integer.
|
||||||
|
pub def property::of_int32(value: i32): property {
|
||||||
|
return property{ kind = property_kind::int32, integer = value as i64 };
|
||||||
|
}
|
||||||
|
|
||||||
|
#! A property of a 64-bit integer, as an object's id.
|
||||||
|
pub def property::of_int64(value: i64): property {
|
||||||
|
return property{ kind = property_kind::int64, integer = value };
|
||||||
|
}
|
||||||
|
|
||||||
|
#! A property of a 32-bit float.
|
||||||
|
pub def property::of_float32(value: f32): property {
|
||||||
|
return property{ kind = property_kind::float32, real = value as f64 };
|
||||||
|
}
|
||||||
|
|
||||||
|
#! A property of a 64-bit float.
|
||||||
|
pub def property::of_float64(value: f64): property {
|
||||||
|
return property{ kind = property_kind::float64, real = value };
|
||||||
|
}
|
||||||
|
|
||||||
|
#! A property of text.
|
||||||
|
pub def property::of_text(value: strview): property {
|
||||||
|
var made := property{ kind = property_kind::text };
|
||||||
|
made.bytes.extend(value);
|
||||||
|
return made;
|
||||||
|
}
|
||||||
|
|
||||||
|
#! A property of bytes, as an embedded file's.
|
||||||
|
pub def property::of_bytes(value: span<u8>): property {
|
||||||
|
var made := property{ kind = property_kind::raw };
|
||||||
|
made.bytes.extend(value);
|
||||||
|
return made;
|
||||||
|
}
|
||||||
|
|
||||||
|
#! A property of an array of integers, of a kind: `booleans`, `int32s`, or
|
||||||
|
#! `int64s`.
|
||||||
|
pub def property::of_integers(kind: property_kind, values: span<i64>): property {
|
||||||
|
var made := property{ kind = kind };
|
||||||
|
made.integers.extend(values);
|
||||||
|
return made;
|
||||||
|
}
|
||||||
|
|
||||||
|
#! A property of an array of floats, of a kind: `float32s` or `float64s`.
|
||||||
|
pub def property::of_reals(kind: property_kind, values: span<f64>): property {
|
||||||
|
var made := property{ kind = kind };
|
||||||
|
made.reals.extend(values);
|
||||||
|
return made;
|
||||||
|
}
|
||||||
|
|
||||||
|
# The footer's first 16 bytes, and its last, as Autodesk's writer gives them.
|
||||||
|
const footer_id: u8[16] = [0xFA, 0xBC, 0xAB, 0x09, 0xD0, 0xC8, 0xD4, 0x66, 0xB1, 0x76, 0xFB, 0x83, 0x1C, 0xF7, 0x26, 0x7E];
|
||||||
|
const footer_magic: u8[16] = [0xF8, 0x5A, 0x8C, 0x6A, 0xDE, 0xF5, 0xD9, 0x7E, 0xEC, 0xE9, 0x0C, 0xE3, 0x75, 0x8F, 0x29, 0x0B];
|
||||||
|
|
||||||
|
#! Writes a document as binary FBX, of its version, or 7.4 where it's of
|
||||||
|
#! before 7.0.
|
||||||
|
#! @param made The document.
|
||||||
|
#! @returns The file's bytes, or why it couldn't be written: `malformed` where a
|
||||||
|
#! node's name is longer than 255 bytes, or a file of 7.4 or before
|
||||||
|
#! would pass 4 GB.
|
||||||
|
pub def encode(made: &document): result<vector<u8>, fbx_error> {
|
||||||
|
val version: u32 = made.version >= 7000 ? made.version : 7400;
|
||||||
|
val wide := version >= 7500;
|
||||||
|
var out := vector::<u8>::new();
|
||||||
|
out.extend(binary_magic);
|
||||||
|
out.append(0);
|
||||||
|
out.append(0x1A);
|
||||||
|
out.append(0);
|
||||||
|
put_u32(&mut out, version);
|
||||||
|
# An ASCII document's objects are named as `Class::name`, which binary FBX
|
||||||
|
# writes as `name\0\1Class`.
|
||||||
|
var renamed: u32 = absent;
|
||||||
|
if !made.binary {
|
||||||
|
if made.child(absent, "Objects") is some(objects) {
|
||||||
|
renamed = objects;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
for k in 0..made.roots.length {
|
||||||
|
write_node(&mut out, made, made.roots[k], k + 1 == made.roots.length, wide, renamed) else (e) { return e; };
|
||||||
|
}
|
||||||
|
put_zeros(&mut out, wide ? 25 : 13);
|
||||||
|
out.extend(footer_id[:]);
|
||||||
|
put_zeros(&mut out, 4);
|
||||||
|
val past := out.length % 16;
|
||||||
|
put_zeros(&mut out, past == 0 ? 16 : 16 - past);
|
||||||
|
put_u32(&mut out, version);
|
||||||
|
put_zeros(&mut out, 120);
|
||||||
|
out.extend(footer_magic[:]);
|
||||||
|
return out;
|
||||||
|
}
|
||||||
|
|
||||||
|
#! Writes a document to a file, as `encode` writes it, its folder made where it
|
||||||
|
#! isn't.
|
||||||
|
#! @returns Nothing, or why it couldn't be written: `unreadable` where the file
|
||||||
|
#! couldn't be.
|
||||||
|
pub def save(made: &document, at: &path): result<void, fbx_error> {
|
||||||
|
val bytes := encode(made) else (e) { return e; };
|
||||||
|
if at.parent() is some(&above) {
|
||||||
|
_ = io::create_directories(above);
|
||||||
|
}
|
||||||
|
io::write_file(at, bytes.span) else (_) { return failed(failure::unreadable, $"{at.span} couldn't be written.".span); };
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
#! Writes a document to a file named by text, as `save` does.
|
||||||
|
pub def save(made: &document, at: strview): result<void, fbx_error> {
|
||||||
|
val named := path::parse(at) else (_) { return failed(failure::unreadable, $"{at} isn't a path.".span); };
|
||||||
|
return save(made, &named);
|
||||||
|
}
|
||||||
|
|
||||||
|
def put_u32(out: &mut vector<u8>, value: u32): void {
|
||||||
|
for i in 0..4u {
|
||||||
|
out.append(((value >> (8 * i)) & 0xFF) as u8);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
def put_u64(out: &mut vector<u8>, value: u64): void {
|
||||||
|
for i in 0..8u {
|
||||||
|
out.append(((value >> (8 * i)) & 0xFF) as u8);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
def put_zeros(out: &mut vector<u8>, count: u64): void {
|
||||||
|
for _ in 0..count {
|
||||||
|
out.append(0);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
# Writes a number at a place written before, 32 or 64 bits wide.
|
||||||
|
def patch(out: &mut vector<u8>, at: u64, value: u64, wide: bool): void {
|
||||||
|
val bytes: u64 = wide ? 8 : 4;
|
||||||
|
for i in 0..bytes {
|
||||||
|
out[at + i] = ((value >> (8 * i)) & 0xFF) as u8;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
# Writes a node: its header, its properties, its children, and the record of
|
||||||
|
# zeros ending them, where it needs one.
|
||||||
|
def write_node(out: &mut vector<u8>, made: &document, index: u32, last: bool, wide: bool, renamed: u32): result<void, fbx_error> {
|
||||||
|
val held := &made.nodes[index as u64];
|
||||||
|
return failed(failure::malformed, $"A node's name is {held.name.length} bytes, past the 255 there may be.".span) if held.name.length > 255;
|
||||||
|
val begun := out.length;
|
||||||
|
put_zeros(out, wide ? 24 : 12);
|
||||||
|
out.append(held.name.length as u8);
|
||||||
|
out.extend(held.name.span);
|
||||||
|
val properties_begun := out.length;
|
||||||
|
for i in 0..held.properties.length {
|
||||||
|
val name := held.properties[i].text();
|
||||||
|
if i == 1 && renamed != absent && held.parent == renamed && held.properties[i].kind == property_kind::text && name.find("::") is some(at) {
|
||||||
|
var turned := string::from(name.substr(at + 2, name.length - at - 2), nothing{});
|
||||||
|
turned.push(0);
|
||||||
|
turned.push(1);
|
||||||
|
turned.append(name.substr(0, at));
|
||||||
|
write_property(out, &property::of_text(turned.span));
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
write_property(out, &held.properties[i]);
|
||||||
|
}
|
||||||
|
val properties_length := out.length - properties_begun;
|
||||||
|
for k in 0..held.children.length {
|
||||||
|
write_node(out, made, held.children[k], k + 1 == held.children.length, wide, renamed) else (e) { return e; };
|
||||||
|
}
|
||||||
|
val always := held.name.span == "AnimationStack" || held.name.span == "AnimationLayer";
|
||||||
|
if held.children.length != 0 || (held.properties.length == 0 && !last) || always {
|
||||||
|
put_zeros(out, wide ? 25 : 13);
|
||||||
|
}
|
||||||
|
val end := out.length as u64;
|
||||||
|
return failed(failure::malformed, "It would pass 4 GB, which FBX of 7.4 and before can't.") if !wide && end > 0xFFFFFFFF;
|
||||||
|
val step: u64 = wide ? 8 : 4;
|
||||||
|
patch(out, begun, end, wide);
|
||||||
|
patch(out, begun + step, held.properties.length as u64, wide);
|
||||||
|
patch(out, begun + 2 * step, properties_length as u64, wide);
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
# Writes a property: its type's letter, then its value.
|
||||||
|
def write_property(out: &mut vector<u8>, held: &property): void {
|
||||||
|
val kind := held.kind;
|
||||||
|
if kind == property_kind::boolean {
|
||||||
|
out.append('C');
|
||||||
|
out.append(held.integer as u8);
|
||||||
|
} else if kind == property_kind::int16 {
|
||||||
|
out.append('Y');
|
||||||
|
val v := held.integer as u64;
|
||||||
|
out.append((v & 0xFF) as u8);
|
||||||
|
out.append(((v >> 8) & 0xFF) as u8);
|
||||||
|
} else if kind == property_kind::int32 {
|
||||||
|
out.append('I');
|
||||||
|
put_u32(out, held.integer as u64 as u32);
|
||||||
|
} else if kind == property_kind::int64 {
|
||||||
|
out.append('L');
|
||||||
|
put_u64(out, held.integer as u64);
|
||||||
|
} else if kind == property_kind::float32 {
|
||||||
|
out.append('F');
|
||||||
|
put_u32(out, math::bits_of(held.real as f32));
|
||||||
|
} else if kind == property_kind::float64 {
|
||||||
|
out.append('D');
|
||||||
|
put_u64(out, math::bits_of(held.real));
|
||||||
|
} else if kind == property_kind::text || kind == property_kind::raw {
|
||||||
|
out.append(kind == property_kind::text ? 'S' : 'R');
|
||||||
|
put_u32(out, held.bytes.length as u32);
|
||||||
|
out.extend(held.bytes.span);
|
||||||
|
} else {
|
||||||
|
val codes: u8[5] = ['b', 'i', 'l', 'f', 'd'];
|
||||||
|
val sizes: u64[5] = [1, 4, 8, 4, 8];
|
||||||
|
val which := (kind as u8 - property_kind::booleans as u8) as u64;
|
||||||
|
val count := held.count();
|
||||||
|
out.append(codes[which]);
|
||||||
|
put_u32(out, count as u32);
|
||||||
|
put_u32(out, 0);
|
||||||
|
put_u32(out, (count * sizes[which]) as u32);
|
||||||
|
for i in 0..count {
|
||||||
|
if which == 0 {
|
||||||
|
out.append(held.integers[i] as u8);
|
||||||
|
} else if which == 1 {
|
||||||
|
put_u32(out, held.integers[i] as u64 as u32);
|
||||||
|
} else if which == 2 {
|
||||||
|
put_u64(out, held.integers[i] as u64);
|
||||||
|
} else if which == 3 {
|
||||||
|
put_u32(out, math::bits_of(held.reals[i] as f32));
|
||||||
|
} else {
|
||||||
|
put_u64(out, math::bits_of(held.reals[i]));
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,240 @@
|
|||||||
|
#! Contains buffers, the views of them, and accessors, which say how a view's
|
||||||
|
#! bytes are read as numbers; and reading an accessor's numbers, as floats or
|
||||||
|
#! as integers, its sparse values put in place.
|
||||||
|
|
||||||
|
import std::math;
|
||||||
|
module malunal::gltf;
|
||||||
|
|
||||||
|
#! A buffer: bytes, read from its file, a `data:` URI, or a `.glb` file's
|
||||||
|
#! binary chunk.
|
||||||
|
pub struct buffer {
|
||||||
|
pub var name: string;
|
||||||
|
#! Its URI, as the JSON writes it, or empty for a `.glb` file's binary chunk.
|
||||||
|
pub var uri: string;
|
||||||
|
#! How many bytes it is, as the JSON says, which its bytes are at least.
|
||||||
|
pub var length: u64;
|
||||||
|
pub var bytes: vector<u8>;
|
||||||
|
}
|
||||||
|
|
||||||
|
#! A part of a buffer, which accessors read.
|
||||||
|
pub struct buffer_view {
|
||||||
|
pub var name: string;
|
||||||
|
pub var buffer: u64;
|
||||||
|
pub var offset: u64;
|
||||||
|
pub var length: u64;
|
||||||
|
#! The bytes from one element to the next, or zero where they're packed.
|
||||||
|
pub var stride: u64;
|
||||||
|
}
|
||||||
|
|
||||||
|
#! The type of each number of an accessor.
|
||||||
|
pub enum component: u8 { byte, unsigned_byte, short, unsigned_short, unsigned_int, float }
|
||||||
|
|
||||||
|
#! How many bytes a number of the type takes.
|
||||||
|
pub val component::bytes: u64 {
|
||||||
|
get => match this {
|
||||||
|
byte, unsigned_byte => 1,
|
||||||
|
short, unsigned_short => 2,
|
||||||
|
unsigned_int, float => 4,
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
#! What each element of an accessor is.
|
||||||
|
pub enum element: u8 { scalar, vec2, vec3, vec4, mat2, mat3, mat4 }
|
||||||
|
|
||||||
|
#! How many numbers an element holds.
|
||||||
|
pub val element::components: u64 {
|
||||||
|
get => match this {
|
||||||
|
scalar => 1,
|
||||||
|
vec2 => 2,
|
||||||
|
vec3 => 3,
|
||||||
|
vec4, mat2 => 4,
|
||||||
|
mat3 => 9,
|
||||||
|
mat4 => 16,
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
# How many rows a matrix has, or 1 for a vector, as a column of a matrix is
|
||||||
|
# kept on its own, at a multiple of 4 bytes.
|
||||||
|
def element::rows(&this): u64 {
|
||||||
|
return match this {
|
||||||
|
mat2 => 2,
|
||||||
|
mat3 => 3,
|
||||||
|
mat4 => 4,
|
||||||
|
else => 0,
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
#! Values an accessor puts in place of some of its elements, of `count`
|
||||||
|
#! indices, in a view of integers, and as many values, in a view of the
|
||||||
|
#! accessor's own type.
|
||||||
|
pub struct sparse {
|
||||||
|
pub var count: u64;
|
||||||
|
pub var indices_view: u64;
|
||||||
|
pub var indices_offset: u64;
|
||||||
|
pub var indices_type := component::unsigned_int;
|
||||||
|
pub var values_view: u64;
|
||||||
|
pub var values_offset: u64;
|
||||||
|
}
|
||||||
|
|
||||||
|
#! How the bytes of a view are read as `count` elements, each of `kind`'s
|
||||||
|
#! numbers of `type`, from `offset`.
|
||||||
|
pub struct accessor {
|
||||||
|
pub var name: string;
|
||||||
|
#! Its view, or none where every element is zero but its sparse ones.
|
||||||
|
pub var view: maybe<u64>;
|
||||||
|
pub var offset: u64;
|
||||||
|
pub var component_type := component::float;
|
||||||
|
#! Whether its integers are read as fractions, 0 to 1, or -1 to 1 where signed.
|
||||||
|
pub var normalized: bool;
|
||||||
|
pub var count: u64;
|
||||||
|
pub var kind := element::scalar;
|
||||||
|
#! The least and the most of each of its numbers, where the JSON says.
|
||||||
|
pub var min: vector<f64>;
|
||||||
|
pub var max: vector<f64>;
|
||||||
|
pub var sparse: maybe<sparse>;
|
||||||
|
}
|
||||||
|
|
||||||
|
# How many bytes an element of an accessor takes, each column of a matrix
|
||||||
|
# begun at a multiple of 4.
|
||||||
|
def accessor::element_bytes(&this): u64 {
|
||||||
|
val rows := this.kind.rows();
|
||||||
|
return this.kind.components * this.component_type.bytes if rows == 0;
|
||||||
|
return rows * column_stride(rows, this.component_type);
|
||||||
|
}
|
||||||
|
|
||||||
|
# The bytes from one column of a matrix to the next.
|
||||||
|
def column_stride(rows: u64, numbers: component): u64 {
|
||||||
|
val bytes := rows * numbers.bytes;
|
||||||
|
return (bytes + 3) / 4 * 4;
|
||||||
|
}
|
||||||
|
|
||||||
|
# Where the number `k` of an element is, from the element's first byte.
|
||||||
|
def accessor::component_at(&this, k: u64): u64 {
|
||||||
|
val rows := this.kind.rows();
|
||||||
|
return k * this.component_type.bytes if rows == 0;
|
||||||
|
return (k / rows) * column_stride(rows, this.component_type) + (k % rows) * this.component_type.bytes;
|
||||||
|
}
|
||||||
|
|
||||||
|
#! The numbers of an accessor, as floats: each element's in turn, `count` of
|
||||||
|
#! them, integers made floats, normalized ones made fractions as glTF says, and
|
||||||
|
#! its sparse values put in place.
|
||||||
|
#! @param this The asset.
|
||||||
|
#! @param which The accessor.
|
||||||
|
#! @returns `count * kind.components` floats.
|
||||||
|
pub def asset::floats(&this, which: u64): vector<f32> {
|
||||||
|
val read := &this.accessors[which];
|
||||||
|
val width := read.kind.components;
|
||||||
|
var made := vector::<f32>::new();
|
||||||
|
made.resize(read.count * width);
|
||||||
|
if read.view is some(v) {
|
||||||
|
val at := this.place_of(read, v);
|
||||||
|
val stride := this.stride_of(read, v);
|
||||||
|
for e in 0..read.count {
|
||||||
|
for k in 0..width {
|
||||||
|
made[e * width + k] = float_at(at.bytes, at.start + e * stride + read.component_at(k), read.component_type, read.normalized);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if read.sparse is some(&s) {
|
||||||
|
val indices := this.place_of_view(s.indices_view, s.indices_offset);
|
||||||
|
val values := this.place_of_view(s.values_view, s.values_offset);
|
||||||
|
val size := read.element_bytes();
|
||||||
|
for i in 0..s.count {
|
||||||
|
val e := integer_at(indices.bytes, indices.start + i * s.indices_type.bytes, s.indices_type);
|
||||||
|
for k in 0..width {
|
||||||
|
made[e * width + k] = float_at(values.bytes, values.start + i * size + read.component_at(k), read.component_type, read.normalized);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return made;
|
||||||
|
}
|
||||||
|
|
||||||
|
#! The numbers of an accessor of integers, as indices and joints are: each
|
||||||
|
#! element's in turn, its sparse values put in place.
|
||||||
|
#! @param this The asset.
|
||||||
|
#! @param which The accessor, of a type of integers, not normalized.
|
||||||
|
#! @returns `count * kind.components` integers.
|
||||||
|
pub def asset::integers(&this, which: u64): vector<u32> {
|
||||||
|
val read := &this.accessors[which];
|
||||||
|
val width := read.kind.components;
|
||||||
|
var made := vector::<u32>::new();
|
||||||
|
made.resize(read.count * width);
|
||||||
|
if read.view is some(v) {
|
||||||
|
val at := this.place_of(read, v);
|
||||||
|
val stride := this.stride_of(read, v);
|
||||||
|
for e in 0..read.count {
|
||||||
|
for k in 0..width {
|
||||||
|
made[e * width + k] = integer_at(at.bytes, at.start + e * stride + read.component_at(k), read.component_type) as u32;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if read.sparse is some(&s) {
|
||||||
|
val indices := this.place_of_view(s.indices_view, s.indices_offset);
|
||||||
|
val values := this.place_of_view(s.values_view, s.values_offset);
|
||||||
|
val size := read.element_bytes();
|
||||||
|
for i in 0..s.count {
|
||||||
|
val e := integer_at(indices.bytes, indices.start + i * s.indices_type.bytes, s.indices_type);
|
||||||
|
for k in 0..width {
|
||||||
|
made[e * width + k] = integer_at(values.bytes, values.start + i * size + read.component_at(k), read.component_type) as u32;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return made;
|
||||||
|
}
|
||||||
|
|
||||||
|
# Where an accessor's, or a view's, bytes begin, in its buffer's.
|
||||||
|
struct place {
|
||||||
|
var bytes: span<u8>;
|
||||||
|
var start: u64;
|
||||||
|
}
|
||||||
|
|
||||||
|
def asset::place_of(&this, read: &accessor, view: u64): place {
|
||||||
|
return this.place_of_view(view, read.offset);
|
||||||
|
}
|
||||||
|
|
||||||
|
def asset::place_of_view(&this, view: u64, offset: u64): place {
|
||||||
|
val v := &this.views[view];
|
||||||
|
return place{ bytes = this.buffers[v.buffer].bytes.span, start = v.offset + offset };
|
||||||
|
}
|
||||||
|
|
||||||
|
# The bytes from one element of an accessor to the next.
|
||||||
|
def asset::stride_of(&this, read: &accessor, view: u64): u64 {
|
||||||
|
val given := this.views[view].stride;
|
||||||
|
return given != 0 ? given : read.element_bytes();
|
||||||
|
}
|
||||||
|
|
||||||
|
# A number of a type, at a byte, as a float, made a fraction where it's
|
||||||
|
# normalized.
|
||||||
|
def float_at(bytes: span<u8>, at: u64, numbers: component, normalized: bool): f32 {
|
||||||
|
if numbers == component::float {
|
||||||
|
return math::real_of_bits(integer_at(bytes, at, component::unsigned_int) as u32);
|
||||||
|
}
|
||||||
|
val raw := integer_at(bytes, at, numbers);
|
||||||
|
val signed := signed_value(raw, numbers);
|
||||||
|
return signed as f32 if !normalized;
|
||||||
|
return match numbers {
|
||||||
|
byte => math::max(signed as f32 / 127, -1f),
|
||||||
|
unsigned_byte => raw as f32 / 255,
|
||||||
|
short => math::max(signed as f32 / 32767, -1f),
|
||||||
|
unsigned_short => raw as f32 / 65535,
|
||||||
|
else => raw as f32 / 4294967295,
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
# The bytes of an integer of a type, at a byte, little-endian, unsigned.
|
||||||
|
def integer_at(bytes: span<u8>, at: u64, numbers: component): u64 {
|
||||||
|
var value: u64 = 0;
|
||||||
|
for i in 0..numbers.bytes {
|
||||||
|
value = value | (bytes[at + i] as u64 << (8 * i) as u32);
|
||||||
|
}
|
||||||
|
return value;
|
||||||
|
}
|
||||||
|
|
||||||
|
# An integer's bytes as the signed value they are, of a signed type.
|
||||||
|
def signed_value(raw: u64, numbers: component): i64 {
|
||||||
|
return match numbers {
|
||||||
|
byte => raw >= 0x80 ? raw as i64 - 0x100 : raw as i64,
|
||||||
|
short => raw >= 0x8000 ? raw as i64 - 0x10000 : raw as i64,
|
||||||
|
else => raw as i64,
|
||||||
|
};
|
||||||
|
}
|
||||||
@@ -0,0 +1,157 @@
|
|||||||
|
#! Contains the files an asset is read from: a `.glb` file's chunks, and the
|
||||||
|
#! bytes a URI names, the data of a `data:` URI, in base64, or a file's, beside
|
||||||
|
#! the asset's, its path percent-decoded.
|
||||||
|
|
||||||
|
import std::io;
|
||||||
|
module malunal::gltf;
|
||||||
|
|
||||||
|
const glb_magic: u32 = 0x46546C67; # `glTF`, little-endian.
|
||||||
|
const json_chunk: u32 = 0x4E4F534A; # `JSON`.
|
||||||
|
const bin_chunk: u32 = 0x004E4942; # `BIN`, and a zero.
|
||||||
|
|
||||||
|
# Whether bytes are a `.glb` file's, by their first four.
|
||||||
|
def is_binary(bytes: span<u8>): bool {
|
||||||
|
return bytes.length >= 4 && word_at(bytes, 0) == glb_magic;
|
||||||
|
}
|
||||||
|
|
||||||
|
# A little-endian `u32` at a byte.
|
||||||
|
def word_at(bytes: span<u8>, at: u64): u32 {
|
||||||
|
return bytes[at] as u32 | (bytes[at + 1] as u32 << 8) | (bytes[at + 2] as u32 << 16) | (bytes[at + 3] as u32 << 24);
|
||||||
|
}
|
||||||
|
|
||||||
|
# The chunks of a `.glb` file: its JSON, and its binary chunk, where it has one.
|
||||||
|
struct chunks {
|
||||||
|
var json: strview;
|
||||||
|
var bin: span<u8>;
|
||||||
|
var has_bin: bool;
|
||||||
|
}
|
||||||
|
|
||||||
|
# Finds a `.glb` file's chunks: the JSON first, as it must be, then the first
|
||||||
|
# binary chunk, passing over others, as glTF says to.
|
||||||
|
def binary_chunks(bytes: span<u8>): result<chunks, gltf_error> {
|
||||||
|
return failed(failure::malformed, "Its .glb header is cut short.") if bytes.length < 20;
|
||||||
|
val version := word_at(bytes, 4);
|
||||||
|
return failed(failure::unsupported, $"Its .glb container is of version {version}, not 2.".span) if version != 2;
|
||||||
|
val length := word_at(bytes, 8) as u64;
|
||||||
|
return failed(failure::malformed, $"Its .glb header says it's {length} bytes, but it's {bytes.length}.".span) if length > bytes.length || length < 20;
|
||||||
|
var made := chunks{};
|
||||||
|
var found_json := false;
|
||||||
|
var at: u64 = 12;
|
||||||
|
while at + 8 <= length {
|
||||||
|
val size := word_at(bytes, at) as u64;
|
||||||
|
val kind := word_at(bytes, at + 4);
|
||||||
|
at += 8;
|
||||||
|
return failed(failure::malformed, "A chunk of its .glb container reaches past its end.") if size > length - at;
|
||||||
|
if !found_json {
|
||||||
|
return failed(failure::malformed, "Its .glb container's first chunk isn't its JSON.") if kind != json_chunk;
|
||||||
|
made.json = strview::over(bytes.data + at, size);
|
||||||
|
found_json = true;
|
||||||
|
} else if kind == bin_chunk && !made.has_bin {
|
||||||
|
made.bin = span::<u8>::over(bytes.data + at, size);
|
||||||
|
made.has_bin = true;
|
||||||
|
}
|
||||||
|
at += size;
|
||||||
|
}
|
||||||
|
return failed(failure::malformed, "Its .glb container holds no JSON.") if !found_json;
|
||||||
|
return made;
|
||||||
|
}
|
||||||
|
|
||||||
|
# The bytes a URI names: a `data:` URI's, decoded from base64, its type kept;
|
||||||
|
# or a file's, its path, percent-decoded, taken from the folder.
|
||||||
|
# @param uri The URI.
|
||||||
|
# @param folder The folder the asset's files are in, or empty for none.
|
||||||
|
# @param whose Whose URI, as `buffers[1]`, for what's wrong with it.
|
||||||
|
# @param type The type a `data:` URI says, as `image/png`, kept.
|
||||||
|
# @returns The bytes, or why they couldn't be had.
|
||||||
|
def bytes_of_uri(uri: strview, folder: strview, whose: strview, mime: &mut string): result<vector<u8>, gltf_error> {
|
||||||
|
if uri.starts_with("data:") {
|
||||||
|
var comma := uri.length;
|
||||||
|
for i in 5..uri.length {
|
||||||
|
if uri[i] == ',' {
|
||||||
|
comma = i;
|
||||||
|
break;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return failed(failure::malformed, $"{whose}: its data URI has no comma.".span) if comma == uri.length;
|
||||||
|
val head := uri.substr(5, comma - 5);
|
||||||
|
return failed(failure::unsupported, $"{whose}: its data URI isn't base64.".span) if !head.ends_with(";base64");
|
||||||
|
mime = string::from(head.substr(0, head.length - 7), nothing{});
|
||||||
|
val decoded := base64(uri.substr(comma + 1, uri.length - comma - 1)) else {
|
||||||
|
return failed(failure::malformed, $"{whose}: its data URI's base64 isn't.".span);
|
||||||
|
};
|
||||||
|
return decoded;
|
||||||
|
}
|
||||||
|
for i in 0..uri.length {
|
||||||
|
if uri[i] == ':' {
|
||||||
|
return failed(failure::unsupported, $"{whose}: {uri} names another place than a file beside it, which isn't read.".span);
|
||||||
|
}
|
||||||
|
break if uri[i] == '/';
|
||||||
|
}
|
||||||
|
val named := percent_decoded(uri) else { return failed(failure::malformed, $"{whose}: {uri} isn't percent-encoded right.".span); };
|
||||||
|
val at := folder.length == 0 ? string::from(named.span, nothing{}) : $"{folder}/{named.span}";
|
||||||
|
val file := path::parse(at.span) else (_) { return failed(failure::unreadable, $"{whose}: {at.span} isn't a path.".span); };
|
||||||
|
val text := io::read_file(&file) else (_) { return failed(failure::unreadable, $"{whose}: {at.span} couldn't be read.".span); };
|
||||||
|
var made := vector::<u8>::new();
|
||||||
|
made.extend(text.span);
|
||||||
|
return made;
|
||||||
|
}
|
||||||
|
|
||||||
|
# Text of `%XX` escapes decoded, or nothing where an escape isn't two hex
|
||||||
|
# digits.
|
||||||
|
def percent_decoded(text: strview): maybe<string> {
|
||||||
|
var made := string::new(nothing{});
|
||||||
|
var i: u64 = 0;
|
||||||
|
while i < text.length {
|
||||||
|
if text[i] != '%' {
|
||||||
|
made.push(text[i]);
|
||||||
|
i++;
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
return nothing{} if i + 2 >= text.length;
|
||||||
|
val high := hex_value(text[i + 1]) else { return nothing{}; };
|
||||||
|
val low := hex_value(text[i + 2]) else { return nothing{}; };
|
||||||
|
made.push(high << 4 | low);
|
||||||
|
i += 3;
|
||||||
|
}
|
||||||
|
return made;
|
||||||
|
}
|
||||||
|
|
||||||
|
def hex_value(c: u8): maybe<u8> {
|
||||||
|
return c - '0' if c >= '0' && c <= '9';
|
||||||
|
return c - 'a' + 10 if c >= 'a' && c <= 'f';
|
||||||
|
return c - 'A' + 10 if c >= 'A' && c <= 'F';
|
||||||
|
return nothing{};
|
||||||
|
}
|
||||||
|
|
||||||
|
# Base64's bytes, its padding optional, or nothing where it isn't base64.
|
||||||
|
def base64(text: strview): maybe<vector<u8>> {
|
||||||
|
var made := vector::<u8>::new();
|
||||||
|
var held: u32 = 0;
|
||||||
|
var bits: u32 = 0;
|
||||||
|
var ended := false;
|
||||||
|
for i in 0..text.length {
|
||||||
|
val c := text[i];
|
||||||
|
if c == '=' {
|
||||||
|
ended = true;
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
return nothing{} if ended;
|
||||||
|
val value := base64_value(c) else { return nothing{}; };
|
||||||
|
held = ((held << 6) | value as u32) & 0xFFFFFF;
|
||||||
|
bits += 6;
|
||||||
|
if bits >= 8 {
|
||||||
|
bits -= 8;
|
||||||
|
made.append(((held >> bits) & 0xFF) as u8);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return made;
|
||||||
|
}
|
||||||
|
|
||||||
|
def base64_value(c: u8): maybe<u8> {
|
||||||
|
return c - 'A' if c >= 'A' && c <= 'Z';
|
||||||
|
return c - 'a' + 26 if c >= 'a' && c <= 'z';
|
||||||
|
return c - '0' + 52 if c >= '0' && c <= '9';
|
||||||
|
return 62 if c == '+';
|
||||||
|
return 63 if c == '/';
|
||||||
|
return nothing{};
|
||||||
|
}
|
||||||
@@ -0,0 +1,123 @@
|
|||||||
|
#! Contains `asset`, a model read from glTF 2.0, why one couldn't be, and
|
||||||
|
#! reading one, from a file or from bytes.
|
||||||
|
#!
|
||||||
|
#! A `.gltf` file is JSON, naming its buffers and images as files beside it or
|
||||||
|
#! as data in `data:` URIs; a `.glb` file is the same JSON and its first buffer
|
||||||
|
#! in one file, as chunks. Either is read whole: its JSON into the parts of an
|
||||||
|
#! `asset`, each index between them checked, its buffers' and images' bytes read,
|
||||||
|
#! and every accessor checked to lie within its buffer, so what an asset holds
|
||||||
|
#! is read without failing after. What an accessor holds is read as numbers by
|
||||||
|
#! `asset::floats` and `asset::integers`.
|
||||||
|
#!
|
||||||
|
#! Indices into an asset's lists are `u64`s, as glTF's are, and one that's
|
||||||
|
#! optional a `maybe<u64>`. Each part keeps glTF's defaults where its JSON leaves
|
||||||
|
#! them out, and a node its translation, rotation, and scale and its matrix both,
|
||||||
|
#! whichever the JSON gave.
|
||||||
|
|
||||||
|
import std::io;
|
||||||
|
import malunal::linear;
|
||||||
|
module malunal::gltf;
|
||||||
|
|
||||||
|
#! What kind of thing kept an asset from being read.
|
||||||
|
pub enum failure: u8 {
|
||||||
|
unreadable, #! A file couldn't be read: the asset's, or a buffer's or an image's it names.
|
||||||
|
malformed, #! The data breaks glTF: JSON that isn't, a member of the wrong kind or missing, an index past what it names, an accessor past its buffer.
|
||||||
|
unsupported, #! It's well formed, but asks for what isn't read: a version but 2, or an extension it requires that isn't read.
|
||||||
|
}
|
||||||
|
|
||||||
|
#! Why an asset couldn't be read: the kind of thing, and what, as
|
||||||
|
#! `meshes[2].primitives[0]: its material is 9, of the 4 there are`. It holds
|
||||||
|
#! its text itself, its first 240 bytes, so it's plain data, as std's errors
|
||||||
|
#! are.
|
||||||
|
pub struct gltf_error {
|
||||||
|
pub var kind: failure;
|
||||||
|
var text: u8[240];
|
||||||
|
var length: u64;
|
||||||
|
}
|
||||||
|
|
||||||
|
#! What was wrong, and where.
|
||||||
|
pub def gltf_error::describe(&this): string {
|
||||||
|
return string::from(strview::over(&this.text[0] as *u8, this.length), nothing{});
|
||||||
|
}
|
||||||
|
|
||||||
|
# An error of a kind, saying why.
|
||||||
|
def failed(kind: failure, why: strview): gltf_error {
|
||||||
|
var made := gltf_error{ kind = kind };
|
||||||
|
made.length = why.length < 240 ? why.length : 240;
|
||||||
|
for i in 0..made.length {
|
||||||
|
made.text[i] = why[i];
|
||||||
|
}
|
||||||
|
return made;
|
||||||
|
}
|
||||||
|
|
||||||
|
#! The extensions read. An asset requiring another is `unsupported`; one using
|
||||||
|
#! another, without requiring it, is read without what it adds.
|
||||||
|
pub const extensions_read: strview[4] = [
|
||||||
|
"KHR_lights_punctual",
|
||||||
|
"KHR_materials_unlit",
|
||||||
|
"KHR_materials_emissive_strength",
|
||||||
|
"KHR_mesh_quantization",
|
||||||
|
];
|
||||||
|
|
||||||
|
#! A model read from glTF 2.0: its scenes, the tree of nodes they hold, and
|
||||||
|
#! what those draw with, each part in the list glTF keeps it in, by index.
|
||||||
|
pub struct asset {
|
||||||
|
#! The glTF version it says it's of, as `2.0`.
|
||||||
|
pub var version: string;
|
||||||
|
#! What wrote it, where it says.
|
||||||
|
pub var generator: string;
|
||||||
|
#! The scene shown at first, where it says.
|
||||||
|
pub var scene: maybe<u64>;
|
||||||
|
pub var scenes: vector<scene>;
|
||||||
|
pub var nodes: vector<node>;
|
||||||
|
pub var meshes: vector<mesh>;
|
||||||
|
pub var materials: vector<material>;
|
||||||
|
pub var textures: vector<texture>;
|
||||||
|
pub var samplers: vector<sampler>;
|
||||||
|
pub var images: vector<image>;
|
||||||
|
pub var accessors: vector<accessor>;
|
||||||
|
pub var views: vector<buffer_view>;
|
||||||
|
pub var buffers: vector<buffer>;
|
||||||
|
pub var cameras: vector<camera>;
|
||||||
|
pub var skins: vector<skin>;
|
||||||
|
pub var animations: vector<animation>;
|
||||||
|
#! Its lights, of `KHR_lights_punctual`.
|
||||||
|
pub var lights: vector<light>;
|
||||||
|
#! The extensions it uses, those not read among them.
|
||||||
|
pub var extensions: vector<string>;
|
||||||
|
}
|
||||||
|
|
||||||
|
#! Reads an asset from a file: `.gltf` or `.glb`, whichever its first bytes
|
||||||
|
#! say, the files it names read from beside it.
|
||||||
|
#! @param at The file's path.
|
||||||
|
#! @returns The asset, or why it couldn't be read: `unreadable` where the file,
|
||||||
|
#! or one it names, couldn't be.
|
||||||
|
pub def load(at: &path): result<asset, gltf_error> {
|
||||||
|
val bytes := io::read_file(at) else (_) { return failed(failure::unreadable, $"{at.span} couldn't be read.".span); };
|
||||||
|
var folder := path::new();
|
||||||
|
if at.parent() is some(&above) {
|
||||||
|
folder = path::copy_of(&above);
|
||||||
|
}
|
||||||
|
return decode(bytes.span, folder.span);
|
||||||
|
}
|
||||||
|
|
||||||
|
#! Reads an asset from a file named by text, as `load` does.
|
||||||
|
pub def load(at: strview): result<asset, gltf_error> {
|
||||||
|
val named := path::parse(at) else (_) { return failed(failure::unreadable, $"{at} isn't a path.".span); };
|
||||||
|
return load(&named);
|
||||||
|
}
|
||||||
|
|
||||||
|
#! Reads an asset from bytes: a `.glb` file's, whose first four are `glTF`, or
|
||||||
|
#! else a `.gltf` file's JSON.
|
||||||
|
#! @param bytes The bytes.
|
||||||
|
#! @param folder The folder the files it names are found in, or empty where
|
||||||
|
#! it names none but data, as a `.glb` file of one buffer.
|
||||||
|
#! @returns The asset, or why it couldn't be read.
|
||||||
|
pub def decode(bytes: span<u8>, folder: strview = ""): result<asset, gltf_error> {
|
||||||
|
if is_binary(bytes) {
|
||||||
|
val chunks := binary_chunks(bytes) else (e) { return e; };
|
||||||
|
return read_json(chunks.json, chunks.bin, chunks.has_bin, folder);
|
||||||
|
}
|
||||||
|
val text := strview::over(bytes.data, bytes.length);
|
||||||
|
return read_json(text, span::<u8>::over(bytes.data, 0), false, folder);
|
||||||
|
}
|
||||||
@@ -0,0 +1,161 @@
|
|||||||
|
#! Contains reading the members of the JSON's objects, each of the kind glTF
|
||||||
|
#! says, with its default where it's left out or null, and an index checked to
|
||||||
|
#! name one of the parts there are; what's wrong said with where it is, as
|
||||||
|
#! `meshes[2].primitives[0]`.
|
||||||
|
|
||||||
|
import std::json;
|
||||||
|
module malunal::gltf;
|
||||||
|
|
||||||
|
# What's wrong with a value of the JSON, and where it is.
|
||||||
|
def wrong(site: strview, why: strview): gltf_error {
|
||||||
|
return failed(failure::malformed, $"{site}: {why}.".span);
|
||||||
|
}
|
||||||
|
|
||||||
|
# A member of an object, where it has it, and it isn't null.
|
||||||
|
def member_of(v: &json::value, key: strview): maybe<json::value> {
|
||||||
|
if v.get(key) is some(found) {
|
||||||
|
return found if !found.is_null;
|
||||||
|
}
|
||||||
|
return nothing{};
|
||||||
|
}
|
||||||
|
|
||||||
|
# A member that must be an object, where there is one.
|
||||||
|
def object_member(v: &json::value, key: strview, site: strview): result<maybe<json::value>, gltf_error> {
|
||||||
|
var none: maybe<json::value> = nothing{};
|
||||||
|
val found := member_of(v, key) else { return none; };
|
||||||
|
return wrong(site, $"its {key} isn't an object".span) if found.kind != json::kind::object;
|
||||||
|
val held: maybe<json::value> = found;
|
||||||
|
return held;
|
||||||
|
}
|
||||||
|
|
||||||
|
# A member that must be an array, where there is one.
|
||||||
|
def array_member(v: &json::value, key: strview, site: strview): result<maybe<json::value>, gltf_error> {
|
||||||
|
var none: maybe<json::value> = nothing{};
|
||||||
|
val found := member_of(v, key) else { return none; };
|
||||||
|
return wrong(site, $"its {key} isn't an array".span) if found.kind != json::kind::array;
|
||||||
|
val held: maybe<json::value> = found;
|
||||||
|
return held;
|
||||||
|
}
|
||||||
|
|
||||||
|
# How many elements an array member holds, or none where it's missing.
|
||||||
|
def length_of(v: &json::value, key: strview): u64 {
|
||||||
|
if member_of(v, key) is some(found) {
|
||||||
|
return found.length if found.kind == json::kind::array;
|
||||||
|
}
|
||||||
|
return 0;
|
||||||
|
}
|
||||||
|
|
||||||
|
# A number, or its default.
|
||||||
|
def number_member(v: &json::value, key: strview, site: strview, given: f64): result<f64, gltf_error> {
|
||||||
|
val found := member_of(v, key) else { return given; };
|
||||||
|
val n := found.as_f64() else (_) { return wrong(site, $"its {key} isn't a number".span); };
|
||||||
|
return n;
|
||||||
|
}
|
||||||
|
|
||||||
|
# A number as an `f32`, or its default.
|
||||||
|
def float_member(v: &json::value, key: strview, site: strview, given: f32): result<f32, gltf_error> {
|
||||||
|
val n := number_member(v, key, site, given as f64) else (e) { return e; };
|
||||||
|
return n as f32;
|
||||||
|
}
|
||||||
|
|
||||||
|
# A number that may be left out.
|
||||||
|
def maybe_number(v: &json::value, key: strview, site: strview): result<maybe<f32>, gltf_error> {
|
||||||
|
var none: maybe<f32> = nothing{};
|
||||||
|
val found := member_of(v, key) else { return none; };
|
||||||
|
val n := found.as_f64() else (_) { return wrong(site, $"its {key} isn't a number".span); };
|
||||||
|
val held: maybe<f32> = n as f32;
|
||||||
|
return held;
|
||||||
|
}
|
||||||
|
|
||||||
|
# A whole number of 0 or more, or its default.
|
||||||
|
def count_member(v: &json::value, key: strview, site: strview, given: u64): result<u64, gltf_error> {
|
||||||
|
val found := member_of(v, key) else { return given; };
|
||||||
|
val n := found.as_u64() else (_) { return wrong(site, $"its {key} isn't a whole number of 0 or more".span); };
|
||||||
|
return n;
|
||||||
|
}
|
||||||
|
|
||||||
|
# A whole number that must be there.
|
||||||
|
def needed_count(v: &json::value, key: strview, site: strview): result<u64, gltf_error> {
|
||||||
|
return wrong(site, $"it has no {key}".span) if member_of(v, key) is none;
|
||||||
|
return count_member(v, key, site, 0);
|
||||||
|
}
|
||||||
|
|
||||||
|
# An index of one of `count` parts of a list, as `meshes`, where it's there.
|
||||||
|
def index_member(v: &json::value, key: strview, site: strview, count: u64, list: strview): result<maybe<u64>, gltf_error> {
|
||||||
|
var none: maybe<u64> = nothing{};
|
||||||
|
return none if member_of(v, key) is none;
|
||||||
|
val n := count_member(v, key, site, 0) else (e) { return e; };
|
||||||
|
return wrong(site, $"its {key} is {n}, of the {count} {list} there are".span) if n >= count;
|
||||||
|
val held: maybe<u64> = n;
|
||||||
|
return held;
|
||||||
|
}
|
||||||
|
|
||||||
|
# An index that must be there.
|
||||||
|
def needed_index(v: &json::value, key: strview, site: strview, count: u64, list: strview): result<u64, gltf_error> {
|
||||||
|
val found := index_member(v, key, site, count, list) else (e) { return e; };
|
||||||
|
val n := found else { return wrong(site, $"it has no {key}".span); };
|
||||||
|
return n;
|
||||||
|
}
|
||||||
|
|
||||||
|
# Text, or empty.
|
||||||
|
def text_member(v: &json::value, key: strview, site: strview): result<string, gltf_error> {
|
||||||
|
val found := member_of(v, key) else { return string::new(nothing{}); };
|
||||||
|
val text := found.as_text() else (_) { return wrong(site, $"its {key} isn't text".span); };
|
||||||
|
return string::from(text, nothing{});
|
||||||
|
}
|
||||||
|
|
||||||
|
# `true` or `false`, or its default.
|
||||||
|
def bool_member(v: &json::value, key: strview, site: strview, given: bool): result<bool, gltf_error> {
|
||||||
|
val found := member_of(v, key) else { return given; };
|
||||||
|
val truth := found.as_bool() else (_) { return wrong(site, $"its {key} isn't true or false".span); };
|
||||||
|
return truth;
|
||||||
|
}
|
||||||
|
|
||||||
|
# An array of numbers: exactly `wanted` of them where that isn't 0, or none
|
||||||
|
# where it's left out.
|
||||||
|
def floats_member(v: &json::value, key: strview, site: strview, wanted: u64): result<vector<f32>, gltf_error> {
|
||||||
|
var made := vector::<f32>::new();
|
||||||
|
val found := array_member(v, key, site) else (e) { return e; };
|
||||||
|
val list := found else { return made; };
|
||||||
|
return wrong(site, $"its {key} holds {list.length} numbers, not {wanted}".span) if wanted != 0 && list.length != wanted;
|
||||||
|
for i in 0..list.length {
|
||||||
|
val each := list.at(i) else { break; };
|
||||||
|
val n := each.as_f64() else (_) { return wrong(site, $"its {key} holds what isn't a number".span); };
|
||||||
|
made.append(n as f32);
|
||||||
|
}
|
||||||
|
return made;
|
||||||
|
}
|
||||||
|
|
||||||
|
# An array of numbers kept as `f64`, as an accessor's least and most.
|
||||||
|
def reals_member(v: &json::value, key: strview, site: strview): result<vector<f64>, gltf_error> {
|
||||||
|
var made := vector::<f64>::new();
|
||||||
|
val found := array_member(v, key, site) else (e) { return e; };
|
||||||
|
val list := found else { return made; };
|
||||||
|
for i in 0..list.length {
|
||||||
|
val each := list.at(i) else { break; };
|
||||||
|
val n := each.as_f64() else (_) { return wrong(site, $"its {key} holds what isn't a number".span); };
|
||||||
|
made.append(n);
|
||||||
|
}
|
||||||
|
return made;
|
||||||
|
}
|
||||||
|
|
||||||
|
# An array of indices of one of `count` parts of a list.
|
||||||
|
def indices_member(v: &json::value, key: strview, site: strview, count: u64, list: strview): result<vector<u64>, gltf_error> {
|
||||||
|
var made := vector::<u64>::new();
|
||||||
|
val found := array_member(v, key, site) else (e) { return e; };
|
||||||
|
val items := found else { return made; };
|
||||||
|
for i in 0..items.length {
|
||||||
|
val each := items.at(i) else { break; };
|
||||||
|
val n := each.as_u64() else (_) { return wrong(site, $"its {key} holds what isn't an index".span); };
|
||||||
|
return wrong(site, $"its {key} names {n}, of the {count} {list} there are".span) if n >= count;
|
||||||
|
made.append(n);
|
||||||
|
}
|
||||||
|
return made;
|
||||||
|
}
|
||||||
|
|
||||||
|
# An array's elements, each an object, as the parts of a list are.
|
||||||
|
def object_at(list: &json::value, i: u64, site: strview): result<json::value, gltf_error> {
|
||||||
|
val each := list.at(i) else { return wrong(site, "it's missing"); };
|
||||||
|
return wrong(site, "it isn't an object") if each.kind != json::kind::object;
|
||||||
|
return each;
|
||||||
|
}
|
||||||
@@ -0,0 +1,133 @@
|
|||||||
|
#! Contains the tree of nodes: each read with where it is within its parent, as
|
||||||
|
#! a translation, rotation, and scale, or as a matrix, the other worked out of
|
||||||
|
#! it; each child's parent found, and the tree checked to have no node of two
|
||||||
|
#! parents and no loop; and where a node is in the world, through its parents.
|
||||||
|
|
||||||
|
import std::json;
|
||||||
|
import std::math;
|
||||||
|
import malunal::linear;
|
||||||
|
module malunal::gltf;
|
||||||
|
|
||||||
|
def read_nodes(made: &mut asset, root: &json::value, n: &counts): result<void, gltf_error> {
|
||||||
|
val found := array_member(root, "nodes", "nodes") else (e) { return e; };
|
||||||
|
val list := found else { return; };
|
||||||
|
for i in 0..list.length {
|
||||||
|
val site := $"nodes[{i}]";
|
||||||
|
val each := object_at(&list, i, site.span) else (e) { return e; };
|
||||||
|
var read := node{};
|
||||||
|
read.name = text_member(&each, "name", site.span) else (e) { return e; };
|
||||||
|
read.children = indices_member(&each, "children", site.span, n.nodes, "nodes") else (e) { return e; };
|
||||||
|
read.mesh = index_member(&each, "mesh", site.span, n.meshes, "meshes") else (e) { return e; };
|
||||||
|
read.camera = index_member(&each, "camera", site.span, n.cameras, "cameras") else (e) { return e; };
|
||||||
|
read.skin = index_member(&each, "skin", site.span, n.skins, "skins") else (e) { return e; };
|
||||||
|
read.weights = floats_member(&each, "weights", site.span, 0) else (e) { return e; };
|
||||||
|
val extensions := object_member(&each, "extensions", site.span) else (e) { return e; };
|
||||||
|
if extensions is some(x) {
|
||||||
|
if member_of(&x, "KHR_lights_punctual") is some(lit) {
|
||||||
|
read.light = index_member(&lit, "light", site.span, n.lights, "lights") else (e) { return e; };
|
||||||
|
}
|
||||||
|
}
|
||||||
|
place_node(&mut read, &each, site.span) else (e) { return e; };
|
||||||
|
made.nodes.append(move(read));
|
||||||
|
}
|
||||||
|
|
||||||
|
# Each child has one parent, and following parents up ends.
|
||||||
|
for i in 0..made.nodes.length {
|
||||||
|
for k in 0..made.nodes[i].children.length {
|
||||||
|
val child := made.nodes[i].children[k];
|
||||||
|
return failed(failure::malformed, $"nodes[{i}]: it's a child of itself.".span) if child == i;
|
||||||
|
if made.nodes[child].parent is some(other) {
|
||||||
|
return failed(failure::malformed, $"nodes[{child}]: it's a child of both {other} and {i}.".span);
|
||||||
|
}
|
||||||
|
made.nodes[child].parent = i;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
for i in 0..made.nodes.length {
|
||||||
|
var at := i;
|
||||||
|
var steps: u64 = 0;
|
||||||
|
while made.nodes[at].parent is some(up) {
|
||||||
|
at = up;
|
||||||
|
steps++;
|
||||||
|
return failed(failure::malformed, $"nodes[{i}]: following its parents up comes back to it.".span) if steps > made.nodes.length;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
# Where a node is within its parent: its matrix, taken apart into its
|
||||||
|
# translation, rotation, and scale; or those, put together into its matrix.
|
||||||
|
def place_node(read: &mut node, v: &json::value, site: strview): result<void, gltf_error> {
|
||||||
|
val matrix := floats_member(v, "matrix", site, 16) else (e) { return e; };
|
||||||
|
if matrix.length == 16 {
|
||||||
|
for i in 0..16u {
|
||||||
|
read.matrix.m[i] = matrix[i];
|
||||||
|
}
|
||||||
|
take_apart(read);
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
val t := floats_member(v, "translation", site, 3) else (e) { return e; };
|
||||||
|
val r := floats_member(v, "rotation", site, 4) else (e) { return e; };
|
||||||
|
val s := floats_member(v, "scale", site, 3) else (e) { return e; };
|
||||||
|
if t.length == 3 {
|
||||||
|
read.translation = vec3{ t[0], t[1], t[2] };
|
||||||
|
}
|
||||||
|
if r.length == 4 {
|
||||||
|
val q := quat{ r[0], r[1], r[2], r[3] };
|
||||||
|
read.rotation = q.length > 0 ? q.normalized() : quat::identity;
|
||||||
|
}
|
||||||
|
if s.length == 3 {
|
||||||
|
read.scale = vec3{ s[0], s[1], s[2] };
|
||||||
|
}
|
||||||
|
read.matrix = mat4::compose(read.translation, read.rotation, read.scale);
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
# Takes a node's matrix apart: its translation, the lengths of its axes as its
|
||||||
|
# scale, x's negative where the matrix mirrors, and the rotation of its axes
|
||||||
|
# made unit length. glTF holds that a node's matrix is no more than that.
|
||||||
|
def take_apart(read: &mut node): void {
|
||||||
|
val m := &read.matrix.m;
|
||||||
|
read.translation = vec3{ m[12], m[13], m[14] };
|
||||||
|
val x := vec3{ m[0], m[1], m[2] };
|
||||||
|
val y := vec3{ m[4], m[5], m[6] };
|
||||||
|
val z := vec3{ m[8], m[9], m[10] };
|
||||||
|
var sx := x.length;
|
||||||
|
val sy := y.length;
|
||||||
|
val sz := z.length;
|
||||||
|
if x.cross(y).dot(z) < 0 {
|
||||||
|
sx = -sx;
|
||||||
|
}
|
||||||
|
read.scale = vec3{ sx, sy, sz };
|
||||||
|
if sx == 0 || sy == 0 || sz == 0 {
|
||||||
|
read.rotation = quat::identity;
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
read.rotation = quat::of_basis(x / sx, y / sy, z / sz).normalized();
|
||||||
|
}
|
||||||
|
|
||||||
|
#! Where a node is in the world: its matrix, by its parent's, by its parent's,
|
||||||
|
#! up to its root.
|
||||||
|
#! @param this The asset.
|
||||||
|
#! @param which The node.
|
||||||
|
#! @returns The matrix taking its space to its scene's.
|
||||||
|
pub def asset::world_matrix(&this, which: u64): mat4 {
|
||||||
|
var made := this.nodes[which].matrix;
|
||||||
|
var at := which;
|
||||||
|
while this.nodes[at].parent is some(up) {
|
||||||
|
made = this.nodes[up].matrix * made;
|
||||||
|
at = up;
|
||||||
|
}
|
||||||
|
return made;
|
||||||
|
}
|
||||||
|
|
||||||
|
#! The nodes at the roots of the tree: those of no parent, in the order the
|
||||||
|
#! asset holds them, as a scene of every one would hold them.
|
||||||
|
pub def asset::roots(&this): vector<u64> {
|
||||||
|
var made := vector::<u64>::new();
|
||||||
|
for i in 0..this.nodes.length {
|
||||||
|
if this.nodes[i].parent is none {
|
||||||
|
made.append(i);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return made;
|
||||||
|
}
|
||||||
@@ -0,0 +1,630 @@
|
|||||||
|
#! Contains reading an asset's JSON into its parts, in the order they need one
|
||||||
|
#! another: its buffers and their bytes, the views of them, the accessors of
|
||||||
|
#! those, each checked to lie within its view, then images, samplers, textures,
|
||||||
|
#! materials, meshes, cameras, lights, skins, the nodes and their tree, scenes,
|
||||||
|
#! and animations.
|
||||||
|
|
||||||
|
import std::json;
|
||||||
|
import std::math;
|
||||||
|
import malunal::linear;
|
||||||
|
module malunal::gltf;
|
||||||
|
|
||||||
|
# How many of each part the JSON holds, so an index is checked as it's read,
|
||||||
|
# whichever comes first.
|
||||||
|
struct counts {
|
||||||
|
var nodes: u64;
|
||||||
|
var meshes: u64;
|
||||||
|
var materials: u64;
|
||||||
|
var textures: u64;
|
||||||
|
var samplers: u64;
|
||||||
|
var images: u64;
|
||||||
|
var accessors: u64;
|
||||||
|
var views: u64;
|
||||||
|
var buffers: u64;
|
||||||
|
var cameras: u64;
|
||||||
|
var skins: u64;
|
||||||
|
var lights: u64;
|
||||||
|
}
|
||||||
|
|
||||||
|
# Reads an asset of its JSON, the binary chunk of its `.glb` file where it has
|
||||||
|
# one, and the folder its files are found in.
|
||||||
|
def read_json(text: strview, bin: span<u8>, has_bin: bool, folder: strview): result<asset, gltf_error> {
|
||||||
|
val doc := json::parse(text) else (e) {
|
||||||
|
val why := e.describe();
|
||||||
|
return failed(failure::malformed, $"Its JSON isn't JSON: {why.span}".span);
|
||||||
|
};
|
||||||
|
val root := doc.root;
|
||||||
|
return failed(failure::malformed, "Its JSON isn't an object.") if root.kind != json::kind::object;
|
||||||
|
var made := asset{};
|
||||||
|
|
||||||
|
val info := object_member(&root, "asset", "asset") else (e) { return e; };
|
||||||
|
val about := info else { return failed(failure::malformed, "It says no asset, of which version of glTF it is."); };
|
||||||
|
made.version = text_member(&about, "version", "asset") else (e) { return e; };
|
||||||
|
made.generator = text_member(&about, "generator", "asset") else (e) { return e; };
|
||||||
|
return failed(failure::unsupported, $"It's of glTF {made.version.span}, not 2.".span) if !made.version.span.starts_with("2.");
|
||||||
|
|
||||||
|
val used := array_member(&root, "extensionsUsed", "extensionsUsed") else (e) { return e; };
|
||||||
|
if used is some(list) {
|
||||||
|
for i in 0..list.length {
|
||||||
|
if list.at(i) is some(each) && each.as_text() is value(name) {
|
||||||
|
made.extensions.append(string::from(name, nothing{}));
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
val required := array_member(&root, "extensionsRequired", "extensionsRequired") else (e) { return e; };
|
||||||
|
if required is some(list) {
|
||||||
|
for i in 0..list.length {
|
||||||
|
val each := list.at(i) else { break; };
|
||||||
|
val name := each.as_text() else (_) { return failed(failure::malformed, "extensionsRequired: it holds what isn't text."); };
|
||||||
|
return failed(failure::unsupported, $"It requires {name}, which isn't read.".span) if !is_read(name);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
val n := counts{
|
||||||
|
nodes = length_of(&root, "nodes"), meshes = length_of(&root, "meshes"), materials = length_of(&root, "materials"),
|
||||||
|
textures = length_of(&root, "textures"), samplers = length_of(&root, "samplers"), images = length_of(&root, "images"),
|
||||||
|
accessors = length_of(&root, "accessors"), views = length_of(&root, "bufferViews"), buffers = length_of(&root, "buffers"),
|
||||||
|
cameras = length_of(&root, "cameras"), skins = length_of(&root, "skins"), lights = light_count(&root),
|
||||||
|
};
|
||||||
|
read_buffers(&mut made, &root, bin, has_bin, folder) else (e) { return e; };
|
||||||
|
read_views(&mut made, &root, &n) else (e) { return e; };
|
||||||
|
read_accessors(&mut made, &root, &n) else (e) { return e; };
|
||||||
|
read_images(&mut made, &root, &n, folder) else (e) { return e; };
|
||||||
|
read_samplers(&mut made, &root) else (e) { return e; };
|
||||||
|
read_textures(&mut made, &root, &n) else (e) { return e; };
|
||||||
|
read_materials(&mut made, &root, &n) else (e) { return e; };
|
||||||
|
read_meshes(&mut made, &root, &n) else (e) { return e; };
|
||||||
|
read_cameras(&mut made, &root) else (e) { return e; };
|
||||||
|
read_lights(&mut made, &root) else (e) { return e; };
|
||||||
|
read_skins(&mut made, &root, &n) else (e) { return e; };
|
||||||
|
read_nodes(&mut made, &root, &n) else (e) { return e; };
|
||||||
|
read_scenes(&mut made, &root, &n) else (e) { return e; };
|
||||||
|
read_animations(&mut made, &root, &n) else (e) { return e; };
|
||||||
|
made.scene = index_member(&root, "scene", "scene", made.scenes.length, "scenes") else (e) { return e; };
|
||||||
|
return made;
|
||||||
|
}
|
||||||
|
|
||||||
|
# Whether an extension is among those read.
|
||||||
|
def is_read(name: strview): bool {
|
||||||
|
for each in extensions_read {
|
||||||
|
return true if each == name;
|
||||||
|
}
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
|
||||||
|
# The lights `KHR_lights_punctual` gives, where it gives them.
|
||||||
|
def lights_of(root: &json::value): maybe<json::value> {
|
||||||
|
val extensions := member_of(root, "extensions") else { return nothing{}; };
|
||||||
|
val lights := member_of(&extensions, "KHR_lights_punctual") else { return nothing{}; };
|
||||||
|
return member_of(&lights, "lights");
|
||||||
|
}
|
||||||
|
|
||||||
|
def light_count(root: &json::value): u64 {
|
||||||
|
if lights_of(root) is some(list) {
|
||||||
|
return list.length if list.kind == json::kind::array;
|
||||||
|
}
|
||||||
|
return 0;
|
||||||
|
}
|
||||||
|
|
||||||
|
def read_buffers(made: &mut asset, root: &json::value, bin: span<u8>, has_bin: bool, folder: strview): result<void, gltf_error> {
|
||||||
|
val found := array_member(root, "buffers", "buffers") else (e) { return e; };
|
||||||
|
val list := found else { return; };
|
||||||
|
for i in 0..list.length {
|
||||||
|
val site := $"buffers[{i}]";
|
||||||
|
val each := object_at(&list, i, site.span) else (e) { return e; };
|
||||||
|
var read := buffer{};
|
||||||
|
read.name = text_member(&each, "name", site.span) else (e) { return e; };
|
||||||
|
read.uri = text_member(&each, "uri", site.span) else (e) { return e; };
|
||||||
|
read.length = needed_count(&each, "byteLength", site.span) else (e) { return e; };
|
||||||
|
if read.uri.length != 0 {
|
||||||
|
var mime := string::new(nothing{});
|
||||||
|
read.bytes = bytes_of_uri(read.uri.span, folder, site.span, &mut mime) else (e) { return e; };
|
||||||
|
} else if i == 0 && has_bin {
|
||||||
|
read.bytes.extend(bin);
|
||||||
|
} else {
|
||||||
|
return wrong(site.span, "it has no URI, and isn't a .glb file's binary chunk");
|
||||||
|
}
|
||||||
|
return wrong(site.span, $"it says it's {read.length} bytes, but it's {read.bytes.length}".span) if read.bytes.length < read.length;
|
||||||
|
made.buffers.append(move(read));
|
||||||
|
}
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
def read_views(made: &mut asset, root: &json::value, n: &counts): result<void, gltf_error> {
|
||||||
|
val found := array_member(root, "bufferViews", "bufferViews") else (e) { return e; };
|
||||||
|
val list := found else { return; };
|
||||||
|
for i in 0..list.length {
|
||||||
|
val site := $"bufferViews[{i}]";
|
||||||
|
val each := object_at(&list, i, site.span) else (e) { return e; };
|
||||||
|
var read := buffer_view{};
|
||||||
|
read.name = text_member(&each, "name", site.span) else (e) { return e; };
|
||||||
|
read.buffer = needed_index(&each, "buffer", site.span, n.buffers, "buffers") else (e) { return e; };
|
||||||
|
read.offset = count_member(&each, "byteOffset", site.span, 0) else (e) { return e; };
|
||||||
|
read.length = needed_count(&each, "byteLength", site.span) else (e) { return e; };
|
||||||
|
read.stride = count_member(&each, "byteStride", site.span, 0) else (e) { return e; };
|
||||||
|
val held := made.buffers[read.buffer].length;
|
||||||
|
return wrong(site.span, $"it reaches byte {read.offset + read.length} of its buffer's {held}".span) if read.offset > held || read.length > held - read.offset;
|
||||||
|
return wrong(site.span, $"its byteStride is {read.stride}, not a multiple of 4 from 4 to 252".span)
|
||||||
|
if read.stride != 0 && (read.stride < 4 || read.stride > 252 || read.stride % 4 != 0);
|
||||||
|
made.views.append(move(read));
|
||||||
|
}
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
# The type of an accessor's numbers, by glTF's code for it.
|
||||||
|
def component_of(code: u64): maybe<component> {
|
||||||
|
return match code {
|
||||||
|
5120 => component::byte,
|
||||||
|
5121 => component::unsigned_byte,
|
||||||
|
5122 => component::short,
|
||||||
|
5123 => component::unsigned_short,
|
||||||
|
5125 => component::unsigned_int,
|
||||||
|
5126 => component::float,
|
||||||
|
else => nothing{},
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
# What an accessor's elements are, by glTF's name for it.
|
||||||
|
def element_of(name: strview): maybe<element> {
|
||||||
|
return element::scalar if name == "SCALAR";
|
||||||
|
return element::vec2 if name == "VEC2";
|
||||||
|
return element::vec3 if name == "VEC3";
|
||||||
|
return element::vec4 if name == "VEC4";
|
||||||
|
return element::mat2 if name == "MAT2";
|
||||||
|
return element::mat3 if name == "MAT3";
|
||||||
|
return element::mat4 if name == "MAT4";
|
||||||
|
return nothing{};
|
||||||
|
}
|
||||||
|
|
||||||
|
def read_accessors(made: &mut asset, root: &json::value, n: &counts): result<void, gltf_error> {
|
||||||
|
val found := array_member(root, "accessors", "accessors") else (e) { return e; };
|
||||||
|
val list := found else { return; };
|
||||||
|
for i in 0..list.length {
|
||||||
|
val site := $"accessors[{i}]";
|
||||||
|
val each := object_at(&list, i, site.span) else (e) { return e; };
|
||||||
|
var read := accessor{};
|
||||||
|
read.name = text_member(&each, "name", site.span) else (e) { return e; };
|
||||||
|
read.view = index_member(&each, "bufferView", site.span, n.views, "bufferViews") else (e) { return e; };
|
||||||
|
read.offset = count_member(&each, "byteOffset", site.span, 0) else (e) { return e; };
|
||||||
|
val code := needed_count(&each, "componentType", site.span) else (e) { return e; };
|
||||||
|
read.component_type = component_of(code) else { return wrong(site.span, $"its componentType {code} is none of glTF's".span); };
|
||||||
|
read.normalized = bool_member(&each, "normalized", site.span, false) else (e) { return e; };
|
||||||
|
read.count = needed_count(&each, "count", site.span) else (e) { return e; };
|
||||||
|
return wrong(site.span, "its count is 0") if read.count == 0;
|
||||||
|
val kind := text_member(&each, "type", site.span) else (e) { return e; };
|
||||||
|
read.kind = element_of(kind.span) else { return wrong(site.span, $"its type {kind.span} is none of glTF's".span); };
|
||||||
|
read.min = reals_member(&each, "min", site.span) else (e) { return e; };
|
||||||
|
read.max = reals_member(&each, "max", site.span) else (e) { return e; };
|
||||||
|
if read.view is some(v) {
|
||||||
|
val view := &made.views[v];
|
||||||
|
val size := read.element_bytes();
|
||||||
|
return wrong(site.span, $"its bufferView's byteStride, {view.stride}, is less than an element's {size} bytes".span)
|
||||||
|
if view.stride != 0 && view.stride < size;
|
||||||
|
val stride := view.stride != 0 ? view.stride : size;
|
||||||
|
return wrong(site.span, $"its {read.count} elements reach past its bufferView's {view.length} bytes".span)
|
||||||
|
if read.offset > view.length || (read.count - 1) * stride + size > view.length - read.offset;
|
||||||
|
}
|
||||||
|
val holds_sparse := object_member(&each, "sparse", site.span) else (e) { return e; };
|
||||||
|
if holds_sparse is some(s) {
|
||||||
|
read.sparse = read_sparse(made, &s, &read, $"{site.span}.sparse".span, n) else (e) { return e; };
|
||||||
|
}
|
||||||
|
made.accessors.append(move(read));
|
||||||
|
}
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
# An accessor's sparse values: where their indices and values are, each
|
||||||
|
# checked to lie within its view, and each index to name an element.
|
||||||
|
def read_sparse(made: &asset, s: &json::value, read: &accessor, site: strview, n: &counts): result<sparse, gltf_error> {
|
||||||
|
var held := sparse{};
|
||||||
|
held.count = needed_count(s, "count", site) else (e) { return e; };
|
||||||
|
return wrong(site, $"its count is {held.count}, of the accessor's {read.count}".span) if held.count == 0 || held.count > read.count;
|
||||||
|
val indices_found := object_member(s, "indices", site) else (e) { return e; };
|
||||||
|
val indices := indices_found else { return wrong(site, "it has no indices"); };
|
||||||
|
val values_found := object_member(s, "values", site) else (e) { return e; };
|
||||||
|
val values := values_found else { return wrong(site, "it has no values"); };
|
||||||
|
held.indices_view = needed_index(&indices, "bufferView", site, n.views, "bufferViews") else (e) { return e; };
|
||||||
|
held.indices_offset = count_member(&indices, "byteOffset", site, 0) else (e) { return e; };
|
||||||
|
val code := needed_count(&indices, "componentType", site) else (e) { return e; };
|
||||||
|
held.indices_type = component_of(code) else { return wrong(site, $"its indices' componentType {code} is none of glTF's".span); };
|
||||||
|
return wrong(site, "its indices aren't of unsigned integers")
|
||||||
|
if held.indices_type != component::unsigned_byte && held.indices_type != component::unsigned_short && held.indices_type != component::unsigned_int;
|
||||||
|
held.values_view = needed_index(&values, "bufferView", site, n.views, "bufferViews") else (e) { return e; };
|
||||||
|
held.values_offset = count_member(&values, "byteOffset", site, 0) else (e) { return e; };
|
||||||
|
|
||||||
|
val index_view := &made.views[held.indices_view];
|
||||||
|
val value_view := &made.views[held.values_view];
|
||||||
|
val index_bytes := held.count * held.indices_type.bytes;
|
||||||
|
val value_bytes := held.count * read.element_bytes();
|
||||||
|
return wrong(site, "its indices reach past their bufferView") if held.indices_offset > index_view.length || index_bytes > index_view.length - held.indices_offset;
|
||||||
|
return wrong(site, "its values reach past their bufferView") if held.values_offset > value_view.length || value_bytes > value_view.length - held.values_offset;
|
||||||
|
val bytes := made.buffers[index_view.buffer].bytes.span;
|
||||||
|
for i in 0..held.count {
|
||||||
|
val e := integer_at(bytes, index_view.offset + held.indices_offset + i * held.indices_type.bytes, held.indices_type);
|
||||||
|
return wrong(site, $"its index {e} is past the accessor's {read.count} elements".span) if e >= read.count;
|
||||||
|
}
|
||||||
|
return held;
|
||||||
|
}
|
||||||
|
|
||||||
|
def read_images(made: &mut asset, root: &json::value, n: &counts, folder: strview): result<void, gltf_error> {
|
||||||
|
val found := array_member(root, "images", "images") else (e) { return e; };
|
||||||
|
val list := found else { return; };
|
||||||
|
for i in 0..list.length {
|
||||||
|
val site := $"images[{i}]";
|
||||||
|
val each := object_at(&list, i, site.span) else (e) { return e; };
|
||||||
|
var read := image{};
|
||||||
|
read.name = text_member(&each, "name", site.span) else (e) { return e; };
|
||||||
|
read.uri = text_member(&each, "uri", site.span) else (e) { return e; };
|
||||||
|
read.mime_type = text_member(&each, "mimeType", site.span) else (e) { return e; };
|
||||||
|
read.view = index_member(&each, "bufferView", site.span, n.views, "bufferViews") else (e) { return e; };
|
||||||
|
if read.uri.length != 0 {
|
||||||
|
var mime := string::new(nothing{});
|
||||||
|
read.bytes = bytes_of_uri(read.uri.span, folder, site.span, &mut mime) else (e) { return e; };
|
||||||
|
if read.mime_type.length == 0 {
|
||||||
|
read.mime_type = move(mime);
|
||||||
|
}
|
||||||
|
} else if read.view is some(v) {
|
||||||
|
val view := &made.views[v];
|
||||||
|
read.bytes.extend(made.buffers[view.buffer].bytes.span[view.offset:view.length]);
|
||||||
|
} else {
|
||||||
|
return wrong(site.span, "it has neither a URI nor a bufferView");
|
||||||
|
}
|
||||||
|
made.images.append(move(read));
|
||||||
|
}
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
def read_samplers(made: &mut asset, root: &json::value): result<void, gltf_error> {
|
||||||
|
val found := array_member(root, "samplers", "samplers") else (e) { return e; };
|
||||||
|
val list := found else { return; };
|
||||||
|
for i in 0..list.length {
|
||||||
|
val site := $"samplers[{i}]";
|
||||||
|
val each := object_at(&list, i, site.span) else (e) { return e; };
|
||||||
|
var read := sampler{};
|
||||||
|
read.name = text_member(&each, "name", site.span) else (e) { return e; };
|
||||||
|
val mag := count_member(&each, "magFilter", site.span, 0) else (e) { return e; };
|
||||||
|
val min := count_member(&each, "minFilter", site.span, 0) else (e) { return e; };
|
||||||
|
val s := count_member(&each, "wrapS", site.span, 10497) else (e) { return e; };
|
||||||
|
val t := count_member(&each, "wrapT", site.span, 10497) else (e) { return e; };
|
||||||
|
read.mag_filter = mag == 9728 ? filter::nearest : mag == 9729 ? filter::linear : filter::unset;
|
||||||
|
# 9984 to 9987: nearest or linear, between the nearest mip level or two.
|
||||||
|
read.min_filter = min == 9728 || min == 9984 || min == 9986 ? filter::nearest : min == 9729 || min == 9985 || min == 9987 ? filter::linear : filter::unset;
|
||||||
|
read.mip_filter = min == 9984 || min == 9985 ? filter::nearest : min == 9986 || min == 9987 ? filter::linear : filter::unset;
|
||||||
|
read.wrap_s = wrap_of(s) else { return wrong(site.span, $"its wrapS {s} is none of glTF's".span); };
|
||||||
|
read.wrap_t = wrap_of(t) else { return wrong(site.span, $"its wrapT {t} is none of glTF's".span); };
|
||||||
|
made.samplers.append(move(read));
|
||||||
|
}
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
def wrap_of(code: u64): maybe<wrap> {
|
||||||
|
return match code {
|
||||||
|
10497 => wrap::repeat,
|
||||||
|
33071 => wrap::clamp,
|
||||||
|
33648 => wrap::mirror,
|
||||||
|
else => nothing{},
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
def read_textures(made: &mut asset, root: &json::value, n: &counts): result<void, gltf_error> {
|
||||||
|
val found := array_member(root, "textures", "textures") else (e) { return e; };
|
||||||
|
val list := found else { return; };
|
||||||
|
for i in 0..list.length {
|
||||||
|
val site := $"textures[{i}]";
|
||||||
|
val each := object_at(&list, i, site.span) else (e) { return e; };
|
||||||
|
var read := texture{};
|
||||||
|
read.name = text_member(&each, "name", site.span) else (e) { return e; };
|
||||||
|
read.sampler = index_member(&each, "sampler", site.span, n.samplers, "samplers") else (e) { return e; };
|
||||||
|
read.source = index_member(&each, "source", site.span, n.images, "images") else (e) { return e; };
|
||||||
|
made.textures.append(move(read));
|
||||||
|
}
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
# A texture a material names, where it names one, and its scale or strength.
|
||||||
|
def texture_member(v: &json::value, key: strview, site: strview, n: &counts, scale_key: strview): result<maybe<texture_ref>, gltf_error> {
|
||||||
|
var none: maybe<texture_ref> = nothing{};
|
||||||
|
val found := object_member(v, key, site) else (e) { return e; };
|
||||||
|
val info := found else { return none; };
|
||||||
|
val inner := $"{site}.{key}";
|
||||||
|
var made := texture_ref{};
|
||||||
|
made.texture = needed_index(&info, "index", inner.span, n.textures, "textures") else (e) { return e; };
|
||||||
|
made.set = count_member(&info, "texCoord", inner.span, 0) else (e) { return e; };
|
||||||
|
if scale_key.length != 0 {
|
||||||
|
made.scale = float_member(&info, scale_key, inner.span, 1) else (e) { return e; };
|
||||||
|
}
|
||||||
|
val held: maybe<texture_ref> = made;
|
||||||
|
return held;
|
||||||
|
}
|
||||||
|
|
||||||
|
def read_materials(made: &mut asset, root: &json::value, n: &counts): result<void, gltf_error> {
|
||||||
|
val found := array_member(root, "materials", "materials") else (e) { return e; };
|
||||||
|
val list := found else { return; };
|
||||||
|
for i in 0..list.length {
|
||||||
|
val site := $"materials[{i}]";
|
||||||
|
val each := object_at(&list, i, site.span) else (e) { return e; };
|
||||||
|
var read := material{};
|
||||||
|
read.name = text_member(&each, "name", site.span) else (e) { return e; };
|
||||||
|
val pbr_found := object_member(&each, "pbrMetallicRoughness", site.span) else (e) { return e; };
|
||||||
|
if pbr_found is some(pbr) {
|
||||||
|
val inner := $"{site.span}.pbrMetallicRoughness";
|
||||||
|
val color := floats_member(&pbr, "baseColorFactor", inner.span, 4) else (e) { return e; };
|
||||||
|
if color.length == 4 {
|
||||||
|
read.base_color = [color[0], color[1], color[2], color[3]];
|
||||||
|
}
|
||||||
|
read.base_color_texture = texture_member(&pbr, "baseColorTexture", inner.span, n, "") else (e) { return e; };
|
||||||
|
read.metallic = float_member(&pbr, "metallicFactor", inner.span, 1) else (e) { return e; };
|
||||||
|
read.roughness = float_member(&pbr, "roughnessFactor", inner.span, 1) else (e) { return e; };
|
||||||
|
read.metallic_roughness_texture = texture_member(&pbr, "metallicRoughnessTexture", inner.span, n, "") else (e) { return e; };
|
||||||
|
}
|
||||||
|
read.normal_texture = texture_member(&each, "normalTexture", site.span, n, "scale") else (e) { return e; };
|
||||||
|
read.occlusion_texture = texture_member(&each, "occlusionTexture", site.span, n, "strength") else (e) { return e; };
|
||||||
|
read.emissive_texture = texture_member(&each, "emissiveTexture", site.span, n, "") else (e) { return e; };
|
||||||
|
val emissive := floats_member(&each, "emissiveFactor", site.span, 3) else (e) { return e; };
|
||||||
|
if emissive.length == 3 {
|
||||||
|
read.emissive = [emissive[0], emissive[1], emissive[2]];
|
||||||
|
}
|
||||||
|
val mode := text_member(&each, "alphaMode", site.span) else (e) { return e; };
|
||||||
|
if mode.span == "MASK" {
|
||||||
|
read.alpha_mode = alpha_mode::mask;
|
||||||
|
} else if mode.span == "BLEND" {
|
||||||
|
read.alpha_mode = alpha_mode::blend;
|
||||||
|
} else if mode.length != 0 && mode.span != "OPAQUE" {
|
||||||
|
return wrong(site.span, $"its alphaMode {mode.span} is none of glTF's".span);
|
||||||
|
}
|
||||||
|
read.alpha_cutoff = float_member(&each, "alphaCutoff", site.span, 0.5) else (e) { return e; };
|
||||||
|
read.double_sided = bool_member(&each, "doubleSided", site.span, false) else (e) { return e; };
|
||||||
|
val extensions := object_member(&each, "extensions", site.span) else (e) { return e; };
|
||||||
|
if extensions is some(x) {
|
||||||
|
read.unlit = member_of(&x, "KHR_materials_unlit") is some(_);
|
||||||
|
if member_of(&x, "KHR_materials_emissive_strength") is some(strength) {
|
||||||
|
val by := float_member(&strength, "emissiveStrength", site.span, 1) else (e) { return e; };
|
||||||
|
read.emissive = [read.emissive[0] * by, read.emissive[1] * by, read.emissive[2] * by];
|
||||||
|
}
|
||||||
|
}
|
||||||
|
made.materials.append(move(read));
|
||||||
|
}
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
# A primitive's attributes, or a morph target's, each naming an accessor.
|
||||||
|
def attributes_of(v: &json::value, site: strview, n: &counts): result<vector<attribute>, gltf_error> {
|
||||||
|
var made := vector::<attribute>::new();
|
||||||
|
for each in v.members() {
|
||||||
|
val index := each.value.as_u64() else (_) { return wrong(site, $"its {each.key} isn't an accessor's index".span); };
|
||||||
|
return wrong(site, $"its {each.key} is {index}, of the {n.accessors} accessors there are".span) if index >= n.accessors;
|
||||||
|
made.append(attribute{ name = string::from(each.key, nothing{}), accessor = index });
|
||||||
|
}
|
||||||
|
return made;
|
||||||
|
}
|
||||||
|
|
||||||
|
def read_meshes(made: &mut asset, root: &json::value, n: &counts): result<void, gltf_error> {
|
||||||
|
val found := array_member(root, "meshes", "meshes") else (e) { return e; };
|
||||||
|
val list := found else { return; };
|
||||||
|
for i in 0..list.length {
|
||||||
|
val site := $"meshes[{i}]";
|
||||||
|
val each := object_at(&list, i, site.span) else (e) { return e; };
|
||||||
|
var read := mesh{};
|
||||||
|
read.name = text_member(&each, "name", site.span) else (e) { return e; };
|
||||||
|
read.weights = floats_member(&each, "weights", site.span, 0) else (e) { return e; };
|
||||||
|
val parts_found := array_member(&each, "primitives", site.span) else (e) { return e; };
|
||||||
|
val parts := parts_found else { return wrong(site.span, "it has no primitives"); };
|
||||||
|
return wrong(site.span, "it has no primitives") if parts.length == 0;
|
||||||
|
for k in 0..parts.length {
|
||||||
|
val inner := $"{site.span}.primitives[{k}]";
|
||||||
|
val part := object_at(&parts, k, inner.span) else (e) { return e; };
|
||||||
|
var drawn := read_primitive(made, &part, inner.span, n) else (e) { return e; };
|
||||||
|
read.primitives.append(move(drawn));
|
||||||
|
}
|
||||||
|
made.meshes.append(move(read));
|
||||||
|
}
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
# A primitive, its accessors checked: its attributes of one count, and its
|
||||||
|
# indices whole numbers naming vertices it has.
|
||||||
|
def read_primitive(made: &asset, v: &json::value, site: strview, n: &counts): result<primitive, gltf_error> {
|
||||||
|
var read := primitive{};
|
||||||
|
val held := object_member(v, "attributes", site) else (e) { return e; };
|
||||||
|
val attributes := held else { return wrong(site, "it has no attributes"); };
|
||||||
|
read.attributes = attributes_of(&attributes, site, n) else (e) { return e; };
|
||||||
|
read.indices = index_member(v, "indices", site, n.accessors, "accessors") else (e) { return e; };
|
||||||
|
read.material = index_member(v, "material", site, n.materials, "materials") else (e) { return e; };
|
||||||
|
val mode := count_member(v, "mode", site, 4) else (e) { return e; };
|
||||||
|
val modes: topology[7] = [
|
||||||
|
topology::points, topology::lines, topology::line_loop, topology::line_strip,
|
||||||
|
topology::triangles, topology::triangle_strip, topology::triangle_fan,
|
||||||
|
];
|
||||||
|
return wrong(site, $"its mode {mode} is none of glTF's".span) if mode > 6;
|
||||||
|
read.mode = modes[mode];
|
||||||
|
val targets_found := array_member(v, "targets", site) else (e) { return e; };
|
||||||
|
if targets_found is some(targets) {
|
||||||
|
for t in 0..targets.length {
|
||||||
|
val inner := $"{site}.targets[{t}]";
|
||||||
|
val target := object_at(&targets, t, inner.span) else (e) { return e; };
|
||||||
|
var moved := attributes_of(&target, inner.span, n) else (e) { return e; };
|
||||||
|
read.targets.append(move(moved));
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
var vertices: u64 = 0;
|
||||||
|
for i in 0..read.attributes.length {
|
||||||
|
val count := made.accessors[read.attributes[i].accessor].count;
|
||||||
|
return wrong(site, $"its {read.attributes[i].name.span} has {count} elements, of the other attributes' {vertices}".span)
|
||||||
|
if vertices != 0 && count != vertices;
|
||||||
|
vertices = count;
|
||||||
|
}
|
||||||
|
if read.indices is some(at) {
|
||||||
|
val list := &made.accessors[at];
|
||||||
|
return wrong(site, "its indices are of other than unsigned integers, one each")
|
||||||
|
if list.kind != element::scalar || list.normalized
|
||||||
|
|| (list.component_type != component::unsigned_byte && list.component_type != component::unsigned_short && list.component_type != component::unsigned_int);
|
||||||
|
if vertices != 0 {
|
||||||
|
val indices := made.integers(at);
|
||||||
|
for i in 0..indices.length {
|
||||||
|
return wrong(site, $"its index {indices[i]} is past its {vertices} vertices".span) if indices[i] as u64 >= vertices;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return read;
|
||||||
|
}
|
||||||
|
|
||||||
|
def read_cameras(made: &mut asset, root: &json::value): result<void, gltf_error> {
|
||||||
|
val found := array_member(root, "cameras", "cameras") else (e) { return e; };
|
||||||
|
val list := found else { return; };
|
||||||
|
for i in 0..list.length {
|
||||||
|
val site := $"cameras[{i}]";
|
||||||
|
val each := object_at(&list, i, site.span) else (e) { return e; };
|
||||||
|
var read := camera{};
|
||||||
|
read.name = text_member(&each, "name", site.span) else (e) { return e; };
|
||||||
|
val kind := text_member(&each, "type", site.span) else (e) { return e; };
|
||||||
|
if kind.span == "perspective" {
|
||||||
|
val held := object_member(&each, "perspective", site.span) else (e) { return e; };
|
||||||
|
val p := held else { return wrong(site.span, "it's a perspective but says none"); };
|
||||||
|
read.fov_y = float_member(&p, "yfov", site.span, 0) else (e) { return e; };
|
||||||
|
read.aspect = maybe_number(&p, "aspectRatio", site.span) else (e) { return e; };
|
||||||
|
read.near = float_member(&p, "znear", site.span, 0) else (e) { return e; };
|
||||||
|
read.far = maybe_number(&p, "zfar", site.span) else (e) { return e; };
|
||||||
|
} else if kind.span == "orthographic" {
|
||||||
|
read.kind = camera_kind::orthographic;
|
||||||
|
val held := object_member(&each, "orthographic", site.span) else (e) { return e; };
|
||||||
|
val o := held else { return wrong(site.span, "it's orthographic but says nothing of it"); };
|
||||||
|
read.x_mag = float_member(&o, "xmag", site.span, 1) else (e) { return e; };
|
||||||
|
read.y_mag = float_member(&o, "ymag", site.span, 1) else (e) { return e; };
|
||||||
|
read.near = float_member(&o, "znear", site.span, 0) else (e) { return e; };
|
||||||
|
read.far = maybe_number(&o, "zfar", site.span) else (e) { return e; };
|
||||||
|
} else {
|
||||||
|
return wrong(site.span, $"its type {kind.span} is none of glTF's".span);
|
||||||
|
}
|
||||||
|
made.cameras.append(move(read));
|
||||||
|
}
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
def read_lights(made: &mut asset, root: &json::value): result<void, gltf_error> {
|
||||||
|
val list := lights_of(root) else { return; };
|
||||||
|
return failed(failure::malformed, "KHR_lights_punctual: its lights aren't an array.") if list.kind != json::kind::array;
|
||||||
|
for i in 0..list.length {
|
||||||
|
val site := $"KHR_lights_punctual.lights[{i}]";
|
||||||
|
val each := object_at(&list, i, site.span) else (e) { return e; };
|
||||||
|
var read := light{};
|
||||||
|
read.name = text_member(&each, "name", site.span) else (e) { return e; };
|
||||||
|
val kind := text_member(&each, "type", site.span) else (e) { return e; };
|
||||||
|
if kind.span == "directional" {
|
||||||
|
read.kind = light_kind::directional;
|
||||||
|
} else if kind.span == "spot" {
|
||||||
|
read.kind = light_kind::spot;
|
||||||
|
} else if kind.span != "point" {
|
||||||
|
return wrong(site.span, $"its type {kind.span} is none of the extension's".span);
|
||||||
|
}
|
||||||
|
val color := floats_member(&each, "color", site.span, 3) else (e) { return e; };
|
||||||
|
if color.length == 3 {
|
||||||
|
read.color = [color[0], color[1], color[2]];
|
||||||
|
}
|
||||||
|
read.intensity = float_member(&each, "intensity", site.span, 1) else (e) { return e; };
|
||||||
|
read.range = maybe_number(&each, "range", site.span) else (e) { return e; };
|
||||||
|
val cone := object_member(&each, "spot", site.span) else (e) { return e; };
|
||||||
|
if cone is some(s) {
|
||||||
|
read.inner_cone = float_member(&s, "innerConeAngle", site.span, 0) else (e) { return e; };
|
||||||
|
read.outer_cone = float_member(&s, "outerConeAngle", site.span, 0.7853981633974483) else (e) { return e; };
|
||||||
|
}
|
||||||
|
made.lights.append(move(read));
|
||||||
|
}
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
def read_skins(made: &mut asset, root: &json::value, n: &counts): result<void, gltf_error> {
|
||||||
|
val found := array_member(root, "skins", "skins") else (e) { return e; };
|
||||||
|
val list := found else { return; };
|
||||||
|
for i in 0..list.length {
|
||||||
|
val site := $"skins[{i}]";
|
||||||
|
val each := object_at(&list, i, site.span) else (e) { return e; };
|
||||||
|
var read := skin{};
|
||||||
|
read.name = text_member(&each, "name", site.span) else (e) { return e; };
|
||||||
|
read.joints = indices_member(&each, "joints", site.span, n.nodes, "nodes") else (e) { return e; };
|
||||||
|
return wrong(site.span, "it has no joints") if read.joints.length == 0;
|
||||||
|
read.inverse_binds = index_member(&each, "inverseBindMatrices", site.span, n.accessors, "accessors") else (e) { return e; };
|
||||||
|
read.skeleton = index_member(&each, "skeleton", site.span, n.nodes, "nodes") else (e) { return e; };
|
||||||
|
if read.inverse_binds is some(at) {
|
||||||
|
val binds := &made.accessors[at];
|
||||||
|
return wrong(site.span, "its inverseBindMatrices aren't a matrix of floats for each joint")
|
||||||
|
if binds.kind != element::mat4 || binds.component_type != component::float || binds.count < read.joints.length;
|
||||||
|
}
|
||||||
|
made.skins.append(move(read));
|
||||||
|
}
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
def read_scenes(made: &mut asset, root: &json::value, n: &counts): result<void, gltf_error> {
|
||||||
|
val found := array_member(root, "scenes", "scenes") else (e) { return e; };
|
||||||
|
val list := found else { return; };
|
||||||
|
for i in 0..list.length {
|
||||||
|
val site := $"scenes[{i}]";
|
||||||
|
val each := object_at(&list, i, site.span) else (e) { return e; };
|
||||||
|
var read := scene{};
|
||||||
|
read.name = text_member(&each, "name", site.span) else (e) { return e; };
|
||||||
|
read.nodes = indices_member(&each, "nodes", site.span, n.nodes, "nodes") else (e) { return e; };
|
||||||
|
for k in 0..read.nodes.length {
|
||||||
|
return wrong(site.span, $"its node {read.nodes[k]} is another's child, not a root".span) if made.nodes[read.nodes[k]].parent is some(_);
|
||||||
|
}
|
||||||
|
made.scenes.append(move(read));
|
||||||
|
}
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
def read_animations(made: &mut asset, root: &json::value, n: &counts): result<void, gltf_error> {
|
||||||
|
val found := array_member(root, "animations", "animations") else (e) { return e; };
|
||||||
|
val list := found else { return; };
|
||||||
|
for i in 0..list.length {
|
||||||
|
val site := $"animations[{i}]";
|
||||||
|
val each := object_at(&list, i, site.span) else (e) { return e; };
|
||||||
|
var read := animation{};
|
||||||
|
read.name = text_member(&each, "name", site.span) else (e) { return e; };
|
||||||
|
val samplers_found := array_member(&each, "samplers", site.span) else (e) { return e; };
|
||||||
|
val samplers := samplers_found else { return wrong(site.span, "it has no samplers"); };
|
||||||
|
for k in 0..samplers.length {
|
||||||
|
val inner := $"{site.span}.samplers[{k}]";
|
||||||
|
val s := object_at(&samplers, k, inner.span) else (e) { return e; };
|
||||||
|
var keys := animation_sampler{};
|
||||||
|
keys.input = needed_index(&s, "input", inner.span, n.accessors, "accessors") else (e) { return e; };
|
||||||
|
keys.output = needed_index(&s, "output", inner.span, n.accessors, "accessors") else (e) { return e; };
|
||||||
|
val how := text_member(&s, "interpolation", inner.span) else (e) { return e; };
|
||||||
|
if how.span == "STEP" {
|
||||||
|
keys.interpolation = interpolation::step;
|
||||||
|
} else if how.span == "CUBICSPLINE" {
|
||||||
|
keys.interpolation = interpolation::cubic_spline;
|
||||||
|
} else if how.length != 0 && how.span != "LINEAR" {
|
||||||
|
return wrong(inner.span, $"its interpolation {how.span} is none of glTF's".span);
|
||||||
|
}
|
||||||
|
val times := &made.accessors[keys.input];
|
||||||
|
return wrong(inner.span, "its input isn't of floats, one each") if times.kind != element::scalar || times.component_type != component::float;
|
||||||
|
read.samplers.append(keys);
|
||||||
|
}
|
||||||
|
val channels_found := array_member(&each, "channels", site.span) else (e) { return e; };
|
||||||
|
val channels := channels_found else { return wrong(site.span, "it has no channels"); };
|
||||||
|
for k in 0..channels.length {
|
||||||
|
val inner := $"{site.span}.channels[{k}]";
|
||||||
|
val c := object_at(&channels, k, inner.span) else (e) { return e; };
|
||||||
|
var moved := channel{};
|
||||||
|
moved.sampler = needed_index(&c, "sampler", inner.span, read.samplers.length, "samplers") else (e) { return e; };
|
||||||
|
val target_found := object_member(&c, "target", inner.span) else (e) { return e; };
|
||||||
|
val target := target_found else { return wrong(inner.span, "it has no target"); };
|
||||||
|
moved.node = index_member(&target, "node", inner.span, n.nodes, "nodes") else (e) { return e; };
|
||||||
|
val path := text_member(&target, "path", inner.span) else (e) { return e; };
|
||||||
|
if path.span == "translation" {
|
||||||
|
moved.path = target_path::translation;
|
||||||
|
} else if path.span == "rotation" {
|
||||||
|
moved.path = target_path::rotation;
|
||||||
|
} else if path.span == "scale" {
|
||||||
|
moved.path = target_path::scale;
|
||||||
|
} else if path.span == "weights" {
|
||||||
|
moved.path = target_path::weights;
|
||||||
|
} else {
|
||||||
|
return wrong(inner.span, $"its path {path.span} is none of glTF's".span);
|
||||||
|
}
|
||||||
|
read.channels.append(moved);
|
||||||
|
}
|
||||||
|
made.animations.append(move(read));
|
||||||
|
}
|
||||||
|
return;
|
||||||
|
}
|
||||||
@@ -0,0 +1,243 @@
|
|||||||
|
#! Contains the parts of an asset, as glTF lays them out: scenes and their nodes,
|
||||||
|
#! meshes and their primitives, materials, textures, samplers, images, cameras,
|
||||||
|
#! skins, animations, and lights, each with glTF's defaults where its JSON
|
||||||
|
#! leaves a member out.
|
||||||
|
|
||||||
|
import malunal::linear;
|
||||||
|
module malunal::gltf;
|
||||||
|
|
||||||
|
#! A scene: the nodes at its roots.
|
||||||
|
pub struct scene {
|
||||||
|
pub var name: string;
|
||||||
|
pub var nodes: vector<u64>;
|
||||||
|
}
|
||||||
|
|
||||||
|
#! A node of the tree a scene holds: where it is within its parent, and what's
|
||||||
|
#! there, a mesh, a camera, a light, or nothing but its children.
|
||||||
|
pub struct node {
|
||||||
|
pub var name: string;
|
||||||
|
pub var children: vector<u64>;
|
||||||
|
#! The node it's a child of, or none at a root.
|
||||||
|
pub var parent: maybe<u64>;
|
||||||
|
pub var mesh: maybe<u64>;
|
||||||
|
pub var camera: maybe<u64>;
|
||||||
|
#! The skin its mesh is bound to.
|
||||||
|
pub var skin: maybe<u64>;
|
||||||
|
#! Its light, of `KHR_lights_punctual`.
|
||||||
|
pub var light: maybe<u64>;
|
||||||
|
#! Where it is within its parent: its translation, rotation, and scale, and
|
||||||
|
#! the matrix of them, whichever the JSON gave, the other worked out of it.
|
||||||
|
pub var translation := vec3::zero;
|
||||||
|
pub var rotation := quat::identity;
|
||||||
|
pub var scale := vec3::one;
|
||||||
|
pub var matrix := mat4::identity;
|
||||||
|
#! The weights of its mesh's morph targets, where it gives its own.
|
||||||
|
pub var weights: vector<f32>;
|
||||||
|
}
|
||||||
|
|
||||||
|
#! What a primitive's vertices make.
|
||||||
|
pub enum topology: u8 { points, lines, line_loop, line_strip, triangles, triangle_strip, triangle_fan }
|
||||||
|
|
||||||
|
#! An attribute of a primitive's vertices: its name, as `POSITION`, `NORMAL`,
|
||||||
|
#! `TEXCOORD_0`, or `COLOR_0`, and the accessor holding it.
|
||||||
|
pub struct attribute {
|
||||||
|
pub var name: string;
|
||||||
|
pub var accessor: u64;
|
||||||
|
}
|
||||||
|
|
||||||
|
#! A part of a mesh drawn at once: its vertices' attributes, the indices of
|
||||||
|
#! them it draws, or none to draw them in order, and its material.
|
||||||
|
pub struct primitive {
|
||||||
|
pub var attributes: vector<attribute>;
|
||||||
|
pub var indices: maybe<u64>;
|
||||||
|
#! Its material, or none for glTF's default: white, not metallic, rough.
|
||||||
|
pub var material: maybe<u64>;
|
||||||
|
pub var mode := topology::triangles;
|
||||||
|
#! Its morph targets, each the attributes it moves.
|
||||||
|
pub var targets: vector<vector<attribute>>;
|
||||||
|
}
|
||||||
|
|
||||||
|
#! The accessor of an attribute of a primitive, by its name, where it has it.
|
||||||
|
pub def primitive::find(&this, name: strview): maybe<u64> {
|
||||||
|
for i in 0..this.attributes.length {
|
||||||
|
return this.attributes[i].accessor if this.attributes[i].name.span == name;
|
||||||
|
}
|
||||||
|
return nothing{};
|
||||||
|
}
|
||||||
|
|
||||||
|
#! A mesh: its primitives, each drawn with its own material.
|
||||||
|
pub struct mesh {
|
||||||
|
pub var name: string;
|
||||||
|
pub var primitives: vector<primitive>;
|
||||||
|
#! The weights of its morph targets, where it gives them.
|
||||||
|
pub var weights: vector<f32>;
|
||||||
|
}
|
||||||
|
|
||||||
|
#! A texture as a material samples it: which, by which of its primitives'
|
||||||
|
#! `TEXCOORD_n`, and, of a normal map, its scale, or of occlusion, its strength.
|
||||||
|
pub struct texture_ref {
|
||||||
|
pub var texture: u64;
|
||||||
|
pub var set: u64;
|
||||||
|
pub var scale: f32 = 1;
|
||||||
|
}
|
||||||
|
|
||||||
|
#! How a material's alpha is taken.
|
||||||
|
pub enum alpha_mode: u8 {
|
||||||
|
#! Not at all: it's opaque.
|
||||||
|
opaque,
|
||||||
|
#! As a cutout: opaque where alpha is at least its cutoff, and not drawn where
|
||||||
|
#! it's below.
|
||||||
|
mask,
|
||||||
|
#! Blended over what's behind it.
|
||||||
|
blend,
|
||||||
|
}
|
||||||
|
|
||||||
|
#! A material, of glTF's metallic and rough model. Its colors are linear, as
|
||||||
|
#! glTF's factors are, and its textures of color are sRGB, as glTF's images are.
|
||||||
|
pub struct material {
|
||||||
|
pub var name: string;
|
||||||
|
#! The color its base color texture is multiplied by, and alpha.
|
||||||
|
pub var base_color: f32[4] = [1, 1, 1, 1];
|
||||||
|
pub var base_color_texture: maybe<texture_ref>;
|
||||||
|
pub var metallic: f32 = 1;
|
||||||
|
pub var roughness: f32 = 1;
|
||||||
|
#! Its roughness in green and metalness in blue.
|
||||||
|
pub var metallic_roughness_texture: maybe<texture_ref>;
|
||||||
|
#! Its normal map: which way each texel faces, across the surface's tangent
|
||||||
|
#! and the way up its texture, as OpenGL's normal maps hold it.
|
||||||
|
pub var normal_texture: maybe<texture_ref>;
|
||||||
|
#! How much light reaches it, in red.
|
||||||
|
pub var occlusion_texture: maybe<texture_ref>;
|
||||||
|
#! The light it gives, by `KHR_materials_emissive_strength` where it says.
|
||||||
|
pub var emissive: f32[3];
|
||||||
|
pub var emissive_texture: maybe<texture_ref>;
|
||||||
|
pub var alpha_mode := alpha_mode::opaque;
|
||||||
|
pub var alpha_cutoff: f32 = 0.5;
|
||||||
|
#! Whether its faces are seen from behind too.
|
||||||
|
pub var double_sided: bool;
|
||||||
|
#! Whether it's drawn as its colors are, unlit, by `KHR_materials_unlit`.
|
||||||
|
pub var unlit: bool;
|
||||||
|
}
|
||||||
|
|
||||||
|
#! A texture: an image, sampled by a sampler, or by repeating and blending
|
||||||
|
#! where it names none.
|
||||||
|
pub struct texture {
|
||||||
|
pub var name: string;
|
||||||
|
pub var sampler: maybe<u64>;
|
||||||
|
pub var source: maybe<u64>;
|
||||||
|
}
|
||||||
|
|
||||||
|
#! How a sampler picks between texels, where it says.
|
||||||
|
pub enum filter: u8 { unset, nearest, linear }
|
||||||
|
|
||||||
|
#! What a sampler reads past a texture's edge.
|
||||||
|
pub enum wrap: u8 { repeat, clamp, mirror }
|
||||||
|
|
||||||
|
#! How a texture is sampled.
|
||||||
|
pub struct sampler {
|
||||||
|
pub var name: string;
|
||||||
|
pub var mag_filter: filter;
|
||||||
|
pub var min_filter: filter;
|
||||||
|
#! Between mip levels, where the minifying filter uses them; unset where it
|
||||||
|
#! doesn't.
|
||||||
|
pub var mip_filter: filter;
|
||||||
|
pub var wrap_s := wrap::repeat;
|
||||||
|
pub var wrap_t := wrap::repeat;
|
||||||
|
}
|
||||||
|
|
||||||
|
#! An image, encoded as its file is, PNG or JPEG: its bytes, read from its file,
|
||||||
|
#! a `data:` URI, or a buffer view.
|
||||||
|
pub struct image {
|
||||||
|
pub var name: string;
|
||||||
|
#! Its URI, as the JSON writes it, or empty where it's in a buffer view.
|
||||||
|
pub var uri: string;
|
||||||
|
#! Its buffer view, where it's in one.
|
||||||
|
pub var view: maybe<u64>;
|
||||||
|
#! Its type, as `image/png`, where the JSON or its `data:` URI says.
|
||||||
|
pub var mime_type: string;
|
||||||
|
pub var bytes: vector<u8>;
|
||||||
|
}
|
||||||
|
|
||||||
|
#! How a camera projects.
|
||||||
|
pub enum camera_kind: u8 { perspective, orthographic }
|
||||||
|
|
||||||
|
#! A camera, looking down its node's -z.
|
||||||
|
pub struct camera {
|
||||||
|
pub var name: string;
|
||||||
|
pub var kind := camera_kind::perspective;
|
||||||
|
#! Of a perspective: how far it sees up and down, in radians, and its width
|
||||||
|
#! by its height, where it says.
|
||||||
|
pub var fov_y: f32;
|
||||||
|
pub var aspect: maybe<f32>;
|
||||||
|
#! Of an orthographic one: half its width and half its height.
|
||||||
|
pub var x_mag: f32;
|
||||||
|
pub var y_mag: f32;
|
||||||
|
pub var near: f32;
|
||||||
|
#! The furthest it draws, or none, of a perspective, for no end.
|
||||||
|
pub var far: maybe<f32>;
|
||||||
|
}
|
||||||
|
|
||||||
|
#! A skin: the nodes of its skeleton, its joints, and the inverses of where
|
||||||
|
#! each was as the mesh was bound to them.
|
||||||
|
pub struct skin {
|
||||||
|
pub var name: string;
|
||||||
|
pub var joints: vector<u64>;
|
||||||
|
#! An accessor of a matrix for each joint, or none for none but the identity.
|
||||||
|
pub var inverse_binds: maybe<u64>;
|
||||||
|
#! The skeleton's root, where it says.
|
||||||
|
pub var skeleton: maybe<u64>;
|
||||||
|
}
|
||||||
|
|
||||||
|
#! What an animation's channel moves.
|
||||||
|
pub enum target_path: u8 { translation, rotation, scale, weights }
|
||||||
|
|
||||||
|
#! How an animation's values change between its keys.
|
||||||
|
pub enum interpolation: u8 { linear, step, cubic_spline }
|
||||||
|
|
||||||
|
#! A channel of an animation: what it moves of a node, by which of its samplers.
|
||||||
|
pub struct channel {
|
||||||
|
pub var sampler: u64;
|
||||||
|
#! The node, or none where an extension names what it moves.
|
||||||
|
pub var node: maybe<u64>;
|
||||||
|
pub var path: target_path;
|
||||||
|
}
|
||||||
|
|
||||||
|
#! The keys of an animation: the accessor of their times, in seconds, and of
|
||||||
|
#! their values.
|
||||||
|
pub struct animation_sampler {
|
||||||
|
pub var input: u64;
|
||||||
|
pub var output: u64;
|
||||||
|
pub var interpolation := interpolation::linear;
|
||||||
|
}
|
||||||
|
|
||||||
|
#! An animation: channels, each moving a node by a sampler's keys.
|
||||||
|
pub struct animation {
|
||||||
|
pub var name: string;
|
||||||
|
pub var channels: vector<channel>;
|
||||||
|
pub var samplers: vector<animation_sampler>;
|
||||||
|
}
|
||||||
|
|
||||||
|
#! What a light is, of `KHR_lights_punctual`.
|
||||||
|
pub enum light_kind: u8 {
|
||||||
|
#! Shining down its node's -z, everywhere.
|
||||||
|
directional,
|
||||||
|
#! Shining every way from its node.
|
||||||
|
point,
|
||||||
|
#! Shining down its node's -z in a cone.
|
||||||
|
spot,
|
||||||
|
}
|
||||||
|
|
||||||
|
#! A light, of `KHR_lights_punctual`: its color, linear, and its intensity, in
|
||||||
|
#! lux for a directional light and in candela for the others.
|
||||||
|
pub struct light {
|
||||||
|
pub var name: string;
|
||||||
|
pub var kind := light_kind::point;
|
||||||
|
pub var color: f32[3] = [1, 1, 1];
|
||||||
|
pub var intensity: f32 = 1;
|
||||||
|
#! How far it reaches, or none where it reaches as far as its intensity does.
|
||||||
|
pub var range: maybe<f32>;
|
||||||
|
#! Of a spot light: the angles from its middle where it begins to dim, and
|
||||||
|
#! where it's dark, in radians.
|
||||||
|
pub var inner_cone: f32;
|
||||||
|
pub var outer_cone: f32 = 0.7853982;
|
||||||
|
}
|
||||||
@@ -0,0 +1,964 @@
|
|||||||
|
#! Contains writing an asset as glTF 2.0: its parts as JSON, each member glTF
|
||||||
|
#! gives a default left out where it's that default, and its buffers' bytes, as
|
||||||
|
#! a `.glb` file's binary chunk, `data:` URIs, or files beside it; and what an
|
||||||
|
#! asset is built of by hand: bytes of its first buffer, views of them, and
|
||||||
|
#! accessors of numbers, with their least and most, and images.
|
||||||
|
#!
|
||||||
|
#! What's read is written as it was read, so an asset read and written reads
|
||||||
|
#! back the same, but for the extensions it used that aren't read, which it
|
||||||
|
#! no longer holds, and a node's matrix, which glTF holds is no more than its
|
||||||
|
#! translation, rotation, and scale, which are written in its place.
|
||||||
|
|
||||||
|
import std::io;
|
||||||
|
import std::json;
|
||||||
|
import std::math;
|
||||||
|
import malunal::linear;
|
||||||
|
module malunal::gltf;
|
||||||
|
|
||||||
|
#! An asset of nothing yet, of glTF 2.0, saying what wrote it.
|
||||||
|
#! @param generator What wrote it, as its JSON says.
|
||||||
|
pub def asset::new(generator: strview = "malunal gltf"): asset {
|
||||||
|
var made := asset{};
|
||||||
|
made.version = string::from("2.0", nothing{});
|
||||||
|
made.generator = string::from(generator, nothing{});
|
||||||
|
return made;
|
||||||
|
}
|
||||||
|
|
||||||
|
#! Adds bytes to the asset's first buffer, which it's given where it has none,
|
||||||
|
#! and a view of them, begun at a multiple of 4 bytes, as accessors need. A
|
||||||
|
#! `.glb` file writes that buffer as its binary chunk, and a `.gltf` file as a
|
||||||
|
#! `data:` URI.
|
||||||
|
#! @param this The asset.
|
||||||
|
#! @param bytes The bytes.
|
||||||
|
#! @param name The view's name, or none.
|
||||||
|
#! @returns The view, by its place among the asset's.
|
||||||
|
pub def asset::add_view(&mut this, bytes: span<u8>, name: strview = ""): u64 {
|
||||||
|
if this.buffers.length == 0 {
|
||||||
|
this.buffers.append(buffer{});
|
||||||
|
}
|
||||||
|
val held := &mut this.buffers.at(0);
|
||||||
|
while held.bytes.length % 4 != 0 {
|
||||||
|
held.bytes.append(0);
|
||||||
|
}
|
||||||
|
val offset := held.bytes.length;
|
||||||
|
held.bytes.extend(bytes);
|
||||||
|
held.length = held.bytes.length;
|
||||||
|
this.views.append(buffer_view{ name = string::from(name, nothing{}), buffer = 0, offset = offset, length = bytes.length });
|
||||||
|
return this.views.length - 1;
|
||||||
|
}
|
||||||
|
|
||||||
|
#! Adds an accessor of floats, of their own view, with the least and the most
|
||||||
|
#! of each of their numbers, as glTF asks of a position's.
|
||||||
|
#! @param this The asset.
|
||||||
|
#! @param values The numbers, each element's in turn.
|
||||||
|
#! @param kind What each element is, of how many of them.
|
||||||
|
#! @param name The accessor's name, or none.
|
||||||
|
#! @returns The accessor, by its place among the asset's.
|
||||||
|
pub def asset::add_floats(&mut this, values: span<f32>, kind: element, name: strview = ""): u64 {
|
||||||
|
val width := kind.components;
|
||||||
|
var bytes := vector::<u8>::new();
|
||||||
|
for i in 0..values.length {
|
||||||
|
put_word(&mut bytes, math::bits_of(values[i]));
|
||||||
|
}
|
||||||
|
val view := this.add_view(bytes.span);
|
||||||
|
var made := accessor{ name = string::from(name, nothing{}), view = view, kind = kind, count = values.length / width };
|
||||||
|
for k in 0..width {
|
||||||
|
var least := math::infinity::<f64>();
|
||||||
|
var most := -math::infinity::<f64>();
|
||||||
|
var i := k;
|
||||||
|
while i < values.length {
|
||||||
|
least = math::min(least, values[i] as f64);
|
||||||
|
most = math::max(most, values[i] as f64);
|
||||||
|
i += width;
|
||||||
|
}
|
||||||
|
made.min.append(least);
|
||||||
|
made.max.append(most);
|
||||||
|
}
|
||||||
|
this.accessors.append(move(made));
|
||||||
|
return this.accessors.length - 1;
|
||||||
|
}
|
||||||
|
|
||||||
|
#! Adds an accessor of indices, as a primitive draws its vertices by: unsigned
|
||||||
|
#! shorts where each is less than 65535, and unsigned ints otherwise.
|
||||||
|
#! @param this The asset.
|
||||||
|
#! @param values The indices.
|
||||||
|
#! @param name The accessor's name, or none.
|
||||||
|
#! @returns The accessor, by its place among the asset's.
|
||||||
|
pub def asset::add_indices(&mut this, values: span<u32>, name: strview = ""): u64 {
|
||||||
|
var most: u32 = 0;
|
||||||
|
for i in 0..values.length {
|
||||||
|
most = math::max(most, values[i]);
|
||||||
|
}
|
||||||
|
val short := most < 65535;
|
||||||
|
var bytes := vector::<u8>::new();
|
||||||
|
for i in 0..values.length {
|
||||||
|
if short {
|
||||||
|
bytes.append((values[i] & 0xFF) as u8);
|
||||||
|
bytes.append((values[i] >> 8) as u8);
|
||||||
|
} else {
|
||||||
|
put_word(&mut bytes, values[i]);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
val view := this.add_view(bytes.span);
|
||||||
|
this.accessors.append(accessor{
|
||||||
|
name = string::from(name, nothing{}), view = view, count = values.length,
|
||||||
|
component_type = short ? component::unsigned_short : component::unsigned_int,
|
||||||
|
});
|
||||||
|
return this.accessors.length - 1;
|
||||||
|
}
|
||||||
|
|
||||||
|
#! Adds an image, of its file's bytes, as encoded, in a view of the first
|
||||||
|
#! buffer.
|
||||||
|
#! @param this The asset.
|
||||||
|
#! @param bytes The file's bytes: PNG or JPEG.
|
||||||
|
#! @param mime Its type, as `image/png`, or none, for what its first bytes say.
|
||||||
|
#! @param name Its name, or none.
|
||||||
|
#! @returns The image, by its place among the asset's.
|
||||||
|
pub def asset::add_image(&mut this, bytes: span<u8>, mime: strview = "", name: strview = ""): u64 {
|
||||||
|
val view := this.add_view(bytes);
|
||||||
|
var made := image{ name = string::from(name, nothing{}), view = view };
|
||||||
|
made.mime_type = string::from(mime.length != 0 ? mime : mime_of(bytes), nothing{});
|
||||||
|
made.bytes.extend(bytes);
|
||||||
|
this.images.append(move(made));
|
||||||
|
return this.images.length - 1;
|
||||||
|
}
|
||||||
|
|
||||||
|
# The type of an image's bytes, by its first: PNG's or JPEG's, or PNG's where
|
||||||
|
# it's neither.
|
||||||
|
def mime_of(bytes: span<u8>): strview {
|
||||||
|
return "image/jpeg" if bytes.length >= 2 && bytes[0] == 0xFF && bytes[1] == 0xD8;
|
||||||
|
return "image/png";
|
||||||
|
}
|
||||||
|
|
||||||
|
#! Writes an asset as glTF: a `.glb` file, its JSON and its first buffer as its
|
||||||
|
#! binary chunk where that names no file, or a `.gltf` file's JSON. Each other
|
||||||
|
#! buffer, and an image of neither a view nor a file, is a `data:` URI; one
|
||||||
|
#! naming a file names it still, which `save` writes, and this leaves to whoever
|
||||||
|
#! writes it.
|
||||||
|
#! @param made The asset.
|
||||||
|
#! @param binary Whether it's a `.glb` file.
|
||||||
|
#! @returns The file's bytes, or why it couldn't be written: `malformed` where a
|
||||||
|
#! number is infinite or NaN, or a name isn't UTF-8.
|
||||||
|
pub def encode(made: &asset, binary: bool = true): result<vector<u8>, gltf_error> {
|
||||||
|
val chunked := binary && made.buffers.length != 0 && !names_file(made.buffers[0].uri.span);
|
||||||
|
var w := json::writer::new();
|
||||||
|
write_asset(&mut w, made, chunked);
|
||||||
|
val text := w.finish() else (_) {
|
||||||
|
return failed(failure::malformed, "A number of it is infinite or NaN, or a name of it isn't UTF-8.");
|
||||||
|
};
|
||||||
|
var out := vector::<u8>::new();
|
||||||
|
if !binary {
|
||||||
|
out.extend(text);
|
||||||
|
return out;
|
||||||
|
}
|
||||||
|
# The header, then the JSON padded with spaces, then the binary chunk
|
||||||
|
# padded with zeros, each chunk a multiple of 4 bytes.
|
||||||
|
var json_bytes := vector::<u8>::new();
|
||||||
|
json_bytes.extend(text);
|
||||||
|
while json_bytes.length % 4 != 0 {
|
||||||
|
json_bytes.append(' ');
|
||||||
|
}
|
||||||
|
var bin := vector::<u8>::new();
|
||||||
|
if chunked {
|
||||||
|
bin.extend(made.buffers[0].bytes.span);
|
||||||
|
while bin.length % 4 != 0 {
|
||||||
|
bin.append(0);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
var total := 12 + 8 + json_bytes.length;
|
||||||
|
if chunked {
|
||||||
|
total += 8 + bin.length;
|
||||||
|
}
|
||||||
|
put_word(&mut out, glb_magic);
|
||||||
|
put_word(&mut out, 2);
|
||||||
|
put_word(&mut out, total as u32);
|
||||||
|
put_word(&mut out, json_bytes.length as u32);
|
||||||
|
put_word(&mut out, json_chunk);
|
||||||
|
out.extend(json_bytes.span);
|
||||||
|
if chunked {
|
||||||
|
put_word(&mut out, bin.length as u32);
|
||||||
|
put_word(&mut out, bin_chunk);
|
||||||
|
out.extend(bin.span);
|
||||||
|
}
|
||||||
|
return out;
|
||||||
|
}
|
||||||
|
|
||||||
|
#! Writes an asset to a file: `.glb` where its name ends so, and `.gltf`
|
||||||
|
#! otherwise, as `encode` writes it; and the files its buffers and images name,
|
||||||
|
#! beside it, of their bytes, its folder made where it isn't.
|
||||||
|
#! @param made The asset.
|
||||||
|
#! @param at The file's path.
|
||||||
|
#! @returns Nothing, or why it couldn't be written: `unreadable` where a file
|
||||||
|
#! couldn't be written, as a file is read.
|
||||||
|
pub def save(made: &asset, at: &path): result<void, gltf_error> {
|
||||||
|
val binary := at.span.ends_with(".glb") || at.span.ends_with(".GLB");
|
||||||
|
var folder := string::new(nothing{});
|
||||||
|
if at.parent() is some(&above) {
|
||||||
|
folder.append(above.span);
|
||||||
|
_ = io::create_directories(above);
|
||||||
|
}
|
||||||
|
for i in 0..made.buffers.length {
|
||||||
|
val uri := made.buffers[i].uri.span;
|
||||||
|
continue if !names_file(uri);
|
||||||
|
write_beside(folder.span, uri, made.buffers[i].bytes.span) else (e) { return e; };
|
||||||
|
}
|
||||||
|
for i in 0..made.images.length {
|
||||||
|
val uri := made.images[i].uri.span;
|
||||||
|
continue if made.images[i].view is some(_) || !names_file(uri);
|
||||||
|
write_beside(folder.span, uri, made.images[i].bytes.span) else (e) { return e; };
|
||||||
|
}
|
||||||
|
val bytes := encode(made, binary) else (e) { return e; };
|
||||||
|
io::write_file(at, bytes.span) else (_) { return failed(failure::unreadable, $"{at.span} couldn't be written.".span); };
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
#! Writes an asset to a file named by text, as `save` does.
|
||||||
|
pub def save(made: &asset, at: strview): result<void, gltf_error> {
|
||||||
|
val named := path::parse(at) else (_) { return failed(failure::unreadable, $"{at} isn't a path.".span); };
|
||||||
|
return save(made, &named);
|
||||||
|
}
|
||||||
|
|
||||||
|
# Whether a URI names a file, rather than nothing or data.
|
||||||
|
def names_file(uri: strview): bool {
|
||||||
|
return uri.length != 0 && !uri.starts_with("data:");
|
||||||
|
}
|
||||||
|
|
||||||
|
# Writes the bytes of a file a URI names, beside the asset's.
|
||||||
|
def write_beside(folder: strview, uri: strview, bytes: span<u8>): result<void, gltf_error> {
|
||||||
|
val named := percent_decoded(uri) else { return failed(failure::malformed, $"{uri} isn't percent-encoded right.".span); };
|
||||||
|
val at := folder.length == 0 ? string::from(named.span, nothing{}) : $"{folder}/{named.span}";
|
||||||
|
val file := path::parse(at.span) else (_) { return failed(failure::unreadable, $"{at.span} isn't a path.".span); };
|
||||||
|
if file.parent() is some(&above) {
|
||||||
|
_ = io::create_directories(above);
|
||||||
|
}
|
||||||
|
io::write_file(&file, bytes) else (_) { return failed(failure::unreadable, $"{at.span} couldn't be written.".span); };
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
# A little-endian `u32`, added to bytes.
|
||||||
|
def put_word(bytes: &mut vector<u8>, value: u32): void {
|
||||||
|
for i in 0..4u {
|
||||||
|
bytes.append(((value >> (8 * i)) & 0xFF) as u8);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
# Bytes as base64, padded.
|
||||||
|
def base64_text(bytes: span<u8>): string {
|
||||||
|
val digits: strview = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";
|
||||||
|
var made := string::new(nothing{});
|
||||||
|
var i: u64 = 0;
|
||||||
|
while i < bytes.length {
|
||||||
|
val left := bytes.length - i;
|
||||||
|
val a := bytes[i] as u32;
|
||||||
|
val b: u32 = left > 1 ? bytes[i + 1] as u32 : 0;
|
||||||
|
val c: u32 = left > 2 ? bytes[i + 2] as u32 : 0;
|
||||||
|
val all := (a << 16) | (b << 8) | c;
|
||||||
|
made.push(digits[((all >> 18) & 63) as u64]);
|
||||||
|
made.push(digits[((all >> 12) & 63) as u64]);
|
||||||
|
made.push(left > 1 ? digits[((all >> 6) & 63) as u64] : '=');
|
||||||
|
made.push(left > 2 ? digits[(all & 63) as u64] : '=');
|
||||||
|
i += 3;
|
||||||
|
}
|
||||||
|
return made;
|
||||||
|
}
|
||||||
|
|
||||||
|
# A `data:` URI of bytes of a type.
|
||||||
|
def data_uri_of(mime: strview, bytes: span<u8>): string {
|
||||||
|
val digits := base64_text(bytes);
|
||||||
|
return $"data:{mime};base64,{digits.span}";
|
||||||
|
}
|
||||||
|
|
||||||
|
# A float, as the shortest text that reads back as it, or `null` where it's
|
||||||
|
# infinite or NaN, which the writer keeps as its failure.
|
||||||
|
def put_float(w: &mut json::writer, value: f32): void {
|
||||||
|
if !(value - value == 0) {
|
||||||
|
w.real(value as f64);
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
val text := $"{value}";
|
||||||
|
w.raw(text.span);
|
||||||
|
}
|
||||||
|
|
||||||
|
# A least or most of an accessor, as a float's text where it's a float's.
|
||||||
|
def put_real(w: &mut json::writer, value: f64): void {
|
||||||
|
if (value as f32) as f64 == value {
|
||||||
|
put_float(w, value as f32);
|
||||||
|
} else {
|
||||||
|
w.real(value);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
# A member of text, where it's given.
|
||||||
|
def put_text(w: &mut json::writer, key: strview, value: &string): void {
|
||||||
|
return if value.length == 0;
|
||||||
|
w.member(key);
|
||||||
|
w.text(value.span);
|
||||||
|
}
|
||||||
|
|
||||||
|
# A member of a whole number.
|
||||||
|
def put_count(w: &mut json::writer, key: strview, value: u64): void {
|
||||||
|
w.member(key);
|
||||||
|
w.unsigned(value);
|
||||||
|
}
|
||||||
|
|
||||||
|
# A member of an index, where it's given.
|
||||||
|
def put_index(w: &mut json::writer, key: strview, value: maybe<u64>): void {
|
||||||
|
if value is some(at) {
|
||||||
|
put_count(w, key, at);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
# A member of indices, where there are any.
|
||||||
|
def put_indices(w: &mut json::writer, key: strview, values: &vector<u64>): void {
|
||||||
|
return if values.length == 0;
|
||||||
|
w.member(key);
|
||||||
|
w.begin_array();
|
||||||
|
for i in 0..values.length {
|
||||||
|
w.unsigned(values[i]);
|
||||||
|
}
|
||||||
|
w.end_array();
|
||||||
|
}
|
||||||
|
|
||||||
|
# A member of floats.
|
||||||
|
def put_floats(w: &mut json::writer, key: strview, values: span<f32>): void {
|
||||||
|
w.member(key);
|
||||||
|
w.begin_array();
|
||||||
|
for i in 0..values.length {
|
||||||
|
put_float(w, values[i]);
|
||||||
|
}
|
||||||
|
w.end_array();
|
||||||
|
}
|
||||||
|
|
||||||
|
# A member of a float, where it isn't its default.
|
||||||
|
def put_number(w: &mut json::writer, key: strview, value: f32, given: f32): void {
|
||||||
|
return if value == given;
|
||||||
|
w.member(key);
|
||||||
|
put_float(w, value);
|
||||||
|
}
|
||||||
|
|
||||||
|
# Writes an asset's JSON, its first buffer the binary chunk where `chunked`.
|
||||||
|
def write_asset(w: &mut json::writer, made: &asset, chunked: bool): void {
|
||||||
|
w.begin_object();
|
||||||
|
w.member("asset");
|
||||||
|
w.begin_object();
|
||||||
|
w.member("version");
|
||||||
|
w.text(made.version.length != 0 ? made.version.span : "2.0");
|
||||||
|
put_text(w, "generator", &made.generator);
|
||||||
|
w.end_object();
|
||||||
|
|
||||||
|
# The extensions it uses, of those written.
|
||||||
|
var used := vector::<strview>::new();
|
||||||
|
var required := vector::<strview>::new();
|
||||||
|
if made.lights.length != 0 {
|
||||||
|
used.append("KHR_lights_punctual");
|
||||||
|
}
|
||||||
|
var unlit := false;
|
||||||
|
var strong := false;
|
||||||
|
for i in 0..made.materials.length {
|
||||||
|
unlit = unlit || made.materials[i].unlit;
|
||||||
|
strong = strong || brightest(&made.materials[i]) > 1;
|
||||||
|
}
|
||||||
|
if unlit {
|
||||||
|
used.append("KHR_materials_unlit");
|
||||||
|
}
|
||||||
|
if strong {
|
||||||
|
used.append("KHR_materials_emissive_strength");
|
||||||
|
}
|
||||||
|
for i in 0..made.extensions.length {
|
||||||
|
if made.extensions[i].span == "KHR_mesh_quantization" {
|
||||||
|
used.append("KHR_mesh_quantization");
|
||||||
|
required.append("KHR_mesh_quantization");
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if used.length != 0 {
|
||||||
|
w.member("extensionsUsed");
|
||||||
|
w.begin_array();
|
||||||
|
for i in 0..used.length {
|
||||||
|
w.text(used[i]);
|
||||||
|
}
|
||||||
|
w.end_array();
|
||||||
|
}
|
||||||
|
if required.length != 0 {
|
||||||
|
w.member("extensionsRequired");
|
||||||
|
w.begin_array();
|
||||||
|
for i in 0..required.length {
|
||||||
|
w.text(required[i]);
|
||||||
|
}
|
||||||
|
w.end_array();
|
||||||
|
}
|
||||||
|
|
||||||
|
put_index(w, "scene", made.scene);
|
||||||
|
write_scenes(w, made);
|
||||||
|
write_nodes(w, made);
|
||||||
|
write_meshes(w, made);
|
||||||
|
write_materials(w, made);
|
||||||
|
write_textures(w, made);
|
||||||
|
write_images(w, made);
|
||||||
|
write_accessors(w, made);
|
||||||
|
write_views(w, made);
|
||||||
|
write_buffers(w, made, chunked);
|
||||||
|
write_cameras(w, made);
|
||||||
|
write_skins(w, made);
|
||||||
|
write_animations(w, made);
|
||||||
|
if made.lights.length != 0 {
|
||||||
|
w.member("extensions");
|
||||||
|
w.begin_object();
|
||||||
|
w.member("KHR_lights_punctual");
|
||||||
|
w.begin_object();
|
||||||
|
write_lights(w, made);
|
||||||
|
w.end_object();
|
||||||
|
w.end_object();
|
||||||
|
}
|
||||||
|
w.end_object();
|
||||||
|
}
|
||||||
|
|
||||||
|
# The most of a material's emission, which more than 1 of is its strength.
|
||||||
|
def brightest(m: &material): f32 {
|
||||||
|
return math::max(m.emissive[0], math::max(m.emissive[1], m.emissive[2]));
|
||||||
|
}
|
||||||
|
|
||||||
|
def write_scenes(w: &mut json::writer, made: &asset): void {
|
||||||
|
return if made.scenes.length == 0;
|
||||||
|
w.member("scenes");
|
||||||
|
w.begin_array();
|
||||||
|
for i in 0..made.scenes.length {
|
||||||
|
val each := &made.scenes[i];
|
||||||
|
w.begin_object();
|
||||||
|
put_text(w, "name", &each.name);
|
||||||
|
put_indices(w, "nodes", &each.nodes);
|
||||||
|
w.end_object();
|
||||||
|
}
|
||||||
|
w.end_array();
|
||||||
|
}
|
||||||
|
|
||||||
|
def write_nodes(w: &mut json::writer, made: &asset): void {
|
||||||
|
return if made.nodes.length == 0;
|
||||||
|
w.member("nodes");
|
||||||
|
w.begin_array();
|
||||||
|
for i in 0..made.nodes.length {
|
||||||
|
val each := &made.nodes[i];
|
||||||
|
w.begin_object();
|
||||||
|
put_text(w, "name", &each.name);
|
||||||
|
put_indices(w, "children", &each.children);
|
||||||
|
put_index(w, "mesh", each.mesh);
|
||||||
|
put_index(w, "camera", each.camera);
|
||||||
|
put_index(w, "skin", each.skin);
|
||||||
|
if each.weights.length != 0 {
|
||||||
|
put_floats(w, "weights", each.weights.span);
|
||||||
|
}
|
||||||
|
val t := each.translation;
|
||||||
|
if t.x != 0 || t.y != 0 || t.z != 0 {
|
||||||
|
val numbers: f32[3] = [t.x, t.y, t.z];
|
||||||
|
put_floats(w, "translation", numbers[:]);
|
||||||
|
}
|
||||||
|
val r := each.rotation;
|
||||||
|
if r.x != 0 || r.y != 0 || r.z != 0 || r.w != 1 {
|
||||||
|
val numbers: f32[4] = [r.x, r.y, r.z, r.w];
|
||||||
|
put_floats(w, "rotation", numbers[:]);
|
||||||
|
}
|
||||||
|
val s := each.scale;
|
||||||
|
if s.x != 1 || s.y != 1 || s.z != 1 {
|
||||||
|
val numbers: f32[3] = [s.x, s.y, s.z];
|
||||||
|
put_floats(w, "scale", numbers[:]);
|
||||||
|
}
|
||||||
|
if each.light is some(lit) {
|
||||||
|
w.member("extensions");
|
||||||
|
w.begin_object();
|
||||||
|
w.member("KHR_lights_punctual");
|
||||||
|
w.begin_object();
|
||||||
|
put_count(w, "light", lit);
|
||||||
|
w.end_object();
|
||||||
|
w.end_object();
|
||||||
|
}
|
||||||
|
w.end_object();
|
||||||
|
}
|
||||||
|
w.end_array();
|
||||||
|
}
|
||||||
|
|
||||||
|
# A primitive's attributes, or a morph target's, as an object of each's name.
|
||||||
|
def write_attributes(w: &mut json::writer, list: &vector<attribute>): void {
|
||||||
|
w.begin_object();
|
||||||
|
for i in 0..list.length {
|
||||||
|
put_count(w, list[i].name.span, list[i].accessor);
|
||||||
|
}
|
||||||
|
w.end_object();
|
||||||
|
}
|
||||||
|
|
||||||
|
def write_meshes(w: &mut json::writer, made: &asset): void {
|
||||||
|
return if made.meshes.length == 0;
|
||||||
|
w.member("meshes");
|
||||||
|
w.begin_array();
|
||||||
|
for i in 0..made.meshes.length {
|
||||||
|
val each := &made.meshes[i];
|
||||||
|
w.begin_object();
|
||||||
|
put_text(w, "name", &each.name);
|
||||||
|
w.member("primitives");
|
||||||
|
w.begin_array();
|
||||||
|
for k in 0..each.primitives.length {
|
||||||
|
val part := &each.primitives[k];
|
||||||
|
w.begin_object();
|
||||||
|
w.member("attributes");
|
||||||
|
write_attributes(w, &part.attributes);
|
||||||
|
put_index(w, "indices", part.indices);
|
||||||
|
put_index(w, "material", part.material);
|
||||||
|
if part.mode != topology::triangles {
|
||||||
|
put_count(w, "mode", part.mode as u64);
|
||||||
|
}
|
||||||
|
if part.targets.length != 0 {
|
||||||
|
w.member("targets");
|
||||||
|
w.begin_array();
|
||||||
|
for t in 0..part.targets.length {
|
||||||
|
write_attributes(w, &part.targets[t]);
|
||||||
|
}
|
||||||
|
w.end_array();
|
||||||
|
}
|
||||||
|
w.end_object();
|
||||||
|
}
|
||||||
|
w.end_array();
|
||||||
|
if each.weights.length != 0 {
|
||||||
|
put_floats(w, "weights", each.weights.span);
|
||||||
|
}
|
||||||
|
w.end_object();
|
||||||
|
}
|
||||||
|
w.end_array();
|
||||||
|
}
|
||||||
|
|
||||||
|
# A texture a material names, with its scale or strength where it has one.
|
||||||
|
def write_texture_ref(w: &mut json::writer, key: strview, held: maybe<texture_ref>, scale_key: strview): void {
|
||||||
|
val used := held else { return; };
|
||||||
|
w.member(key);
|
||||||
|
w.begin_object();
|
||||||
|
put_count(w, "index", used.texture);
|
||||||
|
if used.set != 0 {
|
||||||
|
put_count(w, "texCoord", used.set);
|
||||||
|
}
|
||||||
|
if scale_key.length != 0 {
|
||||||
|
put_number(w, scale_key, used.scale, 1);
|
||||||
|
}
|
||||||
|
w.end_object();
|
||||||
|
}
|
||||||
|
|
||||||
|
def write_materials(w: &mut json::writer, made: &asset): void {
|
||||||
|
return if made.materials.length == 0;
|
||||||
|
w.member("materials");
|
||||||
|
w.begin_array();
|
||||||
|
for i in 0..made.materials.length {
|
||||||
|
val each := &made.materials[i];
|
||||||
|
w.begin_object();
|
||||||
|
put_text(w, "name", &each.name);
|
||||||
|
w.member("pbrMetallicRoughness");
|
||||||
|
w.begin_object();
|
||||||
|
val c := each.base_color;
|
||||||
|
if c[0] != 1 || c[1] != 1 || c[2] != 1 || c[3] != 1 {
|
||||||
|
put_floats(w, "baseColorFactor", c[:]);
|
||||||
|
}
|
||||||
|
write_texture_ref(w, "baseColorTexture", each.base_color_texture, "");
|
||||||
|
put_number(w, "metallicFactor", each.metallic, 1);
|
||||||
|
put_number(w, "roughnessFactor", each.roughness, 1);
|
||||||
|
write_texture_ref(w, "metallicRoughnessTexture", each.metallic_roughness_texture, "");
|
||||||
|
w.end_object();
|
||||||
|
write_texture_ref(w, "normalTexture", each.normal_texture, "scale");
|
||||||
|
write_texture_ref(w, "occlusionTexture", each.occlusion_texture, "strength");
|
||||||
|
write_texture_ref(w, "emissiveTexture", each.emissive_texture, "");
|
||||||
|
# Emission past 1 is written as its strength, by the extension.
|
||||||
|
val strength := brightest(each);
|
||||||
|
val by: f32 = strength > 1 ? strength : 1;
|
||||||
|
if each.emissive[0] != 0 || each.emissive[1] != 0 || each.emissive[2] != 0 {
|
||||||
|
val numbers: f32[3] = [each.emissive[0] / by, each.emissive[1] / by, each.emissive[2] / by];
|
||||||
|
put_floats(w, "emissiveFactor", numbers[:]);
|
||||||
|
}
|
||||||
|
if each.alpha_mode == alpha_mode::mask {
|
||||||
|
w.member("alphaMode");
|
||||||
|
w.text("MASK");
|
||||||
|
put_number(w, "alphaCutoff", each.alpha_cutoff, 0.5);
|
||||||
|
} else if each.alpha_mode == alpha_mode::blend {
|
||||||
|
w.member("alphaMode");
|
||||||
|
w.text("BLEND");
|
||||||
|
}
|
||||||
|
if each.double_sided {
|
||||||
|
w.member("doubleSided");
|
||||||
|
w.boolean(true);
|
||||||
|
}
|
||||||
|
if each.unlit || strength > 1 {
|
||||||
|
w.member("extensions");
|
||||||
|
w.begin_object();
|
||||||
|
if each.unlit {
|
||||||
|
w.member("KHR_materials_unlit");
|
||||||
|
w.begin_object();
|
||||||
|
w.end_object();
|
||||||
|
}
|
||||||
|
if strength > 1 {
|
||||||
|
w.member("KHR_materials_emissive_strength");
|
||||||
|
w.begin_object();
|
||||||
|
w.member("emissiveStrength");
|
||||||
|
put_float(w, strength);
|
||||||
|
w.end_object();
|
||||||
|
}
|
||||||
|
w.end_object();
|
||||||
|
}
|
||||||
|
w.end_object();
|
||||||
|
}
|
||||||
|
w.end_array();
|
||||||
|
}
|
||||||
|
|
||||||
|
# glTF's code of a filter, or 0 for one unset.
|
||||||
|
def filter_code(f: filter): u64 {
|
||||||
|
return match f {
|
||||||
|
unset => 0,
|
||||||
|
nearest => 9728,
|
||||||
|
linear => 9729,
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
# glTF's code of a minifying filter, between mip levels as it says.
|
||||||
|
def min_filter_code(min: filter, mip: filter): u64 {
|
||||||
|
return filter_code(min) if mip == filter::unset;
|
||||||
|
return 0 if min == filter::unset;
|
||||||
|
val linear := min == filter::linear;
|
||||||
|
if mip == filter::nearest {
|
||||||
|
return linear ? 9985 : 9984;
|
||||||
|
}
|
||||||
|
return linear ? 9987 : 9986;
|
||||||
|
}
|
||||||
|
|
||||||
|
def wrap_code(how: wrap): u64 {
|
||||||
|
return match how {
|
||||||
|
repeat => 10497,
|
||||||
|
clamp => 33071,
|
||||||
|
mirror => 33648,
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
def write_textures(w: &mut json::writer, made: &asset): void {
|
||||||
|
if made.textures.length != 0 {
|
||||||
|
w.member("textures");
|
||||||
|
w.begin_array();
|
||||||
|
for i in 0..made.textures.length {
|
||||||
|
val each := &made.textures[i];
|
||||||
|
w.begin_object();
|
||||||
|
put_text(w, "name", &each.name);
|
||||||
|
put_index(w, "sampler", each.sampler);
|
||||||
|
put_index(w, "source", each.source);
|
||||||
|
w.end_object();
|
||||||
|
}
|
||||||
|
w.end_array();
|
||||||
|
}
|
||||||
|
return if made.samplers.length == 0;
|
||||||
|
w.member("samplers");
|
||||||
|
w.begin_array();
|
||||||
|
for i in 0..made.samplers.length {
|
||||||
|
val each := &made.samplers[i];
|
||||||
|
w.begin_object();
|
||||||
|
put_text(w, "name", &each.name);
|
||||||
|
val mag := filter_code(each.mag_filter);
|
||||||
|
if mag != 0 {
|
||||||
|
put_count(w, "magFilter", mag);
|
||||||
|
}
|
||||||
|
val min := min_filter_code(each.min_filter, each.mip_filter);
|
||||||
|
if min != 0 {
|
||||||
|
put_count(w, "minFilter", min);
|
||||||
|
}
|
||||||
|
if each.wrap_s != wrap::repeat {
|
||||||
|
put_count(w, "wrapS", wrap_code(each.wrap_s));
|
||||||
|
}
|
||||||
|
if each.wrap_t != wrap::repeat {
|
||||||
|
put_count(w, "wrapT", wrap_code(each.wrap_t));
|
||||||
|
}
|
||||||
|
w.end_object();
|
||||||
|
}
|
||||||
|
w.end_array();
|
||||||
|
}
|
||||||
|
|
||||||
|
def write_images(w: &mut json::writer, made: &asset): void {
|
||||||
|
return if made.images.length == 0;
|
||||||
|
w.member("images");
|
||||||
|
w.begin_array();
|
||||||
|
for i in 0..made.images.length {
|
||||||
|
val each := &made.images[i];
|
||||||
|
w.begin_object();
|
||||||
|
put_text(w, "name", &each.name);
|
||||||
|
if each.view is some(v) {
|
||||||
|
put_count(w, "bufferView", v);
|
||||||
|
w.member("mimeType");
|
||||||
|
w.text(each.mime_type.length != 0 ? each.mime_type.span : mime_of(each.bytes.span));
|
||||||
|
} else if names_file(each.uri.span) {
|
||||||
|
w.member("uri");
|
||||||
|
w.text(each.uri.span);
|
||||||
|
put_text(w, "mimeType", &each.mime_type);
|
||||||
|
} else {
|
||||||
|
val mime := each.mime_type.length != 0 ? each.mime_type.span : mime_of(each.bytes.span);
|
||||||
|
val uri := data_uri_of(mime, each.bytes.span);
|
||||||
|
w.member("uri");
|
||||||
|
w.text(uri.span);
|
||||||
|
}
|
||||||
|
w.end_object();
|
||||||
|
}
|
||||||
|
w.end_array();
|
||||||
|
}
|
||||||
|
|
||||||
|
# glTF's code of the type of an accessor's numbers.
|
||||||
|
def component_code(c: component): u64 {
|
||||||
|
return match c {
|
||||||
|
byte => 5120,
|
||||||
|
unsigned_byte => 5121,
|
||||||
|
short => 5122,
|
||||||
|
unsigned_short => 5123,
|
||||||
|
unsigned_int => 5125,
|
||||||
|
float => 5126,
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
# glTF's name of what an accessor's elements are.
|
||||||
|
def element_name(e: element): strview {
|
||||||
|
return match e {
|
||||||
|
scalar => "SCALAR",
|
||||||
|
vec2 => "VEC2",
|
||||||
|
vec3 => "VEC3",
|
||||||
|
vec4 => "VEC4",
|
||||||
|
mat2 => "MAT2",
|
||||||
|
mat3 => "MAT3",
|
||||||
|
mat4 => "MAT4",
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
# A member of an accessor's least or most, where it has them.
|
||||||
|
def put_bounds(w: &mut json::writer, key: strview, values: &vector<f64>): void {
|
||||||
|
return if values.length == 0;
|
||||||
|
w.member(key);
|
||||||
|
w.begin_array();
|
||||||
|
for i in 0..values.length {
|
||||||
|
put_real(w, values[i]);
|
||||||
|
}
|
||||||
|
w.end_array();
|
||||||
|
}
|
||||||
|
|
||||||
|
def write_accessors(w: &mut json::writer, made: &asset): void {
|
||||||
|
return if made.accessors.length == 0;
|
||||||
|
w.member("accessors");
|
||||||
|
w.begin_array();
|
||||||
|
for i in 0..made.accessors.length {
|
||||||
|
val each := &made.accessors[i];
|
||||||
|
w.begin_object();
|
||||||
|
put_text(w, "name", &each.name);
|
||||||
|
put_index(w, "bufferView", each.view);
|
||||||
|
if each.offset != 0 {
|
||||||
|
put_count(w, "byteOffset", each.offset);
|
||||||
|
}
|
||||||
|
put_count(w, "componentType", component_code(each.component_type));
|
||||||
|
if each.normalized {
|
||||||
|
w.member("normalized");
|
||||||
|
w.boolean(true);
|
||||||
|
}
|
||||||
|
put_count(w, "count", each.count);
|
||||||
|
w.member("type");
|
||||||
|
w.text(element_name(each.kind));
|
||||||
|
put_bounds(w, "min", &each.min);
|
||||||
|
put_bounds(w, "max", &each.max);
|
||||||
|
if each.sparse is some(s) {
|
||||||
|
w.member("sparse");
|
||||||
|
w.begin_object();
|
||||||
|
put_count(w, "count", s.count);
|
||||||
|
w.member("indices");
|
||||||
|
w.begin_object();
|
||||||
|
put_count(w, "bufferView", s.indices_view);
|
||||||
|
if s.indices_offset != 0 {
|
||||||
|
put_count(w, "byteOffset", s.indices_offset);
|
||||||
|
}
|
||||||
|
put_count(w, "componentType", component_code(s.indices_type));
|
||||||
|
w.end_object();
|
||||||
|
w.member("values");
|
||||||
|
w.begin_object();
|
||||||
|
put_count(w, "bufferView", s.values_view);
|
||||||
|
if s.values_offset != 0 {
|
||||||
|
put_count(w, "byteOffset", s.values_offset);
|
||||||
|
}
|
||||||
|
w.end_object();
|
||||||
|
w.end_object();
|
||||||
|
}
|
||||||
|
w.end_object();
|
||||||
|
}
|
||||||
|
w.end_array();
|
||||||
|
}
|
||||||
|
|
||||||
|
def write_views(w: &mut json::writer, made: &asset): void {
|
||||||
|
return if made.views.length == 0;
|
||||||
|
w.member("bufferViews");
|
||||||
|
w.begin_array();
|
||||||
|
for i in 0..made.views.length {
|
||||||
|
val each := &made.views[i];
|
||||||
|
w.begin_object();
|
||||||
|
put_text(w, "name", &each.name);
|
||||||
|
put_count(w, "buffer", each.buffer);
|
||||||
|
if each.offset != 0 {
|
||||||
|
put_count(w, "byteOffset", each.offset);
|
||||||
|
}
|
||||||
|
put_count(w, "byteLength", each.length);
|
||||||
|
if each.stride != 0 {
|
||||||
|
put_count(w, "byteStride", each.stride);
|
||||||
|
}
|
||||||
|
w.end_object();
|
||||||
|
}
|
||||||
|
w.end_array();
|
||||||
|
}
|
||||||
|
|
||||||
|
def write_buffers(w: &mut json::writer, made: &asset, chunked: bool): void {
|
||||||
|
return if made.buffers.length == 0;
|
||||||
|
w.member("buffers");
|
||||||
|
w.begin_array();
|
||||||
|
for i in 0..made.buffers.length {
|
||||||
|
val each := &made.buffers[i];
|
||||||
|
w.begin_object();
|
||||||
|
put_text(w, "name", &each.name);
|
||||||
|
put_count(w, "byteLength", each.bytes.length);
|
||||||
|
if names_file(each.uri.span) {
|
||||||
|
w.member("uri");
|
||||||
|
w.text(each.uri.span);
|
||||||
|
} else if !(chunked && i == 0) {
|
||||||
|
val uri := data_uri_of("application/octet-stream", each.bytes.span);
|
||||||
|
w.member("uri");
|
||||||
|
w.text(uri.span);
|
||||||
|
}
|
||||||
|
w.end_object();
|
||||||
|
}
|
||||||
|
w.end_array();
|
||||||
|
}
|
||||||
|
|
||||||
|
def write_cameras(w: &mut json::writer, made: &asset): void {
|
||||||
|
return if made.cameras.length == 0;
|
||||||
|
w.member("cameras");
|
||||||
|
w.begin_array();
|
||||||
|
for i in 0..made.cameras.length {
|
||||||
|
val each := &made.cameras[i];
|
||||||
|
w.begin_object();
|
||||||
|
put_text(w, "name", &each.name);
|
||||||
|
if each.kind == camera_kind::perspective {
|
||||||
|
w.member("type");
|
||||||
|
w.text("perspective");
|
||||||
|
w.member("perspective");
|
||||||
|
w.begin_object();
|
||||||
|
w.member("yfov");
|
||||||
|
put_float(w, each.fov_y);
|
||||||
|
if each.aspect is some(aspect) {
|
||||||
|
w.member("aspectRatio");
|
||||||
|
put_float(w, aspect);
|
||||||
|
}
|
||||||
|
} else {
|
||||||
|
w.member("type");
|
||||||
|
w.text("orthographic");
|
||||||
|
w.member("orthographic");
|
||||||
|
w.begin_object();
|
||||||
|
w.member("xmag");
|
||||||
|
put_float(w, each.x_mag);
|
||||||
|
w.member("ymag");
|
||||||
|
put_float(w, each.y_mag);
|
||||||
|
}
|
||||||
|
w.member("znear");
|
||||||
|
put_float(w, each.near);
|
||||||
|
if each.far is some(far) {
|
||||||
|
w.member("zfar");
|
||||||
|
put_float(w, far);
|
||||||
|
}
|
||||||
|
w.end_object();
|
||||||
|
w.end_object();
|
||||||
|
}
|
||||||
|
w.end_array();
|
||||||
|
}
|
||||||
|
|
||||||
|
def write_skins(w: &mut json::writer, made: &asset): void {
|
||||||
|
return if made.skins.length == 0;
|
||||||
|
w.member("skins");
|
||||||
|
w.begin_array();
|
||||||
|
for i in 0..made.skins.length {
|
||||||
|
val each := &made.skins[i];
|
||||||
|
w.begin_object();
|
||||||
|
put_text(w, "name", &each.name);
|
||||||
|
put_indices(w, "joints", &each.joints);
|
||||||
|
put_index(w, "inverseBindMatrices", each.inverse_binds);
|
||||||
|
put_index(w, "skeleton", each.skeleton);
|
||||||
|
w.end_object();
|
||||||
|
}
|
||||||
|
w.end_array();
|
||||||
|
}
|
||||||
|
|
||||||
|
def write_animations(w: &mut json::writer, made: &asset): void {
|
||||||
|
return if made.animations.length == 0;
|
||||||
|
w.member("animations");
|
||||||
|
w.begin_array();
|
||||||
|
for i in 0..made.animations.length {
|
||||||
|
val each := &made.animations[i];
|
||||||
|
w.begin_object();
|
||||||
|
put_text(w, "name", &each.name);
|
||||||
|
w.member("samplers");
|
||||||
|
w.begin_array();
|
||||||
|
for k in 0..each.samplers.length {
|
||||||
|
val keys := &each.samplers[k];
|
||||||
|
w.begin_object();
|
||||||
|
put_count(w, "input", keys.input);
|
||||||
|
put_count(w, "output", keys.output);
|
||||||
|
if keys.interpolation == interpolation::step {
|
||||||
|
w.member("interpolation");
|
||||||
|
w.text("STEP");
|
||||||
|
} else if keys.interpolation == interpolation::cubic_spline {
|
||||||
|
w.member("interpolation");
|
||||||
|
w.text("CUBICSPLINE");
|
||||||
|
}
|
||||||
|
w.end_object();
|
||||||
|
}
|
||||||
|
w.end_array();
|
||||||
|
w.member("channels");
|
||||||
|
w.begin_array();
|
||||||
|
for k in 0..each.channels.length {
|
||||||
|
val moved := &each.channels[k];
|
||||||
|
w.begin_object();
|
||||||
|
put_count(w, "sampler", moved.sampler);
|
||||||
|
w.member("target");
|
||||||
|
w.begin_object();
|
||||||
|
put_index(w, "node", moved.node);
|
||||||
|
w.member("path");
|
||||||
|
w.text(match moved.path {
|
||||||
|
translation => "translation",
|
||||||
|
rotation => "rotation",
|
||||||
|
scale => "scale",
|
||||||
|
weights => "weights",
|
||||||
|
});
|
||||||
|
w.end_object();
|
||||||
|
w.end_object();
|
||||||
|
}
|
||||||
|
w.end_array();
|
||||||
|
w.end_object();
|
||||||
|
}
|
||||||
|
w.end_array();
|
||||||
|
}
|
||||||
|
|
||||||
|
def write_lights(w: &mut json::writer, made: &asset): void {
|
||||||
|
w.member("lights");
|
||||||
|
w.begin_array();
|
||||||
|
for i in 0..made.lights.length {
|
||||||
|
val each := &made.lights[i];
|
||||||
|
w.begin_object();
|
||||||
|
put_text(w, "name", &each.name);
|
||||||
|
w.member("type");
|
||||||
|
w.text(match each.kind {
|
||||||
|
directional => "directional",
|
||||||
|
point => "point",
|
||||||
|
spot => "spot",
|
||||||
|
});
|
||||||
|
if each.color[0] != 1 || each.color[1] != 1 || each.color[2] != 1 {
|
||||||
|
put_floats(w, "color", each.color[:]);
|
||||||
|
}
|
||||||
|
put_number(w, "intensity", each.intensity, 1);
|
||||||
|
if each.range is some(far) {
|
||||||
|
w.member("range");
|
||||||
|
put_float(w, far);
|
||||||
|
}
|
||||||
|
if each.kind == light_kind::spot {
|
||||||
|
w.member("spot");
|
||||||
|
w.begin_object();
|
||||||
|
put_number(w, "innerConeAngle", each.inner_cone, 0);
|
||||||
|
put_number(w, "outerConeAngle", each.outer_cone, 0.7853982);
|
||||||
|
w.end_object();
|
||||||
|
}
|
||||||
|
w.end_object();
|
||||||
|
}
|
||||||
|
w.end_array();
|
||||||
|
}
|
||||||
@@ -0,0 +1,325 @@
|
|||||||
|
#! Contains MTL's materials: their colors and numbers, the physically based
|
||||||
|
#! ones some tools add, and the textures each maps, with the options they're
|
||||||
|
#! given; and reading them from an MTL file's text.
|
||||||
|
|
||||||
|
import malunal::linear;
|
||||||
|
module malunal::obj;
|
||||||
|
|
||||||
|
#! What a texture of a material is a map of, as the statement naming it says.
|
||||||
|
pub enum map_slot: u8 {
|
||||||
|
ambient, #! `map_Ka`
|
||||||
|
diffuse, #! `map_Kd`
|
||||||
|
specular, #! `map_Ks`
|
||||||
|
emissive, #! `map_Ke`
|
||||||
|
shininess, #! `map_Ns`
|
||||||
|
dissolve, #! `map_d`
|
||||||
|
bump, #! `bump` or `map_bump`
|
||||||
|
displacement, #! `disp`
|
||||||
|
decal, #! `decal`
|
||||||
|
reflection, #! `refl`
|
||||||
|
normal, #! `norm`
|
||||||
|
roughness, #! `map_Pr`
|
||||||
|
metallic, #! `map_Pm`
|
||||||
|
sheen, #! `map_Ps`
|
||||||
|
}
|
||||||
|
|
||||||
|
#! The statements naming each slot's texture, in `map_slot`'s order, the first
|
||||||
|
#! of each written.
|
||||||
|
const slot_names: strview[14] = ["map_Ka", "map_Kd", "map_Ks", "map_Ke", "map_Ns", "map_d", "bump", "disp", "decal", "refl", "norm", "map_Pr", "map_Pm", "map_Ps"];
|
||||||
|
const slot_kinds: map_slot[14] = [
|
||||||
|
map_slot::ambient, map_slot::diffuse, map_slot::specular, map_slot::emissive, map_slot::shininess, map_slot::dissolve, map_slot::bump,
|
||||||
|
map_slot::displacement, map_slot::decal, map_slot::reflection, map_slot::normal, map_slot::roughness, map_slot::metallic, map_slot::sheen,
|
||||||
|
];
|
||||||
|
|
||||||
|
# The statement naming a slot's texture, as it's written.
|
||||||
|
def slot_name(slot: map_slot): strview {
|
||||||
|
for k in 0..14 {
|
||||||
|
return slot_names[k] if slot_kinds[k] == slot;
|
||||||
|
}
|
||||||
|
return "map_Kd";
|
||||||
|
}
|
||||||
|
|
||||||
|
#! A texture a material maps, and the options it's given.
|
||||||
|
pub struct texture_map {
|
||||||
|
pub var slot: map_slot;
|
||||||
|
#! The image's file, as the MTL file names it.
|
||||||
|
pub var file: string;
|
||||||
|
#! `-o`, `-s`, and `-t`: where on the texture it begins, how much of it, and
|
||||||
|
#! how much it's turbulent.
|
||||||
|
pub var offset := vec3::zero;
|
||||||
|
pub var scale := vec3::one;
|
||||||
|
pub var turbulence := vec3::zero;
|
||||||
|
#! `-bm`: how much a bump map bumps.
|
||||||
|
pub var bump_multiplier: f32 = 1;
|
||||||
|
#! `-boost`, and `-mm`'s base and gain.
|
||||||
|
pub var boost: f32;
|
||||||
|
pub var base: f32;
|
||||||
|
pub var gain: f32 = 1;
|
||||||
|
#! `-clamp`, `-blendu`, `-blendv`, and `-cc`.
|
||||||
|
pub var clamp: bool;
|
||||||
|
pub var blend_u: bool = true;
|
||||||
|
pub var blend_v: bool = true;
|
||||||
|
pub var color_correct: bool;
|
||||||
|
#! `-texres`, or 0 where it's none.
|
||||||
|
pub var resolution: u32;
|
||||||
|
#! `-imfchan`'s channel, `r`, `g`, `b`, `m`, `l`, or `z`, or 0 where it's none.
|
||||||
|
pub var channel: u8;
|
||||||
|
#! `-type`, a reflection map's: `sphere`, or a side of a cube, as `cube_top`.
|
||||||
|
pub var kind: string;
|
||||||
|
}
|
||||||
|
|
||||||
|
#! A material of an MTL file. Where the file leaves one out, a color is black,
|
||||||
|
#! but diffuse, white, and a number 0, but `dissolve` and `ior`, 1.
|
||||||
|
pub struct material {
|
||||||
|
pub var name: string;
|
||||||
|
#! `Ka`, `Kd`, `Ks`, `Ke`, and `Tf`: ambient, diffuse, specular, emitted, and
|
||||||
|
#! let through.
|
||||||
|
pub var ambient := vec3::zero;
|
||||||
|
pub var diffuse := vec3::one;
|
||||||
|
pub var specular := vec3::zero;
|
||||||
|
pub var emissive := vec3::zero;
|
||||||
|
pub var transmission := vec3::zero;
|
||||||
|
#! `Ns`, the specular exponent, from 0 to 1000.
|
||||||
|
pub var shininess: f32;
|
||||||
|
#! `Ni`, the index of refraction.
|
||||||
|
pub var ior: f32 = 1;
|
||||||
|
#! `d`, how opaque it is, or `Tr`, how transparent, 1 less it.
|
||||||
|
pub var dissolve: f32 = 1;
|
||||||
|
#! `illum`, the illumination model, from 0 to 10.
|
||||||
|
pub var illumination: u32;
|
||||||
|
#! `sharpness`, of reflections.
|
||||||
|
pub var sharpness: f32;
|
||||||
|
#! `Pr`, `Pm`, `Ps`, `Pc`, `Pcr`, `aniso`, and `anisor`: physically based,
|
||||||
|
#! as Blender and others write them.
|
||||||
|
pub var roughness: f32;
|
||||||
|
pub var metallic: f32;
|
||||||
|
pub var sheen: f32;
|
||||||
|
pub var clearcoat: f32;
|
||||||
|
pub var clearcoat_roughness: f32;
|
||||||
|
pub var anisotropy: f32;
|
||||||
|
pub var anisotropy_rotation: f32;
|
||||||
|
#! The textures it maps, in the order the file names them.
|
||||||
|
pub var maps: vector<texture_map>;
|
||||||
|
}
|
||||||
|
|
||||||
|
#! The texture it maps for a slot, where it maps one.
|
||||||
|
pub def material::map(&this, slot: map_slot): maybe<&texture_map> {
|
||||||
|
for i in 0..this.maps.length {
|
||||||
|
return &this.maps[i] if this.maps[i].slot == slot;
|
||||||
|
}
|
||||||
|
return nothing{};
|
||||||
|
}
|
||||||
|
|
||||||
|
#! A material of a name, of the defaults.
|
||||||
|
pub def material::named(name: strview): material {
|
||||||
|
return material{ name = string::from(name, nothing{}) };
|
||||||
|
}
|
||||||
|
|
||||||
|
#! Reads the materials of an MTL file's text.
|
||||||
|
#! @param text The text.
|
||||||
|
#! @returns Its materials, in its order, or why they couldn't be read.
|
||||||
|
pub def decode_materials(text: strview): result<vector<material>, obj_error> {
|
||||||
|
var made := vector::<material>::new();
|
||||||
|
var lines := statements_of(text);
|
||||||
|
while lines.next() {
|
||||||
|
var words := words_of(lines.current);
|
||||||
|
val keyword := words.next();
|
||||||
|
if keyword == "newmtl" {
|
||||||
|
made.append(material::named(words.rest()));
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
return at_line(lines.line, $"`{keyword}` comes before any `newmtl`.".span) if made.length == 0;
|
||||||
|
val held := &mut made[made.length - 1];
|
||||||
|
read_statement(held, keyword, &mut words, lines.line) else (e) { return e; };
|
||||||
|
}
|
||||||
|
return made;
|
||||||
|
}
|
||||||
|
|
||||||
|
# Reads a statement of a material.
|
||||||
|
def read_statement(held: &mut material, keyword: strview, words: &mut words, line: u64): result<void, obj_error> {
|
||||||
|
if keyword == "Ka" || keyword == "Kd" || keyword == "Ks" || keyword == "Ke" || keyword == "Tf" {
|
||||||
|
# `spectral` and `xyz` colors are read as their numbers, where they give
|
||||||
|
# three, and passed over otherwise.
|
||||||
|
var color := vec3::zero;
|
||||||
|
var count: u64 = 0;
|
||||||
|
while count < 3 {
|
||||||
|
val word := words.next();
|
||||||
|
break if word.length == 0;
|
||||||
|
continue if word == "xyz";
|
||||||
|
return if word == "spectral";
|
||||||
|
val value := number_of(word) else { return at_line(line, $"`{word}` isn't a number.".span); };
|
||||||
|
if count == 0 {
|
||||||
|
color = vec3{ value as f32, value as f32, value as f32 };
|
||||||
|
} else if count == 1 {
|
||||||
|
color.y = value as f32;
|
||||||
|
} else {
|
||||||
|
color.z = value as f32;
|
||||||
|
}
|
||||||
|
count++;
|
||||||
|
}
|
||||||
|
return at_line(line, $"`{keyword}` gives no color.".span) if count == 0;
|
||||||
|
if keyword == "Ka" {
|
||||||
|
held.ambient = color;
|
||||||
|
} else if keyword == "Kd" {
|
||||||
|
held.diffuse = color;
|
||||||
|
} else if keyword == "Ks" {
|
||||||
|
held.specular = color;
|
||||||
|
} else if keyword == "Ke" {
|
||||||
|
held.emissive = color;
|
||||||
|
} else {
|
||||||
|
held.transmission = color;
|
||||||
|
}
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
if keyword == "illum" {
|
||||||
|
val word := words.next();
|
||||||
|
val value := integer_of(word) else { return at_line(line, $"`{word}` isn't an illumination model.".span); };
|
||||||
|
held.illumination = value as u32;
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
if keyword == "d" || keyword == "Tr" {
|
||||||
|
var word := words.next();
|
||||||
|
if word == "-halo" {
|
||||||
|
word = words.next();
|
||||||
|
}
|
||||||
|
val value := number_of(word) else { return at_line(line, $"`{word}` isn't a number.".span); };
|
||||||
|
held.dissolve = keyword == "d" ? value as f32 : 1 - value as f32;
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
val numbers: strview[10] = ["Ns", "Ni", "sharpness", "Pr", "Pm", "Ps", "Pc", "Pcr", "aniso", "anisor"];
|
||||||
|
for k in 0..10 {
|
||||||
|
continue if keyword != numbers[k];
|
||||||
|
val word := words.next();
|
||||||
|
val value := number_of(word) else { return at_line(line, $"`{word}` isn't a number.".span); };
|
||||||
|
val n := value as f32;
|
||||||
|
if k == 0 {
|
||||||
|
held.shininess = n;
|
||||||
|
} else if k == 1 {
|
||||||
|
held.ior = n;
|
||||||
|
} else if k == 2 {
|
||||||
|
held.sharpness = n;
|
||||||
|
} else if k == 3 {
|
||||||
|
held.roughness = n;
|
||||||
|
} else if k == 4 {
|
||||||
|
held.metallic = n;
|
||||||
|
} else if k == 5 {
|
||||||
|
held.sheen = n;
|
||||||
|
} else if k == 6 {
|
||||||
|
held.clearcoat = n;
|
||||||
|
} else if k == 7 {
|
||||||
|
held.clearcoat_roughness = n;
|
||||||
|
} else if k == 8 {
|
||||||
|
held.anisotropy = n;
|
||||||
|
} else {
|
||||||
|
held.anisotropy_rotation = n;
|
||||||
|
}
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
val slot := slot_of(keyword) else { return; };
|
||||||
|
var texture := read_map(slot, words, line) else (e) { return e; };
|
||||||
|
held.maps.append(move(texture));
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
# The slot a statement maps a texture for, where it's one that does.
|
||||||
|
def slot_of(keyword: strview): maybe<map_slot> {
|
||||||
|
for k in 0..14 {
|
||||||
|
return slot_kinds[k] if keyword == slot_names[k];
|
||||||
|
}
|
||||||
|
return map_slot::bump if keyword == "map_bump" || keyword == "map_Bump";
|
||||||
|
return map_slot::displacement if keyword == "map_disp";
|
||||||
|
return map_slot::reflection if keyword == "map_refl";
|
||||||
|
return map_slot::normal if keyword == "map_Kn" || keyword == "map_norm";
|
||||||
|
return nothing{};
|
||||||
|
}
|
||||||
|
|
||||||
|
# Reads a texture's options, then its file, the rest of the statement.
|
||||||
|
def read_map(slot: map_slot, words: &mut words, line: u64): result<texture_map, obj_error> {
|
||||||
|
var made := texture_map{ slot = slot };
|
||||||
|
while !words.ended() {
|
||||||
|
val before := words.at;
|
||||||
|
val option := words.next();
|
||||||
|
if option.length < 2 || option[0] != '-' || is_digit(option[1]) {
|
||||||
|
words.at = before;
|
||||||
|
break;
|
||||||
|
}
|
||||||
|
if option == "-o" || option == "-s" || option == "-t" {
|
||||||
|
var v := option == "-s" ? vec3::one : vec3::zero;
|
||||||
|
for k in 0..3 {
|
||||||
|
val at := words.at;
|
||||||
|
val word := words.next();
|
||||||
|
var value: f32 = 0;
|
||||||
|
if number_of(word) is some(n) {
|
||||||
|
value = n as f32;
|
||||||
|
} else {
|
||||||
|
words.at = at;
|
||||||
|
break;
|
||||||
|
}
|
||||||
|
if k == 0 {
|
||||||
|
v.x = value;
|
||||||
|
} else if k == 1 {
|
||||||
|
v.y = value;
|
||||||
|
} else {
|
||||||
|
v.z = value;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if option == "-o" {
|
||||||
|
made.offset = v;
|
||||||
|
} else if option == "-s" {
|
||||||
|
made.scale = v;
|
||||||
|
} else {
|
||||||
|
made.turbulence = v;
|
||||||
|
}
|
||||||
|
} else if option == "-bm" || option == "-boost" {
|
||||||
|
val word := words.next();
|
||||||
|
val value := number_of(word) else { return at_line(line, $"`{option}` needs a number, not `{word}`.".span); };
|
||||||
|
if option == "-bm" {
|
||||||
|
made.bump_multiplier = value as f32;
|
||||||
|
} else {
|
||||||
|
made.boost = value as f32;
|
||||||
|
}
|
||||||
|
} else if option == "-mm" {
|
||||||
|
val base_word := words.next();
|
||||||
|
val gain_word := words.next();
|
||||||
|
val base := number_of(base_word) else { return at_line(line, "`-mm` needs a base and a gain."); };
|
||||||
|
val gain := number_of(gain_word) else { return at_line(line, "`-mm` needs a base and a gain."); };
|
||||||
|
made.base = base as f32;
|
||||||
|
made.gain = gain as f32;
|
||||||
|
} else if option == "-clamp" || option == "-blendu" || option == "-blendv" || option == "-cc" {
|
||||||
|
val word := words.next();
|
||||||
|
return at_line(line, $"`{option}` is `on` or `off`, not `{word}`.".span) if word != "on" && word != "off";
|
||||||
|
val on := word == "on";
|
||||||
|
if option == "-clamp" {
|
||||||
|
made.clamp = on;
|
||||||
|
} else if option == "-blendu" {
|
||||||
|
made.blend_u = on;
|
||||||
|
} else if option == "-blendv" {
|
||||||
|
made.blend_v = on;
|
||||||
|
} else {
|
||||||
|
made.color_correct = on;
|
||||||
|
}
|
||||||
|
} else if option == "-texres" {
|
||||||
|
val word := words.next();
|
||||||
|
val value := integer_of(word) else { return at_line(line, $"`-texres` needs a whole number, not `{word}`.".span); };
|
||||||
|
made.resolution = value as u32;
|
||||||
|
} else if option == "-imfchan" {
|
||||||
|
val word := words.next();
|
||||||
|
return at_line(line, "`-imfchan` needs a channel.") if word.length == 0;
|
||||||
|
made.channel = word[0];
|
||||||
|
} else if option == "-type" {
|
||||||
|
made.kind = string::from(words.next(), nothing{});
|
||||||
|
} else {
|
||||||
|
# An option of another tool's, with a value, passed over.
|
||||||
|
_ = words.next();
|
||||||
|
}
|
||||||
|
}
|
||||||
|
val file := words.rest();
|
||||||
|
return at_line(line, "A texture map names no file.") if file.length == 0;
|
||||||
|
made.file = string::from(file, nothing{});
|
||||||
|
return made;
|
||||||
|
}
|
||||||
|
|
||||||
|
# Whether a byte is a digit.
|
||||||
|
def is_digit(c: u8): bool {
|
||||||
|
return c >= '0' && c <= '9';
|
||||||
|
}
|
||||||
+157
@@ -0,0 +1,157 @@
|
|||||||
|
#! Contains `model`, a model read from Wavefront's OBJ, why one couldn't be,
|
||||||
|
#! and reading one, from a file or from text, with the materials of the MTL
|
||||||
|
#! files it names.
|
||||||
|
#!
|
||||||
|
#! An OBJ file is lines of text, each a statement: `v`, `vt`, and `vn` give
|
||||||
|
#! positions, places on a texture, and normals, and `f`, `l`, and `p` faces,
|
||||||
|
#! lines, and points of them, by their numbers, counted from 1, or back from
|
||||||
|
#! the last where they're negative. `o`, `g`, `s`, and `usemtl` say which
|
||||||
|
#! object, group, smoothing group, and material what follows is of, and
|
||||||
|
#! `mtllib` names the MTL files the materials are in. A model keeps them as
|
||||||
|
#! they are: faces of any number of corners, each corner its position, and its
|
||||||
|
#! place on a texture and its normal where it has them, every index counted
|
||||||
|
#! from 0.
|
||||||
|
|
||||||
|
import std::io;
|
||||||
|
import malunal::linear;
|
||||||
|
module malunal::obj;
|
||||||
|
|
||||||
|
#! What kind of thing kept a model from being read or written.
|
||||||
|
pub enum failure: u8 {
|
||||||
|
unreadable, #! A file couldn't be read, or written.
|
||||||
|
malformed, #! The text breaks OBJ or MTL: a number that isn't one, an index past what it names, a face of fewer than three corners.
|
||||||
|
}
|
||||||
|
|
||||||
|
#! Why a model couldn't be read, or written: the kind of thing, and what, as
|
||||||
|
#! `line 12: its face has 2 corners, of the 3 it needs at least`. It holds its
|
||||||
|
#! text itself, its first 240 bytes, so it's plain data, as std's errors are.
|
||||||
|
pub struct obj_error {
|
||||||
|
pub var kind: failure;
|
||||||
|
var text: u8[240];
|
||||||
|
var length: u64;
|
||||||
|
}
|
||||||
|
|
||||||
|
#! What was wrong, and where.
|
||||||
|
pub def obj_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): obj_error {
|
||||||
|
var made := obj_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 a corner names where it names nothing: no place on a texture, or no
|
||||||
|
#! normal; and what an element is of where it's of no material, object, or
|
||||||
|
#! group.
|
||||||
|
pub const absent: u32 = 0xFFFFFFFF;
|
||||||
|
|
||||||
|
#! A corner of a face, or a point of a line or of points: indices into the
|
||||||
|
#! model's positions, places on a texture, and normals.
|
||||||
|
pub struct corner {
|
||||||
|
pub var position: u32;
|
||||||
|
pub var uv: u32 = absent;
|
||||||
|
pub var normal: u32 = absent;
|
||||||
|
}
|
||||||
|
|
||||||
|
#! A face, a line, or points: a run of the model's corners, and what it's of.
|
||||||
|
pub struct element {
|
||||||
|
#! Its first corner, in the model's `corners`.
|
||||||
|
pub var first: u64;
|
||||||
|
#! How many corners it has: three or more of a face, two or more of a line.
|
||||||
|
pub var count: u32;
|
||||||
|
#! Its material, in the model's `materials`.
|
||||||
|
pub var material: u32 = absent;
|
||||||
|
#! Its smoothing group, or 0 where it's of none, and drawn flat.
|
||||||
|
pub var smoothing: u32;
|
||||||
|
#! The object it's of, in the model's `objects`.
|
||||||
|
pub var object: u32 = absent;
|
||||||
|
#! The group it's of, in the model's `groups`.
|
||||||
|
pub var group: u32 = absent;
|
||||||
|
}
|
||||||
|
|
||||||
|
#! A model read from OBJ: what it's made of, and its faces, lines, and points,
|
||||||
|
#! each a run of corners.
|
||||||
|
pub struct model {
|
||||||
|
pub var positions: vector<vec3>;
|
||||||
|
#! Each position's color, where the file gives them, as `v x y z r g b`,
|
||||||
|
#! white where it gives one none; empty where it gives none.
|
||||||
|
pub var colors: vector<vec3>;
|
||||||
|
pub var uvs: vector<vec2>;
|
||||||
|
pub var normals: vector<vec3>;
|
||||||
|
pub var corners: vector<corner>;
|
||||||
|
pub var faces: vector<element>;
|
||||||
|
pub var lines: vector<element>;
|
||||||
|
pub var points: vector<element>;
|
||||||
|
#! The names of its objects, by `o`, and of its groups, by `g`.
|
||||||
|
pub var objects: vector<string>;
|
||||||
|
pub var groups: vector<string>;
|
||||||
|
#! Its materials: those of the MTL files it names, in their order, then one
|
||||||
|
#! of each name `usemtl` gives that none of them has, of the defaults.
|
||||||
|
pub var materials: vector<material>;
|
||||||
|
#! The MTL files it names, as it names them, and those of them that weren't
|
||||||
|
#! found or couldn't be read.
|
||||||
|
pub var libraries: vector<string>;
|
||||||
|
pub var missing: vector<string>;
|
||||||
|
}
|
||||||
|
|
||||||
|
#! The corners of an element.
|
||||||
|
pub def model::corners_of(&this, of: &element): span<corner> {
|
||||||
|
return this.corners.span[of.first:of.count as u64];
|
||||||
|
}
|
||||||
|
|
||||||
|
#! The material named so, where it has one.
|
||||||
|
pub def model::material_named(&this, name: strview): maybe<u64> {
|
||||||
|
for i in 0..this.materials.length {
|
||||||
|
return i if this.materials[i].name.span == name;
|
||||||
|
}
|
||||||
|
return nothing{};
|
||||||
|
}
|
||||||
|
|
||||||
|
#! Reads a model from a file, and the materials of the MTL files it names, from
|
||||||
|
#! beside it.
|
||||||
|
#! @param at The file's path.
|
||||||
|
#! @returns The model, or why it couldn't be read: `unreadable` where the file
|
||||||
|
#! couldn't be. An MTL file that can't be is named in `missing`.
|
||||||
|
pub def load(at: &path): result<model, obj_error> {
|
||||||
|
val text := io::read_file(at) else (_) { return failed(failure::unreadable, $"{at.span} couldn't be read.".span); };
|
||||||
|
var folder := path::new();
|
||||||
|
if at.parent() is some(&above) {
|
||||||
|
folder = path::copy_of(&above);
|
||||||
|
}
|
||||||
|
return decode(text.span, folder.span);
|
||||||
|
}
|
||||||
|
|
||||||
|
#! Reads a model from a file named by text, as `load` does.
|
||||||
|
pub def load(at: strview): result<model, obj_error> {
|
||||||
|
val named := path::parse(at) else (_) { return failed(failure::unreadable, $"{at} isn't a path.".span); };
|
||||||
|
return load(&named);
|
||||||
|
}
|
||||||
|
|
||||||
|
#! Reads a model from text.
|
||||||
|
#! @param text The OBJ file's text.
|
||||||
|
#! @param folder The folder the MTL files it names are found in, or empty,
|
||||||
|
#! where none are read, but named in `missing`.
|
||||||
|
#! @returns The model, or why it couldn't be read.
|
||||||
|
pub def decode(text: strview, folder: strview = ""): result<model, obj_error> {
|
||||||
|
return read_model(text, folder);
|
||||||
|
}
|
||||||
|
|
||||||
|
#! Reads the materials of an MTL file.
|
||||||
|
#! @param at The file's path.
|
||||||
|
#! @returns Its materials, in its order, or why they couldn't be read.
|
||||||
|
pub def load_materials(at: &path): result<vector<material>, obj_error> {
|
||||||
|
val text := io::read_file(at) else (_) { return failed(failure::unreadable, $"{at.span} couldn't be read.".span); };
|
||||||
|
return decode_materials(text.span);
|
||||||
|
}
|
||||||
|
|
||||||
|
#! Reads the materials of an MTL file named by text, as `load_materials` does.
|
||||||
|
pub def load_materials(at: strview): result<vector<material>, obj_error> {
|
||||||
|
val named := path::parse(at) else (_) { return failed(failure::unreadable, $"{at} isn't a path.".span); };
|
||||||
|
return load_materials(&named);
|
||||||
|
}
|
||||||
@@ -0,0 +1,253 @@
|
|||||||
|
#! Contains reading an OBJ file's statements into a model: what each gives,
|
||||||
|
#! its corners' indices checked once all are read, as one may name a position
|
||||||
|
#! given after it, and the materials of the MTL files it names.
|
||||||
|
|
||||||
|
import std::io;
|
||||||
|
import malunal::linear;
|
||||||
|
module malunal::obj;
|
||||||
|
|
||||||
|
# What the statements read so far say what follows is of.
|
||||||
|
struct state {
|
||||||
|
var material: u32 = absent;
|
||||||
|
var smoothing: u32;
|
||||||
|
var object: u32 = absent;
|
||||||
|
var group: u32 = absent;
|
||||||
|
}
|
||||||
|
|
||||||
|
# Reads a model from OBJ's text, the MTL files it names from a folder.
|
||||||
|
def read_model(text: strview, folder: strview): result<model, obj_error> {
|
||||||
|
var made := model{};
|
||||||
|
# The names `usemtl` gives, which elements' materials index until the end.
|
||||||
|
var named := vector::<string>::new();
|
||||||
|
var now := state{};
|
||||||
|
var lines := statements_of(text);
|
||||||
|
while lines.next() {
|
||||||
|
val line := lines.line;
|
||||||
|
var words := words_of(lines.current);
|
||||||
|
val keyword := words.next();
|
||||||
|
if keyword == "v" {
|
||||||
|
read_position(&mut made, &mut words, line) else (e) { return e; };
|
||||||
|
} else if keyword == "vt" {
|
||||||
|
val numbers := read_numbers(&mut words, line, 1, 3) else (e) { return e; };
|
||||||
|
made.uvs.append(vec2{ numbers[0] as f32, numbers[1] as f32 });
|
||||||
|
} else if keyword == "vn" {
|
||||||
|
val numbers := read_numbers(&mut words, line, 3, 3) else (e) { return e; };
|
||||||
|
made.normals.append(vec3{ numbers[0] as f32, numbers[1] as f32, numbers[2] as f32 });
|
||||||
|
} else if keyword == "f" || keyword == "fo" || keyword == "l" || keyword == "p" {
|
||||||
|
val first := made.corners.length;
|
||||||
|
while true {
|
||||||
|
val word := words.next();
|
||||||
|
break if word.length == 0;
|
||||||
|
val held := read_corner(&made, word, line) else (e) { return e; };
|
||||||
|
made.corners.append(held);
|
||||||
|
}
|
||||||
|
val count := made.corners.length - first;
|
||||||
|
var held := element{ first = first, count = count as u32, material = now.material, smoothing = now.smoothing, object = now.object, group = now.group };
|
||||||
|
if keyword == "l" {
|
||||||
|
return at_line(line, $"Its line has {count} points, of the 2 it needs at least.".span) if count < 2;
|
||||||
|
made.lines.append(held);
|
||||||
|
} else if keyword == "p" {
|
||||||
|
return at_line(line, "Its points are none.") if count < 1;
|
||||||
|
made.points.append(held);
|
||||||
|
} else {
|
||||||
|
return at_line(line, $"Its face has {count} corners, of the 3 it needs at least.".span) if count < 3;
|
||||||
|
made.faces.append(held);
|
||||||
|
}
|
||||||
|
} else if keyword == "o" {
|
||||||
|
now.object = name_index(&mut made.objects, words.rest());
|
||||||
|
} else if keyword == "g" {
|
||||||
|
val name := words.rest();
|
||||||
|
now.group = name.length == 0 ? absent : name_index(&mut made.groups, name);
|
||||||
|
} else if keyword == "s" {
|
||||||
|
val word := words.next();
|
||||||
|
if word == "off" || word.length == 0 {
|
||||||
|
now.smoothing = 0;
|
||||||
|
} else {
|
||||||
|
val value := integer_of(word) else { return at_line(line, $"`{word}` isn't a smoothing group.".span); };
|
||||||
|
now.smoothing = value as u32;
|
||||||
|
}
|
||||||
|
} else if keyword == "usemtl" {
|
||||||
|
val name := words.rest();
|
||||||
|
now.material = name.length == 0 ? absent : name_index(&mut named, name);
|
||||||
|
} else if keyword == "mtllib" {
|
||||||
|
read_libraries(&mut made, &mut words, folder);
|
||||||
|
}
|
||||||
|
# Other statements, of curves and surfaces, and of display, are passed over.
|
||||||
|
}
|
||||||
|
check_corners(&made) else (e) { return e; };
|
||||||
|
read_materials(&mut made, folder) else (e) { return e; };
|
||||||
|
name_materials(&mut made, &named);
|
||||||
|
return made;
|
||||||
|
}
|
||||||
|
|
||||||
|
# Reads a position, and its color, where it has one.
|
||||||
|
def read_position(made: &mut model, words: &mut words, line: u64): result<void, obj_error> {
|
||||||
|
val numbers := read_numbers(words, line, 3, 7) else (e) { return e; };
|
||||||
|
made.positions.append(vec3{ numbers[0] as f32, numbers[1] as f32, numbers[2] as f32 });
|
||||||
|
# Three more are a color; a fourth alone is a weight, which isn't kept.
|
||||||
|
if numbers[7] >= 6 {
|
||||||
|
while made.colors.length + 1 < made.positions.length {
|
||||||
|
made.colors.append(vec3::one);
|
||||||
|
}
|
||||||
|
made.colors.append(vec3{ numbers[3] as f32, numbers[4] as f32, numbers[5] as f32 });
|
||||||
|
} else if made.colors.length != 0 {
|
||||||
|
made.colors.append(vec3::one);
|
||||||
|
}
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
# Reads from a least to a most numbers, those not given 0; how many were given
|
||||||
|
# is the last.
|
||||||
|
def read_numbers(words: &mut words, line: u64, least: u64, most: u64): result<f64[8], obj_error> {
|
||||||
|
var made: f64[8];
|
||||||
|
var count: u64 = 0;
|
||||||
|
while count < most {
|
||||||
|
val word := words.next();
|
||||||
|
break if word.length == 0;
|
||||||
|
val value := number_of(word) else { return at_line(line, $"`{word}` isn't a number.".span); };
|
||||||
|
made[count] = value;
|
||||||
|
count++;
|
||||||
|
}
|
||||||
|
return at_line(line, $"It gives {count} numbers, of the {least} it needs at least.".span) if count < least;
|
||||||
|
made[7] = count as f64;
|
||||||
|
return made;
|
||||||
|
}
|
||||||
|
|
||||||
|
# Reads a corner, `v`, `v/vt`, `v//vn`, or `v/vt/vn`, each index counted from 1,
|
||||||
|
# or back from the last given where it's negative.
|
||||||
|
def read_corner(made: &model, word: strview, line: u64): result<corner, obj_error> {
|
||||||
|
var parts: strview[3];
|
||||||
|
var count: u64 = 0;
|
||||||
|
var begun: u64 = 0;
|
||||||
|
for i in 0..=word.length {
|
||||||
|
if i == word.length || word[i] == '/' {
|
||||||
|
return at_line(line, $"`{word}` isn't a corner.".span) if count == 3;
|
||||||
|
parts[count] = word.substr(begun, i - begun);
|
||||||
|
count++;
|
||||||
|
begun = i + 1;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
var held := corner{};
|
||||||
|
held.position = resolve(parts[0], made.positions.length, word, line) else (e) { return e; };
|
||||||
|
if count > 1 && parts[1].length != 0 {
|
||||||
|
held.uv = resolve(parts[1], made.uvs.length, word, line) else (e) { return e; };
|
||||||
|
}
|
||||||
|
if count > 2 && parts[2].length != 0 {
|
||||||
|
held.normal = resolve(parts[2], made.normals.length, word, line) else (e) { return e; };
|
||||||
|
}
|
||||||
|
return held;
|
||||||
|
}
|
||||||
|
|
||||||
|
# An index, counted from 0, of one counted from 1, or back from the last of
|
||||||
|
# those given so far where it's negative.
|
||||||
|
def resolve(text: strview, given: u64, word: strview, line: u64): result<u32, obj_error> {
|
||||||
|
val value := integer_of(text) else { return at_line(line, $"`{word}` isn't a corner.".span); };
|
||||||
|
if value > 0 {
|
||||||
|
return at_line(line, $"`{word}` names more than there may be.".span) if value > 0xFFFFFFFE;
|
||||||
|
return (value - 1) as u32;
|
||||||
|
}
|
||||||
|
val back := given as i64 + value;
|
||||||
|
return at_line(line, $"`{word}` names nothing: an index is counted from 1, or back from -1.".span) if value == 0 || back < 0;
|
||||||
|
return back as u32;
|
||||||
|
}
|
||||||
|
|
||||||
|
# The index of a name in a list, added where it isn't there.
|
||||||
|
def name_index(names: &mut vector<string>, name: strview): u32 {
|
||||||
|
for i in 0..names.length {
|
||||||
|
return i as u32 if names[i].span == name;
|
||||||
|
}
|
||||||
|
names.append(string::from(name, nothing{}));
|
||||||
|
return (names.length - 1) as u32;
|
||||||
|
}
|
||||||
|
|
||||||
|
# Notes the MTL files a statement names: its words, or the whole of it where
|
||||||
|
# that names a file beside the model, as a name with a space.
|
||||||
|
def read_libraries(made: &mut model, words: &mut words, folder: strview): void {
|
||||||
|
val whole := words.rest();
|
||||||
|
if folder.length != 0 && whole.find(" ") is some(_) {
|
||||||
|
val at := path::parse($"{folder}/{whole}".span) else (_) { return; };
|
||||||
|
if io::exists(&at) {
|
||||||
|
_ = name_index(&mut made.libraries, whole);
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
var each := words_of(whole);
|
||||||
|
while true {
|
||||||
|
val word := each.next();
|
||||||
|
break if word.length == 0;
|
||||||
|
_ = name_index(&mut made.libraries, word);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
# Checks each corner names a position, a place on a texture, and a normal there
|
||||||
|
# are.
|
||||||
|
def check_corners(made: &model): result<void, obj_error> {
|
||||||
|
for i in 0..made.corners.length {
|
||||||
|
val held := made.corners[i];
|
||||||
|
if held.position as u64 >= made.positions.length {
|
||||||
|
return failed(failure::malformed, $"Corner {i} names position {held.position + 1}, of the {made.positions.length} there are.".span);
|
||||||
|
}
|
||||||
|
if held.uv != absent && (held.uv as u64) >= made.uvs.length {
|
||||||
|
return failed(failure::malformed, $"Corner {i} names texture place {held.uv + 1}, of the {made.uvs.length} there are.".span);
|
||||||
|
}
|
||||||
|
if held.normal != absent && (held.normal as u64) >= made.normals.length {
|
||||||
|
return failed(failure::malformed, $"Corner {i} names normal {held.normal + 1}, of the {made.normals.length} there are.".span);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
# Reads the materials of the MTL files the model names, each name kept by the
|
||||||
|
# first that gives it; those that can't be read are noted as missing.
|
||||||
|
def read_materials(made: &mut model, folder: strview): result<void, obj_error> {
|
||||||
|
for k in 0..made.libraries.length {
|
||||||
|
val name := made.libraries[k].span;
|
||||||
|
if folder.length == 0 {
|
||||||
|
made.missing.append(string::from(name, nothing{}));
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
val at := path::parse($"{folder}/{name}".span) else (_) {
|
||||||
|
made.missing.append(string::from(name, nothing{}));
|
||||||
|
continue;
|
||||||
|
};
|
||||||
|
val text := io::read_file(&at) else (_) {
|
||||||
|
made.missing.append(string::from(name, nothing{}));
|
||||||
|
continue;
|
||||||
|
};
|
||||||
|
var read := decode_materials(text.span) else (e) {
|
||||||
|
val why := e.describe();
|
||||||
|
return failed(failure::malformed, $"{name}: {why.span}".span);
|
||||||
|
};
|
||||||
|
for i in 0..read.length {
|
||||||
|
continue if made.material_named(read[i].name.span) is some(_);
|
||||||
|
made.materials.append(move(read[i]));
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
# Gives each element the index of its material in the model's, those named by
|
||||||
|
# `usemtl` that no MTL file gave made of the defaults.
|
||||||
|
def name_materials(made: &mut model, named: &vector<string>): void {
|
||||||
|
var index := vector::<u32>::new();
|
||||||
|
for i in 0..named.length {
|
||||||
|
if made.material_named(named[i].span) is some(found) {
|
||||||
|
index.append(found as u32);
|
||||||
|
} else {
|
||||||
|
made.materials.append(material::named(named[i].span));
|
||||||
|
index.append((made.materials.length - 1) as u32);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
for i in 0..made.faces.length {
|
||||||
|
val m := made.faces[i].material;
|
||||||
|
made.faces[i].material = m == absent ? absent : index[m as u64];
|
||||||
|
}
|
||||||
|
for i in 0..made.lines.length {
|
||||||
|
val m := made.lines[i].material;
|
||||||
|
made.lines[i].material = m == absent ? absent : index[m as u64];
|
||||||
|
}
|
||||||
|
for i in 0..made.points.length {
|
||||||
|
val m := made.points[i].material;
|
||||||
|
made.points[i].material = m == absent ? absent : index[m as u64];
|
||||||
|
}
|
||||||
|
}
|
||||||
+146
@@ -0,0 +1,146 @@
|
|||||||
|
#! Contains reading OBJ's and MTL's text: its statements, a line each, blank
|
||||||
|
#! lines and comments passed over and a line ending with `\` joined to the
|
||||||
|
#! next; and the words and numbers of each.
|
||||||
|
|
||||||
|
module malunal::obj;
|
||||||
|
|
||||||
|
# The statements of a file's text, a line each.
|
||||||
|
struct statements {
|
||||||
|
var text: strview;
|
||||||
|
var at: u64;
|
||||||
|
#! The statement given last, its spaces about it trimmed.
|
||||||
|
var current: strview;
|
||||||
|
#! The number of the line it began on, from 1.
|
||||||
|
var line: u64;
|
||||||
|
var counted: u64;
|
||||||
|
var joined: string;
|
||||||
|
}
|
||||||
|
|
||||||
|
# The statements of text.
|
||||||
|
def statements_of(text: strview): statements {
|
||||||
|
return statements{ text = text, joined = string::new(nothing{}) };
|
||||||
|
}
|
||||||
|
|
||||||
|
# Moves to the next statement, passing over blank lines and those beginning
|
||||||
|
# with `#`.
|
||||||
|
# @returns Whether there was one; it's `current`.
|
||||||
|
def statements::next(&mut this): bool {
|
||||||
|
while this.at < this.text.length {
|
||||||
|
this.joined.clear();
|
||||||
|
var joining := false;
|
||||||
|
this.line = this.counted + 1;
|
||||||
|
while true {
|
||||||
|
val begun := this.at;
|
||||||
|
while this.at < this.text.length && this.text[this.at] != '\n' {
|
||||||
|
this.at++;
|
||||||
|
}
|
||||||
|
var end := this.at;
|
||||||
|
if this.at < this.text.length {
|
||||||
|
this.at++;
|
||||||
|
}
|
||||||
|
this.counted++;
|
||||||
|
while end > begun && is_space(this.text[end - 1]) {
|
||||||
|
end--;
|
||||||
|
}
|
||||||
|
# A line ending with `\` goes on in the next.
|
||||||
|
if end > begun && this.text[end - 1] == '\\' && this.at < this.text.length {
|
||||||
|
this.joined.append(this.text.substr(begun, end - 1 - begun));
|
||||||
|
this.joined.push(' ');
|
||||||
|
joining = true;
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
if joining {
|
||||||
|
this.joined.append(this.text.substr(begun, end - begun));
|
||||||
|
this.current = trimmed(this.joined.span);
|
||||||
|
} else {
|
||||||
|
this.current = trimmed(this.text.substr(begun, end - begun));
|
||||||
|
}
|
||||||
|
break;
|
||||||
|
}
|
||||||
|
continue if this.current.length == 0 || this.current[0] == '#';
|
||||||
|
return true;
|
||||||
|
}
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
|
||||||
|
# Whether a byte is a space between words.
|
||||||
|
def is_space(c: u8): bool {
|
||||||
|
return c == ' ' || c == '\t' || c == '\r' || c == 11 || c == 12;
|
||||||
|
}
|
||||||
|
|
||||||
|
# Text with the spaces about it taken away.
|
||||||
|
def trimmed(text: strview): strview {
|
||||||
|
var first: u64 = 0;
|
||||||
|
var end := text.length;
|
||||||
|
while first < end && is_space(text[first]) {
|
||||||
|
first++;
|
||||||
|
}
|
||||||
|
while end > first && is_space(text[end - 1]) {
|
||||||
|
end--;
|
||||||
|
}
|
||||||
|
return text.substr(first, end - first);
|
||||||
|
}
|
||||||
|
|
||||||
|
# The words of a statement, one after another.
|
||||||
|
struct words {
|
||||||
|
var text: strview;
|
||||||
|
var at: u64;
|
||||||
|
}
|
||||||
|
|
||||||
|
def words_of(text: strview): words {
|
||||||
|
return words{ text = text };
|
||||||
|
}
|
||||||
|
|
||||||
|
# The next word, or empty at the statement's end, or at a word beginning with
|
||||||
|
# `#`, a comment after it.
|
||||||
|
def words::next(&mut this): strview {
|
||||||
|
while this.at < this.text.length && is_space(this.text[this.at]) {
|
||||||
|
this.at++;
|
||||||
|
}
|
||||||
|
if this.at < this.text.length && this.text[this.at] == '#' {
|
||||||
|
this.at = this.text.length;
|
||||||
|
}
|
||||||
|
val begun := this.at;
|
||||||
|
while this.at < this.text.length && !is_space(this.text[this.at]) {
|
||||||
|
this.at++;
|
||||||
|
}
|
||||||
|
return this.text.substr(begun, this.at - begun);
|
||||||
|
}
|
||||||
|
|
||||||
|
# What's left of the statement, the spaces about it trimmed: a name, which may
|
||||||
|
# hold spaces.
|
||||||
|
def words::rest(&mut this): strview {
|
||||||
|
val left := trimmed(this.text.substr(this.at, this.text.length - this.at));
|
||||||
|
this.at = this.text.length;
|
||||||
|
return left;
|
||||||
|
}
|
||||||
|
|
||||||
|
# Whether nothing's left of the statement but spaces, or a comment.
|
||||||
|
def words::ended(&this): bool {
|
||||||
|
var at := this.at;
|
||||||
|
while at < this.text.length && is_space(this.text[at]) {
|
||||||
|
at++;
|
||||||
|
}
|
||||||
|
return at >= this.text.length || this.text[at] == '#';
|
||||||
|
}
|
||||||
|
|
||||||
|
# A word as a number.
|
||||||
|
def number_of(word: strview): maybe<f64> {
|
||||||
|
if real::parse::<f64>(word) is value(n) {
|
||||||
|
return n;
|
||||||
|
}
|
||||||
|
return nothing{};
|
||||||
|
}
|
||||||
|
|
||||||
|
# A word as a whole number.
|
||||||
|
def integer_of(word: strview): maybe<i64> {
|
||||||
|
if integer::parse::<i64>(word) is value(n) {
|
||||||
|
return n;
|
||||||
|
}
|
||||||
|
return nothing{};
|
||||||
|
}
|
||||||
|
|
||||||
|
# An error of malformed text, at a line.
|
||||||
|
def at_line(line: u64, why: strview): obj_error {
|
||||||
|
return failed(failure::malformed, $"line {line}: {why}".span);
|
||||||
|
}
|
||||||
@@ -0,0 +1,272 @@
|
|||||||
|
#! Contains writing a model as OBJ, and its materials as MTL: `encode`,
|
||||||
|
#! `encode_materials`, and `save`, which writes both, the MTL file beside the
|
||||||
|
#! OBJ.
|
||||||
|
|
||||||
|
import std::io;
|
||||||
|
import malunal::linear;
|
||||||
|
module malunal::obj;
|
||||||
|
|
||||||
|
#! Writes a model as OBJ's text: its positions, and their colors where it has
|
||||||
|
#! them, places on a texture, and normals, then its faces, lines, and points,
|
||||||
|
#! each `o`, `g`, `usemtl`, and `s` written where what they're of changes.
|
||||||
|
#! @param made The model.
|
||||||
|
#! @param library The MTL file it names, or empty for the first it read from,
|
||||||
|
#! where it read from any.
|
||||||
|
#! @returns The text, numbers written as the shortest text that reads back as
|
||||||
|
#! them.
|
||||||
|
pub def encode(made: &model, library: strview = ""): string {
|
||||||
|
var out := string::new(nothing{});
|
||||||
|
out.append("# Written by malunal obj\n");
|
||||||
|
if library.length != 0 {
|
||||||
|
out.append($"mtllib {library}\n".span);
|
||||||
|
} else if made.libraries.length != 0 && made.materials.length != 0 {
|
||||||
|
out.append($"mtllib {made.libraries[0].span}\n".span);
|
||||||
|
}
|
||||||
|
val colored := made.colors.length == made.positions.length && made.colors.length != 0;
|
||||||
|
for i in 0..made.positions.length {
|
||||||
|
val p := made.positions[i];
|
||||||
|
out.append("v ");
|
||||||
|
put_numbers(&mut out, p.x, p.y, p.z);
|
||||||
|
if colored {
|
||||||
|
val c := made.colors[i];
|
||||||
|
out.push(' ');
|
||||||
|
put_numbers(&mut out, c.x, c.y, c.z);
|
||||||
|
}
|
||||||
|
out.push('\n');
|
||||||
|
}
|
||||||
|
for i in 0..made.uvs.length {
|
||||||
|
val t := made.uvs[i];
|
||||||
|
out.append("vt ");
|
||||||
|
put_number(&mut out, t.x);
|
||||||
|
out.push(' ');
|
||||||
|
put_number(&mut out, t.y);
|
||||||
|
out.push('\n');
|
||||||
|
}
|
||||||
|
for i in 0..made.normals.length {
|
||||||
|
val n := made.normals[i];
|
||||||
|
out.append("vn ");
|
||||||
|
put_numbers(&mut out, n.x, n.y, n.z);
|
||||||
|
out.push('\n');
|
||||||
|
}
|
||||||
|
var now := state{ object = absent - 1, group = absent - 1, material = absent - 1, smoothing = absent };
|
||||||
|
put_elements(&mut out, made, &made.faces, "f", &mut now);
|
||||||
|
put_elements(&mut out, made, &made.lines, "l", &mut now);
|
||||||
|
put_elements(&mut out, made, &made.points, "p", &mut now);
|
||||||
|
return out;
|
||||||
|
}
|
||||||
|
|
||||||
|
# Writes elements of a kind, and what they're of where it changes.
|
||||||
|
def put_elements(out: &mut string, made: &model, list: &vector<element>, keyword: strview, now: &mut state): void {
|
||||||
|
for i in 0..list.length {
|
||||||
|
val held := list[i];
|
||||||
|
if held.object != now.object {
|
||||||
|
now.object = held.object;
|
||||||
|
if held.object != absent {
|
||||||
|
out.append($"o {made.objects[held.object as u64].span}\n".span);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if held.group != now.group {
|
||||||
|
now.group = held.group;
|
||||||
|
if held.group != absent {
|
||||||
|
out.append($"g {made.groups[held.group as u64].span}\n".span);
|
||||||
|
} else {
|
||||||
|
out.append("g\n");
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if held.material != now.material {
|
||||||
|
now.material = held.material;
|
||||||
|
if held.material != absent {
|
||||||
|
out.append($"usemtl {made.materials[held.material as u64].name.span}\n".span);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if held.smoothing != now.smoothing {
|
||||||
|
now.smoothing = held.smoothing;
|
||||||
|
if held.smoothing == 0 {
|
||||||
|
out.append("s off\n");
|
||||||
|
} else {
|
||||||
|
out.append($"s {held.smoothing}\n".span);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
out.append(keyword);
|
||||||
|
for k in 0..held.count as u64 {
|
||||||
|
val c := made.corners[held.first + k];
|
||||||
|
out.append($" {c.position + 1}".span);
|
||||||
|
if c.uv != absent || c.normal != absent {
|
||||||
|
out.push('/');
|
||||||
|
if c.uv != absent {
|
||||||
|
out.append($"{c.uv + 1}".span);
|
||||||
|
}
|
||||||
|
if c.normal != absent {
|
||||||
|
out.append($"/{c.normal + 1}".span);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
out.push('\n');
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
#! Writes materials as MTL's text: of each, its colors and numbers, and the
|
||||||
|
#! textures it maps, each with the options that aren't their defaults.
|
||||||
|
#! @param list The materials.
|
||||||
|
#! @returns The text.
|
||||||
|
pub def encode_materials(list: span<material>): string {
|
||||||
|
var out := string::new(nothing{});
|
||||||
|
out.append("# Written by malunal obj\n");
|
||||||
|
for i in 0..list.length {
|
||||||
|
val m := &list[i];
|
||||||
|
out.append($"\nnewmtl {m.name.span}\n".span);
|
||||||
|
put_color(&mut out, "Ka", m.ambient);
|
||||||
|
put_color(&mut out, "Kd", m.diffuse);
|
||||||
|
put_color(&mut out, "Ks", m.specular);
|
||||||
|
put_color(&mut out, "Ke", m.emissive);
|
||||||
|
if m.transmission.x != 0 || m.transmission.y != 0 || m.transmission.z != 0 {
|
||||||
|
put_color(&mut out, "Tf", m.transmission);
|
||||||
|
}
|
||||||
|
put_value(&mut out, "Ns", m.shininess);
|
||||||
|
put_value(&mut out, "Ni", m.ior);
|
||||||
|
put_value(&mut out, "d", m.dissolve);
|
||||||
|
out.append($"illum {m.illumination}\n".span);
|
||||||
|
val extra: strview[8] = ["sharpness", "Pr", "Pm", "Ps", "Pc", "Pcr", "aniso", "anisor"];
|
||||||
|
val values: f32[8] = [m.sharpness, m.roughness, m.metallic, m.sheen, m.clearcoat, m.clearcoat_roughness, m.anisotropy, m.anisotropy_rotation];
|
||||||
|
for k in 0..8 {
|
||||||
|
if values[k] != 0 {
|
||||||
|
put_value(&mut out, extra[k], values[k]);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
for k in 0..m.maps.length {
|
||||||
|
put_map(&mut out, &m.maps[k]);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return out;
|
||||||
|
}
|
||||||
|
|
||||||
|
# A statement of a color.
|
||||||
|
def put_color(out: &mut string, keyword: strview, color: vec3): void {
|
||||||
|
out.append(keyword);
|
||||||
|
out.push(' ');
|
||||||
|
put_numbers(out, color.x, color.y, color.z);
|
||||||
|
out.push('\n');
|
||||||
|
}
|
||||||
|
|
||||||
|
# A statement of a number.
|
||||||
|
def put_value(out: &mut string, keyword: strview, value: f32): void {
|
||||||
|
out.append(keyword);
|
||||||
|
out.push(' ');
|
||||||
|
put_number(out, value);
|
||||||
|
out.push('\n');
|
||||||
|
}
|
||||||
|
|
||||||
|
# A texture map's statement: its options where they aren't their defaults,
|
||||||
|
# then its file.
|
||||||
|
def put_map(out: &mut string, held: &texture_map): void {
|
||||||
|
out.append(slot_name(held.slot));
|
||||||
|
if held.blend_u == false {
|
||||||
|
out.append(" -blendu off");
|
||||||
|
}
|
||||||
|
if held.blend_v == false {
|
||||||
|
out.append(" -blendv off");
|
||||||
|
}
|
||||||
|
if held.color_correct {
|
||||||
|
out.append(" -cc on");
|
||||||
|
}
|
||||||
|
if held.clamp {
|
||||||
|
out.append(" -clamp on");
|
||||||
|
}
|
||||||
|
if held.boost != 0 {
|
||||||
|
out.append(" -boost ");
|
||||||
|
put_number(out, held.boost);
|
||||||
|
}
|
||||||
|
if held.base != 0 || held.gain != 1 {
|
||||||
|
out.append(" -mm ");
|
||||||
|
put_numbers2(out, held.base, held.gain);
|
||||||
|
}
|
||||||
|
if held.offset.x != 0 || held.offset.y != 0 || held.offset.z != 0 {
|
||||||
|
out.append(" -o ");
|
||||||
|
put_numbers(out, held.offset.x, held.offset.y, held.offset.z);
|
||||||
|
}
|
||||||
|
if held.scale.x != 1 || held.scale.y != 1 || held.scale.z != 1 {
|
||||||
|
out.append(" -s ");
|
||||||
|
put_numbers(out, held.scale.x, held.scale.y, held.scale.z);
|
||||||
|
}
|
||||||
|
if held.turbulence.x != 0 || held.turbulence.y != 0 || held.turbulence.z != 0 {
|
||||||
|
out.append(" -t ");
|
||||||
|
put_numbers(out, held.turbulence.x, held.turbulence.y, held.turbulence.z);
|
||||||
|
}
|
||||||
|
if held.bump_multiplier != 1 {
|
||||||
|
out.append(" -bm ");
|
||||||
|
put_number(out, held.bump_multiplier);
|
||||||
|
}
|
||||||
|
if held.resolution != 0 {
|
||||||
|
out.append($" -texres {held.resolution}".span);
|
||||||
|
}
|
||||||
|
if held.channel != 0 {
|
||||||
|
out.append(" -imfchan ");
|
||||||
|
out.push(held.channel);
|
||||||
|
}
|
||||||
|
if held.kind.length != 0 {
|
||||||
|
out.append(" -type ");
|
||||||
|
out.append(held.kind.span);
|
||||||
|
}
|
||||||
|
out.push(' ');
|
||||||
|
out.append(held.file.span);
|
||||||
|
out.push('\n');
|
||||||
|
}
|
||||||
|
|
||||||
|
# A number, as the shortest text that reads back as it.
|
||||||
|
def put_number(out: &mut string, value: f32): void {
|
||||||
|
val text := $"{value}";
|
||||||
|
out.append(text.span);
|
||||||
|
}
|
||||||
|
|
||||||
|
def put_numbers2(out: &mut string, a: f32, b: f32): void {
|
||||||
|
put_number(out, a);
|
||||||
|
out.push(' ');
|
||||||
|
put_number(out, b);
|
||||||
|
}
|
||||||
|
|
||||||
|
def put_numbers(out: &mut string, a: f32, b: f32, c: f32): void {
|
||||||
|
put_numbers2(out, a, b);
|
||||||
|
out.push(' ');
|
||||||
|
put_number(out, c);
|
||||||
|
}
|
||||||
|
|
||||||
|
#! Writes a model to an OBJ file, and its materials, where it has any, to an MTL
|
||||||
|
#! file beside it: of the name of the first it read from, or of the OBJ file's
|
||||||
|
#! with `.mtl`. The folder is made where it isn't.
|
||||||
|
#! @param made The model.
|
||||||
|
#! @param at The OBJ file's path.
|
||||||
|
#! @returns Nothing, or why it couldn't be written: `unreadable` where a file
|
||||||
|
#! couldn't be written.
|
||||||
|
pub def save(made: &model, at: &path): result<void, obj_error> {
|
||||||
|
var folder := string::new(nothing{});
|
||||||
|
if at.parent() is some(&above) {
|
||||||
|
folder.append(above.span);
|
||||||
|
_ = io::create_directories(above);
|
||||||
|
}
|
||||||
|
var library := string::new(nothing{});
|
||||||
|
if made.materials.length != 0 {
|
||||||
|
if made.libraries.length != 0 {
|
||||||
|
library.append(made.libraries[0].span);
|
||||||
|
} else {
|
||||||
|
library.append($"{at.stem}.mtl".span);
|
||||||
|
}
|
||||||
|
var beside := string::new(nothing{});
|
||||||
|
if folder.length != 0 {
|
||||||
|
beside.append(folder.span);
|
||||||
|
beside.push('/');
|
||||||
|
}
|
||||||
|
beside.append(library.span);
|
||||||
|
val file := path::parse(beside.span) else (_) { return failed(failure::unreadable, $"{beside.span} isn't a path.".span); };
|
||||||
|
val text := encode_materials(made.materials.span);
|
||||||
|
io::write_file(&file, text.span) else (_) { return failed(failure::unreadable, $"{beside.span} couldn't be written.".span); };
|
||||||
|
}
|
||||||
|
val text := encode(made, library.span);
|
||||||
|
io::write_file(at, text.span) else (_) { return failed(failure::unreadable, $"{at.span} couldn't be written.".span); };
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
#! Writes a model to a file named by text, as `save` does.
|
||||||
|
pub def save(made: &model, at: strview): result<void, obj_error> {
|
||||||
|
val named := path::parse(at) else (_) { return failed(failure::unreadable, $"{at} isn't a path.".span); };
|
||||||
|
return save(made, &named);
|
||||||
|
}
|
||||||
@@ -0,0 +1,113 @@
|
|||||||
|
#! Contains the tests of reading accessors: integers of each size, normalized
|
||||||
|
#! or not, interleaved in a view by its stride; a matrix of bytes, each column
|
||||||
|
#! begun at a multiple of 4; and sparse values, over a view's or over zeros.
|
||||||
|
|
||||||
|
import std::io;
|
||||||
|
import std::testing;
|
||||||
|
import malunal::gltf;
|
||||||
|
|
||||||
|
# A buffer of 68 bytes, its views as `accessors_json` names them.
|
||||||
|
def accessors_buffer(): vector<u8> {
|
||||||
|
var made := packed::new();
|
||||||
|
# View 0, interleaved by 8: a color of normalized bytes, and two normalized
|
||||||
|
# shorts, for each of two elements.
|
||||||
|
for each in [255u, 0, 128, 255] { made.byte(each as u8); }
|
||||||
|
made.short(32767);
|
||||||
|
made.short(0x8000);
|
||||||
|
for each in [0u, 51, 255, 0] { made.byte(each as u8); }
|
||||||
|
made.short(0);
|
||||||
|
made.short(0xC000);
|
||||||
|
# View 1: signed bytes, -3 and 7.
|
||||||
|
made.byte(253);
|
||||||
|
made.byte(7);
|
||||||
|
made.align();
|
||||||
|
# View 2: a matrix of two columns of two bytes, each column padded to 4.
|
||||||
|
for each in [1u, 2, 0, 0, 3, 4, 0, 0] { made.byte(each as u8); }
|
||||||
|
# View 3: four floats; views 4 and 5: sparse indices 3 and 1, and their values.
|
||||||
|
val four: f32[4] = [10, 20, 30, 40];
|
||||||
|
made.floats(four[:]);
|
||||||
|
made.byte(3);
|
||||||
|
made.byte(1);
|
||||||
|
made.align();
|
||||||
|
val two: f32[2] = [-1, -2];
|
||||||
|
made.floats(two[:]);
|
||||||
|
# View 6: a sparse value of two floats; view 7: its index, 2, a short.
|
||||||
|
val pair: f32[2] = [5, 6];
|
||||||
|
made.floats(pair[:]);
|
||||||
|
made.short(2);
|
||||||
|
made.align();
|
||||||
|
return move(made.bytes);
|
||||||
|
}
|
||||||
|
|
||||||
|
def accessors_json(uri: strview): string {
|
||||||
|
var made := string::from("""
|
||||||
|
{
|
||||||
|
"asset": { "version": "2.0" },
|
||||||
|
"accessors": [
|
||||||
|
{ "bufferView": 0, "componentType": 5121, "normalized": true, "count": 2, "type": "VEC4" },
|
||||||
|
{ "bufferView": 0, "byteOffset": 4, "componentType": 5122, "normalized": true, "count": 2, "type": "VEC2" },
|
||||||
|
{ "bufferView": 1, "componentType": 5120, "count": 2, "type": "SCALAR" },
|
||||||
|
{ "bufferView": 2, "componentType": 5121, "count": 1, "type": "MAT2" },
|
||||||
|
{ "bufferView": 3, "componentType": 5126, "count": 4, "type": "SCALAR",
|
||||||
|
"sparse": { "count": 2, "indices": { "bufferView": 4, "componentType": 5121 }, "values": { "bufferView": 5 } } },
|
||||||
|
{ "componentType": 5126, "count": 3, "type": "VEC2",
|
||||||
|
"sparse": { "count": 1, "indices": { "bufferView": 7, "componentType": 5123 }, "values": { "bufferView": 6 } } },
|
||||||
|
{ "bufferView": 7, "componentType": 5123, "count": 1, "type": "SCALAR" }
|
||||||
|
],
|
||||||
|
"bufferViews": [
|
||||||
|
{ "buffer": 0, "byteOffset": 0, "byteLength": 16, "byteStride": 8 },
|
||||||
|
{ "buffer": 0, "byteOffset": 16, "byteLength": 2 },
|
||||||
|
{ "buffer": 0, "byteOffset": 20, "byteLength": 8 },
|
||||||
|
{ "buffer": 0, "byteOffset": 28, "byteLength": 16 },
|
||||||
|
{ "buffer": 0, "byteOffset": 44, "byteLength": 2 },
|
||||||
|
{ "buffer": 0, "byteOffset": 48, "byteLength": 8 },
|
||||||
|
{ "buffer": 0, "byteOffset": 56, "byteLength": 8 },
|
||||||
|
{ "buffer": 0, "byteOffset": 64, "byteLength": 2 }
|
||||||
|
],
|
||||||
|
"buffers": [{ "byteLength": 68
|
||||||
|
""", nothing{});
|
||||||
|
made.append(", \"uri\": \"");
|
||||||
|
made.append(uri);
|
||||||
|
made.append("\" }] }");
|
||||||
|
return made;
|
||||||
|
}
|
||||||
|
|
||||||
|
# The accessors' asset, read.
|
||||||
|
def read_accessors(t: &mut tester): maybe<gltf::asset> {
|
||||||
|
val bytes := accessors_buffer();
|
||||||
|
t.expects(bytes.length == 68);
|
||||||
|
val uri := data_uri(bytes.span);
|
||||||
|
val json := accessors_json(uri.span);
|
||||||
|
match gltf::decode(json.span) {
|
||||||
|
value(read) => return read;
|
||||||
|
error(e) => {
|
||||||
|
io::println(e.describe().span);
|
||||||
|
t.expects(false);
|
||||||
|
return nothing{};
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
@test def reads_numbers_of_every_size_interleaved_by_stride(t: &mut tester): void {
|
||||||
|
val read := read_accessors(t) else { return; };
|
||||||
|
val colors := read.floats(0);
|
||||||
|
t.expects(colors.length == 8 && near(colors[0], 1) && near(colors[1], 0) && near(colors[2], 128.0 / 255) && near(colors[3], 1));
|
||||||
|
t.expects(near(colors[4], 0) && near(colors[5], 0.2) && near(colors[6], 1) && near(colors[7], 0));
|
||||||
|
# A normalized short's least is -1, as -32767 is.
|
||||||
|
val shorts := read.floats(1);
|
||||||
|
t.expects(shorts.length == 4 && near(shorts[0], 1) && near(shorts[1], -1) && near(shorts[2], 0) && near(shorts[3], -16384.0 / 32767));
|
||||||
|
val signed := read.floats(2);
|
||||||
|
t.expects(signed.length == 2 && near(signed[0], -3) && near(signed[1], 7));
|
||||||
|
val matrix := read.floats(3);
|
||||||
|
t.expects(matrix.length == 4 && near(matrix[0], 1) && near(matrix[1], 2) && near(matrix[2], 3) && near(matrix[3], 4));
|
||||||
|
val index := read.integers(6);
|
||||||
|
t.expects(index.length == 1 && index[0] == 2);
|
||||||
|
}
|
||||||
|
|
||||||
|
@test def puts_sparse_values_in_place(t: &mut tester): void {
|
||||||
|
val read := read_accessors(t) else { return; };
|
||||||
|
val over_view := read.floats(4);
|
||||||
|
t.expects(over_view.length == 4 && near(over_view[0], 10) && near(over_view[1], -2) && near(over_view[2], 30) && near(over_view[3], -1));
|
||||||
|
val over_zeros := read.floats(5);
|
||||||
|
t.expects(over_zeros.length == 6 && near(over_zeros[0], 0) && near(over_zeros[3], 0) && near(over_zeros[4], 5) && near(over_zeros[5], 6));
|
||||||
|
}
|
||||||
@@ -0,0 +1,530 @@
|
|||||||
|
#! Contains the tests of `fbx`: an ASCII scene of every part read, written as
|
||||||
|
#! binary and read again; a document built by hand, written as binary of 7.4
|
||||||
|
#! and 7.5 and read back; an array compressed by zlib; models placed by FBX's
|
||||||
|
#! chain of pivots and rotations, and a scene's axes turned; a curve's values;
|
||||||
|
#! and what's refused.
|
||||||
|
|
||||||
|
import std::math;
|
||||||
|
import std::testing;
|
||||||
|
import malunal::linear;
|
||||||
|
import malunal::fbx;
|
||||||
|
|
||||||
|
# Whether two floats are within a ten-thousandth.
|
||||||
|
def close_to(a: f32, b: f32): bool {
|
||||||
|
return math::abs(a - b) < 1e-4;
|
||||||
|
}
|
||||||
|
|
||||||
|
# A scene of every part FBX's scenes hold, as ASCII: its settings, Z up and
|
||||||
|
# in meters; templates; a quad of two triangles, its normals by point, its
|
||||||
|
# places on a texture through indices, and a material for each triangle; a
|
||||||
|
# model placed with a pre-rotation, and a bone beneath it, holding a light;
|
||||||
|
# two materials, the first with a texture, whose video embeds four bytes; a
|
||||||
|
# skin of one cluster; and an animation turning the bone.
|
||||||
|
const scene_text: strview = """
|
||||||
|
; FBX 7.4.0 project file
|
||||||
|
FBXHeaderExtension: {
|
||||||
|
FBXHeaderVersion: 1003
|
||||||
|
FBXVersion: 7400
|
||||||
|
}
|
||||||
|
GlobalSettings: {
|
||||||
|
Version: 1000
|
||||||
|
Properties70: {
|
||||||
|
P: "UpAxis", "int", "Integer", "",2
|
||||||
|
P: "UpAxisSign", "int", "Integer", "",1
|
||||||
|
P: "FrontAxis", "int", "Integer", "",1
|
||||||
|
P: "FrontAxisSign", "int", "Integer", "",-1
|
||||||
|
P: "CoordAxis", "int", "Integer", "",0
|
||||||
|
P: "CoordAxisSign", "int", "Integer", "",1
|
||||||
|
P: "UnitScaleFactor", "double", "Number", "",100
|
||||||
|
P: "TimeMode", "enum", "", "",11
|
||||||
|
}
|
||||||
|
}
|
||||||
|
Definitions: {
|
||||||
|
ObjectType: "Model" {
|
||||||
|
Count: 2
|
||||||
|
PropertyTemplate: "FbxNode" {
|
||||||
|
Properties70: {
|
||||||
|
P: "Lcl Scaling", "Lcl Scaling", "", "A",1,1,1
|
||||||
|
P: "Visibility", "Visibility", "", "A",1
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
ObjectType: "Material" {
|
||||||
|
PropertyTemplate: "FbxSurfacePhong" {
|
||||||
|
Properties70: {
|
||||||
|
P: "ShininessExponent", "Number", "", "A",42
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
Objects: {
|
||||||
|
Geometry: 100, "Geometry::Quad", "Mesh" {
|
||||||
|
Vertices: *12 {
|
||||||
|
a: -1,-1,0,1,-1,0,1,1,0,-1,1,0
|
||||||
|
}
|
||||||
|
PolygonVertexIndex: *6 {
|
||||||
|
a: 0,1,-3,0,2,-4
|
||||||
|
}
|
||||||
|
LayerElementNormal: 0 {
|
||||||
|
Version: 101
|
||||||
|
MappingInformationType: "ByVertice"
|
||||||
|
ReferenceInformationType: "Direct"
|
||||||
|
Normals: *12 {
|
||||||
|
a: 0,0,1,0,0,1,0,0,1,0,0,1
|
||||||
|
}
|
||||||
|
}
|
||||||
|
LayerElementUV: 0 {
|
||||||
|
Name: "UVMap"
|
||||||
|
MappingInformationType: "ByPolygonVertex"
|
||||||
|
ReferenceInformationType: "IndexToDirect"
|
||||||
|
UV: *8 {
|
||||||
|
a: 0,0,1,0,1,1,0,1
|
||||||
|
}
|
||||||
|
UVIndex: *6 {
|
||||||
|
a: 0,1,2,0,2,3
|
||||||
|
}
|
||||||
|
}
|
||||||
|
LayerElementMaterial: 0 {
|
||||||
|
MappingInformationType: "ByPolygon"
|
||||||
|
ReferenceInformationType: "IndexToDirect"
|
||||||
|
Materials: *2 {
|
||||||
|
a: 0,1
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
Model: 200, "Model::Quad", "Mesh" {
|
||||||
|
Properties70: {
|
||||||
|
P: "Lcl Translation", "Lcl Translation", "", "A",0,0,5
|
||||||
|
P: "RotationActive", "bool", "", "",1
|
||||||
|
P: "PreRotation", "Vector3D", "Vector", "",-90,0,0
|
||||||
|
}
|
||||||
|
Shading: T
|
||||||
|
Culling: "CullingOff"
|
||||||
|
}
|
||||||
|
Model: 201, "Model::Bone", "LimbNode" {
|
||||||
|
Properties70: {
|
||||||
|
P: "Lcl Translation", "Lcl Translation", "", "A",0,2,0
|
||||||
|
P: "Lcl Rotation", "Lcl Rotation", "", "A",0,0,90
|
||||||
|
}
|
||||||
|
}
|
||||||
|
Material: 300, "Material::Red", "" {
|
||||||
|
ShadingModel: "phong"
|
||||||
|
Properties70: {
|
||||||
|
P: "DiffuseColor", "Color", "", "A",1,0,0
|
||||||
|
}
|
||||||
|
}
|
||||||
|
Material: 301, "Material::Blue", "" {
|
||||||
|
ShadingModel: "lambert"
|
||||||
|
}
|
||||||
|
Texture: 400, "Texture::Bricks", "" {
|
||||||
|
FileName: "C:/textures/bricks.png"
|
||||||
|
RelativeFilename: "textures/bricks.png"
|
||||||
|
Properties70: {
|
||||||
|
P: "UVSet", "KString", "", "", "UVMap"
|
||||||
|
}
|
||||||
|
}
|
||||||
|
Video: 500, "Video::Bricks", "Clip" {
|
||||||
|
Content: , "AAEC/w=="
|
||||||
|
RelativeFilename: "textures/bricks.png"
|
||||||
|
}
|
||||||
|
NodeAttribute: 600, "NodeAttribute::Sun", "Light" {
|
||||||
|
Properties70: {
|
||||||
|
P: "LightType", "enum", "", "",1
|
||||||
|
P: "Intensity", "Number", "", "A",150
|
||||||
|
}
|
||||||
|
}
|
||||||
|
Deformer: 700, "Deformer::Skin", "Skin" {
|
||||||
|
}
|
||||||
|
Deformer: 701, "SubDeformer::Bone", "Cluster" {
|
||||||
|
Indexes: *2 {
|
||||||
|
a: 0,1
|
||||||
|
}
|
||||||
|
Weights: *2 {
|
||||||
|
a: 1,0.5
|
||||||
|
}
|
||||||
|
Transform: *16 {
|
||||||
|
a: 1,0,0,0,0,1,0,0,0,0,1,0,0,0,0,1
|
||||||
|
}
|
||||||
|
TransformLink: *16 {
|
||||||
|
a: 1,0,0,0,0,1,0,0,0,0,1,0,0,2,0,1
|
||||||
|
}
|
||||||
|
}
|
||||||
|
AnimationStack: 800, "AnimStack::Wave", "" {
|
||||||
|
Properties70: {
|
||||||
|
P: "LocalStop", "KTime", "Time", "",46186158000
|
||||||
|
}
|
||||||
|
}
|
||||||
|
AnimationLayer: 801, "AnimLayer::Base", "" {
|
||||||
|
}
|
||||||
|
AnimationCurveNode: 802, "AnimCurveNode::R", "" {
|
||||||
|
Properties70: {
|
||||||
|
P: "d|X", "Number", "", "A",0
|
||||||
|
P: "d|Y", "Number", "", "A",0
|
||||||
|
P: "d|Z", "Number", "", "A",90
|
||||||
|
}
|
||||||
|
}
|
||||||
|
AnimationCurve: 803, "AnimCurve::", "" {
|
||||||
|
Default: 90
|
||||||
|
KeyVer: 4008
|
||||||
|
KeyTime: *2 {
|
||||||
|
a: 0,46186158000
|
||||||
|
}
|
||||||
|
KeyValueFloat: *2 {
|
||||||
|
a: 90,180
|
||||||
|
}
|
||||||
|
KeyAttrFlags: *1 {
|
||||||
|
a: 4
|
||||||
|
}
|
||||||
|
KeyAttrDataFloat: *4 {
|
||||||
|
a: 0,0,0,0
|
||||||
|
}
|
||||||
|
KeyAttrRefCount: *1 {
|
||||||
|
a: 2
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
Connections: {
|
||||||
|
;Model::Quad, Model::RootNode
|
||||||
|
C: "OO",200,0
|
||||||
|
C: "OO",201,200
|
||||||
|
C: "OO",100,200
|
||||||
|
C: "OO",300,200
|
||||||
|
C: "OO",301,200
|
||||||
|
C: "OP",400,300, "DiffuseColor"
|
||||||
|
C: "OO",500,400
|
||||||
|
C: "OO",600,201
|
||||||
|
C: "OO",700,100
|
||||||
|
C: "OO",701,700
|
||||||
|
C: "OO",201,701
|
||||||
|
C: "OO",801,800
|
||||||
|
C: "OO",802,801
|
||||||
|
C: "OP",802,201, "Lcl Rotation"
|
||||||
|
C: "OP",803,802, "d|Z"
|
||||||
|
}
|
||||||
|
""";
|
||||||
|
|
||||||
|
# Checks the scene read of `scene_text`, whichever way it was written.
|
||||||
|
def expect_scene(t: &mut tester, s: &fbx::scene): void {
|
||||||
|
t.expects(s.settings.up_axis == 2 && s.settings.front_sign == -1 && close_to(s.settings.meters_per_unit(), 1) && s.settings.frame_rate == 24);
|
||||||
|
t.expects(s.meshes.length == 1 && s.models.length == 2 && s.materials.length == 2 && s.textures.length == 1 && s.videos.length == 1);
|
||||||
|
val quad := &s.meshes[0];
|
||||||
|
t.expects(quad.name.span == "Quad" && quad.positions.length == 4 && quad.polygons.length == 2 && quad.polygons[1].first == 3 && quad.polygons[1].count == 3);
|
||||||
|
t.expects(quad.corners.length == 6 && quad.corners[2] == 2 && quad.corners[5] == 3);
|
||||||
|
t.expects(quad.normals.length == 6 && close_to(quad.normals[5].z, 1));
|
||||||
|
t.expects(quad.uv_sets.length == 1 && quad.uv_sets[0].name.span == "UVMap" && close_to(quad.uv_sets[0].uvs[4].x, 1) && close_to(quad.uv_sets[0].uvs[5].y, 1) && close_to(quad.uv_sets[0].uvs[5].x, 0));
|
||||||
|
t.expects(quad.materials.length == 2 && quad.materials[0] == 0 && quad.materials[1] == 1);
|
||||||
|
# The tree, and what's whose.
|
||||||
|
val square := &s.models[0];
|
||||||
|
t.expects(square.name.span == "Quad" && square.kind.span == "Mesh" && square.parent == fbx::absent && square.mesh == 0 && square.materials.length == 2 && square.materials[1] == 1);
|
||||||
|
t.expects(s.roots.length == 1 && s.roots[0] == 0 && square.children.length == 1 && square.children[0] == 1);
|
||||||
|
t.expects(close_to(square.translation.z, 5) && square.rotation_active && close_to(square.pre_rotation.x, -90) && close_to(square.scale.y, 1) && square.visible);
|
||||||
|
val bone := &s.models[1];
|
||||||
|
t.expects(bone.kind.span == "LimbNode" && bone.parent == 0 && bone.light == 0 && close_to(bone.rotation.z, 90));
|
||||||
|
# The bone's place: 2 up, turned by its parent's pre-rotation to 2 back, from 5 forward.
|
||||||
|
val placed := s.world_matrix(1);
|
||||||
|
t.expects(close_to(placed.m[12], 0) && close_to(placed.m[13], 0) && close_to(placed.m[14], 3));
|
||||||
|
# Materials, their template's values, and their textures.
|
||||||
|
val red := &s.materials[0];
|
||||||
|
t.expects(red.name.span == "Red" && red.shading.span == "phong" && close_to(red.diffuse.x, 1) && close_to(red.diffuse.y, 0) && close_to(red.shininess, 42));
|
||||||
|
t.expects(red.map("DiffuseColor") is some(k) && k == 0 && red.map("NormalMap") is none);
|
||||||
|
t.expects(close_to(s.materials[1].diffuse.x, 0.8) && close_to(s.materials[1].shininess, 42) && s.materials[1].shading.span == "lambert");
|
||||||
|
val bricks := &s.textures[0];
|
||||||
|
t.expects(bricks.file.span == "C:/textures/bricks.png" && bricks.relative.span == "textures/bricks.png" && bricks.uv_set.span == "UVMap" && bricks.video == 0);
|
||||||
|
val held := &s.videos[0].content;
|
||||||
|
t.expects(held.length == 4 && held[0] == 0 && held[2] == 2 && held[3] == 255);
|
||||||
|
t.expects(s.lights.length == 1 && s.lights[0].kind == fbx::light_kind::directional && close_to(s.lights[0].intensity, 150));
|
||||||
|
# The skin, its cluster, and its bone.
|
||||||
|
t.expects(s.skins.length == 1 && s.skins[0].mesh == 0 && quad.skin == 0 && s.skins[0].clusters.length == 1);
|
||||||
|
val bound := &s.clusters[0];
|
||||||
|
t.expects(bound.bone == 1 && bound.points.length == 2 && bound.points[1] == 1 && close_to(bound.weights[1], 0.5) && close_to(bound.transform_link.m[13], 2));
|
||||||
|
# The animation, what it turns, and its curve.
|
||||||
|
t.expects(s.stacks.length == 1 && s.stacks[0].stop == 1 && s.stacks[0].layers.length == 1 && s.layers[0].curve_nodes.length == 1);
|
||||||
|
val turning := &s.curve_nodes[0];
|
||||||
|
t.expects(turning.target_kind == fbx::part_kind::model && turning.target == 1 && turning.property.span == "Lcl Rotation" && turning.channels.length == 3);
|
||||||
|
if turning.channel("Z") is some(&z) {
|
||||||
|
t.expects(z.curve == 0 && close_to(z.value, 90));
|
||||||
|
} else {
|
||||||
|
t.expects(false);
|
||||||
|
}
|
||||||
|
t.expects(turning.channel("X") is some(&x) && x.curve == fbx::absent);
|
||||||
|
val wave := &s.curves[0];
|
||||||
|
t.expects(wave.times.length == 2 && wave.times[1] == 1 && wave.interpolations[0] == fbx::key_interpolation::linear && close_to(wave.at(0.5), 135) && close_to(wave.at(2), 180));
|
||||||
|
}
|
||||||
|
|
||||||
|
@test def reads_an_ascii_scene_of_every_part(t: &mut tester): void {
|
||||||
|
var doc := fbx::decode(scene_text).expect("The scene is read.");
|
||||||
|
t.expects(doc.version == 7400 && !doc.binary);
|
||||||
|
if doc.child(fbx::absent, "Objects") is some(objects) {
|
||||||
|
t.expects(doc.nodes[objects as u64].children.length == 14);
|
||||||
|
} else {
|
||||||
|
t.expects(false);
|
||||||
|
}
|
||||||
|
val s := fbx::scene::of(move(doc)).expect("The scene's objects are read.");
|
||||||
|
expect_scene(t, &s);
|
||||||
|
}
|
||||||
|
|
||||||
|
@test def writes_a_scene_as_binary_and_reads_it_again(t: &mut tester): void {
|
||||||
|
val doc := fbx::decode(scene_text).expect("The scene is read.");
|
||||||
|
val bytes := fbx::encode(&doc).expect("It's written.");
|
||||||
|
# The header, and Autodesk's footer.
|
||||||
|
t.expects(bytes.length > 200 && bytes[0] == 'K' && bytes[21] == 0x1A && bytes[bytes.length - 1] == 0x0B && bytes[bytes.length - 16] == 0xF8);
|
||||||
|
var again := fbx::decode(bytes.span).expect("It's read again.");
|
||||||
|
t.expects(again.binary && again.version == 7400 && again.nodes.length == doc.nodes.length);
|
||||||
|
val s := fbx::scene::of(move(again)).expect("The scene's objects are read.");
|
||||||
|
expect_scene(t, &s);
|
||||||
|
}
|
||||||
|
|
||||||
|
# A name as binary FBX writes it: the name, two bytes 0 and 1, and its class.
|
||||||
|
def binary_name(name: strview, class_name: strview): string {
|
||||||
|
var made := string::from(name, nothing{});
|
||||||
|
made.push(0);
|
||||||
|
made.push(1);
|
||||||
|
made.append(class_name);
|
||||||
|
return made;
|
||||||
|
}
|
||||||
|
|
||||||
|
# A document built by hand: a header, a quad's geometry, its model, and the
|
||||||
|
# connections between them.
|
||||||
|
def built_document(version: u32): fbx::document {
|
||||||
|
var doc := fbx::document{ version = version };
|
||||||
|
val header := doc.add(fbx::absent, "FBXHeaderExtension");
|
||||||
|
val stated := doc.add(header, "FBXVersion");
|
||||||
|
doc.nodes[stated as u64].properties.append(fbx::property::of_int32(version as i32));
|
||||||
|
val objects := doc.add(fbx::absent, "Objects");
|
||||||
|
val geometry := doc.add(objects, "Geometry");
|
||||||
|
val geometry_name := binary_name("Quad", "Geometry");
|
||||||
|
doc.nodes[geometry as u64].properties.append(fbx::property::of_int64(100));
|
||||||
|
doc.nodes[geometry as u64].properties.append(fbx::property::of_text(geometry_name.span));
|
||||||
|
doc.nodes[geometry as u64].properties.append(fbx::property::of_text("Mesh"));
|
||||||
|
val places: f64[12] = [-1, -1, 0, 1, -1, 0, 1, 1, 0, -1, 1, 0];
|
||||||
|
val vertices := doc.add(geometry, "Vertices");
|
||||||
|
doc.nodes[vertices as u64].properties.append(fbx::property::of_reals(fbx::property_kind::float64s, places[:]));
|
||||||
|
val corners: i64[6] = [0, 1, -3, 0, 2, -4];
|
||||||
|
val polygons := doc.add(geometry, "PolygonVertexIndex");
|
||||||
|
doc.nodes[polygons as u64].properties.append(fbx::property::of_integers(fbx::property_kind::int32s, corners[:]));
|
||||||
|
val model := doc.add(objects, "Model");
|
||||||
|
val model_name := binary_name("Quad", "Model");
|
||||||
|
doc.nodes[model as u64].properties.append(fbx::property::of_int64(200));
|
||||||
|
doc.nodes[model as u64].properties.append(fbx::property::of_text(model_name.span));
|
||||||
|
doc.nodes[model as u64].properties.append(fbx::property::of_text("Mesh"));
|
||||||
|
val properties := doc.add(model, "Properties70");
|
||||||
|
val moved := doc.add(properties, "P");
|
||||||
|
doc.nodes[moved as u64].properties.append(fbx::property::of_text("Lcl Translation"));
|
||||||
|
doc.nodes[moved as u64].properties.append(fbx::property::of_text("Lcl Translation"));
|
||||||
|
doc.nodes[moved as u64].properties.append(fbx::property::of_text(""));
|
||||||
|
doc.nodes[moved as u64].properties.append(fbx::property::of_text("A"));
|
||||||
|
doc.nodes[moved as u64].properties.append(fbx::property::of_float64(0));
|
||||||
|
doc.nodes[moved as u64].properties.append(fbx::property::of_float64(0));
|
||||||
|
doc.nodes[moved as u64].properties.append(fbx::property::of_float64(5));
|
||||||
|
val shown := doc.add(model, "Shading");
|
||||||
|
doc.nodes[shown as u64].properties.append(fbx::property::of_bool(true));
|
||||||
|
val flags := doc.add(model, "Flags");
|
||||||
|
doc.nodes[flags as u64].properties.append(fbx::property::of_float32(1.5));
|
||||||
|
val connections := doc.add(fbx::absent, "Connections");
|
||||||
|
val pairs: i64[4] = [200, 0, 100, 200];
|
||||||
|
for k in 0..2u {
|
||||||
|
val link := doc.add(connections, "C");
|
||||||
|
doc.nodes[link as u64].properties.append(fbx::property::of_text("OO"));
|
||||||
|
doc.nodes[link as u64].properties.append(fbx::property::of_int64(pairs[k * 2]));
|
||||||
|
doc.nodes[link as u64].properties.append(fbx::property::of_int64(pairs[k * 2 + 1]));
|
||||||
|
}
|
||||||
|
return doc;
|
||||||
|
}
|
||||||
|
|
||||||
|
@test def writes_a_built_document_as_binary_of_both_widths(t: &mut tester): void {
|
||||||
|
for k in 0..2u {
|
||||||
|
val version: u32 = k == 0 ? 7400 : 7500;
|
||||||
|
val doc := built_document(version);
|
||||||
|
val bytes := fbx::encode(&doc).expect("It's written.");
|
||||||
|
var read := fbx::decode(bytes.span).expect("It's read back.");
|
||||||
|
t.expects(read.version == version && read.nodes.length == doc.nodes.length && read.roots.length == 3);
|
||||||
|
for i in 0..doc.nodes.length {
|
||||||
|
val a := &doc.nodes[i];
|
||||||
|
val b := &read.nodes[i];
|
||||||
|
t.expects(a.name.span == b.name.span && a.properties.length == b.properties.length && a.children.length == b.children.length && a.parent == b.parent);
|
||||||
|
for p in 0..a.properties.length {
|
||||||
|
t.expects(a.properties[p].kind == b.properties[p].kind && a.properties[p].integer == b.properties[p].integer && a.properties[p].real == b.properties[p].real);
|
||||||
|
t.expects(a.properties[p].text() == b.properties[p].text() && a.properties[p].count() == b.properties[p].count());
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if read.child(fbx::absent, "Objects") is some(objects) && read.child(objects, "Geometry") is some(geometry) && read.child(geometry, "PolygonVertexIndex") is some(indices) {
|
||||||
|
val values := read.integers(indices);
|
||||||
|
t.expects(values.length == 6 && values[2] == -3 && values[5] == -4);
|
||||||
|
} else {
|
||||||
|
t.expects(false);
|
||||||
|
}
|
||||||
|
val s := fbx::scene::of(move(read)).expect("Its scene is read.");
|
||||||
|
t.expects(s.models.length == 1 && s.models[0].name.span == "Quad" && s.models[0].mesh == 0 && close_to(s.models[0].translation.z, 5));
|
||||||
|
t.expects(s.meshes.length == 1 && s.meshes[0].name.span == "Quad" && s.meshes[0].polygons.length == 2 && close_to(s.meshes[0].positions[2].y, 1));
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
# The Adler-32 of bytes.
|
||||||
|
def adler_of(data: span<u8>): u32 {
|
||||||
|
var low: u32 = 1;
|
||||||
|
var high: u32 = 0;
|
||||||
|
for byte in data {
|
||||||
|
low = (low + byte as u32) % 65521;
|
||||||
|
high = (high + low) % 65521;
|
||||||
|
}
|
||||||
|
return (high << 16) | low;
|
||||||
|
}
|
||||||
|
|
||||||
|
def put_word(out: &mut vector<u8>, value: u32): void {
|
||||||
|
for i in 0..4u {
|
||||||
|
out.append(((value >> (8 * i)) & 0xFF) as u8);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
@test def reads_an_array_compressed_by_zlib(t: &mut tester): void {
|
||||||
|
# Two doubles, 0.5 and -2, compressed as a stored block within zlib.
|
||||||
|
var raw := vector::<u8>::new();
|
||||||
|
for value in [0.5, -2.0] {
|
||||||
|
val bits := math::bits_of(value as f64);
|
||||||
|
for i in 0..8u {
|
||||||
|
raw.append(((bits >> (8 * i)) & 0xFF) as u8);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
var zlib := vector::<u8>::new();
|
||||||
|
zlib.append(0x78);
|
||||||
|
zlib.append(0x01);
|
||||||
|
zlib.append(0x01);
|
||||||
|
zlib.append(16);
|
||||||
|
zlib.append(0);
|
||||||
|
zlib.append(0xEF);
|
||||||
|
zlib.append(0xFF);
|
||||||
|
zlib.extend(raw.span);
|
||||||
|
val sum := adler_of(raw.span);
|
||||||
|
for i in 0..4u {
|
||||||
|
zlib.append(((sum >> (8 * (3 - i))) & 0xFF) as u8);
|
||||||
|
}
|
||||||
|
# A node `A` of that array, then the record of zeros ending the root.
|
||||||
|
var file := vector::<u8>::new();
|
||||||
|
file.extend("Kaydara FBX Binary ");
|
||||||
|
file.append(0);
|
||||||
|
file.append(0x1A);
|
||||||
|
file.append(0);
|
||||||
|
put_word(&mut file, 7400);
|
||||||
|
val properties := 1 + 12 + zlib.length;
|
||||||
|
val end := file.length + 13 + 1 + properties;
|
||||||
|
put_word(&mut file, end as u32);
|
||||||
|
put_word(&mut file, 1);
|
||||||
|
put_word(&mut file, properties as u32);
|
||||||
|
file.append(1);
|
||||||
|
file.append('A');
|
||||||
|
file.append('d');
|
||||||
|
put_word(&mut file, 2);
|
||||||
|
put_word(&mut file, 1);
|
||||||
|
put_word(&mut file, zlib.length as u32);
|
||||||
|
file.extend(zlib.span);
|
||||||
|
for _ in 0..13u {
|
||||||
|
file.append(0);
|
||||||
|
}
|
||||||
|
val doc := fbx::decode(file.span).expect("The compressed array is read.");
|
||||||
|
t.expects(doc.nodes.length == 1 && doc.nodes[0].name.span == "A" && doc.nodes[0].properties[0].kind == fbx::property_kind::float64s);
|
||||||
|
val values := doc.reals(0);
|
||||||
|
t.expects(values.length == 2 && values[0] == 0.5 && values[1] == -2);
|
||||||
|
# Its checksum broken, it won't inflate.
|
||||||
|
file[file.length - 14] = file[file.length - 14] ^ 0xFF;
|
||||||
|
t.expects(fbx::decode(file.span) is error(e) && e.kind == fbx::failure::malformed);
|
||||||
|
}
|
||||||
|
|
||||||
|
@test def places_models_by_fbx_chain_of_pivots_and_rotations(t: &mut tester): void {
|
||||||
|
# Turned a quarter about z, about a pivot at x = 1.
|
||||||
|
var pivoted := fbx::model{};
|
||||||
|
pivoted.rotation = vec3{ 0, 0, 90 };
|
||||||
|
pivoted.rotation_pivot = vec3{ 1, 0, 0 };
|
||||||
|
val turned := pivoted.local_matrix().transform_point(vec3{ 2, 0, 0 });
|
||||||
|
t.expects(close_to(turned.x, 1) && close_to(turned.y, 1) && close_to(turned.z, 0));
|
||||||
|
# Scaled twice about a pivot at x = 1.
|
||||||
|
var scaled := fbx::model{};
|
||||||
|
scaled.scale = vec3{ 2, 2, 2 };
|
||||||
|
scaled.scaling_pivot = vec3{ 1, 0, 0 };
|
||||||
|
val grown := scaled.local_matrix().transform_point(vec3{ 2, 0, 0 });
|
||||||
|
t.expects(close_to(grown.x, 3) && close_to(grown.y, 0));
|
||||||
|
# The order of a rotation: x first, or z first; and an order not active is
|
||||||
|
# taken as x first.
|
||||||
|
var ordered := fbx::model{};
|
||||||
|
ordered.rotation = vec3{ 90, 90, 0 };
|
||||||
|
val first_x := ordered.local_matrix().transform_point(vec3{ 0, 1, 0 });
|
||||||
|
t.expects(close_to(first_x.x, 1) && close_to(first_x.z, 0));
|
||||||
|
ordered.order = fbx::rotation_order::zyx;
|
||||||
|
ordered.rotation_active = true;
|
||||||
|
val first_z := ordered.local_matrix().transform_point(vec3{ 0, 1, 0 });
|
||||||
|
t.expects(close_to(first_z.z, 1) && close_to(first_z.x, 0));
|
||||||
|
ordered.rotation_active = false;
|
||||||
|
val inactive := ordered.local_matrix().transform_point(vec3{ 0, 1, 0 });
|
||||||
|
t.expects(close_to(inactive.x, 1));
|
||||||
|
# A post-rotation is turned back.
|
||||||
|
var posted := fbx::model{ rotation_active = true };
|
||||||
|
posted.post_rotation = vec3{ 0, 0, 90 };
|
||||||
|
val back := posted.local_matrix().transform_point(vec3{ 1, 0, 0 });
|
||||||
|
t.expects(close_to(back.y, -1));
|
||||||
|
# Z up, -y to the front, in centimeters, turned to y up and meters.
|
||||||
|
val zup := fbx::settings{ up_axis = 2, front_axis = 1, front_sign = -1 };
|
||||||
|
val up := zup.axes().transform_point(vec3{ 0, 0, 1 });
|
||||||
|
val front := zup.conversion().transform_point(vec3{ 0, -100, 0 });
|
||||||
|
t.expects(close_to(up.y, 1) && close_to(front.z, 1) && close_to(front.y, 0));
|
||||||
|
}
|
||||||
|
|
||||||
|
@test def gives_a_curve_s_values_between_its_keys(t: &mut tester): void {
|
||||||
|
var held := fbx::curve{ value = 7 };
|
||||||
|
t.expects(held.at(1) == 7);
|
||||||
|
held.times.append(0);
|
||||||
|
held.times.append(1);
|
||||||
|
held.times.append(2);
|
||||||
|
held.values.append(0);
|
||||||
|
held.values.append(10);
|
||||||
|
held.values.append(10);
|
||||||
|
held.interpolations.append(fbx::key_interpolation::constant);
|
||||||
|
held.interpolations.append(fbx::key_interpolation::cubic);
|
||||||
|
held.interpolations.append(fbx::key_interpolation::linear);
|
||||||
|
held.right_slopes.append(0);
|
||||||
|
held.right_slopes.append(0);
|
||||||
|
held.right_slopes.append(0);
|
||||||
|
held.next_left_slopes.append(0);
|
||||||
|
held.next_left_slopes.append(0);
|
||||||
|
held.next_left_slopes.append(0);
|
||||||
|
t.expects(held.at(-1) == 0 && held.at(0.5) == 0 && held.at(3) == 10);
|
||||||
|
# A cubic of flat slopes, between equal values, stays.
|
||||||
|
t.expects(close_to(held.at(1.5), 10));
|
||||||
|
}
|
||||||
|
|
||||||
|
# Whether bytes are refused as a kind, saying what's given.
|
||||||
|
def refused(bytes: span<u8>, kind: fbx::failure, says: strview): bool {
|
||||||
|
if fbx::decode(bytes) is error(e) {
|
||||||
|
val why := e.describe();
|
||||||
|
return e.kind == kind && why.span.find(says) is some(_);
|
||||||
|
}
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
|
||||||
|
@test def refuses_what_breaks_fbx(t: &mut tester): void {
|
||||||
|
val doc := built_document(7400);
|
||||||
|
var bytes := fbx::encode(&doc).expect("It's written.");
|
||||||
|
# Cut short, and a property of a type FBX hasn't.
|
||||||
|
var cut := vector::<u8>::new();
|
||||||
|
cut.extend(bytes.span[0:60]);
|
||||||
|
t.expects(refused(cut.span, fbx::failure::malformed, "past the file's end"));
|
||||||
|
var wrong := vector::<u8>::new();
|
||||||
|
wrong.extend(bytes.span);
|
||||||
|
# The first property of the first node, `FBXHeaderExtension`'s child, is
|
||||||
|
# `FBXVersion`'s, after its header and name.
|
||||||
|
val first: u64 = 27 + 13 + 18 + 13 + 10;
|
||||||
|
t.expects(wrong[first] == 'I');
|
||||||
|
wrong[first] = 'Z';
|
||||||
|
t.expects(refused(wrong.span, fbx::failure::malformed, "isn't FBX's"));
|
||||||
|
# Before 7.0.
|
||||||
|
var old := vector::<u8>::new();
|
||||||
|
old.extend(bytes.span);
|
||||||
|
old[23] = 0xD4;
|
||||||
|
old[24] = 0x17;
|
||||||
|
t.expects(refused(old.span, fbx::failure::unsupported, "6100"));
|
||||||
|
# ASCII unclosed, of an array short, and of version 6.
|
||||||
|
t.expects(refused("Objects: {\n Model: 1, \"Model::A\", \"Null\" {\n", fbx::failure::malformed, "isn't closed"));
|
||||||
|
t.expects(refused("Objects: {\n Geometry: 1, \"Geometry::A\", \"Mesh\" {\n Vertices: *3 {\n a: 0,0\n }\n }\n}\n", fbx::failure::malformed, "holds 2"));
|
||||||
|
t.expects(refused("FBXHeaderExtension: {\n FBXVersion: 6100\n}\n", fbx::failure::unsupported, "6100"));
|
||||||
|
# A polygon naming a point the mesh hasn't.
|
||||||
|
var broken := fbx::decode("Objects: {\n Geometry: 1, \"Geometry::A\", \"Mesh\" {\n Vertices: *3 {\n a: 0,0,0\n }\n PolygonVertexIndex: *3 {\n a: 0,0,-3\n }\n }\n}\n").expect("The text is read.");
|
||||||
|
t.expects(fbx::scene::of(move(broken)) is error(e) && e.kind == fbx::failure::malformed);
|
||||||
|
}
|
||||||
@@ -0,0 +1,10 @@
|
|||||||
|
#! Contains the `main` that runs gltf's tests, each in a copy of the program of
|
||||||
|
#! its own. `blossom test` runs them, and `-- --only TEXT` those whose name
|
||||||
|
#! holds the text.
|
||||||
|
|
||||||
|
import system;
|
||||||
|
import std::testing;
|
||||||
|
|
||||||
|
def main(args: span<strview>): void {
|
||||||
|
exit(tester::run(args));
|
||||||
|
}
|
||||||
@@ -0,0 +1,119 @@
|
|||||||
|
#! Contains the tests of the tree of nodes: a matrix taken apart into a
|
||||||
|
#! translation, rotation, and scale, one mirroring, those put together, and
|
||||||
|
#! where a child is in the world; and the cameras, lights, skins, and
|
||||||
|
#! animations nodes name.
|
||||||
|
|
||||||
|
import std::io;
|
||||||
|
import std::testing;
|
||||||
|
import malunal::linear;
|
||||||
|
import malunal::gltf;
|
||||||
|
|
||||||
|
# A buffer of two identity matrices, two times, and two translations.
|
||||||
|
def nodes_buffer(): vector<u8> {
|
||||||
|
var made := packed::new();
|
||||||
|
val identity: f32[16] = [1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1];
|
||||||
|
made.floats(identity[:]);
|
||||||
|
made.floats(identity[:]);
|
||||||
|
val times: f32[2] = [0, 1];
|
||||||
|
made.floats(times[:]);
|
||||||
|
val places: f32[6] = [0, 0, 3, 0, 1, 3];
|
||||||
|
made.floats(places[:]);
|
||||||
|
return move(made.bytes);
|
||||||
|
}
|
||||||
|
|
||||||
|
# A root turned a quarter about y, scaled by 2, and moved 1 along x, as a
|
||||||
|
# matrix; a child of it 3 along z, as a translation, with a camera and a spot
|
||||||
|
# light; a node mirrored in x; and one with a skin.
|
||||||
|
def nodes_json(uri: strview): string {
|
||||||
|
var made := string::from("""
|
||||||
|
{
|
||||||
|
"asset": { "version": "2.0" },
|
||||||
|
"extensionsUsed": ["KHR_lights_punctual"],
|
||||||
|
"extensions": { "KHR_lights_punctual": { "lights": [
|
||||||
|
{ "name": "lamp", "type": "spot", "color": [1, 0.5, 0], "intensity": 20, "range": 8, "spot": { "outerConeAngle": 0.5 } }
|
||||||
|
] } },
|
||||||
|
"scenes": [{ "nodes": [0, 2, 3] }],
|
||||||
|
"nodes": [
|
||||||
|
{ "name": "Root", "children": [1], "matrix": [0, 0, -2, 0, 0, 2, 0, 0, 2, 0, 0, 0, 1, 0, 0, 1] },
|
||||||
|
{ "name": "Child", "translation": [0, 0, 3], "camera": 0, "extensions": { "KHR_lights_punctual": { "light": 0 } } },
|
||||||
|
{ "name": "Mirror", "matrix": [-1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1] },
|
||||||
|
{ "name": "Skinned", "skin": 0 }
|
||||||
|
],
|
||||||
|
"cameras": [
|
||||||
|
{ "type": "perspective", "perspective": { "yfov": 0.8, "znear": 0.1 } },
|
||||||
|
{ "type": "orthographic", "orthographic": { "xmag": 2, "ymag": 1, "znear": 0, "zfar": 10 } }
|
||||||
|
],
|
||||||
|
"skins": [{ "joints": [0, 1], "inverseBindMatrices": 0 }],
|
||||||
|
"animations": [{ "name": "rise",
|
||||||
|
"channels": [{ "sampler": 0, "target": { "node": 1, "path": "translation" } }],
|
||||||
|
"samplers": [{ "input": 1, "output": 2, "interpolation": "STEP" }]
|
||||||
|
}],
|
||||||
|
"accessors": [
|
||||||
|
{ "bufferView": 0, "componentType": 5126, "count": 2, "type": "MAT4" },
|
||||||
|
{ "bufferView": 1, "componentType": 5126, "count": 2, "type": "SCALAR" },
|
||||||
|
{ "bufferView": 2, "componentType": 5126, "count": 2, "type": "VEC3" }
|
||||||
|
],
|
||||||
|
"bufferViews": [
|
||||||
|
{ "buffer": 0, "byteOffset": 0, "byteLength": 128 },
|
||||||
|
{ "buffer": 0, "byteOffset": 128, "byteLength": 8 },
|
||||||
|
{ "buffer": 0, "byteOffset": 136, "byteLength": 24 }
|
||||||
|
],
|
||||||
|
"buffers": [{ "byteLength": 160
|
||||||
|
""", nothing{});
|
||||||
|
made.append(", \"uri\": \"");
|
||||||
|
made.append(uri);
|
||||||
|
made.append("\" }] }");
|
||||||
|
return made;
|
||||||
|
}
|
||||||
|
|
||||||
|
def read_nodes(t: &mut tester): maybe<gltf::asset> {
|
||||||
|
val bytes := nodes_buffer();
|
||||||
|
val uri := data_uri(bytes.span);
|
||||||
|
val json := nodes_json(uri.span);
|
||||||
|
match gltf::decode(json.span) {
|
||||||
|
value(read) => return read;
|
||||||
|
error(e) => {
|
||||||
|
io::println(e.describe().span);
|
||||||
|
t.expects(false);
|
||||||
|
return nothing{};
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
@test def takes_matrices_apart_and_puts_transforms_together(t: &mut tester): void {
|
||||||
|
val read := read_nodes(t) else { return; };
|
||||||
|
val root := &read.nodes[0];
|
||||||
|
t.expects(near(root.translation.x, 1) && near(root.translation.z, 0));
|
||||||
|
t.expects(near(root.scale.x, 2) && near(root.scale.y, 2) && near(root.scale.z, 2));
|
||||||
|
# A quarter turn about y.
|
||||||
|
t.expects(near(root.rotation.x, 0) && near(root.rotation.y, 0.70710677) && near(root.rotation.z, 0) && near(root.rotation.w, 0.70710677));
|
||||||
|
val child := &read.nodes[1];
|
||||||
|
t.expects(child.parent is some(p) && p == 0 && near(child.matrix.m[14], 3) && root.parent is none);
|
||||||
|
# Its place, 3 along z, turned to x, doubled, and moved 1 along x.
|
||||||
|
val world := read.world_matrix(1);
|
||||||
|
t.expects(near(world.m[12], 7) && near(world.m[13], 0) && near(world.m[14], 0));
|
||||||
|
val mirror := &read.nodes[2];
|
||||||
|
t.expects(near(mirror.scale.x, -1) && near(mirror.scale.y, 1) && near(mirror.rotation.w, 1));
|
||||||
|
val roots := read.roots();
|
||||||
|
t.expects(roots.length == 3 && roots[0] == 0 && roots[1] == 2 && roots[2] == 3);
|
||||||
|
}
|
||||||
|
|
||||||
|
@test def reads_cameras_lights_skins_and_animations(t: &mut tester): void {
|
||||||
|
val read := read_nodes(t) else { return; };
|
||||||
|
t.expects(read.cameras.length == 2 && read.nodes[1].camera is some(c) && c == 0);
|
||||||
|
val eye := &read.cameras[0];
|
||||||
|
t.expects(eye.kind == gltf::camera_kind::perspective && near(eye.fov_y, 0.8) && eye.aspect is none && eye.far is none);
|
||||||
|
val plan := &read.cameras[1];
|
||||||
|
t.expects(plan.kind == gltf::camera_kind::orthographic && near(plan.x_mag, 2) && plan.far is some(f) && near(f, 10));
|
||||||
|
t.expects(read.lights.length == 1 && read.nodes[1].light is some(l) && l == 0);
|
||||||
|
val lamp := &read.lights[0];
|
||||||
|
t.expects(lamp.kind == gltf::light_kind::spot && lamp.name.span == "lamp" && near(lamp.color[1], 0.5) && near(lamp.intensity, 20));
|
||||||
|
t.expects(lamp.range is some(r) && near(r, 8) && near(lamp.inner_cone, 0) && near(lamp.outer_cone, 0.5));
|
||||||
|
t.expects(read.skins.length == 1 && read.skins[0].joints.length == 2 && read.nodes[3].skin is some(s) && s == 0);
|
||||||
|
t.expects(read.floats(0).length == 32);
|
||||||
|
val rise := &read.animations[0];
|
||||||
|
t.expects(rise.name.span == "rise" && rise.channels.length == 1 && rise.channels[0].path == gltf::target_path::translation);
|
||||||
|
t.expects(rise.channels[0].node is some(n) && n == 1 && rise.samplers[0].interpolation == gltf::interpolation::step);
|
||||||
|
val keys := read.floats(rise.samplers[0].output);
|
||||||
|
t.expects(keys.length == 6 && near(keys[4], 1));
|
||||||
|
}
|
||||||
@@ -0,0 +1,196 @@
|
|||||||
|
#! Contains the tests of `obj`: a cube read with its materials, of every form
|
||||||
|
#! of corner, colors, groups, and smoothing; lines and points, and an MTL file
|
||||||
|
#! that isn't there; what's refused; and a model written as OBJ and MTL and
|
||||||
|
#! read back the same.
|
||||||
|
|
||||||
|
import std::io;
|
||||||
|
import std::math;
|
||||||
|
import std::testing;
|
||||||
|
import malunal::linear;
|
||||||
|
import malunal::obj;
|
||||||
|
|
||||||
|
# The folder the tests write their files into.
|
||||||
|
const written: strview = ".blossom/obj tests";
|
||||||
|
|
||||||
|
# Writes a file the tests read, beneath `written`, making its folder.
|
||||||
|
def put(at: strview, text: strview): void {
|
||||||
|
var file := path::parse($"{written}/{at}".span).expect("A path.");
|
||||||
|
if file.parent() is some(&above) {
|
||||||
|
_ = io::create_directories(above);
|
||||||
|
}
|
||||||
|
io::write_file(&file, text).expect("The file is written.");
|
||||||
|
}
|
||||||
|
|
||||||
|
# Whether two floats are within a millionth.
|
||||||
|
def near(a: f32, b: f32): bool {
|
||||||
|
return math::abs(a - b) < 1e-5;
|
||||||
|
}
|
||||||
|
|
||||||
|
# The materials of the cube: red, its texture mapped with options, and blue,
|
||||||
|
# physically based, half see-through.
|
||||||
|
const cube_mtl: strview = """
|
||||||
|
# Two materials
|
||||||
|
newmtl red
|
||||||
|
Ka 0.1 0.1 0.1
|
||||||
|
Kd 1 0 0
|
||||||
|
Ks 0.5 0.5 0.5
|
||||||
|
Ns 96
|
||||||
|
illum 2
|
||||||
|
map_Kd -s 2 2 1 -o 0.5 0 -bm 0.25 -clamp on textures/red brick.png
|
||||||
|
bump -bm 2 bumps.png
|
||||||
|
|
||||||
|
newmtl blue
|
||||||
|
Kd 0 0 1
|
||||||
|
Tr 0.5
|
||||||
|
Pr 0.25
|
||||||
|
Pm 1
|
||||||
|
norm blue_normal.png
|
||||||
|
""";
|
||||||
|
|
||||||
|
# A cube of six quads, its corners given every way: positions alone, with
|
||||||
|
# places on a texture, with normals, and with both, some counted back from the
|
||||||
|
# last; colors, a comment after a statement, two groups, smoothing on and off,
|
||||||
|
# and a material no MTL file gives.
|
||||||
|
const cube_obj: strview = """
|
||||||
|
# A cube
|
||||||
|
mtllib cube.mtl
|
||||||
|
o Cube
|
||||||
|
v -1 -1 -1 1 0 0
|
||||||
|
v 1 -1 -1 0 1 0
|
||||||
|
v 1 1 -1 0 0 1
|
||||||
|
v -1 1 -1
|
||||||
|
v -1 -1 1
|
||||||
|
v 1 -1 1
|
||||||
|
v 1 1 1 0.5 0.5 0.5
|
||||||
|
v -1 1 1
|
||||||
|
vt 0 0
|
||||||
|
vt 1 0
|
||||||
|
vt 1 1
|
||||||
|
vt 0 1
|
||||||
|
vn 0 0 -1
|
||||||
|
vn 0 0 1
|
||||||
|
g front
|
||||||
|
usemtl red
|
||||||
|
s 1
|
||||||
|
f 1 4 3 2
|
||||||
|
f 5/1 6/2 7/3 8/4 # the back
|
||||||
|
g sides
|
||||||
|
usemtl blue
|
||||||
|
s off
|
||||||
|
f 1//1 2//1 6//1 5//1
|
||||||
|
f -5/-4/-1 -1/-3/-1 -2/-2/-1 -6/-1/-1
|
||||||
|
usemtl green
|
||||||
|
f 1 5 8 4
|
||||||
|
f 2 3 7 6
|
||||||
|
""";
|
||||||
|
|
||||||
|
@test def reads_a_cube_and_its_materials(t: &mut tester): void {
|
||||||
|
put("cube.mtl", cube_mtl);
|
||||||
|
put("cube.obj", cube_obj);
|
||||||
|
val cube := obj::load($"{written}/cube.obj".span).expect("The cube is read.");
|
||||||
|
t.expects(cube.positions.length == 8 && cube.uvs.length == 4 && cube.normals.length == 2 && cube.faces.length == 6);
|
||||||
|
t.expects(near(cube.positions[6].x, 1) && near(cube.positions[6].z, 1));
|
||||||
|
# Colors, the line joined to the next among them, white where none's given.
|
||||||
|
t.expects(cube.colors.length == 8 && near(cube.colors[0].x, 1) && near(cube.colors[2].z, 1) && near(cube.colors[3].x, 1) && near(cube.colors[6].y, 0.5));
|
||||||
|
# Every form of corner, and those counted back from the last.
|
||||||
|
val back := cube.corners_of(&cube.faces[1]);
|
||||||
|
t.expects(back.length == 4 && back[0].position == 4 && back[0].uv == 0 && back[0].normal == obj::absent);
|
||||||
|
val side := cube.corners_of(&cube.faces[2]);
|
||||||
|
t.expects(side[1].position == 1 && side[1].uv == obj::absent && side[1].normal == 0);
|
||||||
|
val counted := cube.corners_of(&cube.faces[3]);
|
||||||
|
t.expects(counted[0].position == 3 && counted[0].uv == 0 && counted[0].normal == 1 && counted[1].position == 7 && counted[3].uv == 3);
|
||||||
|
# Objects, groups, and smoothing.
|
||||||
|
t.expects(cube.objects.length == 1 && cube.objects[0].span == "Cube" && cube.groups.length == 2 && cube.groups[1].span == "sides");
|
||||||
|
t.expects(cube.faces[0].object == 0 && cube.faces[0].group == 0 && cube.faces[0].smoothing == 1 && cube.faces[2].group == 1 && cube.faces[2].smoothing == 0);
|
||||||
|
# The materials of the MTL file, and the one it doesn't give, of the defaults.
|
||||||
|
t.expects(cube.libraries.length == 1 && cube.missing.length == 0 && cube.materials.length == 3);
|
||||||
|
val red := &cube.materials[0];
|
||||||
|
t.expects(red.name.span == "red" && near(red.diffuse.x, 1) && near(red.diffuse.y, 0) && near(red.ambient.x, 0.1) && near(red.shininess, 96) && red.illumination == 2);
|
||||||
|
t.expects(cube.faces[0].material == 0 && cube.faces[2].material == 1 && cube.faces[4].material == 2 && cube.materials[2].name.span == "green");
|
||||||
|
if red.map(obj::map_slot::diffuse) is some(&brick) {
|
||||||
|
t.expects(brick.file.span == "textures/red brick.png" && near(brick.scale.x, 2) && near(brick.scale.z, 1) && near(brick.offset.x, 0.5) && near(brick.bump_multiplier, 0.25) && brick.clamp);
|
||||||
|
} else {
|
||||||
|
t.expects(false);
|
||||||
|
}
|
||||||
|
t.expects(red.map(obj::map_slot::bump) is some(&bumps) && bumps.file.span == "bumps.png" && near(bumps.bump_multiplier, 2));
|
||||||
|
val blue := &cube.materials[1];
|
||||||
|
t.expects(near(blue.dissolve, 0.5) && near(blue.roughness, 0.25) && near(blue.metallic, 1) && blue.map(obj::map_slot::normal) is some(_));
|
||||||
|
}
|
||||||
|
|
||||||
|
@test def reads_lines_and_points_and_notes_missing_libraries(t: &mut tester): void {
|
||||||
|
val text: strview = """
|
||||||
|
mtllib nowhere.mtl
|
||||||
|
v 0 0 0
|
||||||
|
v 1 0 0
|
||||||
|
v 1 1 0
|
||||||
|
vt 0 0
|
||||||
|
vt 1 1
|
||||||
|
usemtl line
|
||||||
|
l 1/1 2/2 3
|
||||||
|
p 1 2 3
|
||||||
|
""";
|
||||||
|
val read := obj::decode(text, written).expect("The lines are read.");
|
||||||
|
t.expects(read.lines.length == 1 && read.lines[0].count == 3 && read.points.length == 1 && read.points[0].count == 3 && read.faces.length == 0);
|
||||||
|
t.expects(read.corners_of(&read.lines[0])[1].uv == 1);
|
||||||
|
t.expects(read.missing.length == 1 && read.missing[0].span == "nowhere.mtl" && read.materials.length == 1 && read.lines[0].material == 0);
|
||||||
|
# A line ending with `\` goes on in the next.
|
||||||
|
val joined := obj::decode("v 1 2 \\\n 3 4 5 6\r\nv 0 0 0\n").expect("The joined line is read.");
|
||||||
|
t.expects(joined.positions.length == 2 && near(joined.positions[0].z, 3) && joined.colors.length == 2 && near(joined.colors[0].z, 6) && near(joined.colors[1].x, 1));
|
||||||
|
}
|
||||||
|
|
||||||
|
# Whether text is refused as malformed, saying what's given.
|
||||||
|
def refused(text: strview, says: strview): bool {
|
||||||
|
if obj::decode(text) is error(e) {
|
||||||
|
val why := e.describe();
|
||||||
|
return e.kind == obj::failure::malformed && why.span.find(says) is some(_);
|
||||||
|
}
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
|
||||||
|
@test def refuses_what_breaks_obj(t: &mut tester): void {
|
||||||
|
t.expects(refused("v 0 0 0\nv 1 0 0\nf 1 2\n", "line 3: Its face has 2 corners"));
|
||||||
|
t.expects(refused("v 0 0 0\nv 1 0 0\nv 1 1 0\nf 1 2 4\n", "names position 4, of the 3"));
|
||||||
|
t.expects(refused("v 0 0 0\nf 0 1 1\n", "names nothing"));
|
||||||
|
t.expects(refused("v 0 zero 0\n", "`zero` isn't a number"));
|
||||||
|
t.expects(refused("v 0 0\n", "of the 3 it needs"));
|
||||||
|
t.expects(refused("v 0 0 0\nv 1 0 0\nv 1 1 0\nf 1/9 2 3\n", "names texture place 9"));
|
||||||
|
t.expects(obj::decode_materials("Kd 1 0 0\n") is error(e) && e.kind == obj::failure::malformed);
|
||||||
|
t.expects(obj::load("nowhere/nothing.obj") is error(gone) && gone.kind == obj::failure::unreadable);
|
||||||
|
}
|
||||||
|
|
||||||
|
@test def writes_a_model_and_its_materials_and_reads_them_back(t: &mut tester): void {
|
||||||
|
put("cube.mtl", cube_mtl);
|
||||||
|
put("cube.obj", cube_obj);
|
||||||
|
val cube := obj::load($"{written}/cube.obj".span).expect("The cube is read.");
|
||||||
|
obj::save(&cube, $"{written}/out/again.obj".span).expect("The cube is written.");
|
||||||
|
val again := obj::load($"{written}/out/again.obj".span).expect("The cube is read again.");
|
||||||
|
t.expects(again.libraries.length == 1 && again.libraries[0].span == "cube.mtl" && again.missing.length == 0);
|
||||||
|
t.expects(again.positions.length == 8 && again.uvs.length == 4 && again.normals.length == 2 && again.colors.length == 8 && again.faces.length == 6);
|
||||||
|
for i in 0..cube.corners.length {
|
||||||
|
val a := cube.corners[i];
|
||||||
|
val b := again.corners[i];
|
||||||
|
t.expects(a.position == b.position && a.uv == b.uv && a.normal == b.normal);
|
||||||
|
}
|
||||||
|
for i in 0..cube.faces.length {
|
||||||
|
val a := cube.faces[i];
|
||||||
|
val b := again.faces[i];
|
||||||
|
t.expects(a.count == b.count && a.material == b.material && a.smoothing == b.smoothing && a.group == b.group && a.object == b.object);
|
||||||
|
}
|
||||||
|
t.expects(near(again.colors[6].x, 0.5) && near(again.positions[0].x, -1));
|
||||||
|
t.expects(again.materials.length == 3 && again.materials[2].name.span == "green");
|
||||||
|
val red := &again.materials[0];
|
||||||
|
t.expects(near(red.ambient.x, 0.1) && near(red.shininess, 96) && red.maps.length == 2);
|
||||||
|
t.expects(red.map(obj::map_slot::diffuse) is some(&brick) && brick.file.span == "textures/red brick.png" && near(brick.scale.y, 2) && near(brick.offset.x, 0.5) && brick.clamp && near(brick.bump_multiplier, 0.25));
|
||||||
|
t.expects(near(again.materials[1].dissolve, 0.5) && near(again.materials[1].metallic, 1));
|
||||||
|
# A model of no materials is written alone.
|
||||||
|
var bare := obj::model{};
|
||||||
|
bare.positions.append(vec3{ 0, 0, 0 });
|
||||||
|
bare.positions.append(vec3{ 1, 0, 0 });
|
||||||
|
bare.positions.append(vec3{ 0, 1, 0 });
|
||||||
|
bare.corners.append(obj::corner{ position = 0 });
|
||||||
|
bare.corners.append(obj::corner{ position = 1 });
|
||||||
|
bare.corners.append(obj::corner{ position = 2 });
|
||||||
|
bare.faces.append(obj::element{ first = 0, count = 3 });
|
||||||
|
val text := obj::encode(&bare);
|
||||||
|
t.expects(text.span.find("mtllib") is none && text.span.find("f 1 2 3") is some(_));
|
||||||
|
}
|
||||||
@@ -0,0 +1,186 @@
|
|||||||
|
#! Contains the tests of reading assets: from `.gltf` JSON with its buffer in a
|
||||||
|
#! `data:` URI, from a `.glb` file, and from files beside it; and what's refused,
|
||||||
|
#! each with why.
|
||||||
|
|
||||||
|
import std::io;
|
||||||
|
import std::testing;
|
||||||
|
import malunal::linear;
|
||||||
|
import malunal::gltf;
|
||||||
|
|
||||||
|
# Checks what the quad holds, read any way.
|
||||||
|
def expect_quad(t: &mut tester, read: &gltf::asset): void {
|
||||||
|
t.expects(read.version.span == "2.0" && read.generator.span == "gltf tests");
|
||||||
|
t.expects(read.scene is some(s) && s == 0 && read.scenes.length == 1 && read.scenes[0].name.span == "Quad");
|
||||||
|
t.expects(read.nodes.length == 1 && read.nodes[0].name.span == "Square" && read.nodes[0].mesh is some(m) && m == 0);
|
||||||
|
t.expects(near(read.nodes[0].translation.y, 2) && near(read.nodes[0].matrix.m[14], 3));
|
||||||
|
val part := &read.meshes[0].primitives[0];
|
||||||
|
t.expects(part.mode == gltf::topology::triangles && part.find("POSITION") is some(p) && p == 0 && part.find("TEXCOORD_0") is none);
|
||||||
|
val places := read.floats(0);
|
||||||
|
t.expects(places.length == 12 && near(places[3], 0.5) && near(places[7], 0.5));
|
||||||
|
val normals := read.floats(1);
|
||||||
|
t.expects(normals.length == 12 && near(normals[2], 1));
|
||||||
|
val indices := read.integers(2);
|
||||||
|
t.expects(indices.length == 6 && indices[4] == 2 && indices[5] == 3);
|
||||||
|
val red := &read.materials[0];
|
||||||
|
t.expects(red.name.span == "red" && red.double_sided && near(red.base_color[0], 1) && near(red.base_color[1], 0));
|
||||||
|
t.expects(near(red.metallic, 0) && near(red.roughness, 1) && red.alpha_mode == gltf::alpha_mode::opaque && red.base_color_texture is none);
|
||||||
|
t.expects(read.accessors[0].max.length == 3 && read.accessors[0].max[0] == 0.5);
|
||||||
|
}
|
||||||
|
|
||||||
|
@test def reads_json_with_its_buffer_in_a_data_uri(t: &mut tester): void {
|
||||||
|
val bytes := quad_buffer();
|
||||||
|
val uri := data_uri(bytes.span);
|
||||||
|
val json := quad_json(uri.span);
|
||||||
|
val read := gltf::decode(json.span) else (e) {
|
||||||
|
t.expects(false);
|
||||||
|
io::println(e.describe().span);
|
||||||
|
return;
|
||||||
|
};
|
||||||
|
expect_quad(t, &read);
|
||||||
|
}
|
||||||
|
|
||||||
|
@test def reads_glb_files(t: &mut tester): void {
|
||||||
|
val json := quad_json("");
|
||||||
|
val bytes := quad_buffer();
|
||||||
|
val glb := glb_of(json.span, bytes.span);
|
||||||
|
put("quad.glb", glb.span);
|
||||||
|
val read := gltf::load(".blossom/gltf tests/quad.glb") else (e) {
|
||||||
|
t.expects(false);
|
||||||
|
io::println(e.describe().span);
|
||||||
|
return;
|
||||||
|
};
|
||||||
|
expect_quad(t, &read);
|
||||||
|
t.expects(read.buffers[0].uri.length == 0 && read.buffers[0].bytes.length >= 108);
|
||||||
|
}
|
||||||
|
|
||||||
|
# A buffer and an image as files beside the asset, the buffer's named with a
|
||||||
|
# space, percent-encoded, and an image in a buffer view of a `.glb` file.
|
||||||
|
@test def reads_buffers_and_images_from_files_beside_it(t: &mut tester): void {
|
||||||
|
val bytes := quad_buffer();
|
||||||
|
put("beside/quad data.bin", bytes.span);
|
||||||
|
val picture: u8[8] = [0x89, 'P', 'N', 'G', 13, 10, 26, 10];
|
||||||
|
put("beside/red.png", picture[:]);
|
||||||
|
val json := quad_json("quad%20data.bin", ", \"images\": [{ \"uri\": \"red.png\" }], \"textures\": [{ \"source\": 0 }]");
|
||||||
|
put("beside/quad.gltf", json.span);
|
||||||
|
val read := gltf::load(".blossom/gltf tests/beside/quad.gltf") else (e) {
|
||||||
|
t.expects(false);
|
||||||
|
io::println(e.describe().span);
|
||||||
|
return;
|
||||||
|
};
|
||||||
|
expect_quad(t, &read);
|
||||||
|
t.expects(read.images.length == 1 && read.images[0].bytes.length == 8 && read.images[0].bytes[1] == 'P');
|
||||||
|
t.expects(read.textures[0].source is some(s) && s == 0 && read.textures[0].sampler is none);
|
||||||
|
|
||||||
|
# The same image, in a view of a `.glb` file's buffer, after the quad's.
|
||||||
|
var packed_bytes := quad_buffer();
|
||||||
|
packed_bytes.extend(picture[:]);
|
||||||
|
val inner := quad_json("", ", \"images\": [{ \"bufferView\": 2, \"mimeType\": \"image/png\" }]");
|
||||||
|
# Its buffer is the quad's and the image's: 116 bytes, the image a third view.
|
||||||
|
val with_image := replaced(replaced(inner.span, "\"byteLength\": 108", "\"byteLength\": 116").span,
|
||||||
|
"{ \"buffer\": 0, \"byteOffset\": 96, \"byteLength\": 12 }",
|
||||||
|
"{ \"buffer\": 0, \"byteOffset\": 96, \"byteLength\": 12 }, { \"buffer\": 0, \"byteOffset\": 108, \"byteLength\": 8 }");
|
||||||
|
val glb := glb_of(with_image.span, packed_bytes.span);
|
||||||
|
val bound := gltf::decode(glb.span) else (e) {
|
||||||
|
t.expects(false);
|
||||||
|
io::println(e.describe().span);
|
||||||
|
return;
|
||||||
|
};
|
||||||
|
t.expects(bound.images[0].mime_type.span == "image/png" && bound.images[0].bytes.length == 8 && bound.images[0].bytes[3] == 'G');
|
||||||
|
}
|
||||||
|
|
||||||
|
# Two texts, one after the other.
|
||||||
|
def joined(a: strview, b: strview): string {
|
||||||
|
var made := string::from(a, nothing{});
|
||||||
|
made.append(b);
|
||||||
|
return made;
|
||||||
|
}
|
||||||
|
|
||||||
|
# Text with the first of some text replaced.
|
||||||
|
def replaced(text: strview, what: strview, with: strview): string {
|
||||||
|
var made := string::new(nothing{});
|
||||||
|
var i: u64 = 0;
|
||||||
|
var done := false;
|
||||||
|
while i < text.length {
|
||||||
|
if !done && i + what.length <= text.length && text.substr(i, what.length) == what {
|
||||||
|
made.append(with);
|
||||||
|
i += what.length;
|
||||||
|
done = true;
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
made.push(text[i]);
|
||||||
|
i++;
|
||||||
|
}
|
||||||
|
return made;
|
||||||
|
}
|
||||||
|
|
||||||
|
# Whether what's refused is refused as `kind`, saying `says` somewhere in why.
|
||||||
|
def refuses(t: &mut tester, json: strview, kind: gltf::failure, says: strview): void {
|
||||||
|
match gltf::decode(json) {
|
||||||
|
value(_) => {
|
||||||
|
io::println($"read, but shouldn't be: {json}".span);
|
||||||
|
t.expects(false);
|
||||||
|
}
|
||||||
|
error(e) => {
|
||||||
|
val why := e.describe();
|
||||||
|
val found := holds(why.span, says);
|
||||||
|
if e.kind != kind || !found {
|
||||||
|
io::println($"refused as `{why.span}`, not as `{says}`".span);
|
||||||
|
}
|
||||||
|
t.expects(e.kind == kind && found);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
def holds(text: strview, part: strview): bool {
|
||||||
|
return true if part.length == 0;
|
||||||
|
var i: u64 = 0;
|
||||||
|
while i + part.length <= text.length {
|
||||||
|
return true if text.substr(i, part.length) == part;
|
||||||
|
i++;
|
||||||
|
}
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
|
||||||
|
@test def refuses_what_breaks_gltf(t: &mut tester): void {
|
||||||
|
refuses(t, "{ not json", gltf::failure::malformed, "JSON");
|
||||||
|
refuses(t, "{ \"asset\": { \"version\": \"1.0\" } }", gltf::failure::unsupported, "1.0");
|
||||||
|
refuses(t, "{ \"scenes\": [] }", gltf::failure::malformed, "version");
|
||||||
|
refuses(t, asset_with("\"extensionsRequired\": [\"KHR_draco_mesh_compression\"]").span, gltf::failure::unsupported, "KHR_draco_mesh_compression");
|
||||||
|
refuses(t, asset_with("\"nodes\": [{ \"mesh\": 0 }]").span, gltf::failure::malformed, "nodes[0]: its mesh is 0, of the 0 meshes");
|
||||||
|
refuses(t, asset_with("\"nodes\": [{ \"children\": [1] }, { \"children\": [0] }]").span, gltf::failure::malformed, "comes back to it");
|
||||||
|
refuses(t, asset_with("\"nodes\": [{ \"children\": [1] }, {}, { \"children\": [1] }]").span, gltf::failure::malformed, "child of both");
|
||||||
|
refuses(t, asset_with("\"nodes\": [{ \"children\": [1] }, {}], \"scenes\": [{ \"nodes\": [1] }]").span, gltf::failure::malformed, "not a root");
|
||||||
|
refuses(t, asset_with("\"buffers\": [{ \"byteLength\": 8 }]").span, gltf::failure::malformed, "buffers[0]");
|
||||||
|
refuses(t, asset_with("\"buffers\": [{ \"byteLength\": 8, \"uri\": \"missing.bin\" }]").span, gltf::failure::unreadable, "missing.bin");
|
||||||
|
refuses(t, asset_with("\"buffers\": [{ \"byteLength\": 4, \"uri\": \"https://example.com/a.bin\" }]").span, gltf::failure::unsupported, "another place");
|
||||||
|
refuses(t, asset_with("\"buffers\": [{ \"byteLength\": 4, \"uri\": \"data:application/octet-stream;base64,AAAA\" }]").span, gltf::failure::malformed, "3");
|
||||||
|
|
||||||
|
# An accessor reaching past its view, and one of a type glTF hasn't.
|
||||||
|
val one_view := "\"buffers\": [{ \"byteLength\": 12, \"uri\": \"data:application/octet-stream;base64,AAAAAAAAAAAAAAAA\" }], \"bufferViews\": [{ \"buffer\": 0, \"byteLength\": 12 }]";
|
||||||
|
refuses(t, asset_with(joined(one_view, ", \"accessors\": [{ \"bufferView\": 0, \"componentType\": 5126, \"count\": 2, \"type\": \"VEC2\" }]").span).span,
|
||||||
|
gltf::failure::malformed, "reach past");
|
||||||
|
refuses(t, asset_with(joined(one_view, ", \"accessors\": [{ \"bufferView\": 0, \"componentType\": 5124, \"count\": 1, \"type\": \"SCALAR\" }]").span).span,
|
||||||
|
gltf::failure::malformed, "componentType 5124");
|
||||||
|
val twelve := "\"buffers\": [{ \"byteLength\": 12, \"uri\": \"data:application/octet-stream;base64,AAAAAAAAAAAAAAAA\" }]";
|
||||||
|
refuses(t, asset_with(joined(twelve, ", \"bufferViews\": [{ \"buffer\": 0, \"byteOffset\": 8, \"byteLength\": 8 }]").span).span,
|
||||||
|
gltf::failure::malformed, "reaches byte 16");
|
||||||
|
|
||||||
|
# A `.glb` file of another version, and one cut short.
|
||||||
|
val none := vector::<u8>::new();
|
||||||
|
var glb := glb_of(asset_with("").span, none.span);
|
||||||
|
glb[4] = 1;
|
||||||
|
refuses(t, strview::over(glb.data, glb.length), gltf::failure::unsupported, "version 1");
|
||||||
|
glb[4] = 2;
|
||||||
|
refuses(t, strview::over(glb.data, 16), gltf::failure::malformed, "cut short");
|
||||||
|
}
|
||||||
|
|
||||||
|
# What an asset uses but doesn't require, of extensions it doesn't read, is
|
||||||
|
# read without them, and named among its extensions.
|
||||||
|
@test def reads_past_extensions_it_only_uses(t: &mut tester): void {
|
||||||
|
val json := asset_with("\"extensionsUsed\": [\"KHR_texture_transform\"], \"nodes\": [{ \"extensions\": { \"KHR_texture_transform\": {} } }]");
|
||||||
|
val read := gltf::decode(json.span) else (_) {
|
||||||
|
t.expects(false);
|
||||||
|
return;
|
||||||
|
};
|
||||||
|
t.expects(read.extensions.length == 1 && read.extensions[0].span == "KHR_texture_transform" && read.nodes.length == 1);
|
||||||
|
}
|
||||||
@@ -0,0 +1,181 @@
|
|||||||
|
#! Contains what the tests of `gltf` share: buffers packed of numbers, their
|
||||||
|
#! base64 for `data:` URIs, `.glb` files put together of JSON and a buffer, and
|
||||||
|
#! files written where the tests read them back.
|
||||||
|
|
||||||
|
import std::io;
|
||||||
|
import std::math;
|
||||||
|
import malunal::gltf;
|
||||||
|
|
||||||
|
# The folder the tests write their files into.
|
||||||
|
const written: strview = ".blossom/gltf tests";
|
||||||
|
|
||||||
|
# Bytes being packed, little-endian, as a buffer holds them.
|
||||||
|
struct packed {
|
||||||
|
var bytes: vector<u8>;
|
||||||
|
}
|
||||||
|
|
||||||
|
def packed::new(): packed {
|
||||||
|
return packed{ bytes = vector::<u8>::new() };
|
||||||
|
}
|
||||||
|
|
||||||
|
def packed::byte(&mut this, value: u8): void {
|
||||||
|
this.bytes.append(value);
|
||||||
|
}
|
||||||
|
|
||||||
|
def packed::short(&mut this, value: u16): void {
|
||||||
|
this.bytes.append((value & 0xFF) as u8);
|
||||||
|
this.bytes.append((value >> 8) as u8);
|
||||||
|
}
|
||||||
|
|
||||||
|
def packed::word(&mut this, value: u32): void {
|
||||||
|
for i in 0..4u {
|
||||||
|
this.bytes.append(((value >> (8 * i)) & 0xFF) as u8);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
def packed::float(&mut this, value: f32): void {
|
||||||
|
this.word(math::bits_of(value));
|
||||||
|
}
|
||||||
|
|
||||||
|
def packed::floats(&mut this, values: span<f32>): void {
|
||||||
|
for i in 0..values.length {
|
||||||
|
this.float(values[i]);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
# Pads with zeros to a multiple of 4 bytes.
|
||||||
|
def packed::align(&mut this): void {
|
||||||
|
while this.bytes.length % 4 != 0 {
|
||||||
|
this.bytes.append(0);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
# Bytes as base64, padded.
|
||||||
|
def base64_of(bytes: span<u8>): string {
|
||||||
|
val digits: strview = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";
|
||||||
|
var made := string::new(nothing{});
|
||||||
|
var i: u64 = 0;
|
||||||
|
while i < bytes.length {
|
||||||
|
val left := bytes.length - i;
|
||||||
|
val a := bytes[i] as u32;
|
||||||
|
val b: u32 = left > 1 ? bytes[i + 1] as u32 : 0;
|
||||||
|
val c: u32 = left > 2 ? bytes[i + 2] as u32 : 0;
|
||||||
|
val all := (a << 16) | (b << 8) | c;
|
||||||
|
made.push(digits[((all >> 18) & 63) as u64]);
|
||||||
|
made.push(digits[((all >> 12) & 63) as u64]);
|
||||||
|
made.push(left > 1 ? digits[((all >> 6) & 63) as u64] : '=');
|
||||||
|
made.push(left > 2 ? digits[(all & 63) as u64] : '=');
|
||||||
|
i += 3;
|
||||||
|
}
|
||||||
|
return made;
|
||||||
|
}
|
||||||
|
|
||||||
|
# A `data:` URI of a buffer's bytes.
|
||||||
|
def data_uri(bytes: span<u8>): string {
|
||||||
|
val digits := base64_of(bytes);
|
||||||
|
return $"data:application/octet-stream;base64,{digits.span}";
|
||||||
|
}
|
||||||
|
|
||||||
|
# A `.glb` file of JSON and a buffer: its header, then the JSON chunk, padded
|
||||||
|
# with spaces, and the binary chunk, padded with zeros.
|
||||||
|
def glb_of(json: strview, bin: span<u8>): vector<u8> {
|
||||||
|
var text := packed::new();
|
||||||
|
text.bytes.extend(json);
|
||||||
|
while text.bytes.length % 4 != 0 {
|
||||||
|
text.bytes.append(' ');
|
||||||
|
}
|
||||||
|
var data := packed::new();
|
||||||
|
data.bytes.extend(bin);
|
||||||
|
data.align();
|
||||||
|
var made := packed::new();
|
||||||
|
made.word(0x46546C67);
|
||||||
|
made.word(2);
|
||||||
|
made.word((12 + 8 + text.bytes.length + (bin.length != 0 ? 8 + data.bytes.length : 0)) as u32);
|
||||||
|
made.word(text.bytes.length as u32);
|
||||||
|
made.word(0x4E4F534A);
|
||||||
|
made.bytes.extend(text.bytes.span);
|
||||||
|
if bin.length != 0 {
|
||||||
|
made.word(data.bytes.length as u32);
|
||||||
|
made.word(0x004E4942);
|
||||||
|
made.bytes.extend(data.bytes.span);
|
||||||
|
}
|
||||||
|
return move(made.bytes);
|
||||||
|
}
|
||||||
|
|
||||||
|
# Writes a file the tests read, beneath `written`, making its folder.
|
||||||
|
def put(at: strview, bytes: span<u8>): void {
|
||||||
|
var file := path::parse($"{written}/{at}".span).expect("A path.");
|
||||||
|
if file.parent() is some(&above) {
|
||||||
|
_ = io::create_directories(above);
|
||||||
|
}
|
||||||
|
io::write_file(&file, bytes).expect("The file is written.");
|
||||||
|
}
|
||||||
|
|
||||||
|
# The positions, normals, and indices of a quad of two triangles, facing +z, a
|
||||||
|
# unit across, packed one after another: 48 bytes of positions, 48 of normals,
|
||||||
|
# and 12 of indices, as `quad_json` names them.
|
||||||
|
def quad_buffer(): vector<u8> {
|
||||||
|
var made := packed::new();
|
||||||
|
val places: f32[12] = [-0.5, -0.5, 0, 0.5, -0.5, 0, 0.5, 0.5, 0, -0.5, 0.5, 0];
|
||||||
|
val normals: f32[12] = [0, 0, 1, 0, 0, 1, 0, 0, 1, 0, 0, 1];
|
||||||
|
made.floats(places[:]);
|
||||||
|
made.floats(normals[:]);
|
||||||
|
for each in [0u, 1, 2, 0, 2, 3] {
|
||||||
|
made.short(each as u16);
|
||||||
|
}
|
||||||
|
made.align();
|
||||||
|
return move(made.bytes);
|
||||||
|
}
|
||||||
|
|
||||||
|
# The JSON of the quad, of one node of one mesh, its material red and double
|
||||||
|
# sided, its buffer named by a URI, or the `.glb` file's where that's empty,
|
||||||
|
# and other members after, where given.
|
||||||
|
def quad_json(uri: strview, more: strview = ""): string {
|
||||||
|
var made := string::from("""
|
||||||
|
{
|
||||||
|
"asset": { "version": "2.0", "generator": "gltf tests" },
|
||||||
|
"scene": 0,
|
||||||
|
"scenes": [{ "name": "Quad", "nodes": [0] }],
|
||||||
|
"nodes": [{ "name": "Square", "mesh": 0, "translation": [1, 2, 3] }],
|
||||||
|
"meshes": [{ "name": "quad", "primitives": [{
|
||||||
|
"attributes": { "POSITION": 0, "NORMAL": 1 }, "indices": 2, "material": 0
|
||||||
|
}] }],
|
||||||
|
"materials": [{ "name": "red", "doubleSided": true, "pbrMetallicRoughness": { "baseColorFactor": [1, 0, 0, 1], "metallicFactor": 0 } }],
|
||||||
|
"accessors": [
|
||||||
|
{ "bufferView": 0, "componentType": 5126, "count": 4, "type": "VEC3", "min": [-0.5, -0.5, 0], "max": [0.5, 0.5, 0] },
|
||||||
|
{ "bufferView": 0, "byteOffset": 48, "componentType": 5126, "count": 4, "type": "VEC3" },
|
||||||
|
{ "bufferView": 1, "componentType": 5123, "count": 6, "type": "SCALAR" }
|
||||||
|
],
|
||||||
|
"bufferViews": [
|
||||||
|
{ "buffer": 0, "byteOffset": 0, "byteLength": 96 },
|
||||||
|
{ "buffer": 0, "byteOffset": 96, "byteLength": 12 }
|
||||||
|
],
|
||||||
|
"buffers": [{ "byteLength": 108
|
||||||
|
""", nothing{});
|
||||||
|
if uri.length != 0 {
|
||||||
|
made.append(", \"uri\": \"");
|
||||||
|
made.append(uri);
|
||||||
|
made.append("\"");
|
||||||
|
}
|
||||||
|
made.append(" }]");
|
||||||
|
made.append(more);
|
||||||
|
made.append(" }");
|
||||||
|
return made;
|
||||||
|
}
|
||||||
|
|
||||||
|
# JSON of an asset, a version and the members given, as the tests of what's
|
||||||
|
# refused write each.
|
||||||
|
def asset_with(members: strview): string {
|
||||||
|
var made := string::from("{ \"asset\": { \"version\": \"2.0\" }", nothing{});
|
||||||
|
if members.length != 0 {
|
||||||
|
made.append(", ");
|
||||||
|
made.append(members);
|
||||||
|
}
|
||||||
|
made.append(" }");
|
||||||
|
return made;
|
||||||
|
}
|
||||||
|
|
||||||
|
# Whether two floats are within a millionth.
|
||||||
|
def near(a: f32, b: f32): bool {
|
||||||
|
return math::abs(a - b) < 1e-5;
|
||||||
|
}
|
||||||
@@ -0,0 +1,240 @@
|
|||||||
|
#! Contains the tests of writing assets: one built by hand, as `.glb` and as
|
||||||
|
#! `.gltf` JSON, read back; one read, written, and read again, its every part;
|
||||||
|
#! and files saved, beside it where they're named so.
|
||||||
|
|
||||||
|
import std::io;
|
||||||
|
import std::testing;
|
||||||
|
import malunal::linear;
|
||||||
|
import malunal::gltf;
|
||||||
|
|
||||||
|
# A quad built by hand, of positions, normals, and indices, a red material, a
|
||||||
|
# node placed and turned, and a PNG's first bytes as an image.
|
||||||
|
def built_quad(): gltf::asset {
|
||||||
|
var made := gltf::asset::new("gltf tests");
|
||||||
|
val places: f32[12] = [-0.5, -0.5, 0, 0.5, -0.5, 0, 0.5, 0.5, 0, -0.5, 0.5, 0];
|
||||||
|
val normals: f32[12] = [0, 0, 1, 0, 0, 1, 0, 0, 1, 0, 0, 1];
|
||||||
|
val indices: u32[6] = [0, 1, 2, 0, 2, 3];
|
||||||
|
val p := made.add_floats(places[:], gltf::element::vec3, "places");
|
||||||
|
val n := made.add_floats(normals[:], gltf::element::vec3);
|
||||||
|
val i := made.add_indices(indices[:]);
|
||||||
|
var part := gltf::primitive{ indices = i, material = 0 };
|
||||||
|
part.attributes.append(gltf::attribute{ name = string::from("POSITION", nothing{}), accessor = p });
|
||||||
|
part.attributes.append(gltf::attribute{ name = string::from("NORMAL", nothing{}), accessor = n });
|
||||||
|
var shape := gltf::mesh{ name = string::from("quad", nothing{}) };
|
||||||
|
shape.primitives.append(move(part));
|
||||||
|
made.meshes.append(move(shape));
|
||||||
|
var red := gltf::material{ name = string::from("red", nothing{}), metallic = 0, double_sided = true };
|
||||||
|
red.base_color = [1, 0, 0, 1];
|
||||||
|
red.emissive = [4, 2, 0];
|
||||||
|
made.materials.append(move(red));
|
||||||
|
val picture: u8[8] = [0x89, 'P', 'N', 'G', 13, 10, 26, 10];
|
||||||
|
_ = made.add_image(picture[:]);
|
||||||
|
made.textures.append(gltf::texture{ source = 0 });
|
||||||
|
var square := gltf::node{ name = string::from("Square", nothing{}), mesh = 0 };
|
||||||
|
square.translation = vec3{ 1, 2, 3 };
|
||||||
|
square.rotation = quat::axis_angle(vec3::up, 0.5);
|
||||||
|
made.nodes.append(move(square));
|
||||||
|
var whole := gltf::scene{ name = string::from("Quad", nothing{}) };
|
||||||
|
whole.nodes.append(0);
|
||||||
|
made.scenes.append(move(whole));
|
||||||
|
made.scene = 0;
|
||||||
|
return made;
|
||||||
|
}
|
||||||
|
|
||||||
|
# Checks what the quad built holds, read back.
|
||||||
|
def expect_built(t: &mut tester, read: &gltf::asset): void {
|
||||||
|
t.expects(read.version.span == "2.0" && read.generator.span == "gltf tests");
|
||||||
|
t.expects(read.scene is some(s) && s == 0 && read.scenes[0].name.span == "Quad" && read.scenes[0].nodes.length == 1);
|
||||||
|
val node := &read.nodes[0];
|
||||||
|
t.expects(node.name.span == "Square" && node.mesh is some(m) && m == 0 && near(node.translation.z, 3));
|
||||||
|
val turned := quat::axis_angle(vec3::up, 0.5);
|
||||||
|
t.expects(near(node.rotation.y, turned.y) && near(node.rotation.w, turned.w) && near(node.scale.x, 1));
|
||||||
|
val part := &read.meshes[0].primitives[0];
|
||||||
|
t.expects(read.meshes[0].name.span == "quad" && part.find("POSITION") is some(at) && at == 0 && part.material is some(k) && k == 0);
|
||||||
|
val places := read.floats(0);
|
||||||
|
t.expects(places.length == 12 && near(places[3], 0.5) && near(places[10], 0.5));
|
||||||
|
t.expects(read.accessors[0].name.span == "places" && read.accessors[0].min.length == 3 && read.accessors[0].min[0] == -0.5 && read.accessors[0].max[1] == 0.5);
|
||||||
|
val normals := read.floats(1);
|
||||||
|
t.expects(normals.length == 12 && near(normals[11], 1));
|
||||||
|
val indices := read.integers(2);
|
||||||
|
t.expects(indices.length == 6 && indices[2] == 2 && indices[5] == 3 && read.accessors[2].component_type == gltf::component::unsigned_short);
|
||||||
|
val red := &read.materials[0];
|
||||||
|
t.expects(red.name.span == "red" && red.double_sided && near(red.base_color[0], 1) && near(red.base_color[1], 0) && near(red.metallic, 0));
|
||||||
|
# Emission past 1 comes back by its strength.
|
||||||
|
t.expects(near(red.emissive[0], 4) && near(red.emissive[1], 2) && near(red.emissive[2], 0));
|
||||||
|
t.expects(read.images.length == 1 && read.images[0].bytes.length == 8 && read.images[0].bytes[1] == 'P' && read.images[0].mime_type.span == "image/png");
|
||||||
|
t.expects(read.textures[0].source is some(src) && src == 0);
|
||||||
|
}
|
||||||
|
|
||||||
|
@test def writes_what_it_built_as_glb_and_json(t: &mut tester): void {
|
||||||
|
val built := built_quad();
|
||||||
|
val glb := gltf::encode(&built, true) else (e) {
|
||||||
|
t.expects(false);
|
||||||
|
io::println(e.describe().span);
|
||||||
|
return;
|
||||||
|
};
|
||||||
|
t.expects(glb.length % 4 == 0 && glb[0] == 'g' && glb[1] == 'l' && glb[2] == 'T' && glb[3] == 'F');
|
||||||
|
val from_glb := gltf::decode(glb.span) else (e) {
|
||||||
|
t.expects(false);
|
||||||
|
io::println(e.describe().span);
|
||||||
|
return;
|
||||||
|
};
|
||||||
|
expect_built(t, &from_glb);
|
||||||
|
t.expects(from_glb.buffers.length == 1 && from_glb.buffers[0].uri.length == 0);
|
||||||
|
|
||||||
|
val json := gltf::encode(&built, false) else (e) {
|
||||||
|
t.expects(false);
|
||||||
|
io::println(e.describe().span);
|
||||||
|
return;
|
||||||
|
};
|
||||||
|
val text := string::from(strview::over(json.data, json.length), nothing{});
|
||||||
|
t.expects(text.span.find("\"uri\":\"data:application/octet-stream;base64,") is some(_));
|
||||||
|
t.expects(text.span.find("KHR_materials_emissive_strength") is some(_) && text.span.find("\"emissiveStrength\":4") is some(_));
|
||||||
|
val from_json := gltf::decode(json.span) else (e) {
|
||||||
|
t.expects(false);
|
||||||
|
io::println(e.describe().span);
|
||||||
|
return;
|
||||||
|
};
|
||||||
|
expect_built(t, &from_json);
|
||||||
|
}
|
||||||
|
|
||||||
|
@test def writes_what_it_read_as_it_was(t: &mut tester): void {
|
||||||
|
# Every part, read of JSON: lights, a camera of each kind, a skin, an
|
||||||
|
# animation, a sampler, textures of a material, and a node's children.
|
||||||
|
# The quad's buffer, and the animation's keys, two times and two rotations,
|
||||||
|
# in a buffer of their own, each a data URI.
|
||||||
|
val bytes := quad_buffer();
|
||||||
|
val quad_uri := data_uri(bytes.span);
|
||||||
|
var keys := packed::new();
|
||||||
|
val times: f32[2] = [0, 1];
|
||||||
|
val turns: f32[8] = [0, 0, 0, 1, 0, 0.7071068, 0, 0.7071068];
|
||||||
|
keys.floats(times[:]);
|
||||||
|
keys.floats(turns[:]);
|
||||||
|
val keys_uri := data_uri(keys.bytes.span);
|
||||||
|
val whole := string::from("""
|
||||||
|
{
|
||||||
|
"asset": { "version": "2.0", "generator": "gltf tests" },
|
||||||
|
"extensionsUsed": ["KHR_lights_punctual", "KHR_materials_unlit", "EXT_unknown"],
|
||||||
|
"scene": 0,
|
||||||
|
"scenes": [{ "name": "Quad", "nodes": [0] }],
|
||||||
|
"nodes": [
|
||||||
|
{ "name": "Square", "mesh": 0, "translation": [1, 2, 3], "children": [1], "skin": 0 },
|
||||||
|
{ "name": "Lamp", "scale": [2, 2, 2], "extensions": { "KHR_lights_punctual": { "light": 1 } } }
|
||||||
|
],
|
||||||
|
"meshes": [{ "name": "quad", "primitives": [{
|
||||||
|
"attributes": { "POSITION": 0, "NORMAL": 1 }, "indices": 2, "material": 0
|
||||||
|
}] }],
|
||||||
|
"materials": [{ "name": "red", "doubleSided": true,
|
||||||
|
"pbrMetallicRoughness": { "baseColorFactor": [1, 0, 0, 1], "metallicFactor": 0 },
|
||||||
|
"normalTexture": { "index": 0, "scale": 0.5 }, "extensions": { "KHR_materials_unlit": {} } }],
|
||||||
|
"textures": [{ "sampler": 0, "source": 0 }],
|
||||||
|
"samplers": [{ "magFilter": 9728, "minFilter": 9987, "wrapS": 33071 }],
|
||||||
|
"images": [{ "uri": "data:image/png;base64,iVBORw0KGgo=" }],
|
||||||
|
"accessors": [
|
||||||
|
{ "bufferView": 0, "componentType": 5126, "count": 4, "type": "VEC3", "min": [-0.5, -0.5, 0], "max": [0.5, 0.5, 0] },
|
||||||
|
{ "bufferView": 0, "byteOffset": 48, "componentType": 5126, "count": 4, "type": "VEC3" },
|
||||||
|
{ "bufferView": 1, "componentType": 5123, "count": 6, "type": "SCALAR" },
|
||||||
|
{ "bufferView": 2, "componentType": 5126, "count": 2, "type": "SCALAR" },
|
||||||
|
{ "bufferView": 2, "byteOffset": 8, "componentType": 5126, "count": 2, "type": "VEC4" }
|
||||||
|
],
|
||||||
|
"bufferViews": [
|
||||||
|
{ "buffer": 0, "byteOffset": 0, "byteLength": 96 },
|
||||||
|
{ "buffer": 0, "byteOffset": 96, "byteLength": 12 },
|
||||||
|
{ "buffer": 1, "byteLength": 40 }
|
||||||
|
],
|
||||||
|
"buffers": [{ "byteLength": 108, "uri": "QUAD" }, { "byteLength": 40, "uri": "KEYS" }],
|
||||||
|
"cameras": [
|
||||||
|
{ "name": "Eye", "type": "perspective", "perspective": { "yfov": 0.8, "znear": 0.1 } },
|
||||||
|
{ "type": "orthographic", "orthographic": { "xmag": 2, "ymag": 1, "znear": 0, "zfar": 50 } }
|
||||||
|
],
|
||||||
|
"skins": [{ "joints": [0] }],
|
||||||
|
"animations": [{ "name": "Spin",
|
||||||
|
"samplers": [{ "input": 3, "output": 4, "interpolation": "STEP" }],
|
||||||
|
"channels": [{ "sampler": 0, "target": { "node": 0, "path": "rotation" } }] }],
|
||||||
|
"extensions": { "KHR_lights_punctual": { "lights": [
|
||||||
|
{ "name": "Sun", "type": "directional", "intensity": 3 },
|
||||||
|
{ "type": "spot", "color": [1, 0.5, 0], "range": 10, "spot": { "innerConeAngle": 0.2, "outerConeAngle": 0.4 } }
|
||||||
|
] } }
|
||||||
|
}
|
||||||
|
""", nothing{});
|
||||||
|
val json := replaced(replaced(whole.span, "QUAD", quad_uri.span).span, "KEYS", keys_uri.span);
|
||||||
|
val read := gltf::decode(json.span) else (e) {
|
||||||
|
t.expects(false);
|
||||||
|
io::println(e.describe().span);
|
||||||
|
return;
|
||||||
|
};
|
||||||
|
for binary in [false, true] {
|
||||||
|
val written := gltf::encode(&read, binary) else (e) {
|
||||||
|
t.expects(false);
|
||||||
|
io::println(e.describe().span);
|
||||||
|
return;
|
||||||
|
};
|
||||||
|
val again := gltf::decode(written.span) else (e) {
|
||||||
|
t.expects(false);
|
||||||
|
io::println(e.describe().span);
|
||||||
|
return;
|
||||||
|
};
|
||||||
|
t.expects(again.generator.span == "gltf tests" && again.scene is some(s) && s == 0 && again.scenes[0].name.span == "Quad");
|
||||||
|
t.expects(again.nodes[0].name.span == "Square" && near(again.nodes[0].translation.y, 2) && again.nodes[0].children.length == 1);
|
||||||
|
val places := again.floats(0);
|
||||||
|
val indices := again.integers(2);
|
||||||
|
t.expects(places.length == 12 && near(places[3], 0.5) && indices.length == 6 && indices[5] == 3);
|
||||||
|
t.expects(again.accessors[0].max.length == 3 && again.accessors[0].max[0] == 0.5 && again.accessors[1].offset == 48);
|
||||||
|
val red := &again.materials[0];
|
||||||
|
t.expects(red.name.span == "red" && red.double_sided && near(red.base_color[1], 0) && near(red.metallic, 0) && near(red.roughness, 1));
|
||||||
|
t.expects(again.lights.length == 2 && again.lights[0].name.span == "Sun" && again.lights[0].kind == gltf::light_kind::directional && near(again.lights[0].intensity, 3));
|
||||||
|
t.expects(again.lights[1].kind == gltf::light_kind::spot && near(again.lights[1].color[1], 0.5) && again.lights[1].range is some(r) && near(r, 10) && near(again.lights[1].outer_cone, 0.4));
|
||||||
|
t.expects(again.cameras.length == 2 && near(again.cameras[0].fov_y, 0.8) && again.cameras[0].far is none && again.cameras[1].kind == gltf::camera_kind::orthographic);
|
||||||
|
t.expects(again.cameras[1].far is some(f) && near(f, 50) && near(again.cameras[1].x_mag, 2));
|
||||||
|
t.expects(again.samplers[0].mag_filter == gltf::filter::nearest && again.samplers[0].min_filter == gltf::filter::linear && again.samplers[0].mip_filter == gltf::filter::linear);
|
||||||
|
t.expects(again.samplers[0].wrap_s == gltf::wrap::clamp && again.samplers[0].wrap_t == gltf::wrap::repeat);
|
||||||
|
t.expects(again.images[0].bytes.length == 8 && again.images[0].mime_type.span == "image/png");
|
||||||
|
t.expects(again.materials[0].unlit && again.materials[0].normal_texture is some(nt) && near(nt.scale, 0.5));
|
||||||
|
t.expects(again.skins.length == 1 && again.skins[0].joints[0] == 0 && again.nodes[0].skin is some(sk) && sk == 0);
|
||||||
|
t.expects(again.nodes.length == 2 && again.nodes[1].parent is some(up) && up == 0 && again.nodes[1].light is some(l) && l == 1 && near(again.nodes[1].scale.y, 2));
|
||||||
|
val spin := &again.animations[0];
|
||||||
|
t.expects(spin.name.span == "Spin" && spin.samplers[0].interpolation == gltf::interpolation::step && spin.channels[0].path == gltf::target_path::rotation);
|
||||||
|
val turned := again.floats(spin.samplers[0].output);
|
||||||
|
t.expects(turned.length == 8 && near(turned[5], 0.7071068));
|
||||||
|
# The extension it didn't read isn't written.
|
||||||
|
val text := string::from(strview::over(written.data, written.length), nothing{});
|
||||||
|
t.expects(text.span.find("EXT_unknown") is none && text.span.find("KHR_materials_unlit") is some(_));
|
||||||
|
# A .glb file's first buffer, the keys', is its binary chunk; the quad's
|
||||||
|
# is a data URI.
|
||||||
|
if binary {
|
||||||
|
t.expects(again.buffers[0].uri.length == 0 && again.buffers[1].uri.span.starts_with("data:"));
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
@test def saves_files_and_those_beside_them(t: &mut tester): void {
|
||||||
|
var built := built_quad();
|
||||||
|
# Its buffer is a file beside it, named with a space.
|
||||||
|
built.buffers.at(0).uri = string::from("quad%20data.bin", nothing{});
|
||||||
|
gltf::save(&built, ".blossom/gltf tests/saved/quad.gltf") else (e) {
|
||||||
|
t.expects(false);
|
||||||
|
io::println(e.describe().span);
|
||||||
|
return;
|
||||||
|
};
|
||||||
|
t.expects(io::read_file(&path::parse(".blossom/gltf tests/saved/quad data.bin").expect("A path.")) is value(_));
|
||||||
|
val read := gltf::load(".blossom/gltf tests/saved/quad.gltf") else (e) {
|
||||||
|
t.expects(false);
|
||||||
|
io::println(e.describe().span);
|
||||||
|
return;
|
||||||
|
};
|
||||||
|
expect_built(t, &read);
|
||||||
|
|
||||||
|
# As a .glb file, the buffer named a file still is one.
|
||||||
|
gltf::save(&built, ".blossom/gltf tests/saved/quad.glb") else (e) {
|
||||||
|
t.expects(false);
|
||||||
|
io::println(e.describe().span);
|
||||||
|
return;
|
||||||
|
};
|
||||||
|
val glb := gltf::load(".blossom/gltf tests/saved/quad.glb") else (e) {
|
||||||
|
t.expects(false);
|
||||||
|
io::println(e.describe().span);
|
||||||
|
return;
|
||||||
|
};
|
||||||
|
expect_built(t, &glb);
|
||||||
|
t.expects(glb.buffers[0].uri.span == "quad%20data.bin");
|
||||||
|
}
|
||||||
Reference in new issue
Block a user