Skip to main content

bread_format/
role.rs

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