1use std::collections::{HashMap, HashSet};
30use std::fmt;
31
32use crate::bytes::{In, Out, fits_u32};
33use crate::container::ChunkTag;
34use crate::program::is_name;
35use crate::scene::{NodeKind, Scene, Transform, read_transform, write_transform};
36
37pub const VOLUME_TAG: ChunkTag = ChunkTag(*b"VOLM");
39
40pub const VOLUME_VERSION: u16 = 1;
42
43pub const VOLUME_SUPPORT_ENFORCER: u8 = 1;
45
46pub const VOLUME_SUPPORT_BLOCKER: u8 = 2;
48
49pub const VOLUME_MODIFIER: u8 = 3;
51
52pub const VOLUME_NEGATIVE: u8 = 4;
54
55pub const VOLUME_UNCUT: u8 = 5;
57
58#[derive(Clone, Debug, Default, PartialEq)]
60pub struct VolumeEntry {
61 pub model: usize,
63 pub kind: u8,
66 pub mesh: usize,
68 pub name: Option<String>,
70 pub transform: Option<Transform>,
73 pub program: String,
77 pub version: u32,
79 pub document: Vec<u8>,
82}
83
84impl VolumeEntry {
85 pub fn is_known(&self) -> bool {
88 matches!(
89 self.kind,
90 VOLUME_SUPPORT_ENFORCER
91 | VOLUME_SUPPORT_BLOCKER
92 | VOLUME_MODIFIER
93 | VOLUME_NEGATIVE
94 | VOLUME_UNCUT
95 )
96 }
97
98 pub fn is_volume(&self) -> bool {
100 self.is_known() && self.kind != VOLUME_UNCUT
101 }
102}
103
104#[derive(Clone, Debug, PartialEq, Eq)]
106pub enum EncodeVolumesError {
107 BadName { program: String },
109 NotALeaf,
112 NoSuchMesh,
114 VolumeShown,
116 UncutMoved,
118 UncutCount,
121 ReservedKind,
123 TooLarge,
126}
127
128impl fmt::Display for EncodeVolumesError {
129 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
130 match self {
131 Self::BadName { program } => write!(f, "{program:?} is not a program name"),
132 Self::NotALeaf => f.write_str(NOT_A_LEAF),
133 Self::NoSuchMesh => f.write_str(NO_SUCH_MESH),
134 Self::VolumeShown => f.write_str(VOLUME_SHOWN),
135 Self::UncutMoved => f.write_str(UNCUT_MOVED),
136 Self::UncutCount => f.write_str(UNCUT_COUNT),
137 Self::ReservedKind => f.write_str("a volume entry has a reserved kind"),
138 Self::TooLarge => f.write_str("the volumes are too large for their chunk"),
139 }
140 }
141}
142
143impl std::error::Error for EncodeVolumesError {}
144
145#[derive(Clone, Debug, PartialEq, Eq)]
147pub enum DecodeVolumesError {
148 Malformed,
151 NotALeaf,
154 NoSuchMesh,
156 VolumeShown,
158 UncutMoved,
160 UncutCount,
163}
164
165impl fmt::Display for DecodeVolumesError {
166 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
167 match self {
168 Self::Malformed => f.write_str("the volume data is malformed"),
169 Self::NotALeaf => f.write_str(NOT_A_LEAF),
170 Self::NoSuchMesh => f.write_str(NO_SUCH_MESH),
171 Self::VolumeShown => f.write_str(VOLUME_SHOWN),
172 Self::UncutMoved => f.write_str(UNCUT_MOVED),
173 Self::UncutCount => f.write_str(UNCUT_COUNT),
174 }
175 }
176}
177
178impl std::error::Error for DecodeVolumesError {}
179
180const NOT_A_LEAF: &str = "a volume belongs to a scene part that is not a leaf";
181const NO_SUCH_MESH: &str = "a volume names a mesh the file does not have";
182const VOLUME_SHOWN: &str = "a leaf shows the mesh of a volume, which never prints";
183const UNCUT_MOVED: &str = "the uncut model of a volume entry has a transform";
184const UNCUT_COUNT: &str = "a model's negative volumes and its uncut model do not go together";
185
186enum Broken {
188 NotALeaf,
189 NoSuchMesh,
190 VolumeShown,
191 UncutMoved,
192 UncutCount,
193}
194
195impl From<Broken> for EncodeVolumesError {
196 fn from(broken: Broken) -> Self {
197 match broken {
198 Broken::NotALeaf => Self::NotALeaf,
199 Broken::NoSuchMesh => Self::NoSuchMesh,
200 Broken::VolumeShown => Self::VolumeShown,
201 Broken::UncutMoved => Self::UncutMoved,
202 Broken::UncutCount => Self::UncutCount,
203 }
204 }
205}
206
207impl From<Broken> for DecodeVolumesError {
208 fn from(broken: Broken) -> Self {
209 match broken {
210 Broken::NotALeaf => Self::NotALeaf,
211 Broken::NoSuchMesh => Self::NoSuchMesh,
212 Broken::VolumeShown => Self::VolumeShown,
213 Broken::UncutMoved => Self::UncutMoved,
214 Broken::UncutCount => Self::UncutCount,
215 }
216 }
217}
218
219const MIN_ENTRY: usize = 4 + 1 + 4 + 1 + 1 + 5 + 4 + 4;
222
223pub fn encode_volumes(
226 entries: &[VolumeEntry],
227 scene: &Scene,
228) -> Result<Vec<u8>, EncodeVolumesError> {
229 if let Some(entry) = entries
230 .iter()
231 .find(|entry| !is_name(entry.program.as_bytes()))
232 {
233 return Err(EncodeVolumesError::BadName {
234 program: entry.program.clone(),
235 });
236 }
237 check(entries, scene)?;
238 if entries.iter().any(|entry| !entry.is_known()) {
239 return Err(EncodeVolumesError::ReservedKind);
240 }
241 let fits = fits_u32(entries.len())
242 && entries.iter().all(|entry| {
243 entry.name.as_ref().is_none_or(|name| fits_u32(name.len()))
244 && fits_u32(entry.document.len())
245 });
246 if !fits {
247 return Err(EncodeVolumesError::TooLarge);
248 }
249 let mut out = Out::default();
250 out.len(entries.len());
251 for entry in entries {
252 out.len(entry.model);
255 out.u8(entry.kind);
256 out.len(entry.mesh);
257 out.text(entry.name.as_deref());
258 write_transform(&mut out, entry.transform.as_ref());
259 out.bytes(entry.program.as_bytes());
260 out.u32(entry.version);
261 out.bytes(&entry.document);
262 }
263 Ok(out.0)
264}
265
266pub fn decode_volumes(
269 payload: &[u8],
270 scene: &Scene,
271) -> Result<Vec<VolumeEntry>, DecodeVolumesError> {
272 let mut input = In(payload);
273 let entries = read(&mut input).ok_or(DecodeVolumesError::Malformed)?;
274 if !input.is_empty() {
275 return Err(DecodeVolumesError::Malformed);
276 }
277 check(&entries, scene)?;
278 Ok(entries)
279}
280
281fn read(input: &mut In<'_>) -> Option<Vec<VolumeEntry>> {
282 let count = input.count(MIN_ENTRY)?;
283 let mut entries = Vec::with_capacity(count);
284 for _ in 0..count {
285 let model = input.len()?;
286 let kind = input.u8()?;
287 let mesh = input.len()?;
288 let name = input.text()?;
289 let transform = read_transform(input)?;
290 let program = input.bytes()?;
291 if !is_name(program) {
292 return None;
293 }
294 let program = String::from_utf8_lossy(program).into_owned();
296 let version = input.u32()?;
297 let document = input.bytes()?.to_vec();
298 entries.push(VolumeEntry {
299 model,
300 kind,
301 mesh,
302 name,
303 transform,
304 program,
305 version,
306 document,
307 });
308 }
309 Some(entries)
310}
311
312fn check(entries: &[VolumeEntry], scene: &Scene) -> Result<(), Broken> {
317 for entry in entries {
318 scene.leaf_mesh(entry.model).ok_or(Broken::NotALeaf)?;
319 if entry.mesh >= scene.meshes.len() {
320 return Err(Broken::NoSuchMesh);
321 }
322 }
323 let shown = shown_meshes(scene);
324 let mut cut = HashSet::new();
325 let mut uncut: HashMap<usize, usize> = HashMap::new();
326 for entry in entries.iter().filter(|entry| entry.is_known()) {
327 if entry.is_volume() && shown.contains(&entry.mesh) {
328 return Err(Broken::VolumeShown);
329 }
330 match entry.kind {
331 VOLUME_NEGATIVE => {
332 cut.insert(entry.model);
333 }
334 VOLUME_UNCUT => {
335 if entry.transform.is_some() {
336 return Err(Broken::UncutMoved);
337 }
338 *uncut.entry(entry.model).or_default() += 1;
339 }
340 _ => {}
341 }
342 }
343 let one_each = uncut.values().all(|&n| n == 1);
344 let same_models = cut.len() == uncut.len() && cut.iter().all(|model| uncut.contains_key(model));
345 if !one_each || !same_models {
346 return Err(Broken::UncutCount);
347 }
348 Ok(())
349}
350
351fn shown_meshes(scene: &Scene) -> HashSet<usize> {
354 scene
355 .nodes
356 .iter()
357 .filter_map(|node| match node.kind {
358 NodeKind::Leaf { mesh } => Some(mesh),
359 NodeKind::SharedLeaf { resource } => scene.mesh_resources.get(resource).copied(),
360 _ => None,
361 })
362 .collect()
363}