Skip to main content

unityrs_meshdecode/
triangles.rs

1// Ported from UnityPy 1.25.2 (MIT): UnityPy/helpers/MeshHelper.py's MeshHandler.get_triangles. See THIRD_PARTY_LICENSES.
2//! `get_triangles` (`helpers/MeshHelper.py:630-683`): each submesh's
3//! triangles from the index buffer.
4//!
5//! A submesh starts at `firstByte // 2` indices, halved again for 32-bit
6//! indices, and spans `indexCount` of them:
7//!
8//! - **Triangles** (`topology` 0): every third index from the start, each
9//!   with the slice of three that begins there, `buffer[i:i+3]`. Python's
10//!   slice stops at the buffer's end, so past it the tuples are shorter,
11//!   then empty: [`SubMeshTriangles`] holds the whole ones, the one cut
12//!   short, if any, and the count of empty ones, never allocating those.
13//! - **Strips** (below 4, or `topology` 1): a triangle at each index but
14//!   the last two, each from the three indices there; one with two equal
15//!   indices is skipped, and every odd one from the start swaps its first
16//!   two. The submesh's `indexCount` is then set to three per triangle
17//!   kept ([`SubMeshTriangles::index_count`]): UnityPy writes it into the
18//!   `SubMesh`, so a second call reads the new count, where this crate
19//!   reads its input and changes nothing. A strip whose indices run past
20//!   the buffer raises `ValueError` "not enough values to unpack".
21//! - **Quads** (`topology` 2): two triangles per four indices, `(a, b, c)`
22//!   and `(a, c, d)`, in a list of `indexCount // 2`: a count that is not
23//!   a multiple of 4 overruns it, `IndexError` "list assignment index out
24//!   of range", once every quad before has unpacked.
25//! - Anything else, lines, points, no `topology` at all from 4 on, or any
26//!   other value: `ValueError` "Failed getting triangles. Submesh topology
27//!   is lines or points.".
28//!
29//! **Bounds.** The submeshes are counted as decode work on the caller's
30//! meter, one unit each, before the loop over them; then each submesh's
31//! triangles are charged to it, and a list's tuples or a strip's or quads'
32//! loop counted, before the submesh is read (`docs/plans/extract.md` E59),
33//! and every field read counts its scans ([`unityrs_core::objmode`]). Empty
34//! tuples cost nothing, so a count of 2^32 past a short buffer is one
35//! number.
36
37use std::sync::Arc;
38
39use unityrs_core::limits::{Charge, Meter, MeteredVec};
40
41use crate::Version;
42use crate::error::{IndexKind, MeshError};
43use crate::format::MeshTopology;
44use crate::vertex::field;
45use unityrs_core::objmode::{Obj, SUB_MESH};
46
47/// `get_triangles()`'s list: one [`SubMeshTriangles`] per submesh.
48#[derive(Debug)]
49pub struct Triangles {
50    submeshes: Vec<SubMeshTriangles>,
51    // Declared last: the charge is returned after the list is freed.
52    _charge: Charge,
53}
54
55const _: () = crate::send_sync::<Triangles>();
56
57impl Triangles {
58    /// Takes ownership of already charged submeshes from an API adapter.
59    #[must_use]
60    pub fn from_submeshes(submeshes: MeteredVec<SubMeshTriangles>) -> Self {
61        let (submeshes, charge) = submeshes.into_parts();
62        Self {
63            submeshes,
64            _charge: charge,
65        }
66    }
67
68    /// No triangle evaluation, for exporters that return before faces when
69    /// positions are absent. Allocates nothing; retains the caller's meter.
70    #[must_use]
71    pub fn empty(meter: &Arc<Meter>) -> Self {
72        Self {
73            submeshes: Vec::new(),
74            _charge: Charge::zero(meter),
75        }
76    }
77
78    /// Each submesh's triangles, in the source's order.
79    #[must_use]
80    pub fn submeshes(&self) -> &[SubMeshTriangles] {
81        &self.submeshes
82    }
83}
84
85/// One submesh's list of index tuples (module docs): the whole triangles,
86/// then at most one tuple a triangle list's buffer cut short, then empty
87/// tuples.
88#[derive(Debug)]
89pub struct SubMeshTriangles {
90    triangles: Vec<[u32; 3]>,
91    cut: [u32; 2],
92    cut_len: u8,
93    empty: u64,
94    index_count: u64,
95    // Declared last: the charge is returned after the triangles are freed.
96    _charge: Charge,
97}
98
99const _: () = crate::send_sync::<SubMeshTriangles>();
100
101impl SubMeshTriangles {
102    /// Takes ownership of an already charged list of complete triangles.
103    #[must_use]
104    pub fn from_triangles(triangles: MeteredVec<[u32; 3]>) -> Self {
105        let (triangles, charge) = triangles.into_parts();
106        let index_count = (triangles.len() as u64).saturating_mul(3);
107        Self {
108            triangles,
109            cut: [0; 2],
110            cut_len: 0,
111            empty: 0,
112            index_count,
113            _charge: charge,
114        }
115    }
116
117    /// The tuples of three, first in the list.
118    #[must_use]
119    pub fn triangles(&self) -> &[[u32; 3]] {
120        &self.triangles
121    }
122
123    /// The tuple of one or two indices after them, where a triangle list's
124    /// slice met the buffer's end; empty if there is none.
125    #[must_use]
126    pub fn cut(&self) -> &[u32] {
127        self.cut
128            .get(..usize::from(self.cut_len))
129            .unwrap_or_default()
130    }
131
132    /// How many empty tuples end the list (a triangle list's slices past
133    /// the buffer's end).
134    #[must_use]
135    pub fn empty(&self) -> u64 {
136        self.empty
137    }
138
139    /// The list's length.
140    #[must_use]
141    pub fn len(&self) -> u64 {
142        u64::try_from(self.triangles.len())
143            .unwrap_or(u64::MAX)
144            .saturating_add(u64::from(self.cut_len > 0))
145            .saturating_add(self.empty)
146    }
147
148    /// Whether the list is empty.
149    #[must_use]
150    pub fn is_empty(&self) -> bool {
151        self.len() == 0
152    }
153
154    /// The submesh's `indexCount` after the call: a strip's is three per
155    /// triangle kept, any other's is unchanged.
156    #[must_use]
157    pub fn index_count(&self) -> u64 {
158        self.index_count
159    }
160}
161
162/// `get_triangles()` on what `process` left: the source, the version, the
163/// index size and the index buffer (module docs).
164pub(crate) fn get_triangles(
165    src: &Obj<'_>,
166    version: Version,
167    use_16bit: bool,
168    buffer: Option<&[u32]>,
169    meter: &Arc<Meter>,
170) -> Result<Triangles, MeshError> {
171    // UnityPy MeshHelper.py:631-632
172    let buffer = buffer.ok_or(MeshError::Assertion(""))?;
173    let subs = src
174        .list("m_SubMeshes", &SUB_MESH)?
175        .ok_or(MeshError::Assertion(""))?;
176    let mut out = MeteredVec::<SubMeshTriangles>::with_capacity(meter, subs.len())?;
177    // One unit a submesh, those of no indices included.
178    meter.count_decode(u64::try_from(subs.len()).unwrap_or(u64::MAX))?;
179    for sub in subs.iter() {
180        let sub = sub?;
181        // UnityPy MeshHelper.py:637-642
182        let mut first = field(&sub, "firstByte", u64::from(u32::MAX))? / 2;
183        if !use_16bit {
184            first /= 2;
185        }
186        let count = field(&sub, "indexCount", u64::from(u32::MAX))?;
187        let topology = sub.int32("topology")?;
188        let is = |t: MeshTopology| topology == Some(t.value());
189        let one = if is(MeshTopology::Triangles) {
190            list(buffer, first, count, meter)?
191        } else if version.major()? < 4 || is(MeshTopology::TriangleStrip) {
192            strip(buffer, first, count, meter)?
193        } else if is(MeshTopology::Quads) {
194            quads(buffer, first, count, meter)?
195        } else {
196            return Err(MeshError::Topology);
197        };
198        out.push(one)?;
199    }
200    let (submeshes, charge) = out.into_parts();
201    Ok(Triangles {
202        submeshes,
203        _charge: charge,
204    })
205}
206
207/// `buffer[i]`, the index at a position known to be in it.
208fn at(buffer: &[u32], i: u64) -> u32 {
209    usize::try_from(i)
210        .ok()
211        .and_then(|i| buffer.get(i))
212        .copied()
213        .unwrap_or(0)
214}
215
216fn len64(buffer: &[u32]) -> u64 {
217    u64::try_from(buffer.len()).unwrap_or(u64::MAX)
218}
219
220/// A triangle list (`helpers/MeshHelper.py:646-649`).
221fn list(
222    buffer: &[u32],
223    first: u64,
224    count: u64,
225    meter: &Arc<Meter>,
226) -> Result<SubMeshTriangles, MeshError> {
227    let n = len64(buffer);
228    let tuples = count.div_ceil(3);
229    let whole = if n >= first.saturating_add(3) {
230        tuples.min((n - first) / 3)
231    } else {
232        0
233    };
234    // Charged, then counted: a refused charge counts no work.
235    let mut triangles =
236        MeteredVec::<[u32; 3]>::with_capacity(meter, usize::try_from(whole).unwrap_or(usize::MAX))?;
237    meter.count_decode(whole.saturating_mul(12))?;
238    for k in 0..whole {
239        let i = first + 3 * k;
240        triangles.push([at(buffer, i), at(buffer, i + 1), at(buffer, i + 2)])?;
241    }
242    let mut cut = [0u32; 2];
243    let mut cut_len = 0u8;
244    let mut rest = tuples - whole;
245    if rest > 0 {
246        let i = first.saturating_add(3 * whole);
247        if i < n {
248            // Fewer than three are left, or `whole` would count it.
249            let left = n - i;
250            cut = [at(buffer, i), if left > 1 { at(buffer, i + 1) } else { 0 }];
251            cut_len = u8::try_from(left.min(2)).unwrap_or(2);
252            rest -= 1;
253        }
254    }
255    let (triangles, charge) = triangles.into_parts();
256    Ok(SubMeshTriangles {
257        triangles,
258        cut,
259        cut_len,
260        empty: rest,
261        index_count: count,
262        _charge: charge,
263    })
264}
265
266/// A strip (`helpers/MeshHelper.py:651-666`).
267fn strip(
268    buffer: &[u32],
269    first: u64,
270    count: u64,
271    meter: &Arc<Meter>,
272) -> Result<SubMeshTriangles, MeshError> {
273    let end = len64(buffer);
274    let steps = count.saturating_sub(2);
275    // UnityPy MeshHelper.py:655: each step unpacks three; the first that
276    // meets the buffer's end raises, whatever the steps before it kept.
277    if steps > 0 && first.saturating_add(count) > end {
278        let failing = first.max(end.saturating_sub(2));
279        let got = u8::try_from(end.saturating_sub(failing)).unwrap_or(0);
280        return Err(MeshError::Unpack { expected: 3, got });
281    }
282    // Charged, then counted: a refused charge counts no work. Every step's
283    // triangle is charged, the degenerate ones it drops included.
284    let mut triangles =
285        MeteredVec::<[u32; 3]>::with_capacity(meter, usize::try_from(steps).unwrap_or(usize::MAX))?;
286    meter.count_decode(steps.saturating_mul(12))?;
287    for k in 0..steps {
288        let pos = first + k;
289        let (a, b, c) = (at(buffer, pos), at(buffer, pos + 1), at(buffer, pos + 2));
290        if a == b || a == c || b == c {
291            continue;
292        }
293        triangles.push(if k & 1 == 1 { [b, a, c] } else { [a, b, c] })?;
294    }
295    let kept = u64::try_from(triangles.len()).unwrap_or(u64::MAX);
296    let (triangles, charge) = triangles.into_parts();
297    Ok(SubMeshTriangles {
298        triangles,
299        cut: [0; 2],
300        cut_len: 0,
301        empty: 0,
302        // UnityPy MeshHelper.py:666
303        index_count: kept.saturating_mul(3),
304        _charge: charge,
305    })
306}
307
308/// Quads (`helpers/MeshHelper.py:668-676`).
309fn quads(
310    buffer: &[u32],
311    first: u64,
312    count: u64,
313    meter: &Arc<Meter>,
314) -> Result<SubMeshTriangles, MeshError> {
315    let end = len64(buffer);
316    let quads = count.div_ceil(4);
317    // UnityPy MeshHelper.py:673: the first quad that meets the buffer's
318    // end raises.
319    let unpacked = if end >= first.saturating_add(4) {
320        (end - first - 4) / 4 + 1
321    } else {
322        0
323    };
324    if unpacked < quads {
325        let failing = first.saturating_add(4 * unpacked);
326        let got = u8::try_from(end.saturating_sub(failing)).unwrap_or(0);
327        return Err(MeshError::Unpack { expected: 4, got });
328    }
329    // UnityPy MeshHelper.py:674-675: a last quad past `indexCount // 2`
330    // triangles.
331    if !count.is_multiple_of(4) {
332        return Err(MeshError::Index(IndexKind::ListAssignment));
333    }
334    let len = quads.saturating_mul(2);
335    // Charged, then counted: a refused charge counts no work.
336    let mut triangles =
337        MeteredVec::<[u32; 3]>::with_capacity(meter, usize::try_from(len).unwrap_or(usize::MAX))?;
338    meter.count_decode(len.saturating_mul(12))?;
339    for q in 0..quads {
340        let pos = first + 4 * q;
341        let (a, b, c, d) = (
342            at(buffer, pos),
343            at(buffer, pos + 1),
344            at(buffer, pos + 2),
345            at(buffer, pos + 3),
346        );
347        triangles.push([a, b, c])?;
348        triangles.push([a, c, d])?;
349    }
350    let (triangles, charge) = triangles.into_parts();
351    Ok(SubMeshTriangles {
352        triangles,
353        cut: [0; 2],
354        cut_len: 0,
355        empty: 0,
356        index_count: count,
357        _charge: charge,
358    })
359}