Skip to main content

bread_format/
app.rs

1/*
2 * SPDX-FileCopyrightText: 2026 SynrgStudio
3 * SPDX-License-Identifier: Apache-2.0
4 */
5
6//! The application chunks (`SPEC.md`, section 7.3): documents that belong to
7//! one program, carried without being read.
8//!
9//! The project settings chunk is the settings document itself. The supports
10//! and hollows chunks share one envelope: a list of entries, each about one
11//! model of the scene, naming one more part of it, and holding a document
12//! named by the generator that wrote it. In the supports chunk that part is
13//! the leaf that shows the supports; in the hollows chunk it is the mesh the
14//! model was hollowed from. The crate checks the envelope against the scene
15//! and never reads the documents: telling which generators and document
16//! versions it understands is up to the program.
17//!
18//! ```text
19//! entries   u32 count, then per entry:
20//!           u32 the model leaf's node index in the scene chunk
21//!           u32 supports: the support leaf's node index
22//!               hollows: the original's mesh index
23//!           u32 length, UTF-8 generator name
24//!           u32 generator document version
25//!           u32 length, document bytes
26//! ```
27
28use std::collections::HashSet;
29use std::fmt;
30
31use crate::bytes::{In, Out, fits_u32};
32use crate::container::ChunkTag;
33use crate::scene::{NodeKind, Scene};
34
35/// The tag of the project settings chunk, whose payload is the settings
36/// document: UTF-8 TOML that starts with its own version.
37pub const SETTINGS_TAG: ChunkTag = ChunkTag(*b"PROJ");
38
39/// The project settings chunk version this build writes and reads.
40pub const SETTINGS_VERSION: u16 = 1;
41
42/// The tag of the supports chunk. Its support leaves are stored with an
43/// empty mesh, which the generator rebuilds from the document.
44pub const SUPPORTS_TAG: ChunkTag = ChunkTag(*b"SUPP");
45
46/// The supports payload layout this build writes and reads.
47pub const SUPPORTS_VERSION: u16 = 2;
48
49/// The tag of the hollows chunk. Its models show the hollow.
50pub const HOLLOWS_TAG: ChunkTag = ChunkTag(*b"HOLW");
51
52/// The hollows payload layout this build writes and reads.
53pub const HOLLOWS_VERSION: u16 = 2;
54
55/// A program's supports for one model of the scene.
56#[derive(Clone, Debug, PartialEq, Eq)]
57pub struct SupportEntry {
58    /// The leaf of the model the supports stand on, as an index into the
59    /// scene's nodes.
60    pub model: usize,
61    /// The leaf that shows the supports, with an empty mesh.
62    pub support: usize,
63    /// Which generator wrote `document`, such as `"df"`.
64    pub generator: String,
65    /// The generator's own version of `document`.
66    pub version: u32,
67    pub document: Vec<u8>,
68}
69
70/// How a program hollowed one model of the scene.
71#[derive(Clone, Debug, PartialEq, Eq)]
72pub struct HollowEntry {
73    /// The leaf of the hollowed model, as an index into the scene's nodes.
74    pub model: usize,
75    /// The mesh the model was hollowed from, as an index into the scene's
76    /// meshes.
77    pub original: usize,
78    /// Which generator wrote `document`, such as `"df"`.
79    pub generator: String,
80    /// The generator's own version of `document`.
81    pub version: u32,
82    pub document: Vec<u8>,
83}
84
85/// Why a list of supports or hollows could not be encoded.
86#[derive(Clone, Debug, PartialEq, Eq)]
87pub enum EncodeDocumentsError {
88    /// A model or a support leaf names a node the scene does not have, or
89    /// one that is not a leaf.
90    NotALeaf,
91    /// An original names a mesh the scene does not have.
92    NoSuchMesh,
93    /// Two entries name the same model.
94    SameModel,
95    /// Two entries name the same support leaf, or a support leaf is also a
96    /// model.
97    SharedSupport,
98    /// There are 2^32 or more entries, or a generator name or a document of
99    /// 4 GiB or more.
100    TooLarge,
101}
102
103impl fmt::Display for EncodeDocumentsError {
104    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
105        match self {
106            Self::NotALeaf => f.write_str(NOT_A_LEAF),
107            Self::NoSuchMesh => f.write_str(NO_SUCH_MESH),
108            Self::SameModel => f.write_str(SAME_MODEL),
109            Self::SharedSupport => f.write_str(SHARED_SUPPORT),
110            Self::TooLarge => f.write_str("the documents are too large for their chunk"),
111        }
112    }
113}
114
115impl std::error::Error for EncodeDocumentsError {}
116
117/// Why a supports or hollows payload could not be decoded.
118#[derive(Clone, Debug, PartialEq, Eq)]
119pub enum DecodeDocumentsError {
120    /// The payload is cut short, padded, or not text where text belongs.
121    Malformed,
122    /// A model or a support leaf names a node the scene does not have, or
123    /// one that is not a leaf.
124    NotALeaf,
125    /// An original names a mesh the scene does not have.
126    NoSuchMesh,
127    /// Two entries name the same model.
128    SameModel,
129    /// Two entries name the same support leaf, or a support leaf is also a
130    /// model.
131    SharedSupport,
132}
133
134impl fmt::Display for DecodeDocumentsError {
135    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
136        match self {
137            Self::Malformed => f.write_str("the document data is malformed"),
138            Self::NotALeaf => f.write_str(NOT_A_LEAF),
139            Self::NoSuchMesh => f.write_str(NO_SUCH_MESH),
140            Self::SameModel => f.write_str(SAME_MODEL),
141            Self::SharedSupport => f.write_str(SHARED_SUPPORT),
142        }
143    }
144}
145
146impl std::error::Error for DecodeDocumentsError {}
147
148const NOT_A_LEAF: &str = "a document names a scene part that is not a model";
149const NO_SUCH_MESH: &str = "a hollow names an original mesh the file does not have";
150const SAME_MODEL: &str = "two documents of one kind belong to the same model";
151const SHARED_SUPPORT: &str = "a support part belongs to two models, or is a model itself";
152
153/// A rule of section 7.3 that some entries break.
154enum Broken {
155    NotALeaf,
156    NoSuchMesh,
157    SameModel,
158    SharedSupport,
159}
160
161impl From<Broken> for EncodeDocumentsError {
162    fn from(broken: Broken) -> Self {
163        match broken {
164            Broken::NotALeaf => Self::NotALeaf,
165            Broken::NoSuchMesh => Self::NoSuchMesh,
166            Broken::SameModel => Self::SameModel,
167            Broken::SharedSupport => Self::SharedSupport,
168        }
169    }
170}
171
172impl From<Broken> for DecodeDocumentsError {
173    fn from(broken: Broken) -> Self {
174        match broken {
175            Broken::NotALeaf => Self::NotALeaf,
176            Broken::NoSuchMesh => Self::NoSuchMesh,
177            Broken::SameModel => Self::SameModel,
178            Broken::SharedSupport => Self::SharedSupport,
179        }
180    }
181}
182
183/// The fields every entry has, in the order of the payload.
184struct Entry<'a> {
185    model: usize,
186    part: usize,
187    generator: &'a str,
188    version: u32,
189    document: &'a [u8],
190}
191
192/// Encodes `supports` as a supports payload, checking them against `scene`.
193pub fn encode_supports(
194    supports: &[SupportEntry],
195    scene: &Scene,
196) -> Result<Vec<u8>, EncodeDocumentsError> {
197    check_supports(supports, scene)?;
198    encode(supports.iter().map(|entry| Entry {
199        model: entry.model,
200        part: entry.support,
201        generator: &entry.generator,
202        version: entry.version,
203        document: &entry.document,
204    }))
205}
206
207/// Encodes `hollows` as a hollows payload, checking them against `scene`.
208pub fn encode_hollows(
209    hollows: &[HollowEntry],
210    scene: &Scene,
211) -> Result<Vec<u8>, EncodeDocumentsError> {
212    check_hollows(hollows, scene)?;
213    encode(hollows.iter().map(|entry| Entry {
214        model: entry.model,
215        part: entry.original,
216        generator: &entry.generator,
217        version: entry.version,
218        document: &entry.document,
219    }))
220}
221
222/// Decodes a supports payload, checking it against `scene`, the scene of the
223/// same file.
224pub fn decode_supports(
225    payload: &[u8],
226    scene: &Scene,
227) -> Result<Vec<SupportEntry>, DecodeDocumentsError> {
228    let supports: Vec<_> = decode(payload)?
229        .into_iter()
230        .map(|entry| SupportEntry {
231            model: entry.model,
232            support: entry.part,
233            generator: entry.generator.to_owned(),
234            version: entry.version,
235            document: entry.document.to_vec(),
236        })
237        .collect();
238    check_supports(&supports, scene)?;
239    Ok(supports)
240}
241
242/// Decodes a hollows payload, checking it against `scene`, the scene of the
243/// same file.
244pub fn decode_hollows(
245    payload: &[u8],
246    scene: &Scene,
247) -> Result<Vec<HollowEntry>, DecodeDocumentsError> {
248    let hollows: Vec<_> = decode(payload)?
249        .into_iter()
250        .map(|entry| HollowEntry {
251            model: entry.model,
252            original: entry.part,
253            generator: entry.generator.to_owned(),
254            version: entry.version,
255            document: entry.document.to_vec(),
256        })
257        .collect();
258    check_hollows(&hollows, scene)?;
259    Ok(hollows)
260}
261
262fn encode<'a>(
263    entries: impl ExactSizeIterator<Item = Entry<'a>>,
264) -> Result<Vec<u8>, EncodeDocumentsError> {
265    if !fits_u32(entries.len()) {
266        return Err(EncodeDocumentsError::TooLarge);
267    }
268    let mut out = Out::default();
269    out.len(entries.len());
270    for entry in entries {
271        // Both indices were checked against the scene, whose counts fit.
272        if !fits_u32(entry.generator.len()) || !fits_u32(entry.document.len()) {
273            return Err(EncodeDocumentsError::TooLarge);
274        }
275        out.len(entry.model);
276        out.len(entry.part);
277        out.bytes(entry.generator.as_bytes());
278        out.u32(entry.version);
279        out.bytes(entry.document);
280    }
281    Ok(out.0)
282}
283
284fn decode(payload: &[u8]) -> Result<Vec<Entry<'_>>, DecodeDocumentsError> {
285    let mut input = In(payload);
286    let malformed = DecodeDocumentsError::Malformed;
287    let count = input.count(20).ok_or(malformed.clone())?;
288    let mut entries = Vec::with_capacity(count);
289    for _ in 0..count {
290        let model = input.len().ok_or(malformed.clone())?;
291        let part = input.len().ok_or(malformed.clone())?;
292        let generator = input
293            .bytes()
294            .and_then(|bytes| std::str::from_utf8(bytes).ok())
295            .ok_or(malformed.clone())?;
296        let version = input.u32().ok_or(malformed.clone())?;
297        let document = input.bytes().ok_or(malformed.clone())?;
298        entries.push(Entry {
299            model,
300            part,
301            generator,
302            version,
303            document,
304        });
305    }
306    if !input.is_empty() {
307        return Err(malformed);
308    }
309    Ok(entries)
310}
311
312/// Every model and support leaf is a leaf, no two entries share a model, and
313/// each support leaf belongs to one entry and is no model.
314fn check_supports(supports: &[SupportEntry], scene: &Scene) -> Result<(), Broken> {
315    let mut models = HashSet::new();
316    for entry in supports {
317        if !is_leaf(scene, entry.model) || !is_leaf(scene, entry.support) {
318            return Err(Broken::NotALeaf);
319        }
320        if !models.insert(entry.model) {
321            return Err(Broken::SameModel);
322        }
323    }
324    let mut leaves = HashSet::new();
325    for entry in supports {
326        if models.contains(&entry.support) || !leaves.insert(entry.support) {
327            return Err(Broken::SharedSupport);
328        }
329    }
330    Ok(())
331}
332
333/// Every model is a leaf, every original a mesh, and no two entries share a
334/// model.
335fn check_hollows(hollows: &[HollowEntry], scene: &Scene) -> Result<(), Broken> {
336    let mut models = HashSet::new();
337    for entry in hollows {
338        if !is_leaf(scene, entry.model) {
339            return Err(Broken::NotALeaf);
340        }
341        if entry.original >= scene.meshes.len() {
342            return Err(Broken::NoSuchMesh);
343        }
344        if !models.insert(entry.model) {
345            return Err(Broken::SameModel);
346        }
347    }
348    Ok(())
349}
350
351fn is_leaf(scene: &Scene, node: usize) -> bool {
352    matches!(
353        scene.nodes.get(node).map(|node| &node.kind),
354        Some(NodeKind::Leaf { .. } | NodeKind::SharedLeaf { .. })
355    )
356}