Skip to main content

CharacterInputs

Struct CharacterInputs 

Source
#[non_exhaustive]
pub struct CharacterInputs<'a> { pub skin: Option<CharacterSkin<'a>>, pub blend_shapes: &'a [&'a [[f32; 3]]], pub joint_poses: &'a [&'a [[[f32; 4]; 3]]], pub sample_poses: &'a [&'a [[f32; 3]]], }
Expand description

Borrowed character data; not in C++ meshoptimizer.

Fields (Non-exhaustive)§

This struct is marked as non-exhaustive
Non-exhaustive structs could have additional fields added in future. Therefore, non-exhaustive structs cannot be constructed in external crates using the traditional Struct { .. } syntax; cannot be matched against without a wildcard ..; and struct update syntax will not work.
§skin: Option<CharacterSkin<'a>>

Optional skin; absent for morph-only meshes.

§blend_shapes: &'a [&'a [[f32; 3]]]

One vertex-length delta array per full-weight blend shape.

§joint_poses: &'a [&'a [[[f32; 4]; 3]]]

Optional sample poses: one model-space affine skin matrix per bone. Matrices already include inverse bind transforms; rows multiply [x, y, z, 1]. These poses are measured separately, without blend shapes.

§sample_poses: &'a [&'a [[f32; 3]]]

Additional pre-evaluated vertex positions, measured after joint poses.

Implementations§

Source§

impl<'a> CharacterInputs<'a>

Source

pub fn new() -> Self

Empty deformation inputs.

