Skip to main content

bread_format/
surface.rs

1/*
2 * SPDX-FileCopyrightText: 2026 SynrgStudio
3 * SPDX-License-Identifier: Apache-2.0
4 */
5
6//! The surface paint chunk (`SPEC.md`, section 10): what a person painted on
7//! the faces of models, one mask per leaf and kind.
8//!
9//! Only the envelope is checked: each entry names a leaf, and no two entries
10//! share a leaf and a kind. Documents are carried without being read, since a
11//! document never makes a file unreadable; the program that uses the paint
12//! checks it against the leaf's mesh.
13//!
14//! ```text
15//! entries   u32 count, then per entry:
16//!           u32 the leaf's node index in the scene chunk
17//!           u8  the kind: 0 detail, 1 supports must touch, 2 must not touch
18//!           u32 document version
19//!           u32 length, document
20//! ```
21
22use std::collections::HashSet;
23use std::fmt;
24
25use crate::bytes::{In, Out, fits_u32};
26use crate::container::ChunkTag;
27use crate::scene::Scene;
28
29/// The tag of the surface paint chunk.
30pub const SURFACE_TAG: ChunkTag = ChunkTag(*b"SURF");
31
32/// The surface paint payload layout this build writes and reads.
33pub const SURFACE_VERSION: u16 = 1;
34
35/// One painted mask of one leaf.
36#[derive(Clone, Debug, Default, PartialEq, Eq)]
37pub struct SurfaceEntry {
38    /// The painted leaf, as an index into the scene's nodes.
39    pub leaf: usize,
40    /// What the paint means: 0 detail, 1 supports must touch, 2 supports
41    /// must not touch. Other values are reserved, and carried as they are.
42    pub kind: u8,
43    /// The version of the document.
44    pub version: u32,
45    /// The mask, carried without being read.
46    pub document: Vec<u8>,
47}
48
49/// Why a list of paint entries could not be encoded.
50#[derive(Clone, Debug, PartialEq, Eq)]
51pub enum EncodeSurfaceError {
52    /// An entry names a node the scene does not have, or one that is not a
53    /// leaf.
54    NotALeaf,
55    /// Two entries have the same leaf and kind.
56    SameEntry,
57    /// There are 2^32 or more entries, or a document of 4 GiB or more.
58    TooLarge,
59}
60
61impl fmt::Display for EncodeSurfaceError {
62    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
63        match self {
64            Self::NotALeaf => f.write_str(NOT_A_LEAF),
65            Self::SameEntry => f.write_str(SAME_ENTRY),
66            Self::TooLarge => f.write_str("the surface paint is too large for its chunk"),
67        }
68    }
69}
70
71impl std::error::Error for EncodeSurfaceError {}
72
73/// Why a surface paint payload could not be decoded.
74#[derive(Clone, Debug, PartialEq, Eq)]
75pub enum DecodeSurfaceError {
76    /// The payload is cut short or padded.
77    Malformed,
78    /// An entry names a node the scene does not have, or one that is not a
79    /// leaf.
80    NotALeaf,
81    /// Two entries have the same leaf and kind.
82    SameEntry,
83}
84
85impl fmt::Display for DecodeSurfaceError {
86    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
87        match self {
88            Self::Malformed => f.write_str("the surface paint data is malformed"),
89            Self::NotALeaf => f.write_str(NOT_A_LEAF),
90            Self::SameEntry => f.write_str(SAME_ENTRY),
91        }
92    }
93}
94
95impl std::error::Error for DecodeSurfaceError {}
96
97const NOT_A_LEAF: &str = "surface paint names a scene part that is not a leaf";
98const SAME_ENTRY: &str = "two surface paint entries have the same leaf and kind";
99
100/// A rule of section 10 that some entries break.
101enum Broken {
102    NotALeaf,
103    SameEntry,
104}
105
106impl From<Broken> for EncodeSurfaceError {
107    fn from(broken: Broken) -> Self {
108        match broken {
109            Broken::NotALeaf => Self::NotALeaf,
110            Broken::SameEntry => Self::SameEntry,
111        }
112    }
113}
114
115impl From<Broken> for DecodeSurfaceError {
116    fn from(broken: Broken) -> Self {
117        match broken {
118            Broken::NotALeaf => Self::NotALeaf,
119            Broken::SameEntry => Self::SameEntry,
120        }
121    }
122}
123
124/// Encodes `entries` as a surface paint payload, in their order, checking
125/// them against `scene`.
126pub fn encode_surface(
127    entries: &[SurfaceEntry],
128    scene: &Scene,
129) -> Result<Vec<u8>, EncodeSurfaceError> {
130    check(entries, scene)?;
131    if !fits_u32(entries.len()) || entries.iter().any(|entry| !fits_u32(entry.document.len())) {
132        return Err(EncodeSurfaceError::TooLarge);
133    }
134    let mut out = Out::default();
135    out.len(entries.len());
136    for entry in entries {
137        // The leaf was checked against the scene, whose node count fits.
138        out.len(entry.leaf);
139        out.u8(entry.kind);
140        out.u32(entry.version);
141        out.bytes(&entry.document);
142    }
143    Ok(out.0)
144}
145
146/// Decodes a surface paint payload, checking it against `scene`, the scene
147/// of the same file.
148pub fn decode_surface(
149    payload: &[u8],
150    scene: &Scene,
151) -> Result<Vec<SurfaceEntry>, DecodeSurfaceError> {
152    let mut input = In(payload);
153    let malformed = DecodeSurfaceError::Malformed;
154    let count = input.count(13).ok_or(malformed.clone())?;
155    let mut entries = Vec::with_capacity(count);
156    for _ in 0..count {
157        let leaf = input.len().ok_or(malformed.clone())?;
158        let kind = input.u8().ok_or(malformed.clone())?;
159        let version = input.u32().ok_or(malformed.clone())?;
160        let document = input.bytes().ok_or(malformed.clone())?.to_vec();
161        entries.push(SurfaceEntry {
162            leaf,
163            kind,
164            version,
165            document,
166        });
167    }
168    if !input.is_empty() {
169        return Err(malformed);
170    }
171    check(&entries, scene)?;
172    Ok(entries)
173}
174
175/// Every entry names a leaf, and no two share a leaf and a kind.
176fn check(entries: &[SurfaceEntry], scene: &Scene) -> Result<(), Broken> {
177    let mut seen = HashSet::new();
178    for entry in entries {
179        scene.leaf_mesh(entry.leaf).ok_or(Broken::NotALeaf)?;
180        if !seen.insert((entry.leaf, entry.kind)) {
181            return Err(Broken::SameEntry);
182        }
183    }
184    Ok(())
185}