Skip to main content

bread_format/
scene.rs

1/*
2 * SPDX-FileCopyrightText: 2026 SynrgStudio
3 * SPDX-License-Identifier: Apache-2.0
4 */
5
6//! The scene chunk: the tree of nodes that places the meshes (`SPEC.md`,
7//! section 5).
8//!
9//! A [`Scene`] names everything by index, as the chunk does: meshes in the
10//! order of the file's mesh chunks, and nodes in the order they are listed,
11//! which is how other chunks name them. A mesh several leaves show is one
12//! index they share, stored once.
13//!
14//! Nodes are listed children first: a node names only nodes listed before it,
15//! and a reference only a subtree whose root is, so no node can contain
16//! itself. Each node has at most one place: a group's child, a root, or a
17//! subtree's root. The decoder refuses a payload that breaks these rules, and
18//! the encoder a scene that does, so it never writes one a reader must refuse.
19//!
20//! ```text
21//! metadata    u8 0 | 1, then name and comment (u8 0 | 1, u32 length, UTF-8)
22//! meshes      u32 number of mesh chunks
23//! resources   u32 count, then u32 mesh per mesh resource
24//! records     u32 count, then per record a u8 kind:
25//!               0 group      node, u32 count, u32 child nodes
26//!               1 leaf       node, u32 mesh
27//!               2 leaf       node, u32 mesh resource
28//!               4 reference  node, u32 subtree
29//!               5 subtree    u32 node, the root of the next subtree
30//!             where node is its metadata, then its transform:
31//!             u8 0 (identity) | 1 and 12 f64 (rows of the linear part, then
32//!             the translation)
33//! roots       u32 count, u32 nodes
34//! ```
35
36use std::fmt;
37
38use crate::bytes::{In, Out, fits_u32};
39use crate::container::ChunkTag;
40use crate::mesh::Mesh;
41use crate::meta::{Meta, read_meta, write_meta};
42
43/// The tag of the scene chunk.
44pub const SCENE_TAG: ChunkTag = ChunkTag(*b"SCNE");
45
46/// The scene payload layout this build writes and reads.
47pub const SCENE_VERSION: u16 = 1;
48
49const GROUP: u8 = 0;
50const LEAF: u8 = 1;
51const SHARED_LEAF: u8 = 2;
52const REFERENCE: u8 = 4;
53const SUBTREE: u8 = 5;
54
55/// A scene: the meshes, and the nodes that place them.
56#[derive(Clone, Debug, Default, PartialEq)]
57pub struct Scene {
58    pub meta: Option<Meta>,
59    /// The meshes, one per mesh chunk, in file order.
60    pub meshes: Vec<Mesh>,
61    /// The meshes the scene keeps as shared on purpose, as indices into
62    /// `meshes`: a program editing one changes every leaf that shows it.
63    pub mesh_resources: Vec<usize>,
64    /// The nodes, children first.
65    pub nodes: Vec<Node>,
66    /// The subtrees references copy, as the indices of their root nodes.
67    pub subtrees: Vec<usize>,
68    /// The top-level nodes, in order.
69    pub roots: Vec<usize>,
70}
71
72impl Scene {
73    /// The mesh the node `node` shows, or `None` when it is not a leaf.
74    pub fn leaf_mesh(&self, node: usize) -> Option<&Mesh> {
75        let mesh = match self.nodes.get(node)?.kind {
76            NodeKind::Leaf { mesh } => mesh,
77            NodeKind::SharedLeaf { resource } => *self.mesh_resources.get(resource)?,
78            NodeKind::Group { .. } | NodeKind::Reference { .. } => return None,
79        };
80        self.meshes.get(mesh)
81    }
82}
83
84/// A node of the scene.
85#[derive(Clone, Debug, PartialEq)]
86pub struct Node {
87    pub meta: Option<Meta>,
88    /// The transform from the node's space to its parent's, or `None` for
89    /// the identity, which is stored apart from an identity matrix.
90    pub transform: Option<Transform>,
91    pub kind: NodeKind,
92}
93
94/// What a node is.
95#[derive(Clone, Debug, PartialEq, Eq)]
96pub enum NodeKind {
97    /// A group of nodes, as indices into the scene's nodes, in order.
98    Group { children: Vec<usize> },
99    /// A leaf that shows a mesh, as an index into the scene's meshes.
100    Leaf { mesh: usize },
101    /// A leaf that shows a shared mesh, as an index into the scene's mesh
102    /// resources.
103    SharedLeaf { resource: usize },
104    /// One more copy of a subtree, as an index into the scene's subtrees.
105    Reference { subtree: usize },
106}
107
108/// An affine transform: a point *p* goes to `linear` · *p* + `translation`.
109#[derive(Clone, Copy, Debug, PartialEq)]
110pub struct Transform {
111    /// The 3 × 3 matrix, row by row.
112    pub linear: [[f64; 3]; 3],
113    pub translation: [f64; 3],
114}
115
116/// Why a scene could not be encoded.
117#[derive(Clone, Debug, PartialEq, Eq)]
118pub enum EncodeSceneError {
119    /// Something the scene names is missing, or not listed before what
120    /// names it, or a node has two places.
121    Inconsistent,
122    /// The scene has 2^32 or more meshes, mesh resources, roots, or nodes and
123    /// subtrees together.
124    TooLarge,
125}
126
127impl fmt::Display for EncodeSceneError {
128    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
129        f.write_str(match self {
130            Self::Inconsistent => "the scene graph is inconsistent",
131            Self::TooLarge => "the scene is too large for a scene chunk",
132        })
133    }
134}
135
136impl std::error::Error for EncodeSceneError {}
137
138/// Why a scene payload could not be decoded.
139#[derive(Clone, Debug, PartialEq, Eq)]
140pub enum DecodeSceneError {
141    /// The payload is cut short, padded, names something not listed before
142    /// it, or gives a node two places.
143    Malformed,
144    /// The payload names a different number of meshes than the file holds.
145    MeshCount { named: usize, found: usize },
146}
147
148impl fmt::Display for DecodeSceneError {
149    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
150        match self {
151            Self::Malformed => f.write_str("the scene data is malformed"),
152            Self::MeshCount { named, found } => {
153                write!(
154                    f,
155                    "the scene names {named} meshes but the file holds {found}"
156                )
157            }
158        }
159    }
160}
161
162impl std::error::Error for DecodeSceneError {}
163
164/// Encodes `scene` as a scene chunk payload. Its meshes go in mesh chunks of
165/// their own, in order.
166///
167/// Each subtree is listed right after its root, or after the subtree before
168/// it when that comes later. Nodes without a place are written as they are,
169/// so the indices other chunks use stay valid, but a program building a
170/// scene should not leave any.
171pub fn encode_scene(scene: &Scene) -> Result<Vec<u8>, EncodeSceneError> {
172    let counts = [
173        scene.meshes.len(),
174        scene.mesh_resources.len(),
175        scene.nodes.len() + scene.subtrees.len(),
176        scene.roots.len(),
177    ];
178    if !counts.into_iter().all(fits_u32) {
179        return Err(EncodeSceneError::TooLarge);
180    }
181    encode(scene).ok_or(EncodeSceneError::Inconsistent)
182}
183
184fn encode(scene: &Scene) -> Option<Vec<u8>> {
185    let mut out = Out::default();
186    write_meta(&mut out, scene.meta.as_ref());
187    out.len(scene.meshes.len());
188    out.len(scene.mesh_resources.len());
189    for &mesh in &scene.mesh_resources {
190        out.len(below(mesh, scene.meshes.len())?);
191    }
192
193    out.len(scene.nodes.len() + scene.subtrees.len());
194    let mut placed = vec![false; scene.nodes.len()];
195    let mut subtrees = 0;
196    for (listed, node) in scene.nodes.iter().enumerate() {
197        out.u8(match node.kind {
198            NodeKind::Group { .. } => GROUP,
199            NodeKind::Leaf { .. } => LEAF,
200            NodeKind::SharedLeaf { .. } => SHARED_LEAF,
201            NodeKind::Reference { .. } => REFERENCE,
202        });
203        write_meta(&mut out, node.meta.as_ref());
204        write_transform(&mut out, node.transform.as_ref());
205        match &node.kind {
206            NodeKind::Group { children } => {
207                for &child in children {
208                    place(&mut placed, child, listed)?;
209                }
210                out.len(children.len());
211                for &child in children {
212                    out.len(child);
213                }
214            }
215            NodeKind::Leaf { mesh } => out.len(below(*mesh, scene.meshes.len())?),
216            NodeKind::SharedLeaf { resource } => {
217                out.len(below(*resource, scene.mesh_resources.len())?);
218            }
219            NodeKind::Reference { subtree } => out.len(below(*subtree, subtrees)?),
220        }
221        while let Some(&root) = scene.subtrees.get(subtrees).filter(|&&root| root <= listed) {
222            place(&mut placed, root, listed + 1)?;
223            out.u8(SUBTREE);
224            out.len(root);
225            subtrees += 1;
226        }
227    }
228    if subtrees != scene.subtrees.len() {
229        return None;
230    }
231
232    out.len(scene.roots.len());
233    for &root in &scene.roots {
234        place(&mut placed, root, scene.nodes.len())?;
235        out.len(root);
236    }
237    Some(out.0)
238}
239
240/// Decodes a scene chunk payload over the meshes of the file's mesh chunks,
241/// in file order.
242pub fn decode_scene(payload: &[u8], meshes: Vec<Mesh>) -> Result<Scene, DecodeSceneError> {
243    let mut input = In(payload);
244    let meta = read_meta(&mut input).ok_or(DecodeSceneError::Malformed)?;
245    let named = input.len().ok_or(DecodeSceneError::Malformed)?;
246    if named != meshes.len() {
247        return Err(DecodeSceneError::MeshCount {
248            named,
249            found: meshes.len(),
250        });
251    }
252    let mut scene = Scene {
253        meta,
254        meshes,
255        ..Scene::default()
256    };
257    decode(&mut input, &mut scene).ok_or(DecodeSceneError::Malformed)?;
258    Ok(scene)
259}
260
261fn decode(input: &mut In<'_>, scene: &mut Scene) -> Option<()> {
262    for _ in 0..input.count(4)? {
263        let mesh = below(input.len()?, scene.meshes.len())?;
264        scene.mesh_resources.push(mesh);
265    }
266
267    let mut placed = Vec::new();
268    for _ in 0..input.count(5)? {
269        let kind = input.u8()?;
270        if kind == SUBTREE {
271            let root = input.len()?;
272            place(&mut placed, root, scene.nodes.len())?;
273            scene.subtrees.push(root);
274            continue;
275        }
276        let meta = read_meta(input)?;
277        let transform = read_transform(input)?;
278        let kind = match kind {
279            GROUP => {
280                let count = input.count(4)?;
281                let mut children = Vec::with_capacity(count);
282                for _ in 0..count {
283                    let child = input.len()?;
284                    place(&mut placed, child, scene.nodes.len())?;
285                    children.push(child);
286                }
287                NodeKind::Group { children }
288            }
289            LEAF => NodeKind::Leaf {
290                mesh: below(input.len()?, scene.meshes.len())?,
291            },
292            SHARED_LEAF => NodeKind::SharedLeaf {
293                resource: below(input.len()?, scene.mesh_resources.len())?,
294            },
295            REFERENCE => NodeKind::Reference {
296                subtree: below(input.len()?, scene.subtrees.len())?,
297            },
298            _ => return None,
299        };
300        scene.nodes.push(Node {
301            meta,
302            transform,
303            kind,
304        });
305        placed.push(false);
306    }
307
308    for _ in 0..input.count(4)? {
309        let root = input.len()?;
310        place(&mut placed, root, scene.nodes.len())?;
311        scene.roots.push(root);
312    }
313    input.is_empty().then_some(())
314}
315
316/// `index`, when it is below `count`.
317fn below(index: usize, count: usize) -> Option<usize> {
318    (index < count).then_some(index)
319}
320
321/// Gives `node` its one place in the scene: `None` when it is not among the
322/// first `listed` nodes or already has a place.
323fn place(placed: &mut [bool], node: usize, listed: usize) -> Option<()> {
324    let slot = placed.get_mut(below(node, listed)?)?;
325    (!std::mem::replace(slot, true)).then_some(())
326}
327
328fn write_transform(out: &mut Out, transform: Option<&Transform>) {
329    match transform {
330        None => out.u8(0),
331        Some(transform) => {
332            out.u8(1);
333            for value in transform
334                .linear
335                .as_flattened()
336                .iter()
337                .chain(&transform.translation)
338            {
339                out.f64(*value);
340            }
341        }
342    }
343}
344
345fn read_transform(input: &mut In<'_>) -> Option<Option<Transform>> {
346    match input.u8()? {
347        0 => Some(None),
348        1 => {
349            let mut transform = Transform {
350                linear: [[0.0; 3]; 3],
351                translation: [0.0; 3],
352            };
353            for value in transform
354                .linear
355                .as_flattened_mut()
356                .iter_mut()
357                .chain(&mut transform.translation)
358            {
359                *value = input.f64()?;
360            }
361            Some(Some(transform))
362        }
363        _ => None,
364    }
365}