Skip to main content

meshoptimizer_rs/
character.rs

1//! Character simplification, an extension not in C++ meshoptimizer.
2use crate::{
3    Attributes, Error, Limits, LodChain, LodChainAttributes, LodChainOptions, LodQuality,
4    LodQualityMesh, LodQualityOptions, Positions, SimplifiedMesh, SimplifySettings, Usage,
5    Workspace,
6};
7use alloc::vec::Vec;
8
9/// Up to eight linear blend skinning influences; not in C++ meshoptimizer.
10#[derive(Clone, Copy, Debug)]
11#[non_exhaustive]
12pub struct CharacterSkin<'a> {
13    /// Flat vertex-major joint indices. Duplicate joints are summed.
14    pub joints: &'a [u32],
15    /// Flat vertex-major nonnegative weights, summing to one within 0.001.
16    pub weights: &'a [f32],
17    /// Four or eight entries per vertex (zero weights pad unused entries).
18    pub influences: usize,
19    /// One finite nonnegative importance per bone, including unused bones.
20    pub importance: &'a [f32],
21}
22impl<'a> CharacterSkin<'a> {
23    /// Borrow skin data. Validation occurs when simplifying.
24    pub fn new(
25        joints: &'a [u32],
26        weights: &'a [f32],
27        influences: usize,
28        importance: &'a [f32],
29    ) -> Self {
30        Self {
31            joints,
32            weights,
33            influences,
34            importance,
35        }
36    }
37}
38/// Borrowed character data; not in C++ meshoptimizer.
39#[derive(Clone, Copy, Debug)]
40#[non_exhaustive]
41pub struct CharacterInputs<'a> {
42    /// Optional skin; absent for morph-only meshes.
43    pub skin: Option<CharacterSkin<'a>>,
44    /// One vertex-length delta array per full-weight blend shape.
45    pub blend_shapes: &'a [&'a [[f32; 3]]],
46    /// Optional sample poses: one model-space affine skin matrix per bone.
47    /// Matrices already include inverse bind transforms; rows multiply `[x, y, z, 1]`.
48    /// These poses are measured separately, without blend shapes.
49    pub joint_poses: &'a [&'a [[[f32; 4]; 3]]],
50    /// Additional pre-evaluated vertex positions, measured after joint poses.
51    pub sample_poses: &'a [&'a [[f32; 3]]],
52}
53impl<'a> CharacterInputs<'a> {
54    /// Empty deformation inputs.
55    pub fn new() -> Self {
56        Self {
57            skin: None,
58            blend_shapes: &[],
59            joint_poses: &[],
60            sample_poses: &[],
61        }
62    }
63}
64impl Default for CharacterInputs<'_> {
65    fn default() -> Self {
66        Self::new()
67    }
68}
69/// Metric weights; not in C++ meshoptimizer.
70#[derive(Clone, Copy, Debug)]
71#[non_exhaustive]
72pub struct CharacterOptions {
73    /// Global multiplier on each bone channel (also multiplied by importance).
74    pub skin_weight: f32,
75    /// Multiplier on normalized full-target position channels.
76    pub blend_shape_weight: f32,
77    /// Select the lower worst sampled deviation per chain level (default false).
78    pub best_of: bool,
79}
80impl Default for CharacterOptions {
81    fn default() -> Self {
82        Self {
83            skin_weight: 1.0,
84            blend_shape_weight: 1.0,
85            best_of: false,
86        }
87    }
88}
89/// Character levels and sampled pose quality; not in C++ meshoptimizer.
90#[derive(Debug)]
91#[non_exhaustive]
92pub struct CharacterLodChain {
93    /// Indices reference the original vertices and deformation streams.
94    pub chain: LodChain,
95    /// Pose-major LOD quality reports: bind, blend shapes, joint poses, then sample poses.
96    pub quality: Vec<Vec<LodQuality>>,
97    /// Per-level candidate scores; empty unless best-of selection is enabled.
98    pub selections: Vec<CharacterLodSelection>,
99}
100
101/// Winning method in best-of selection; not in C++ meshoptimizer.
102#[derive(Clone, Copy, Debug, PartialEq, Eq)]
103#[non_exhaustive]
104pub enum CharacterLodMethod {
105    /// Plain simplification, with optional chain attributes.
106    Plain,
107    /// Character attribute metric.
108    Character,
109}
110/// Per-level sampled candidate scores; not in C++ meshoptimizer.
111#[derive(Clone, Copy, Debug)]
112#[non_exhaustive]
113pub struct CharacterLodSelection {
114    /// Winner: lower score, then fewer triangles, then plain.
115    pub method: CharacterLodMethod,
116    /// Worst sampled symmetric deviation of the plain candidate.
117    pub plain_max: f64,
118    /// Worst sampled symmetric deviation of the character candidate.
119    pub character_max: f64,
120}
121
122// Whole-call limits include prepared attributes, retained levels, pose buffers,
123// report storage, and every nested algorithm's scratch and work.
124struct Meter {
125    limits: Limits,
126    bytes: usize,
127    peak: usize,
128    work: u64,
129}
130impl Meter {
131    fn charge(&mut self, n: usize) -> Result<(), Error> {
132        self.work = self
133            .work
134            .checked_add(u64::try_from(n).map_err(|_| Error::SizeOverflow)?)
135            .ok_or(Error::SizeOverflow)?;
136        if self.work > self.limits.max_work {
137            return Err(Error::LimitExceeded);
138        }
139        Ok(())
140    }
141    fn alloc<T>(&mut self, n: usize, ws: &mut Workspace) -> Result<Vec<T>, Error> {
142        let bytes = n
143            .checked_mul(core::mem::size_of::<T>())
144            .ok_or(Error::SizeOverflow)?;
145        let total = self.bytes.checked_add(bytes).ok_or(Error::SizeOverflow)?;
146        ws.charge_owned(total)?;
147        let mut v = Vec::new();
148        v.try_reserve_exact(n)
149            .map_err(|_| Error::AllocationFailed)?;
150        self.bytes = self
151            .bytes
152            .checked_add(
153                v.capacity()
154                    .checked_mul(core::mem::size_of::<T>())
155                    .ok_or(Error::SizeOverflow)?,
156            )
157            .ok_or(Error::SizeOverflow)?;
158        ws.charge_owned(self.bytes)?;
159        self.peak = self.peak.max(ws.usage().bytes).max(self.bytes);
160        Ok(v)
161    }
162    fn call<T>(
163        &mut self,
164        ws: &mut Workspace,
165        f: impl FnOnce(&mut Workspace) -> Result<T, Error>,
166    ) -> Result<T, Error> {
167        ws.set_lod_limits(Limits {
168            max_bytes: self
169                .limits
170                .max_bytes
171                .checked_sub(self.bytes)
172                .ok_or(Error::LimitExceeded)?,
173            max_work: self
174                .limits
175                .max_work
176                .checked_sub(self.work)
177                .ok_or(Error::LimitExceeded)?,
178        });
179        let r = f(ws);
180        let u = ws.usage();
181        ws.set_lod_limits(self.limits);
182        self.work = self.work.checked_add(u.work).ok_or(Error::SizeOverflow)?;
183        self.peak = self
184            .peak
185            .max(self.bytes.checked_add(u.bytes).ok_or(Error::SizeOverflow)?);
186        r
187    }
188    fn retain<T>(&mut self, v: &Vec<T>) -> Result<(), Error> {
189        self.bytes = self
190            .bytes
191            .checked_add(
192                v.capacity()
193                    .checked_mul(core::mem::size_of::<T>())
194                    .ok_or(Error::SizeOverflow)?,
195            )
196            .ok_or(Error::SizeOverflow)?;
197        Ok(())
198    }
199}
200fn run<T>(
201    ws: &mut Workspace,
202    f: impl FnOnce(&mut Meter, &mut Workspace) -> Result<T, Error>,
203) -> Result<T, Error> {
204    let _ = ws.begin();
205    let mut m = Meter {
206        limits: ws.limits(),
207        bytes: 0,
208        peak: 0,
209        work: 0,
210    };
211    let r = f(&mut m, ws);
212    ws.set_lod_limits(m.limits);
213    ws.set_lod_usage(Usage {
214        bytes: m.peak,
215        work: m.work,
216    });
217    r
218}
219fn finite(x: f32) -> Result<f32, Error> {
220    if x.is_finite() {
221        Ok(x)
222    } else {
223        Err(Error::NumericalFailure)
224    }
225}
226fn prepare(
227    p: Positions<'_>,
228    data: &CharacterInputs<'_>,
229    o: &CharacterOptions,
230    m: &mut Meter,
231    ws: &mut Workspace,
232) -> Result<(Vec<f32>, usize), Error> {
233    if !o.skin_weight.is_finite()
234        || o.skin_weight < 0.0
235        || !o.blend_shape_weight.is_finite()
236        || o.blend_shape_weight < 0.0
237    {
238        return Err(Error::InvalidParameter);
239    }
240    let n = p.len();
241    let bones = data.skin.map_or(0, |s| s.importance.len());
242    let width = bones
243        .checked_add(
244            data.blend_shapes
245                .len()
246                .checked_mul(3)
247                .ok_or(Error::SizeOverflow)?,
248        )
249        .ok_or(Error::SizeOverflow)?;
250    if width > 32 {
251        // The former fixed-width rejection hid valid real-character streams.
252        // Meter importance/shape validation as well as the per-vertex work below.
253        m.charge(width)?;
254    }
255    m.charge(
256        n.checked_mul(width.checked_add(1).ok_or(Error::SizeOverflow)?)
257            .ok_or(Error::SizeOverflow)?,
258    )?;
259    if let Some(s) = data.skin {
260        if !matches!(s.influences, 4 | 8)
261            || s.joints.len() != n.checked_mul(s.influences).ok_or(Error::SizeOverflow)?
262            || s.weights.len() != s.joints.len()
263        {
264            return Err(Error::InvalidLayout);
265        }
266        for &v in s.importance {
267            if !v.is_finite() || v < 0.0 {
268                return Err(Error::InvalidParameter);
269            }
270        }
271    } else if !data.joint_poses.is_empty() {
272        return Err(Error::InvalidParameter);
273    }
274    for sample in data.sample_poses {
275        m.charge(sample.len())?;
276        if sample.len() != n {
277            return Err(Error::InvalidLayout);
278        }
279        for p in *sample {
280            for &v in p {
281                finite(v)?;
282            }
283        }
284    }
285    for shape in data.blend_shapes {
286        if shape.len() != n {
287            return Err(Error::InvalidLayout);
288        }
289    }
290    for pose in data.joint_poses {
291        m.charge(pose.len())?;
292        if pose.len() != bones {
293            return Err(Error::InvalidLayout);
294        }
295        for matrix in *pose {
296            for row in matrix {
297                for &v in row {
298                    finite(v)?;
299                }
300            }
301        }
302    }
303    let scale = crate::simplify_scale(p)?;
304    let scale = if scale == 0.0 { 1.0 } else { scale };
305    let mut a = m.alloc(n.checked_mul(width).ok_or(Error::SizeOverflow)?, ws)?;
306    for i in 0..n {
307        let base = a.len();
308        a.resize(base.checked_add(width).ok_or(Error::SizeOverflow)?, 0.0);
309        if let Some(s) = data.skin {
310            m.charge(s.influences)?;
311            let mut sum = 0.0;
312            for k in 0..s.influences {
313                let j = i * s.influences + k;
314                let b = usize::try_from(s.joints[j]).map_err(|_| Error::SizeOverflow)?;
315                let w = s.weights[j];
316                if b >= bones || !w.is_finite() || w < 0.0 {
317                    return Err(Error::InvalidParameter);
318                }
319                sum += w;
320                a[base + b] = finite(a[base + b] + w * s.importance[b] * o.skin_weight)?;
321            }
322            if (sum - 1.0).abs() > 0.001 {
323                return Err(Error::InvalidParameter);
324            }
325        }
326        let rest = p.get(i).ok_or(Error::InvalidLayout)?;
327        for (j, shape) in data.blend_shapes.iter().enumerate() {
328            for k in 0..3 {
329                // Absolute full-target positions include rest-pose residuals.
330                let target = finite(rest[k] + finite(shape[i][k])?)?;
331                a[base + bones + j * 3 + k] = finite(target / scale * o.blend_shape_weight)?;
332            }
333        }
334    }
335    Ok((a, width))
336}
337fn view(a: &[f32], n: usize, width: usize) -> Result<Attributes<'_>, Error> {
338    if width <= 32 {
339        Attributes::from_interleaved(a, n, width, width, 0)
340    } else {
341        Attributes::from_character_packed(a, n, width)
342    }
343}
344/// Simplify with exact dense bone-weight and full blend-target position channels.
345/// This extension is not in C++ meshoptimizer. The summed attribute energy is a
346/// pose-aware surrogate, not a maximum-pose geometric error guarantee. Bone IDs
347/// are channel identities, never numeric attributes. Influence order is irrelevant
348/// except for floating-point summation of duplicates. No streams are rewritten.
349/// Exact channels (bone count + 3 * blend count) are bounded by workspace memory
350/// and work limits, never projected or truncated. Public attribute constructors
351/// retain their 32-component limit. Empty deformation inputs use plain simplify.
352///
353/// ```
354/// use meshoptimizer_rs::*;
355/// let p = [[0.,0.,0.], [1.,0.,0.], [0.,1.,0.]];
356/// let result = simplify_character(&[0,1,2], Positions::from_packed(&p),
357///     &CharacterInputs::new(), &CharacterOptions::default(),
358///     SimplifySettings { target_index_count: 3, target_error: 1., options: SimplifyOptions::EMPTY },
359///     &mut Workspace::default())?;
360/// assert_eq!(result.indices.len(), 3);
361/// # Ok::<(), Error>(())
362/// ```
363/// # Errors
364/// Layout, parameter, numerical, size and resource errors; underlying simplify errors.
365pub fn simplify_character(
366    indices: &[u32],
367    positions: Positions<'_>,
368    data: &CharacterInputs<'_>,
369    options: &CharacterOptions,
370    settings: SimplifySettings,
371    workspace: &mut Workspace,
372) -> Result<SimplifiedMesh, Error> {
373    run(workspace, |m, ws| {
374        let (a, width) = prepare(positions, data, options, m, ws)?;
375        let mut wide_weights = Vec::new();
376        if width > 32 {
377            m.charge(width)?;
378            wide_weights = m.alloc(width, ws)?;
379            wide_weights.resize(width, 1.0);
380        }
381        let small_weights = [1.; 32];
382        let weights = if width <= 32 {
383            &small_weights[..width]
384        } else {
385            wide_weights.as_slice()
386        };
387        m.call(ws, |ws| {
388            if width == 0 {
389                crate::simplify(indices, positions, settings, ws)
390            } else {
391                crate::simplify_with_attributes(
392                    indices,
393                    positions,
394                    view(&a, positions.len(), width)?,
395                    weights,
396                    None,
397                    settings,
398                    ws,
399                )
400            }
401        })
402    })
403}
404/// Build character LODs and LOD quality reports in bind, full blend, and caller joint poses.
405/// This extension is not in C++ meshoptimizer. Joint poses use linear blend
406/// skinning of rest positions. Blend targets and joint poses are sampled separately;
407/// combined morph/animation extrema are not implied. Quality is sampled, not a bound.
408/// Limits cover the whole call. Failure returns no partial chain.
409/// # Errors
410/// Same as [`simplify_character`], chain and quality errors. Existing `attributes`
411/// in chain options are rejected unless `options.best_of` is true. In best-of
412/// mode they apply only to the plain candidate; character channels occupy the
413/// character metric. Both candidates use the same input, target, flags and cap.
414/// Scores measure against the original source across all supplied poses. Selection
415/// minimizes the worst symmetric sampled deviation, then triangles, then prefers
416/// plain. Successive levels continue from the winner; independent levels use the
417/// source. This guarantees no worse score than the plain candidate of that level,
418/// not than an independently evolving plain chain or unsampled poses.
419///
420/// ```
421/// use meshoptimizer_rs::*;
422/// let p = [[0.,0.,0.], [1.,0.,0.], [0.,1.,0.], [1.,1.,0.]];
423/// let mut options = CharacterOptions::default();
424/// options.best_of = true;
425/// let co = LodChainOptions::new(LodTargets::Counts(&[3]), LodErrors::Uniform(100.));
426/// let result = build_character_lod_chain(&[0,1,2,2,1,3], Positions::from_packed(&p),
427///     &CharacterInputs::new(), &options, &co, &LodQualityOptions::default(),
428///     &mut Workspace::default())?;
429/// assert_eq!(result.selections[0].method, CharacterLodMethod::Plain);
430/// # Ok::<(), Error>(())
431/// ```
432pub fn build_character_lod_chain(
433    indices: &[u32],
434    positions: Positions<'_>,
435    data: &CharacterInputs<'_>,
436    options: &CharacterOptions,
437    chain_options: &LodChainOptions<'_>,
438    quality_options: &LodQualityOptions,
439    workspace: &mut Workspace,
440) -> Result<CharacterLodChain, Error> {
441    run(workspace, |m, ws| {
442        if !options.best_of && chain_options.attributes.is_some() {
443            return Err(Error::InvalidParameter);
444        }
445        let (a, width) = prepare(positions, data, options, m, ws)?;
446        let mut wide_weights = Vec::new();
447        if width > 32 {
448            m.charge(width)?;
449            wide_weights = m.alloc(width, ws)?;
450            wide_weights.resize(width, 1.0);
451        }
452        let small_weights = [1.; 32];
453        let weights = if width <= 32 {
454            &small_weights[..width]
455        } else {
456            wide_weights.as_slice()
457        };
458        let mut co = *chain_options;
459        co.attributes = None;
460        if width != 0 {
461            co.attributes = Some(LodChainAttributes::new(
462                view(&a, positions.len(), width)?,
463                weights,
464            ));
465        }
466        if options.best_of {
467            return best_of(
468                indices,
469                positions,
470                data,
471                chain_options,
472                &co,
473                quality_options,
474                m,
475                ws,
476            );
477        }
478        let chain = m.call(ws, |ws| {
479            crate::build_lod_chain(indices, positions, &co, ws).map_err(|e| e.error)
480        })?;
481        m.retain(&chain.levels)?;
482        for level in &chain.levels {
483            m.retain(&level.indices)?;
484        }
485        let quality = measure(indices, positions, data, &chain, quality_options, m, ws)?;
486        Ok(CharacterLodChain {
487            chain,
488            quality,
489            selections: Vec::new(),
490        })
491    })
492}
493
494#[allow(clippy::too_many_arguments)]
495fn measure(
496    indices: &[u32],
497    positions: Positions<'_>,
498    data: &CharacterInputs<'_>,
499    chain: &LodChain,
500    quality_options: &LodQualityOptions,
501    m: &mut Meter,
502    ws: &mut Workspace,
503) -> Result<Vec<Vec<LodQuality>>, Error> {
504    let count = 1usize
505        .checked_add(data.blend_shapes.len())
506        .and_then(|v| v.checked_add(data.joint_poses.len()))
507        .and_then(|v| v.checked_add(data.sample_poses.len()))
508        .ok_or(Error::SizeOverflow)?;
509    let mut quality = m.alloc(count, ws)?;
510    let mut posed = m.alloc(positions.len(), ws)?;
511    for pose in 0..count {
512        posed.clear();
513        for i in 0..positions.len() {
514            m.charge(1)?;
515            let rest = positions.get(i).ok_or(Error::InvalidLayout)?;
516            let mut p = rest;
517            if pose > data.blend_shapes.len() + data.joint_poses.len() {
518                p = data.sample_poses[pose - data.blend_shapes.len() - data.joint_poses.len() - 1]
519                    [i];
520            } else if pose > 0 && pose <= data.blend_shapes.len() {
521                for k in 0..3 {
522                    p[k] = finite(rest[k] + data.blend_shapes[pose - 1][i][k])?;
523                }
524            } else if pose > data.blend_shapes.len() {
525                let s = data.skin.ok_or(Error::InvalidParameter)?;
526                let matrices = data.joint_poses[pose - data.blend_shapes.len() - 1];
527                p = [0.; 3];
528                m.charge(s.influences)?;
529                for k in 0..s.influences {
530                    let j = i * s.influences + k;
531                    let matrix =
532                        matrices[usize::try_from(s.joints[j]).map_err(|_| Error::SizeOverflow)?];
533                    for r in 0..3 {
534                        p[r] = finite(
535                            p[r] + s.weights[j]
536                                * (matrix[r][0] * rest[0]
537                                    + matrix[r][1] * rest[1]
538                                    + matrix[r][2] * rest[2]
539                                    + matrix[r][3]),
540                        )?;
541                    }
542                }
543            }
544            posed.push(p);
545        }
546        let mut reports = m.alloc(chain.levels.len(), ws)?;
547        for level in &chain.levels {
548            let p = Positions::from_packed(&posed);
549            reports.push(m.call(ws, |ws| {
550                crate::measure_lod_quality(
551                    LodQualityMesh::new(indices, p),
552                    LodQualityMesh::new(&level.indices, p),
553                    quality_options,
554                    ws,
555                )
556            })?);
557        }
558        quality.push(reports);
559    }
560    Ok(quality)
561}
562
563#[allow(clippy::too_many_arguments)]
564fn best_of(
565    indices: &[u32],
566    positions: Positions<'_>,
567    data: &CharacterInputs<'_>,
568    plain_options: &LodChainOptions<'_>,
569    character_options: &LodChainOptions<'_>,
570    qo: &LodQualityOptions,
571    m: &mut Meter,
572    ws: &mut Workspace,
573) -> Result<CharacterLodChain, Error> {
574    use crate::{LodErrors, LodTargets};
575    let len = match plain_options.targets {
576        LodTargets::Counts(v) => v.len(),
577        LodTargets::Ratios(v) => v.len(),
578    };
579    if len == 0 {
580        return Err(Error::InvalidParameter);
581    }
582    if let LodErrors::PerLevel(v) = plain_options.errors {
583        if v.len() != len {
584            return Err(Error::InvalidParameter);
585        }
586    }
587    let mut targets = m.alloc(len, ws)?;
588    let mut prev = indices.len();
589    let mut prev_ratio = 1.0;
590    for i in 0..len {
591        m.charge(1)?;
592        let t = match plain_options.targets {
593            LodTargets::Counts(v) => {
594                if v[i] >= prev {
595                    return Err(Error::InvalidParameter);
596                }
597                v[i]
598            }
599            LodTargets::Ratios(v) => {
600                let r = v[i];
601                if !r.is_finite() || r < 0. || r >= prev_ratio {
602                    return Err(Error::InvalidParameter);
603                }
604                prev_ratio = r;
605                ((f64::from(r) * (indices.len() / 3) as f64) as usize)
606                    .checked_mul(3)
607                    .ok_or(Error::SizeOverflow)?
608            }
609        };
610        let cap = match plain_options.errors {
611            LodErrors::Uniform(v) => v,
612            LodErrors::PerLevel(v) => v[i],
613        };
614        if !cap.is_finite() || cap < 0. {
615            return Err(Error::InvalidParameter);
616        }
617        targets.push((t, cap));
618        prev = t;
619    }
620    let mut levels: Vec<crate::LodLevel> = m.alloc(len, ws)?;
621    let mut selections = m.alloc(len, ws)?;
622    let count = 1usize
623        .checked_add(data.blend_shapes.len())
624        .and_then(|v| v.checked_add(data.joint_poses.len()))
625        .and_then(|v| v.checked_add(data.sample_poses.len()))
626        .ok_or(Error::SizeOverflow)?;
627    let mut quality = m.alloc(count, ws)?;
628    for _ in 0..count {
629        quality.push(m.alloc(len, ws)?);
630    }
631    for (target, cap) in targets {
632        let input = if plain_options.independent || levels.is_empty() {
633            indices
634        } else {
635            &levels[levels.len() - 1].indices
636        };
637        let base = m.bytes;
638        let counts = [target.min(input.len())];
639        // Fixed-size storage avoids unmetered heap metadata.
640        let mut chains = [None, None];
641        let mut reports = [None, None];
642        let mut scores = [0.; 2];
643        for (j, source) in [plain_options, character_options].iter().enumerate() {
644            let mut co = **source;
645            co.targets = LodTargets::Counts(&counts);
646            co.errors = LodErrors::Uniform(cap);
647            let chain = m.call(ws, |ws| {
648                crate::lod_chain::build_lod_chain_internal(input, positions, &co, ws, true)
649                    .map(crate::LodChain::from)
650                    .map_err(|e| e.error)
651            })?;
652            m.retain(&chain.levels)?;
653            m.retain(&chain.levels[0].indices)?;
654            let q = measure(indices, positions, data, &chain, qo, m, ws)?;
655            scores[j] = q.iter().fold(0.0f64, |v, p| v.max(p[0].symmetric.max));
656            chains[j] = Some(chain);
657            reports[j] = Some(q);
658        }
659        let plain = chains[0].take().ok_or(Error::InvalidParameter)?;
660        let character = chains[1].take().ok_or(Error::InvalidParameter)?;
661        let choose_character = scores[1] < scores[0]
662            || (scores[1] == scores[0]
663                && character.levels[0].triangle_count < plain.levels[0].triangle_count);
664        let j = usize::from(choose_character);
665        let kept = if choose_character { character } else { plain };
666        let mut kept = kept;
667        let mut level = kept.levels.pop().ok_or(Error::InvalidParameter)?;
668        level.target_reached = level.indices.len() <= target;
669        m.bytes = base;
670        m.retain(&level.indices)?;
671        levels.push(level);
672        for (out, mut q) in quality
673            .iter_mut()
674            .zip(reports[j].take().ok_or(Error::InvalidParameter)?)
675        {
676            out.push(q.pop().ok_or(Error::InvalidParameter)?);
677        }
678        selections.push(CharacterLodSelection {
679            method: if choose_character {
680                CharacterLodMethod::Character
681            } else {
682                CharacterLodMethod::Plain
683            },
684            plain_max: scores[0],
685            character_max: scores[1],
686        });
687    }
688    Ok(CharacterLodChain {
689        chain: LodChain { levels },
690        quality,
691        selections,
692    })
693}