Examples found in repository?
examples/character_compare.rs (line 38)
17fn main() -> Result<(), Box<dyn StdError>> {
18    let path = std::env::args().nth(1).ok_or("input file required")?;
19    let bytes = std::fs::read(&path)?;
20    let mut r = Reader(&bytes);
21    let [n, ni, nb, ns, np] = core::array::from_fn::<_, 5, _>(|_| r.u() as usize);
22    let p: Vec<[f32; 3]> = (0..n).map(|_| core::array::from_fn(|_| r.f())).collect();
23    let indices: Vec<u32> = (0..ni).map(|_| r.u()).collect();
24    let joints: Vec<u32> = (0..n * 4).map(|_| r.u()).collect();
25    let weights: Vec<f32> = (0..n * 4).map(|_| r.f()).collect();
26    let shapes: Vec<Vec<[f32; 3]>> = (0..ns)
27        .map(|_| (0..n).map(|_| core::array::from_fn(|_| r.f())).collect())
28        .collect();
29    let poses: Vec<Vec<[[f32; 4]; 3]>> = (0..np)
30        .map(|_| {
31            (0..nb)
32                .map(|_| core::array::from_fn(|_| core::array::from_fn(|_| r.f())))
33                .collect()
34        })
35        .collect();
36    assert!(r.0.is_empty());
37    let importance = vec![1.; nb];
38    let mut data = CharacterInputs::new();
39    if nb > 0 {
40        data.skin = Some(CharacterSkin::new(&joints, &weights, 4, &importance));
41    }
42    let shapes_ref: Vec<_> = shapes.iter().map(Vec::as_slice).collect();
43    let poses_ref: Vec<_> = poses.iter().map(Vec::as_slice).collect();
44    data.blend_shapes = &shapes_ref;
45    data.joint_poses = &poses_ref;
46    let mut samples = vec![p.clone()];
47    for s in &shapes {
48        samples.push(
49            p.iter()
50                .zip(s)
51                .map(|(p, s)| core::array::from_fn(|k| p[k] + s[k]))
52                .collect(),
53        );
54    }
55    for pose in &poses {
56        samples.push(
57            (0..n)
58                .map(|i| {
59                    core::array::from_fn(|k| {
60                        (0..4)
61                            .map(|j| {
62                                let m = pose[joints[i * 4 + j] as usize][k];
63                                weights[i * 4 + j]
64                                    * (m[0] * p[i][0] + m[1] * p[i][1] + m[2] * p[i][2] + m[3])
65                            })
66                            .sum()
67                    })
68                })
69                .collect(),
70        );
71    }
72    let mut ws = Workspace::default();
73    println!("ratio,method,triangles,bind,max_pose,milliseconds");
74    for ratio in [0.5, 0.25, 0.1] {
75        let settings = SimplifySettings {
76            target_index_count: ((ni / 3) as f64 * ratio) as usize * 3,
77            target_error: 100.,
78            options: SimplifyOptions::EMPTY,
79        };
80        for (method, blend_weight, skin_weight) in [
81            ("plain", 0., 0.),
82            ("character", 1., 1.),
83            ("skin_only", 0., 1.),
84        ] {
85            let mut options = CharacterOptions::default();
86            options.blend_shape_weight = blend_weight;
87            options.skin_weight = skin_weight;
88            let mut timings = Vec::new();
89            let mut output = None;
90            for repeat in 0..8 {
91                let start = Instant::now();
92                let mesh = if method == "plain" {
93                    simplify(&indices, Positions::from_packed(&p), settings, &mut ws)
94                        .map_err(|e| e.to_string())?
95                } else {
96                    simplify_character(
97                        &indices,
98                        Positions::from_packed(&p),
99                        &data,
100                        &options,
101                        settings,
102                        &mut ws,
103                    )
104                    .map_err(|e| e.to_string())?
105                };
106                if repeat > 0 {
107                    timings.push(start.elapsed().as_secs_f64() * 1000.);
108                }
109                if let Some(previous) = &output {
110                    let previous: &SimplifiedMesh = previous;
111                    assert_eq!(mesh.indices, previous.indices);
112                    assert_eq!(mesh.error.to_bits(), previous.error.to_bits());
113                }
114                output = Some(mesh);
115            }
116            timings.sort_by(f64::total_cmp);
117            let ms = timings[timings.len() / 2];
118            let mesh = output.ok_or("missing output")?;
119            let mut maxima = Vec::new();
120            let mut qo = LodQualityOptions::default();
121            qo.samples_per_unit_area = 0.;
122            for sample in &samples {
123                let p = Positions::from_packed(sample);
124                maxima.push(
125                    measure_lod_quality(
126                        LodQualityMesh::new(&indices, p),
127                        LodQualityMesh::new(&mesh.indices, p),
128                        &qo,
129                        &mut ws,
130                    )
131                    .map_err(|e| e.to_string())?
132                    .symmetric
133                    .max,
134                );
135            }
136            println!(
137                "{ratio},{method},{},{:.9},{:.9},{ms:.3}",
138                mesh.indices.len() / 3,
139                maxima[0],
140                maxima.iter().copied().fold(0., f64::max)
141            );
142        }
143    }
144    // Exercise chain pose evaluation on the same public model as well.
145    let co = LodChainOptions::new(
146        LodTargets::Ratios(&[0.5, 0.25, 0.1]),
147        LodErrors::Uniform(100.),
148    )
149    .with_independent(true);
150    let mut qo = LodQualityOptions::default();
151    qo.samples_per_unit_area = 0.;
152    let chain = build_character_lod_chain(
153        &indices,
154        Positions::from_packed(&p),
155        &data,
156        &CharacterOptions::default(),
157        &co,
158        &qo,
159        &mut ws,
160    )
161    .map_err(|e| e.to_string())?;
162    assert_eq!(chain.quality.len(), samples.len());
163    Ok(())
164}
More examples
Hide additional examples
examples/character_eval.rs (line 127)
74fn main() -> Result<(), Box<dyn StdError>> {
75    let path = std::env::args().nth(1).ok_or("input required")?;
76    let timing_only = std::env::args().any(|arg| arg == "--timing-only");
77    let bytes = std::fs::read(&path)?;
78    let mut r = Reader(&bytes);
79    let [n, ni, nb, ns, np, na, influences, aw, kw] =
80        core::array::from_fn::<_, 9, _>(|_| r.u() as usize);
81    let p = r.points(n);
82    let indices: Vec<_> = (0..ni).map(|_| r.u()).collect();
83    let joints: Vec<_> = (0..n * influences).map(|_| r.u()).collect();
84    let weights: Vec<_> = (0..n * influences).map(|_| r.f()).collect();
85    let shapes: Vec<_> = (0..ns).map(|_| r.points(n)).collect();
86    let attr: Vec<_> = (0..n * aw).map(|_| r.f()).collect();
87    let keys = &r.0[..n * kw];
88    r.0 = &r.0[n * kw..];
89    let importance: Vec<_> = (0..nb).map(|_| r.f()).collect();
90    let samples: Vec<_> = (0..np).map(|_| r.points(n)).collect();
91    assert!(r.0.is_empty());
92    let mut ws = Workspace::default();
93    // Split wide exact keys into supported byte streams; no hashing or rounding.
94    let streams: Vec<_> = (0..kw)
95        .step_by(256)
96        .map(|offset| VertexStream::new(keys, n, (kw - offset).min(256), kw, offset))
97        .collect::<Result<_, _>>()?;
98    let remap = generate_vertex_remap_multi(Some(&indices), &streams, &mut ws)?;
99    let mut representatives = vec![usize::MAX; remap.vertex_count];
100    for (i, &j) in remap.remap.iter().enumerate() {
101        if j != u32::MAX {
102            representatives[j as usize] = i;
103        }
104    }
105    let indices = remap_index_buffer(Some(&indices), &remap.remap, &mut ws)?;
106    let p = compact(&p, 1, &representatives);
107    let joints = compact(&joints, influences, &representatives);
108    let weights = compact(&weights, influences, &representatives);
109    let attr = compact(&attr, aw, &representatives);
110    let shapes: Vec<_> = shapes
111        .iter()
112        .map(|s| compact(s, 1, &representatives))
113        .collect();
114    let samples: Vec<_> = samples
115        .iter()
116        .map(|s| compact(s, 1, &representatives))
117        .collect();
118    eprintln!(
119        "weld vertices {n}->{} triangles {}->{} channels {}",
120        p.len(),
121        ni / 3,
122        indices.len() / 3,
123        nb + ns * 3
124    );
125    let shape_refs: Vec<_> = shapes.iter().map(Vec::as_slice).collect();
126    let unit = vec![1.; nb];
127    let mut data = CharacterInputs::new();
128    data.blend_shapes = &shape_refs;
129    let ratios = if ni / 3 >= 10000 {
130        vec![0.5, 0.25, 0.1, 0.05]
131    } else {
132        vec![0.5, 0.25, 0.1]
133    };
134    if std::env::args().any(|arg| arg == "--best-of") {
135        // Full character chains meter every sampled pose together, unlike the
136        // original harness's separate quality calls. Keep the default byte cap.
137        ws = Workspace::new(Limits {
138            max_work: 1 << 42,
139            ..Limits::default()
140        });
141        data.skin = if nb == 0 {
142            None
143        } else {
144            Some(CharacterSkin::new(&joints, &weights, influences, &unit))
145        };
146        let sample_refs: Vec<_> = samples.iter().map(Vec::as_slice).collect();
147        data.sample_poses = &sample_refs;
148        println!(
149            "target,chosen,triangles,plain_max,character_max,selected_max,character_ms,bestof_ms"
150        );
151        for ratio in ratios {
152            let counts = [((ni / 3) as f64 * ratio) as usize * 3];
153            let mut co =
154                LodChainOptions::new(LodTargets::Counts(&counts), LodErrors::Uniform(100.));
155            let attr_weights = vec![1.; aw];
156            if aw != 0 {
157                co.attributes = Some(LodChainAttributes::new(
158                    Attributes::from_interleaved(&attr, p.len(), aw, aw, 0)?,
159                    &attr_weights,
160                ));
161            }
162            let extent = samples
163                .iter()
164                .chain(std::iter::once(&p))
165                .map(|s| simplify_scale(Positions::from_packed(s)))
166                .collect::<Result<Vec<_>, _>>()?
167                .into_iter()
168                .fold(0.0f32, f32::max);
169            let mut qo = LodQualityOptions::default();
170            qo.samples_per_unit_area = if extent > 0. {
171                1e-6 / f64::from(extent).powi(2)
172            } else {
173                0.
174            };
175            let mut character_co = co;
176            character_co.attributes = None;
177            eprintln!("target {ratio}: character chain");
178            let start = Instant::now();
179            let character = build_character_lod_chain(
180                &indices,
181                Positions::from_packed(&p),
182                &data,
183                &CharacterOptions::default(),
184                &character_co,
185                &qo,
186                &mut ws,
187            )?;
188            let character_ms = start.elapsed().as_secs_f64() * 1000.;
189            eprintln!(
190                "target {ratio}: character {character_ms:.3} ms, usage {:?}",
191                ws.usage()
192            );
193            let mut options = CharacterOptions::default();
194            options.best_of = true;
195            eprintln!("target {ratio}: best-of chain");
196            let start = Instant::now();
197            let selected = build_character_lod_chain(
198                &indices,
199                Positions::from_packed(&p),
200                &data,
201                &options,
202                &co,
203                &qo,
204                &mut ws,
205            )?;
206            let bestof_ms = start.elapsed().as_secs_f64() * 1000.;
207            eprintln!(
208                "target {ratio}: best-of {bestof_ms:.3} ms, usage {:?}",
209                ws.usage()
210            );
211            let report = selected.selections[0];
212            let max = selected
213                .quality
214                .iter()
215                .fold(0.0f64, |v, q| v.max(q[0].symmetric.max));
216            let char_max = character
217                .quality
218                .iter()
219                .fold(0.0f64, |v, q| v.max(q[0].symmetric.max));
220            assert_eq!(char_max, report.character_max);
221            assert!(max <= report.plain_max && max <= report.character_max);
222            let chosen = match report.method {
223                CharacterLodMethod::Plain => "plain",
224                CharacterLodMethod::Character => "character",
225                _ => unreachable!(),
226            };
227            println!(
228                "{ratio},{chosen},{},{:.17},{:.17},{max:.17},{character_ms:.6},{bestof_ms:.6}",
229                selected.chain.levels[0].triangle_count, report.plain_max, report.character_max
230            );
231            let out: Vec<_> = selected.chain.levels[0]
232                .indices
233                .iter()
234                .flat_map(|v| v.to_le_bytes())
235                .collect();
236            std::fs::write(format!("{path}.{ratio}.bestof.indices"), out)?;
237        }
238        return Ok(());
239    }
240    println!("ratio,method,vertices,triangles,bind,animation_max,animation_p95,morph_max,morph_p95,ms,worst_pose,status");
241    for ratio in ratios {
242        let settings = SimplifySettings {
243            target_index_count: ((ni / 3) as f64 * ratio) as usize * 3,
244            target_error: 100.,
245            options: SimplifyOptions::EMPTY,
246        };
247        for method in ["plain", "character", "important"] {
248            let imp = if method == "important" {
249                &importance
250            } else {
251                &unit
252            };
253            data.skin = if nb == 0 {
254                None
255            } else {
256                Some(CharacterSkin::new(&joints, &weights, influences, imp))
257            };
258            let result = time_mesh(
259                || {
260                    let positions = std::hint::black_box(Positions::from_packed(&p));
261                    let settings = std::hint::black_box(settings);
262                    let indices = std::hint::black_box(indices.as_slice());
263                    if method == "plain" {
264                        if aw == 0 {
265                            simplify(indices, positions, settings, std::hint::black_box(&mut ws))
266                        } else {
267                            simplify_with_attributes(
268                                indices,
269                                positions,
270                                Attributes::from_interleaved(&attr, p.len(), aw, aw, 0)?,
271                                &vec![1.; aw],
272                                None,
273                                settings,
274                                std::hint::black_box(&mut ws),
275                            )
276                        }
277                    } else {
278                        simplify_character(
279                            indices,
280                            positions,
281                            std::hint::black_box(&data),
282                            &CharacterOptions::default(),
283                            settings,
284                            std::hint::black_box(&mut ws),
285                        )
286                    }
287                },
288                (1_000_000 / indices.len().max(1)).clamp(1, 4096),
289            );
290            let (mesh, ms) = match result {
291                Ok(result) => result,
292                Err(e) => {
293                    println!("{ratio},{method},{},,,,,,,,,{e:?}", p.len());
294                    continue;
295                }
296            };
297            if timing_only {
298                println!(
299                    "{ratio},{method},{},{},,,,,,{ms:.6},,timing_only",
300                    p.len(),
301                    mesh.indices.len() / 3
302                );
303                let mut out = Vec::new();
304                for index in &mesh.indices {
305                    out.extend_from_slice(&index.to_le_bytes());
306                }
307                std::fs::write(format!("{path}.{ratio}.{method}.indices"), out)?;
308                continue;
309            }
310            let measure = |sample: &[[f32; 3]], ws: &mut Workspace| -> Result<f64, Error> {
311                let pos = Positions::from_packed(sample);
312                let extent = f64::from(simplify_scale(pos)?);
313                let mut qo = LodQualityOptions::default();
314                // Every nondegenerate triangle has area below 2 * extent^2,
315                // so ceil(area * density) contributes one interior sample.
316                qo.samples_per_unit_area = if extent > 0. {
317                    1e-6 / (extent * extent)
318                } else {
319                    0.
320                };
321                Ok(measure_lod_quality(
322                    LodQualityMesh::new(&indices, pos),
323                    LodQualityMesh::new(&mesh.indices, pos),
324                    &qo,
325                    ws,
326                )?
327                .symmetric
328                .max)
329            };
330            let bind = measure(&p, &mut ws)?;
331            let deviations: Vec<_> = samples
332                .iter()
333                .map(|s| measure(s, &mut ws))
334                .collect::<Result<_, _>>()?;
335            let worst = deviations
336                .iter()
337                .enumerate()
338                .max_by(|a, b| a.1.total_cmp(b.1))
339                .map(|v| v.0)
340                .filter(|&index| deviations[index] > bind);
341            let worst_label = worst.map_or_else(|| "bind".to_owned(), |index| index.to_string());
342            println!(
343                "{ratio},{method},{},{},{bind:.9},{:.9},{:.9},{:.9},{:.9},{:.6},{worst_label},ok",
344                p.len(),
345                mesh.indices.len() / 3,
346                maximum(&deviations[..na]),
347                p95(&deviations[..na]),
348                maximum(&deviations[na..]),
349                p95(&deviations[na..]),
350                ms
351            );
352            // Retain indices and exact worst-pose coordinates for independent rendering.
353            let prefix = format!("{path}.{ratio}.{method}");
354            let mut out = Vec::new();
355            for v in &mesh.indices {
356                out.extend_from_slice(&v.to_le_bytes());
357            }
358            std::fs::write(format!("{prefix}.indices"), out)?;
359            let mut out = Vec::new();
360            for point in worst.and_then(|index| samples.get(index)).unwrap_or(&p) {
361                for v in point {
362                    out.extend_from_slice(&v.to_le_bytes());
363                }
364            }
365            std::fs::write(format!("{prefix}.pose"), out)?;
366        }
367    }
368    let mut out = Vec::new();
369    for v in &indices {
370        out.extend_from_slice(&v.to_le_bytes());
371    }
372    std::fs::write(format!("{path}.source.indices"), out)?;
373    Ok(())
374}

