pub struct Attributes<'a>(/* private fields */);Expand description
Checked borrowed attribute view with at most 32 components per vertex.
Implementations§
Source§impl<'a> Attributes<'a>
impl<'a> Attributes<'a>
Sourcepub fn from_interleaved(
data: &'a [f32],
count: usize,
components: usize,
stride: usize,
offset: usize,
) -> Result<Self, Error>
pub fn from_interleaved( data: &'a [f32], count: usize, components: usize, stride: usize, offset: usize, ) -> Result<Self, Error>
Borrow interleaved attributes; stride and offset are in f32 elements. Zero components are supported; stride is at most 64 elements.
§Errors
InvalidLayout for an unsupported width, stride, offset or buffer length;
SizeOverflow if view size arithmetic overflows.
Examples found in repository?
examples/vg_foliage_measure.rs (line 41)
16fn main() -> Result<(), Box<dyn Error>> {
17 let data = fs::read(std::env::args().nth(1).ok_or("input required")?)?;
18 let mut at = 0;
19 let mut word = || {
20 let x = u32::from_le_bytes(data[at..at + 4].try_into().expect("input word"));
21 at += 4;
22 x
23 };
24 let n = word() as usize;
25 let ni = word() as usize;
26 let w = word();
27 let h = word();
28 let p: Vec<[f32; 3]> = (0..n)
29 .map(|_| {
30 [
31 f32::from_bits(word()),
32 f32::from_bits(word()),
33 f32::from_bits(word()),
34 ]
35 })
36 .collect();
37 let uv: Vec<f32> = (0..n * 2).map(|_| f32::from_bits(word())).collect();
38 let indices: Vec<u32> = (0..ni).map(|_| word()).collect();
39 let mask = AlphaMask::new(&data[at..], w, h)?;
40 let masks = [Some(mask)];
41 let attrs = Attributes::from_interleaved(&uv, n, 2, 2, 0)?;
42 let mut config = cl::default_config(32)?;
43 config.partition_size = 2;
44 config.optimize_clusters = false;
45 let grid = QuantGrid::new(-16)?;
46 let run = |alpha| {
47 let mut m = BuildMesh::new(&indices, &p);
48 m.attributes = Some(attrs);
49 m.attribute_weights = &[0., 0.];
50 if alpha {
51 m.alpha_coverage = Some(AlphaCoverage::new(&masks, 0));
52 }
53 v2::build(config, m, grid, &mut Workspace::default())
54 };
55 let mut off = run(false)?;
56 let mut on = run(true)?;
57 // Use the actual container's repaired spheres and quantisation error floor.
58 for b in [&mut off, &mut on] {
59 let source =
60 cl::dag_format::v2::Source::new(&b.groups, &b.clusters, &b.positions, &b.indices);
61 let (file, _) = cl::dag_format::v2::write(
62 &source,
63 &cl::dag_format::v2::WriteOptions::new(grid),
64 &mut Workspace::default(),
65 )?;
66 let reader = cl::dag_format::v2::Reader::read_all(&file, &mut Workspace::default())?;
67 let count = b.groups.len();
68 for (i, g) in b.groups.iter_mut().enumerate() {
69 let record = reader.group(count - 1 - i)?;
70 g.center = record.center;
71 g.radius = record.radius;
72 g.error = record.error;
73 }
74 }
75 let radius = p
76 .iter()
77 .map(|p| p.iter().map(|v| v * v).sum::<f32>().sqrt())
78 .fold(0f32, f32::max);
79 let bounds = ImpostorBounds::new([0.; 3], radius * 1.001)?;
80 let grid_views = ImpostorGrid::new(ImpostorLayout::Sphere, 3)?;
81 let render = |b: &v2::Built, idx: &[u32], resolution| {
82 let uvs: Vec<[f32; 2]> = b
83 .attributes
84 .chunks_exact(b.attribute_stride)
85 .map(|a| [a[0], a[1]])
86 .collect();
87 let sampler = |_: usize, uv: [f32; 2]| {
88 let x = ((uv[0] as f64).rem_euclid(1.0) * w as f64) as u32;
89 let y = ((uv[1] as f64).rem_euclid(1.0) * h as f64) as u32;
90 [
91 1.,
92 1.,
93 1.,
94 f32::from(mask.alpha(x.min(w - 1), y.min(h - 1)).unwrap_or(0)) / 255.,
95 ]
96 };
97 let mut options = ImpostorOptions::default();
98 options.grid = grid_views;
99 options.bounds = Some(bounds);
100 options.view_resolution = resolution;
101 options.dilation = 0;
102 options.coverage_threshold = 1.;
103 bake_impostor(
104 idx,
105 Positions::from_packed(&b.positions),
106 None,
107 ImpostorAlbedo::Texture {
108 uvs: &uvs,
109 sampler: &sampler,
110 },
111 options,
112 &mut Workspace::default(),
113 )
114 };
115 let leaf: Vec<u32> = off
116 .clusters
117 .iter()
118 .filter(|c| c.refined < 0)
119 .flat_map(|c| {
120 off.indices[c.first_index as usize..(c.first_index + c.index_count) as usize]
121 .iter()
122 .copied()
123 })
124 .collect();
125 println!("source_triangles={} off_stuck={} on_stuck={} alpha_stuck={} raised={} off_dag_triangles={} on_dag_triangles={}",ni/3,off.stuck_groups,on.stuck_groups,on.alpha_coverage_stuck_groups,on.alpha_coverage_raised_groups,off.indices.len()/3,on.indices.len()/3);
126 for distance in [4f32, 8., 16., 32., 64.] {
127 let view = CutView {
128 position: [0., 0., distance],
129 projection: Projection::Perspective {
130 proj_y: 1.0 / (0.5f32).tan(),
131 znear: 0.01,
132 },
133 viewport_height: 1080.,
134 scale: 1.0,
135 };
136 let resolution = ((2. * radius / distance * (1080. / (2. * (0.5f32).tan()))).round()
137 as u32)
138 .clamp(8, 512);
139 let reference = render(&off, &leaf, resolution)?;
140 for (name, b) in [("off", &off), ("on", &on)] {
141 let mut cut = vec![0u32; b.clusters.len()];
142 let count = cut::select_cut(
143 &b.groups,
144 &b.clusters,
145 &view,
146 Threshold::Pixels(1.0),
147 None,
148 &mut cut,
149 )?;
150 let chosen: Vec<u32> = cut[..count]
151 .iter()
152 .flat_map(|&c| {
153 let c = &b.clusters[c as usize];
154 b.indices[c.first_index as usize..(c.first_index + c.index_count) as usize]
155 .iter()
156 .copied()
157 })
158 .collect();
159 let atlas = render(b, &chosen, resolution)?;
160 let r = resolution as usize;
161 let size = r * 3;
162 let mut ratios = Vec::new();
163 let mut max_blur = 0f64;
164 for v in 0..9 {
165 let (ox, oy) = ((v % 3) * r, (v / 3) * r);
166 let mut sums = [0u64; 2];
167 let mut blur = 0.;
168 for y in 0..r {
169 for x in 0..r {
170 let i = (oy + y) * size + ox + x;
171 sums[0] += u64::from(reference.albedo_alpha[i][3]);
172 sums[1] += u64::from(atlas.albedo_alpha[i][3]);
173 let mut d = 0i32;
174 for dy in -1isize..=1 {
175 for dx in -1isize..=1 {
176 let j = (oy + y.saturating_add_signed(dy).min(r - 1)) * size
177 + ox
178 + x.saturating_add_signed(dx).min(r - 1);
179 d += i32::from(reference.albedo_alpha[j][3])
180 - i32::from(atlas.albedo_alpha[j][3]);
181 }
182 }
183 blur += f64::from(d.abs()) / (255. * 9.);
184 }
185 }
186 ratios.push(if sums[0] == 0 {
187 if sums[1] == 0 {
188 1.
189 } else {
190 f64::INFINITY
191 }
192 } else {
193 sums[1] as f64 / sums[0] as f64
194 });
195 max_blur = max_blur.max(blur / (r * r) as f64);
196 }
197 println!("distance={distance} resolution={resolution} policy={name} triangles={} ratio_min={:.6} ratio_max={:.6} blurred_max={max_blur:.6}",chosen.len()/3,ratios.iter().copied().fold(f64::INFINITY,f64::min),ratios.iter().copied().fold(0.,f64::max));
198 }
199 }
200 for (name, b) in [("off", &off), ("on", &on)] {
201 let report =
202 v2::measure_fallback(b, &LodQualityOptions::default(), &mut Workspace::default())?;
203 println!(
204 "fallback={name} triangles={} sampled_max={} sampled_rms={}",
205 report.indices.len() / 3,
206 report.quality.symmetric.max,
207 report.quality.symmetric.rms
208 );
209 }
210 Ok(())
211}More examples
examples/character_eval.rs (line 158)
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}Sourcepub fn from_bytes(
data: &'a [u8],
count: usize,
components: usize,
stride: usize,
offset: usize,
order: ByteOrder,
) -> Result<Self, Error>
pub fn from_bytes( data: &'a [u8], count: usize, components: usize, stride: usize, offset: usize, order: ByteOrder, ) -> Result<Self, Error>
Borrow initialized attribute bytes with an explicit byte order. Byte stride is a multiple of four and at most 256 bytes.
§Errors
InvalidLayout for an unsupported width, stride, offset or buffer length;
SizeOverflow if view size arithmetic overflows.
Sourcepub const fn components(self) -> usize
pub const fn components(self) -> usize
Components per vertex.
Trait Implementations§
Source§impl<'a> Clone for Attributes<'a>
impl<'a> Clone for Attributes<'a>
impl<'a> Copy for Attributes<'a>
Auto Trait Implementations§
impl<'a> Forget for Attributes<'a>
impl<'a> Freeze for Attributes<'a>
impl<'a> Move for Attributes<'a>
impl<'a> RefUnwindSafe for Attributes<'a>
impl<'a> Send for Attributes<'a>
impl<'a> Sync for Attributes<'a>
impl<'a> Unpin for Attributes<'a>
impl<'a> UnsafeUnpin for Attributes<'a>
impl<'a> UnwindSafe for Attributes<'a>
Blanket Implementations§
Source§impl<T> BorrowMut<T> for Twhere
T: ?Sized,
impl<T> BorrowMut<T> for Twhere
T: ?Sized,
Source§fn borrow_mut(&mut self) -> &mut T
fn borrow_mut(&mut self) -> &mut T
Mutably borrows from an owned value. Read more
Source§impl<T> CloneToUninit for Twhere
T: Clone,
impl<T> CloneToUninit for Twhere
T: Clone,
Source§impl<T> IntoEither for T
impl<T> IntoEither for T
Source§fn into_either(self, into_left: bool) -> Either<Self, Self> ⓘ
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 moreSource§fn into_either_with<F>(self, into_left: F) -> Either<Self, Self> ⓘ
fn into_either_with<F>(self, into_left: F) -> Either<Self, Self> ⓘ
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