1use std::collections::HashSet;
30use std::fmt;
31
32use crate::bytes::{In, Out, fits_u32};
33use crate::container::ChunkTag;
34use crate::program::is_name;
35use crate::scene::Scene;
36
37pub const SURFACE_TAG: ChunkTag = ChunkTag(*b"SURF");
39
40pub const SURFACE_VERSION: u16 = 2;
43
44#[derive(Clone, Debug, Default, PartialEq, Eq)]
46pub struct SurfaceEntry {
47 pub program: Option<String>,
53 pub leaf: usize,
55 pub kind: u8,
59 pub version: u32,
61 pub document: Vec<u8>,
63}
64
65#[derive(Clone, Debug, PartialEq, Eq)]
67pub enum EncodeSurfaceError {
68 NoProgram,
70 BadName { program: String },
72 NotALeaf,
75 SameEntry,
77 TooLarge,
79}
80
81impl fmt::Display for EncodeSurfaceError {
82 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
83 match self {
84 Self::NoProgram => f.write_str("a surface paint entry names no program"),
85 Self::BadName { program } => write!(f, "{program:?} is not a program name"),
86 Self::NotALeaf => f.write_str(NOT_A_LEAF),
87 Self::SameEntry => f.write_str(SAME_ENTRY),
88 Self::TooLarge => f.write_str("the surface paint is too large for its chunk"),
89 }
90 }
91}
92
93impl std::error::Error for EncodeSurfaceError {}
94
95#[derive(Clone, Debug, PartialEq, Eq)]
97pub enum DecodeSurfaceError {
98 Malformed,
101 NotALeaf,
104 SameEntry,
106}
107
108impl fmt::Display for DecodeSurfaceError {
109 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
110 match self {
111 Self::Malformed => f.write_str("the surface paint data is malformed"),
112 Self::NotALeaf => f.write_str(NOT_A_LEAF),
113 Self::SameEntry => f.write_str(SAME_ENTRY),
114 }
115 }
116}
117
118impl std::error::Error for DecodeSurfaceError {}
119
120const NOT_A_LEAF: &str = "surface paint names a scene part that is not a leaf";
121const SAME_ENTRY: &str = "two surface paint entries have the same program, leaf and kind";
122
123enum Broken {
125 NotALeaf,
126 SameEntry,
127}
128
129impl From<Broken> for EncodeSurfaceError {
130 fn from(broken: Broken) -> Self {
131 match broken {
132 Broken::NotALeaf => Self::NotALeaf,
133 Broken::SameEntry => Self::SameEntry,
134 }
135 }
136}
137
138impl From<Broken> for DecodeSurfaceError {
139 fn from(broken: Broken) -> Self {
140 match broken {
141 Broken::NotALeaf => Self::NotALeaf,
142 Broken::SameEntry => Self::SameEntry,
143 }
144 }
145}
146
147pub fn encode_surface(
151 entries: &[SurfaceEntry],
152 scene: &Scene,
153) -> Result<Vec<u8>, EncodeSurfaceError> {
154 for entry in entries {
155 let program = entry
156 .program
157 .as_ref()
158 .ok_or(EncodeSurfaceError::NoProgram)?;
159 if !is_name(program.as_bytes()) {
160 return Err(EncodeSurfaceError::BadName {
161 program: program.clone(),
162 });
163 }
164 }
165 check(entries, scene)?;
166 if !fits_u32(entries.len()) || entries.iter().any(|entry| !fits_u32(entry.document.len())) {
167 return Err(EncodeSurfaceError::TooLarge);
168 }
169 let mut out = Out::default();
170 out.len(entries.len());
171 for entry in entries {
172 out.bytes(entry.program.as_deref().unwrap_or_default().as_bytes());
174 out.len(entry.leaf);
176 out.u8(entry.kind);
177 out.u32(entry.version);
178 out.bytes(&entry.document);
179 }
180 Ok(out.0)
181}
182
183pub fn decode_surface(
186 payload: &[u8],
187 scene: &Scene,
188) -> Result<Vec<SurfaceEntry>, DecodeSurfaceError> {
189 decode(payload, scene, true)
190}
191
192pub fn decode_surface_v1(
195 payload: &[u8],
196 scene: &Scene,
197) -> Result<Vec<SurfaceEntry>, DecodeSurfaceError> {
198 decode(payload, scene, false)
199}
200
201fn decode(
203 payload: &[u8],
204 scene: &Scene,
205 named: bool,
206) -> Result<Vec<SurfaceEntry>, DecodeSurfaceError> {
207 let mut input = In(payload);
208 let malformed = DecodeSurfaceError::Malformed;
209 let smallest = if named { 18 } else { 13 };
212 let count = input.count(smallest).ok_or(malformed.clone())?;
213 let mut entries = Vec::with_capacity(count);
214 for _ in 0..count {
215 let program = if named {
216 let name = input.bytes().ok_or(malformed.clone())?;
217 if !is_name(name) {
218 return Err(malformed);
219 }
220 Some(String::from_utf8_lossy(name).into_owned())
222 } else {
223 None
224 };
225 let leaf = input.len().ok_or(malformed.clone())?;
226 let kind = input.u8().ok_or(malformed.clone())?;
227 let version = input.u32().ok_or(malformed.clone())?;
228 let document = input.bytes().ok_or(malformed.clone())?.to_vec();
229 entries.push(SurfaceEntry {
230 program,
231 leaf,
232 kind,
233 version,
234 document,
235 });
236 }
237 if !input.is_empty() {
238 return Err(malformed);
239 }
240 check(&entries, scene)?;
241 Ok(entries)
242}
243
244fn check(entries: &[SurfaceEntry], scene: &Scene) -> Result<(), Broken> {
248 let mut seen = HashSet::new();
249 for entry in entries {
250 scene.leaf_mesh(entry.leaf).ok_or(Broken::NotALeaf)?;
251 if !seen.insert((entry.program.as_deref(), entry.leaf, entry.kind)) {
252 return Err(Broken::SameEntry);
253 }
254 }
255 Ok(())
256}