Trait Implementations§

Source§

impl<'a> Clone for CharacterInputs<'a>

Source§

fn clone(&self) -> Self

Returns a duplicate of the value. Read more
1.0.0 (const: unstable) · Source§

fn clone_from(&mut self, source: &Self)

Performs copy-assignment from source. Read more
Source§

impl<'a> Copy for CharacterInputs<'a>

Source§

impl<'a> Debug for CharacterInputs<'a>

Source§

fn fmt(&self, f: &mut Formatter<'_>) -> Result

Formats the value using the given formatter. Read more
Source§

impl Default for CharacterInputs<'_>

Source§

fn default() -> Self

Returns the “default value” for a type. Read more

Auto Trait Implementations§

§

impl<'a> Forget for CharacterInputs<'a>

§

impl<'a> Freeze for CharacterInputs<'a>

§

impl<'a> RefUnwindSafe for CharacterInputs<'a>

§

impl<'a> Send for CharacterInputs<'a>

§

impl<'a> Sync for CharacterInputs<'a>

§

impl<'a> Unpin for CharacterInputs<'a>

§

impl<'a> UnsafeUnpin for CharacterInputs<'a>

§

impl<'a> UnwindSafe for CharacterInputs<'a>

Blanket Implementations§

Source§

impl<T> Any for T
where T: 'static + ?Sized,

Source§

fn type_id(&self) -> TypeId

Gets the TypeId of self. Read more
Source§

impl<T> Borrow<T> for T
where T: ?Sized,

Source§

fn borrow(&self) -> &T

Immutably borrows from an owned value. Read more
Source§

impl<T> BorrowMut<T> for T
where T: ?Sized,

Source§

fn borrow_mut(&mut self) -> &mut T

Mutably borrows from an owned value. Read more
Source§

impl<T> CloneToUninit for T
where T: Clone,

Source§

unsafe fn clone_to_uninit(&self, dest: *mut u8)

🔬This is a nightly-only experimental API. (clone_to_uninit)
Performs copy-assignment from self to dest. Read more
Source§

impl<T> From<T> for T

Source§

fn from(t: T) -> T

Returns the argument unchanged.

Source§

impl<T, U> Into<U> for T
where U: From<T>,

Source§

fn into(self) -> U

Calls U::from(self).

That is, this conversion is whatever the implementation of From<T> for U chooses to do.

Source§

impl<T> IntoEither for T

Source§

fn into_either(self, into_left: bool) -> Either<Self, Self> ⓘ

Converts self into a Left variant of Either<Self, Self> if into_left is true. Converts self into a Right variant of Either<Self, Self> otherwise. Read more
Source§

fn into_either_with<F>(self, into_left: F) -> Either<Self, Self> ⓘ
where F: FnOnce(&Self) -> bool,

Converts self into a Left variant of Either<Self, Self> if into_left(&self) returns true. Converts self into a Right variant of Either<Self, Self> otherwise. Read more
Source§

impl<T> Pointable for T

Source§

const ALIGN: usize

The alignment of pointer.
Source§

type Init = T

The type for initializers.
Source§

unsafe fn init(init: <T as Pointable>::Init) -> usize

Initializes a with the given initializer. Read more
Source§

unsafe fn deref<'a>(ptr: usize) -> &'a T

Dereferences the given pointer. Read more
Source§

unsafe fn deref_mut<'a>(ptr: usize) -> &'a mut T

Mutably dereferences the given pointer. Read more
Source§

unsafe fn drop(ptr: usize)

Drops the object pointed to by the given pointer. Read more
Source§

impl<T> ToOwned for T
where T: Clone,

Source§

type Owned = T

The resulting type after obtaining ownership.
Source§

fn to_owned(&self) -> T

Creates owned data from borrowed data, usually by cloning. Read more
Source§

fn clone_into(&self, target: &mut T)

Uses borrowed data to replace owned data, usually by cloning. Read more
Source§

impl<T, U> TryFrom<U> for T
where U: Into<T>,

Source§

type Error = !

The type returned in the event of a conversion error.
Source§

fn try_from(value: U) -> Result<T, !>

Performs the conversion.
Source§

impl<T, U> TryInto<U> for T
where U: TryFrom<T>,

Source§

type Error = <U as TryFrom<T>>::Error

The type returned in the event of a conversion error.
Source§

fn try_into(self) -> Result<U, <U as TryFrom<T>>::Error>

Performs the conversion.