From 368731f7a424019b67130f13c8d65f97fcd5d2ea Mon Sep 17 00:00:00 2001 From: chasse20 Date: Tue, 10 Nov 2026 05:30:17 -0500 Subject: [PATCH] Fix Clippy checks and clean up affected functions --- crates/automation/src/security.rs | 19 +++-- crates/bake/src/cage/high_poly_reach.rs | 6 +- crates/bake/src/test/high_poly_reach.rs | 3 +- crates/bake/src/test/setting.rs | 7 ++ crates/bake/src/tests.rs | 22 +++--- crates/compose/src/display.rs | 88 ++++++++++++---------- crates/compose/src/eval.rs | 47 +++++++----- crates/engine/src/quick_mask.rs | 31 ++++---- crates/engine/tests/it/bake.rs | 19 ++--- crates/engine/tests/it/bake_tiles.rs | 5 ++ crates/formats/src/fonts.rs | 61 ++++++++------- crates/formats/src/mesh_export.rs | 43 ++++++----- crates/formats/src/mesh_export/usd.rs | 58 +++++++------- crates/formats/src/mesh_import/abc/mod.rs | 69 ++++++++++------- crates/formats/src/mesh_import/fbx.rs | 79 ++++++++++--------- crates/formats/src/mesh_import/gltf.rs | 66 ++++++++-------- crates/formats/src/mesh_import/mod.rs | 22 ++++-- crates/formats/src/mesh_import/obj.rs | 66 +++++++++------- crates/formats/src/mesh_import/usd/usdc.rs | 20 ++--- crates/formats/src/project_file/mod.rs | 64 +++++++++------- crates/geom/src/mesh.rs | 58 ++++++++------ crates/paint/src/particles.rs | 32 ++++---- crates/render/src/subdivide.rs | 67 ++++++++-------- 23 files changed, 538 insertions(+), 414 deletions(-) diff --git a/crates/automation/src/security.rs b/crates/automation/src/security.rs index 7613ecd5..63c12b0e 100644 --- a/crates/automation/src/security.rs +++ b/crates/automation/src/security.rs @@ -178,8 +178,11 @@ pub struct ConnectionLimiter(Arc); pub struct Permit(Arc); impl ConnectionLimiter { - pub fn try_acquire(&self, max: usize) -> Option { - self.0.try_update(Ordering::AcqRel, Ordering::Acquire, |n| (n < max).then_some(n + 1)).ok().map(|_| Permit(self.0.clone())) + pub fn try_acquire(&self, max_connections: usize) -> Option { + self.0 + .try_update(Ordering::AcqRel, Ordering::Acquire, |connections| (connections < max_connections).then_some(connections + 1)) + .ok() + .map(|_| Permit(self.0.clone())) } } @@ -328,10 +331,12 @@ mod tests { #[test] fn limiter_releases() { - let l = ConnectionLimiter::default(); - let p = l.try_acquire(1).unwrap(); - assert!(l.try_acquire(1).is_none()); - drop(p); - assert!(l.try_acquire(1).is_some()); + let limiter = ConnectionLimiter::default(); + + let permit = limiter.try_acquire(1).unwrap(); + assert!(limiter.try_acquire(1).is_none()); + + drop(permit); + assert!(limiter.try_acquire(1).is_some()); } } diff --git a/crates/bake/src/cage/high_poly_reach.rs b/crates/bake/src/cage/high_poly_reach.rs index f957ce49..2f461343 100644 --- a/crates/bake/src/cage/high_poly_reach.rs +++ b/crates/bake/src/cage/high_poly_reach.rs @@ -77,20 +77,21 @@ impl HighPolyReach { /// Each vertex's mesh-name key, from the first triangle that uses it fn vertex_keys(mesh: &Mesh, triangle_keys: &[u32]) -> Vec { let mut keys = vec![ANY; mesh.positions.len()]; - for (corners, &triangle_key) in mesh.indices.chunks_exact(3).zip(triangle_keys) { + for (corners, &triangle_key) in mesh.indices.as_chunks::<3>().0.iter().zip(triangle_keys) { for &corner in corners { if let Some(key) = keys.get_mut(corner as usize).filter(|key| **key == ANY) { *key = triangle_key; } } } + keys } /// Each vertex's sum of its triangles' winding normals, weighted by area: the side the bake's backface test sees as the front fn winding_normals(mesh: &Mesh) -> Vec { let mut normals = vec![Vec3::ZERO; mesh.positions.len()]; - for corners in mesh.indices.chunks_exact(3) { + for corners in mesh.indices.as_chunks::<3>().0 { let position = |corner: u32| mesh.positions.get(corner as usize).copied().unwrap_or(Vec3::ZERO); let winding_normal = (position(corners[1]) - position(corners[0])).cross(position(corners[2]) - position(corners[0])); for &corner in corners { @@ -99,5 +100,6 @@ fn winding_normals(mesh: &Mesh) -> Vec { } } } + normals } diff --git a/crates/bake/src/test/high_poly_reach.rs b/crates/bake/src/test/high_poly_reach.rs index e6d66d07..8a4f83c4 100644 --- a/crates/bake/src/test/high_poly_reach.rs +++ b/crates/bake/src/test/high_poly_reach.rs @@ -23,7 +23,7 @@ fn bumpy_high_poly() -> (Mesh, Vec) { let mut flipped = vec![false; mesh.positions.len()]; let mut unflipped = vec![false; mesh.positions.len()]; - for corners in mesh.indices.chunks_exact_mut(3) { + for corners in mesh.indices.as_chunks_mut::<3>().0 { let center_x = corners.iter().map(|&corner| mesh.positions[corner as usize].x).sum::() / 3.0; if center_x > FLIPPED_FROM_X { corners.swap(1, 2); @@ -32,6 +32,7 @@ fn bumpy_high_poly() -> (Mesh, Vec) { if center_x > FLIPPED_FROM_X { flipped[corner as usize] = true } else { unflipped[corner as usize] = true } } } + // Vertices on the border face both ways: neither answer is right for them let mixed = flipped.iter().zip(&unflipped).map(|(flipped, unflipped)| *flipped && *unflipped).collect(); (mesh, mixed) diff --git a/crates/bake/src/test/setting.rs b/crates/bake/src/test/setting.rs index 03a97b77..668338a7 100644 --- a/crates/bake/src/test/setting.rs +++ b/crates/bake/src/test/setting.rs @@ -41,13 +41,18 @@ fn matching_skips_a_closer_unrelated_high_mesh_and_backfaces() { parameters.cage.relative_to_bounding_box = false; parameters.maps.height.parameters.normalization = HeightNormalization::Manual; let height = |parameters: &BakeSettings, high: &Mesh| transfer(&low, high, None, parameters).unwrap().maps[&BakedMap::Height][128]; + assert!((height(¶meters, &high) - 0.54).abs() < 1e-5); + parameters.high_poly.match_mode = MeshMatchMode::ByMeshName; assert!((height(¶meters, &high) - 0.52).abs() < 1e-5); + for triangle in high.indices.as_chunks_mut::<3>().0 { triangle.swap(1, 2); } + assert_eq!(height(¶meters, &high), 0.5); + parameters.high_poly.ignore_backface = false; assert!((height(¶meters, &high) - 0.52).abs() < 1e-5); } @@ -159,9 +164,11 @@ fn position_axis_and_material_bounds_change_only_the_requested_space() { mesh.append(&distant); let mut parameters = settings(16, &[BakedMap::Position]); parameters.maps.position.parameters.axis = PositionAxis::X; + let global = run(&mesh, ¶meters).unwrap(); parameters.maps.position.parameters.scale = PositionNormalizationScale::PerMaterial; let local = run(&mesh, ¶meters).unwrap(); + assert!(global.maps[&BakedMap::Position].iter().all(|value| *value < 0.2)); assert!(local.maps[&BakedMap::Position].iter().any(|value| *value > 0.9)); assert!(local.maps[&BakedMap::Position].as_chunks::<3>().0.iter().all(|pixel| pixel[0] == pixel[1] && pixel[1] == pixel[2])); diff --git a/crates/bake/src/tests.rs b/crates/bake/src/tests.rs index 1bf7fa25..0c313462 100644 --- a/crates/bake/src/tests.rs +++ b/crates/bake/src/tests.rs @@ -100,18 +100,20 @@ fn open_quad_is_unoccluded() { #[test] fn inside_of_a_closed_box_is_occluded() { - let mut m = primitives::cube(2.0); - for t in m.indices.as_chunks_mut::<3>().0.iter_mut() { - t.swap(1, 2); + let mut mesh = primitives::cube(2.0); + for triangle in mesh.indices.as_chunks_mut::<3>().0 { + triangle.swap(1, 2); } - for n in &mut m.normals { - *n = -*n; + for normal in &mut mesh.normals { + *normal = -*normal; } - m.compute_tangents(); - let s = with_rays(settings(64, &[BakedMap::AmbientOcclusion]), 64, 4.0); - let out = run(&m, &s).unwrap(); - let ao = mean(covered_values(&m, &out, BakedMap::AmbientOcclusion).into_iter().map(|v| v.1)); - assert!(ao < 0.3, "{ao}"); + mesh.compute_tangents(); + let parameters = with_rays(settings(64, &[BakedMap::AmbientOcclusion]), 64, 4.0); + + let output = run(&mesh, ¶meters).unwrap(); + + let mean_occlusion = mean(covered_values(&mesh, &output, BakedMap::AmbientOcclusion).into_iter().map(|v| v.1)); + assert!(mean_occlusion < 0.3, "{mean_occlusion}"); } #[test] diff --git a/crates/compose/src/display.rs b/crates/compose/src/display.rs index 0b126594..5ebb667b 100644 --- a/crates/compose/src/display.rs +++ b/crates/compose/src/display.rs @@ -93,20 +93,21 @@ fn u8_of(v: u16) -> u8 { (v >> 8) as u8 } -/// Tile bytes (`TILE × TILE`, row-major) for `kind` from the composite, or None when the tile is -/// absent in every source (the GPU texture keeps its cleared default). -pub fn tile_bytes(comp: &Composite, baked: &BakedMaps, kind: DisplayKind, tx: u32, ty: u32) -> Vec { - let bpt = kind.bytes_per_texel(); - let mut out = vec![0u8; TILE_AREA * bpt]; - let lut = srgb_lut(); - let get = |c: Channel| comp.channels.get(&c).and_then(|img| img.tile(tx, ty)); - let res = comp.resolution; +/// Tile bytes (`TILE × TILE`, row-major) for `kind`, using channel defaults for absent source tiles. +pub fn tile_bytes(composite: &Composite, baked: &BakedMaps, kind: DisplayKind, tx: u32, ty: u32) -> Vec { + let bytes_per_texel = kind.bytes_per_texel(); + let mut out = vec![0u8; TILE_AREA * bytes_per_texel]; + let srgb = srgb_lut(); + let get = |c: Channel| composite.channels.get(&c).and_then(|img| img.tile(tx, ty)); + let resolution = composite.resolution; let default16 = |c: Channel| texturecraft_texel::to_u16(c.default_value()[0]); - // A scalar channel's texel `i` as 8 bits (its default where the set lacks it). + + // A scalar channel's texel `i` as 8 bits (its default where the set lacks it) let scalar8 = |c: Channel| { let (t, d) = (get(c), default16(c)); move |i: usize| u8_of(t.and_then(|t| t.get(i).copied()).unwrap_or(d)) }; + match kind { DisplayKind::BaseColor | DisplayKind::Emissive | DisplayKind::Sheen => { let (c, alpha) = match kind { @@ -117,81 +118,87 @@ pub fn tile_bytes(comp: &Composite, baked: &BakedMaps, kind: DisplayKind, tx: u3 let (src, alpha) = (get(c), scalar8(alpha)); let d = c.default_value().map(|v| (texturecraft_texel::linear_to_srgb(v) * 255.0 + 0.5) as u8); for i in 0..TILE_AREA { - let px = &mut out[i * 4..i * 4 + 4]; + let pixel = &mut out[i * 4..i * 4 + 4]; match src { Some(s) => { for k in 0..3 { - px[k] = lut[(s.get(i * 3 + k).copied().unwrap_or(0) >> 4) as usize]; + pixel[k] = srgb[(s.get(i * 3 + k).copied().unwrap_or(0) >> 4) as usize]; } } - None => px[..3].copy_from_slice(&d), + None => pixel[..3].copy_from_slice(&d), } - px[3] = alpha(i); + pixel[3] = alpha(i); } } DisplayKind::Lobes => { let lanes = [Channel::CoatWeight, Channel::CoatRoughness, Channel::AnisotropyLevel, Channel::AnisotropyAngle].map(scalar8); - for (i, px) in out.as_chunks_mut::<4>().0.iter_mut().enumerate() { - for (d, lane) in px.iter_mut().zip(&lanes) { + for (i, pixel) in out.as_chunks_mut::<4>().0.iter_mut().enumerate() { + for (d, lane) in pixel.iter_mut().zip(&lanes) { *d = lane(i); } } } DisplayKind::Extra => { let (n, transmission) = (get(Channel::CoatNormal), scalar8(Channel::Transmission)); - // Signed 8-bit around 128 so the flat normal packs exactly. - let snorm = |v: u16| (128.0 + 127.0 * (v as f32 / 65535.0 * 2.0 - 1.0)).round().clamp(0.0, 255.0) as u8; - // A TILE never straddles two atlas blocks. - let scale = (-32.0 * comp.block_scales.at(tx * TILE, ty * TILE).log2()).round().clamp(0.0, 255.0) as u8; - for (i, px) in out.as_chunks_mut::<4>().0.iter_mut().enumerate() { - for (k, d) in px.iter_mut().take(2).enumerate() { - *d = n.and_then(|t| t.get(i * 3 + k)).map_or(128, |v| snorm(*v)); + + // Signed 8-bit around 128 so the flat normal packs exactly + let pack_signed_normal = |v: u16| (128.0 + 127.0 * (v as f32 / 65535.0 * 2.0 - 1.0)).round().clamp(0.0, 255.0) as u8; + + // A TILE never straddles two atlas blocks + let scale = (-32.0 * composite.block_scales.at(tx * TILE, ty * TILE).log2()).round().clamp(0.0, 255.0) as u8; + for (i, pixel) in out.as_chunks_mut::<4>().0.iter_mut().enumerate() { + for (k, d) in pixel.iter_mut().take(2).enumerate() { + *d = n.and_then(|t| t.get(i * 3 + k)).map_or(128, |v| pack_signed_normal(*v)); } - px[2] = transmission(i); - px[3] = scale; + pixel[2] = transmission(i); + pixel[3] = scale; } } DisplayKind::Orm => { let (ao, m, s) = (get(Channel::AmbientOcclusion), get(Channel::Metallic), get(Channel::SpecularLevel)); - // Specular/glossiness sets: the viewport shades roughness = 1 − glossiness. - let gloss = comp.channels.contains_key(&Channel::Glossiness); + + // Specular/glossiness sets: the viewport shades roughness = 1 − glossiness + let gloss = composite.channels.contains_key(&Channel::Glossiness); let (r, r_default) = if gloss { (get(Channel::Glossiness), default16(Channel::Glossiness)) } else { (get(Channel::Roughness), default16(Channel::Roughness)) }; for i in 0..TILE_AREA { let (x, y) = (tx * TILE + (i as u32 % TILE), ty * TILE + (i as u32 / TILE)); - let baked_ao = baked.sample_working(BakedMap::AmbientOcclusion, x, y, (res, comp.height), &comp.block_scales).map_or(1.0, |value| value[0]); + let baked_ao = baked + .sample_working(BakedMap::AmbientOcclusion, x, y, (resolution, composite.height), &composite.block_scales) + .map_or(1.0, |value| value[0]); let ch_ao = ao.and_then(|a| a.get(i)).map(|v| *v as f32 / 65535.0).unwrap_or(1.0); - let px = &mut out[i * 4..i * 4 + 4]; - px[0] = ((baked_ao * ch_ao).clamp(0.0, 1.0) * 255.0 + 0.5) as u8; + let pixel = &mut out[i * 4..i * 4 + 4]; + pixel[0] = ((baked_ao * ch_ao).clamp(0.0, 1.0) * 255.0 + 0.5) as u8; let v = r.and_then(|t| t.get(i).copied()).unwrap_or(r_default); - px[1] = u8_of(if gloss { 65535 - v } else { v }); - px[2] = u8_of(m.and_then(|t| t.get(i).copied()).unwrap_or(0)); - px[3] = u8_of(s.and_then(|t| t.get(i).copied()).unwrap_or(default16(Channel::SpecularLevel))); + pixel[1] = u8_of(if gloss { 65535 - v } else { v }); + pixel[2] = u8_of(m.and_then(|t| t.get(i).copied()).unwrap_or(0)); + pixel[3] = u8_of(s.and_then(|t| t.get(i).copied()).unwrap_or(default16(Channel::SpecularLevel))); } } DisplayKind::Normal => { - let (n, sheen_rough) = (get(Channel::Normal), scalar8(Channel::SheenRoughness)); + let (n, sheen_roughness) = (get(Channel::Normal), scalar8(Channel::SheenRoughness)); for i in 0..TILE_AREA { - let px = &mut out[i * 4..i * 4 + 4]; - // The baked normal is the base the painted normal details sit on (as in export). + let pixel = &mut out[i * 4..i * 4 + 4]; + + // The baked normal is the base the painted normal details sit on (as in export) let (x, y) = (tx * TILE + (i as u32 % TILE), ty * TILE + (i as u32 / TILE)); - let base = baked.sample_working(BakedMap::Normal, x, y, (res, comp.height), &comp.block_scales); + let base = baked.sample_working(BakedMap::Normal, x, y, (resolution, composite.height), &composite.block_scales); match (n, base) { (Some(t), None) => { - for (k, d) in px.iter_mut().take(3).enumerate() { + for (k, d) in pixel.iter_mut().take(3).enumerate() { *d = u8_of(t.get(i * 3 + k).copied().unwrap_or(0)); } } (detail, Some(base)) => { let detail = detail.map_or([0.5, 0.5, 1.0], |t| [0, 1, 2].map(|k| t.get(i * 3 + k).map_or(0.0, |v| *v as f32 / 65535.0))); let v = texturecraft_core::blend::rnm(base, detail); - for (d, v) in px.iter_mut().zip(v) { + for (d, v) in pixel.iter_mut().zip(v) { *d = (v.clamp(0.0, 1.0) * 255.0 + 0.5) as u8; } } - (None, None) => px[..3].copy_from_slice(&[128, 128, 255]), + (None, None) => pixel[..3].copy_from_slice(&[128, 128, 255]), } - px[3] = sheen_rough(i); + pixel[3] = sheen_roughness(i); } } DisplayKind::Height => { @@ -206,6 +213,7 @@ pub fn tile_bytes(comp: &Composite, baked: &BakedMaps, kind: DisplayKind, tx: u3 } } } + out } diff --git a/crates/compose/src/eval.rs b/crates/compose/src/eval.rs index 26d08f67..3a9404d3 100644 --- a/crates/compose/src/eval.rs +++ b/crates/compose/src/eval.rs @@ -2203,60 +2203,67 @@ pub type FlatTile = (Channel, (u32, u32), Vec); /// Flatten one paint or fill layer: its content (with content effects) times its mask, as /// premultiplied (value, coverage) tiles per enabled channel, ready to become a plain paint /// layer. Groups are not supported (None). -pub fn flatten_layer(inp: &Inputs, id: LayerId, tiles: &[(u32, u32)]) -> Option> { - let set = inp.project.texture_set(inp.ts).ok()?; - if inp.project.content_layer(id)?.is_group() { +pub fn flatten_layer(inputs: &Inputs, id: LayerId, tiles: &[(u32, u32)]) -> Option> { + let set = inputs.project.texture_set(inputs.ts).ok()?; + if inputs.project.content_layer(id)?.is_group() { return None; } + let channels: Vec = set.channel_list(); - // Plan the layer forced visible so hidden layers flatten too. - let mut solo = inp.project.clone(); + + // Plan the layer forced visible so hidden layers flatten too + let mut solo = inputs.project.clone(); if let Some(l) = solo.layers.get_mut(&id) { l.visible = true; } - let solo_inp = Inputs { project: &solo, preview: None, block_scales: inp.block_scales.clone(), ..*inp }; - let fields = neighbourhood_fields(&solo_inp, &channels, tiles); + let visible_inputs = Inputs { project: &solo, preview: None, block_scales: inputs.block_scales.clone(), ..*inputs }; + let fields = neighbourhood_fields(&visible_inputs, &channels, tiles); + let out: Vec> = tiles .par_iter() .map(|&(tx, ty)| { - let nodes = plan(&solo_inp, &[id], &channels, tx, ty, 0, Some(&fields)); + let nodes = plan(&visible_inputs, &[id], &channels, tx, ty, 0, Some(&fields)); let Some(n) = nodes.first() else { return Vec::new() }; - let full = anchor_plan(&solo_inp, id, &channels, tx, ty, Some(&fields)); - let mut bufs: Vec<(Channel, Vec, bool)> = + let full = anchor_plan(&visible_inputs, id, &channels, tx, ty, Some(&fields)); + let mut buffers: Vec<(Channel, Vec, bool)> = n.chans.iter().filter_map(|c| Channel::ALL.get(c.ch).map(|ch| (*ch, vec![0u16; TILE_AREA * (c.comps + 1)], false))).collect(); - for (ch, buf, _) in &mut bufs { + for (ch, buffer, _) in &mut buffers { if ch.kind() == ChannelKind::Signed { - for px in buf.as_chunks_mut::<2>().0.iter_mut() { - px[0] = to_u16_signed(0.0); + for pixel in buffer.as_chunks_mut::<2>().0 { + pixel[0] = to_u16_signed(0.0); } } } - for (x, y, o) in tile_texels(inp.gbuf, tx, ty) { - let mut tex = Texel::new(&solo_inp, x, y, o, 0.0); + + for (x, y, o) in tile_texels(inputs.gbuf, tx, ty) { + let mut tex = Texel::new(&visible_inputs, x, y, o, 0.0); if !full.is_empty() { tex.anchors_below(&full, id); } let m = tex.node_mask(n); - for (c, (ch, buf, any)) in n.chans.iter().zip(bufs.iter_mut()) { + for (c, (ch, buffer, any)) in n.chans.iter().zip(buffers.iter_mut()) { let Some((v, cov)) = tex.content(&n.content, c) else { continue }; let a = (cov * m).clamp(0.0, 1.0); if a <= 0.0 { continue; } + *any = true; let comps = c.comps; - let Some(px) = buf.get_mut(o * (comps + 1)..(o + 1) * (comps + 1)) else { continue }; - for (slot, pv) in px.iter_mut().zip(v.iter().take(comps)) { + let Some(pixel) = buffer.get_mut(o * (comps + 1)..(o + 1) * (comps + 1)) else { continue }; + for (slot, pv) in pixel.iter_mut().zip(v.iter().take(comps)) { *slot = if ch.kind() == ChannelKind::Signed { to_u16_signed(pv * a) } else { to_u16(pv * a) }; } - if let Some(slot) = px.get_mut(comps) { + if let Some(slot) = pixel.get_mut(comps) { *slot = to_u16(a); } } } - bufs.into_iter().filter(|(_, _, any)| *any).map(|(ch, buf, _)| (ch, (tx, ty), buf)).collect() + + buffers.into_iter().filter(|(_, _, any)| *any).map(|(ch, buffer, _)| (ch, (tx, ty), buffer)).collect() }) .collect(); + Some(out.into_iter().flatten().collect()) } diff --git a/crates/engine/src/quick_mask.rs b/crates/engine/src/quick_mask.rs index 92d00962..93087c14 100644 --- a/crates/engine/src/quick_mask.rs +++ b/crates/engine/src/quick_mask.rs @@ -105,34 +105,37 @@ impl Session { /// Includes the stroke in progress. pub fn quick_mask_rgba(&self, ts: usize, size: u32) -> Option> { let cache = self.caches.get(ts)?; - let (w, h) = cache.size; - let size = size.clamp(1, w.max(h)); + let (width, height) = cache.size; + let size = size.clamp(1, width.max(height)); let mask = self.quick_mask_image(ts, cache.size); let live = self.stroke.as_ref().filter(|s| s.ts == ts && s.target.is_none()).map(|s| (&s.canvas.alpha, s.stroke.settings.opacity, s.erase)); let base = cache.composite.channels.get(&Channel::BaseColor); - let lut = srgb_lut(); + let srgb = srgb_lut(); let inverted = self.quick_mask.inverted; let mut out = vec![255u8; size as usize * size as usize * 4]; + out.par_chunks_mut(size as usize * 4).enumerate().for_each(|(y, row)| { - let ty = (y as u64 * u64::from(h) / u64::from(size)) as u32; - for (x, px) in row.as_chunks_mut::<4>().0.iter_mut().enumerate() { - let tx = (x as u64 * u64::from(w) / u64::from(size)) as u32; - let mut m = from_u16(mask.get(tx, ty)[0]); + let ty = (y as u64 * u64::from(height) / u64::from(size)) as u32; + for (x, pixel) in row.as_chunks_mut::<4>().0.iter_mut().enumerate() { + let tx = (x as u64 * u64::from(width) / u64::from(size)) as u32; + let mut coverage = from_u16(mask.get(tx, ty)[0]); if let Some((alpha, opacity, erase)) = live { - let a = from_u16(alpha.get(tx, ty)[0]) * opacity; - m = if erase { m * (1.0 - a) } else { a + m * (1.0 - a) }; + let stroke_coverage = from_u16(alpha.get(tx, ty)[0]) * opacity; + coverage = if erase { coverage * (1.0 - stroke_coverage) } else { stroke_coverage + coverage * (1.0 - stroke_coverage) }; } - let blocked = if inverted { m } else { 1.0 - m }; + + let blocked = if inverted { coverage } else { 1.0 - coverage }; let raw = base.map(|b| b.get(tx, ty)).unwrap_or([32768; 4]); - let t = 0.55 * blocked; + let tint_amount = 0.55 * blocked; for (k, tint) in [0.9, 0.1, 0.15].into_iter().enumerate() { - let c = f32::from(lut.get(usize::from(raw[k] >> 4)).copied().unwrap_or(0)) / 255.0; - if let Some(slot) = px.get_mut(k) { - *slot = ((c + (tint - c) * t).clamp(0.0, 1.0) * 255.0 + 0.5) as u8; + let color = f32::from(srgb.get(usize::from(raw[k] >> 4)).copied().unwrap_or(0)) / 255.0; + if let Some(slot) = pixel.get_mut(k) { + *slot = ((color + (tint - color) * tint_amount).clamp(0.0, 1.0) * 255.0 + 0.5) as u8; } } } }); + Some(out) } } diff --git a/crates/engine/tests/it/bake.rs b/crates/engine/tests/it/bake.rs index 013834b6..85b0142c 100644 --- a/crates/engine/tests/it/bake.rs +++ b/crates/engine/tests/it/bake.rs @@ -10,17 +10,18 @@ fn plane_session() -> Session { Session::new_project("t", mesh, "builtin:plane", None, 256).unwrap() } -/// `mesh` as OBJ text, lifted by `dy`, keeping only vertices with x ≤ `max_x` (triangles that -/// lose a vertex are dropped), every vertex colored `rgb`. -fn obj(mesh: &Mesh, dy: f32, max_x: f32, rgb: [f32; 3]) -> String { - let mut s = String::from("o Part_high\n"); - for p in &mesh.positions { - s += &format!("v {} {} {} {} {} {}\n", p.x.min(max_x), p.y + dy, p.z, rgb[0], rgb[1], rgb[2]); +/// `mesh` as OBJ text, shifted by `offset_y`, with x clamped to `max_x` and every vertex colored `rgb`. +fn obj(mesh: &Mesh, offset_y: f32, max_x: f32, rgb: [f32; 3]) -> String { + let mut text = String::from("o Part_high\n"); + for position in &mesh.positions { + text += &format!("v {} {} {} {} {} {}\n", position.x.min(max_x), position.y + offset_y, position.z, rgb[0], rgb[1], rgb[2]); } - for t in mesh.indices.as_chunks::<3>().0 { - s += &format!("f {} {} {}\n", t[0] + 1, t[1] + 1, t[2] + 1); + + for triangle in mesh.indices.as_chunks::<3>().0 { + text += &format!("f {} {} {}\n", triangle[0] + 1, triangle[1] + 1, triangle[2] + 1); } - s + + text } fn temp_file(name: &str, text: &str) -> String { diff --git a/crates/engine/tests/it/bake_tiles.rs b/crates/engine/tests/it/bake_tiles.rs index a7f3f1a0..16851173 100644 --- a/crates/engine/tests/it/bake_tiles.rs +++ b/crates/engine/tests/it/bake_tiles.rs @@ -53,6 +53,7 @@ fn partial_bake_preserves_unchecked_tiles_and_uses_the_workers_selection() { execute(&mut session, "bake.tile.set", &json!({"tile": 1002, "enabled": true})).unwrap(); execute(&mut session, "bake.tile.set", &json!({"tile": 1001, "enabled": false})).unwrap(); let before = session.doc.baked.clone(); + let output = task.run(&Progress::new()).unwrap(); session.apply_bake(0, output).unwrap(); @@ -61,6 +62,7 @@ fn partial_bake_preserves_unchecked_tiles_and_uses_the_workers_selection() { assert!(row[..32].iter().all(|value| *value > 0.99)); assert!(row[32..].iter().all(|value| *value == 0.25)); } + session.undo().unwrap(); assert_eq!(session.doc.baked, before); } @@ -76,7 +78,9 @@ fn partial_bake_resizes_retained_tiles_and_unchecked_map_outputs() { }, ); execute(&mut session, "bake.tile.set", &json!({"tile": 1002, "enabled": false})).unwrap(); + let result = execute(&mut session, "bake.run", &json!({"resolution": 64, "cpu": true})).unwrap(); + assert_eq!(result["baked"], json!([0])); let baked = &session.doc.baked[&0]; @@ -87,6 +91,7 @@ fn partial_bake_resizes_retained_tiles_and_unchecked_map_outputs() { } assert_eq!(baked.maps[&BakedMap::Normal].len(), 128 * 64 * 3); assert!(baked.maps[&BakedMap::Normal].iter().all(|value| *value == 0.4)); + let reopened = Session::from_project_bytes(&session.to_project_bytes().unwrap()).unwrap(); assert_eq!(reopened.doc.baked, session.doc.baked); } diff --git a/crates/formats/src/fonts.rs b/crates/formats/src/fonts.rs index ca7db930..fbd27985 100644 --- a/crates/formats/src/fonts.rs +++ b/crates/formats/src/fonts.rs @@ -72,34 +72,37 @@ fn collect(dir: &Path, depth: usize, out: &mut Vec) { /// The faces of the font file at `path` (each face of a collection). pub fn faces_of(path: &Path) -> std::io::Result> { - let mut f = std::fs::File::open(path)?; - let mut at = |offset: u64, len: usize| -> std::io::Result> { - f.seek(SeekFrom::Start(offset))?; - let mut buf = vec![0; len]; - f.read_exact(&mut buf)?; + let mut file = std::fs::File::open(path)?; + let mut read_at = |offset: u64, length: usize| -> std::io::Result> { + file.seek(SeekFrom::Start(offset))?; + let mut buf = vec![0; length]; + file.read_exact(&mut buf)?; Ok(buf) }; - let head = at(0, 12)?; - let offsets: Vec = if head.get(..4) == Some(b"ttcf") { - let n = u32_at(&head, 8).unwrap_or(0).min(MAX_FACES_PER_FILE); - let table = at(12, 4 * n as usize)?; - (0..n as usize).filter_map(|i| u32_at(&table, 4 * i)).map(u64::from).collect() + + let header = read_at(0, 12)?; + let offsets: Vec = if header.get(..4) == Some(b"ttcf") { + let face_count = u32_at(&header, 8).unwrap_or(0).min(MAX_FACES_PER_FILE); + let table = read_at(12, 4 * face_count as usize)?; + (0..face_count as usize).filter_map(|i| u32_at(&table, 4 * i)).map(u64::from).collect() } else { vec![0] }; + let mut faces = Vec::new(); for (index, offset) in offsets.into_iter().enumerate() { - let dir = at(offset, 12)?; - let tables = at(offset + 12, 16 * usize::from(u16_at(&dir, 4).unwrap_or(0)))?; - let Some(rec) = tables.as_chunks::<16>().0.iter().find(|r| r.get(..4) == Some(b"name")) else { continue }; - let (Some(off), Some(len)) = (u32_at(rec, 8), u32_at(rec, 12)) else { continue }; - let names = at(u64::from(off), len.min(MAX_NAME_TABLE) as usize)?; + let directory = read_at(offset, 12)?; + let tables = read_at(offset + 12, 16 * usize::from(u16_at(&directory, 4).unwrap_or(0)))?; + let Some(record) = tables.as_chunks::<16>().0.iter().find(|r| r.get(..4) == Some(b"name")) else { continue }; + let (Some(offset), Some(length)) = (u32_at(record, 8), u32_at(record, 12)) else { continue }; + let names = read_at(u64::from(offset), length.min(MAX_NAME_TABLE) as usize)?; let name = |ids: [u16; 2]| ids.iter().find_map(|id| name_string(&names, *id)); if let Some(family) = name([16, 1]) { let style = name([17, 2]).unwrap_or_else(|| "Regular".into()); faces.push(FontFace { family, style, path: path.to_path_buf(), index: index as u32 }); } } + Ok(faces) } @@ -113,30 +116,32 @@ fn u32_at(b: &[u8], o: usize) -> Option { /// Name `id` of a `name` table, in English when it has several languages: Windows and Unicode /// records are UTF-16BE, Macintosh ones single-byte (read as Latin-1). -fn name_string(t: &[u8], id: u16) -> Option { - let (count, base) = (usize::from(u16_at(t, 2)?), usize::from(u16_at(t, 4)?)); +fn name_string(table: &[u8], id: u16) -> Option { + let (count, base) = (usize::from(u16_at(table, 2)?), usize::from(u16_at(table, 4)?)); let mut best: Option<(u8, String)> = None; - for r in (0..count).filter_map(|i| t.get(6 + 12 * i..18 + 12 * i)) { - let (platform, language, name_id) = (u16_at(r, 0)?, u16_at(r, 4)?, u16_at(r, 6)?); - let (len, off) = (usize::from(u16_at(r, 8)?), usize::from(u16_at(r, 10)?)); - let Some(bytes) = t.get(base + off..base + off + len) else { continue }; + for record in (0..count).filter_map(|i| table.get(6 + 12 * i..18 + 12 * i)) { + let (platform, language, name_id) = (u16_at(record, 0)?, u16_at(record, 4)?, u16_at(record, 6)?); + let (length, offset) = (usize::from(u16_at(record, 8)?), usize::from(u16_at(record, 10)?)); + let Some(bytes) = table.get(base + offset..base + offset + length) else { continue }; if name_id != id { continue; } - let (rank, s) = match platform { + + let (rank, name) = match platform { 3 | 0 => { - let s = String::from_utf16_lossy(&bytes.as_chunks::<2>().0.iter().map(|c| u16::from_be_bytes([c[0], c[1]])).collect::>()); - (if language == 0x409 { 0 } else { 1 }, s) + let name = String::from_utf16_lossy(&bytes.as_chunks::<2>().0.iter().map(|c| u16::from_be_bytes(*c)).collect::>()); + (if language == 0x409 { 0 } else { 1 }, name) } 1 => (if language == 0 { 2 } else { 3 }, bytes.iter().map(|b| char::from(*b)).collect()), _ => continue, }; - let s = s.trim().to_string(); - if !s.is_empty() && best.as_ref().is_none_or(|(r, _)| rank < *r) { - best = Some((rank, s)); + let name = name.trim().to_string(); + if !name.is_empty() && best.as_ref().is_none_or(|(best_rank, _)| rank < *best_rank) { + best = Some((rank, name)); } } - best.map(|(_, s)| s) + + best.map(|(_, name)| name) } #[cfg(test)] diff --git a/crates/formats/src/mesh_export.rs b/crates/formats/src/mesh_export.rs index 454ceffd..404b09bb 100644 --- a/crates/formats/src/mesh_export.rs +++ b/crates/formats/src/mesh_export.rs @@ -67,47 +67,50 @@ pub fn obj_with_mtl(mesh: &Mesh, name: &str, stem: &str, textures: &[Vec) -> String { - let mut s = String::with_capacity(mesh.positions.len() * 96 + mesh.indices.len() * 12); - let _ = writeln!(s, "# {}, exported by TextureCraft", token(name)); + let mut text = String::with_capacity(mesh.positions.len() * 96 + mesh.indices.len() * 12); + let _ = writeln!(text, "# {}, exported by TextureCraft", token(name)); if let Some(lib) = mtllib { - let _ = writeln!(s, "mtllib {lib}"); + let _ = writeln!(text, "mtllib {lib}"); } - let _ = writeln!(s, "o {}", token(name)); + let _ = writeln!(text, "o {}", token(name)); for p in &mesh.positions { - let _ = writeln!(s, "v {} {} {}", p.x, p.y, p.z); + let _ = writeln!(text, "v {} {} {}", p.x, p.y, p.z); } + let uvs = mesh.uvs.len() == mesh.positions.len(); let normals = mesh.normals.len() == mesh.positions.len(); if uvs { for t in &mesh.uvs { - let _ = writeln!(s, "vt {} {}", t.x, 1.0 - t.y); + let _ = writeln!(text, "vt {} {}", t.x, 1.0 - t.y); } } if normals { for n in &mesh.normals { - let _ = writeln!(s, "vn {} {} {}", n.x, n.y, n.z); + let _ = writeln!(text, "vn {} {} {}", n.x, n.y, n.z); } } + let materials = unique_ids(&mesh.materials, token); - for sm in &parts(mesh, name) { - let material = materials.get(sm.material).map_or("default", String::as_str); - let _ = writeln!(s, "g {}\nusemtl {material}", token(&sm.name)); - let (a, b) = (sm.start as usize, sm.start as usize + sm.count as usize); - for tri in mesh.indices.get(a..b).unwrap_or_default().as_chunks::<3>().0 { - s.push('f'); - for i in tri { + for part in &parts(mesh, name) { + let material = materials.get(part.material).map_or("default", String::as_str); + let _ = writeln!(text, "g {}\nusemtl {material}", token(&part.name)); + let (a, b) = (part.start as usize, part.start as usize + part.count as usize); + for triangle in mesh.indices.get(a..b).unwrap_or_default().as_chunks::<3>().0 { + text.push('f'); + for i in triangle { let i = i + 1; let _ = match (uvs, normals) { - (true, true) => write!(s, " {i}/{i}/{i}"), - (true, false) => write!(s, " {i}/{i}"), - (false, true) => write!(s, " {i}//{i}"), - (false, false) => write!(s, " {i}"), + (true, true) => write!(text, " {i}/{i}/{i}"), + (true, false) => write!(text, " {i}/{i}"), + (false, true) => write!(text, " {i}//{i}"), + (false, false) => write!(text, " {i}"), }; } - s.push('\n'); + text.push('\n'); } } - s + + text } /// `id` of each material name, made unique with `_2`, `_3`… where two would be the same, also diff --git a/crates/formats/src/mesh_export/usd.rs b/crates/formats/src/mesh_export/usd.rs index 25c8f04c..2f57f7aa 100644 --- a/crates/formats/src/mesh_export/usd.rs +++ b/crates/formats/src/mesh_export/usd.rs @@ -166,60 +166,64 @@ fn identifier(s: &str, taken: &mut Vec) -> String { /// The export scene: `/` with the `Mesh` and `Materials`. `files[m]` are the texture /// file names (by slot) of material `m`. fn scene(mesh: &Mesh, name: &str, files: &[Vec<(usize, String)>]) -> Result { - let n = mesh.positions.len(); - if n == 0 || mesh.indices.len() < 3 { + let vertex_count = mesh.positions.len(); + if vertex_count == 0 || mesh.indices.len() < 3 { return Err(FormatError::Invalid("the mesh is empty".into())); } + let ints = |v: &[u32]| v.iter().map(|&i| i32::try_from(i).map_err(|_| FormatError::TooLarge("vertex index beyond 2^31".into()))).collect::>>(); let mut taken = Vec::new(); let root_name = identifier(name, &mut taken); let mut root = UsdPrim::new(&root_name, "Xform"); - let mut geo = UsdPrim::new(&identifier(&format!("{name}_mesh"), &mut taken), "Mesh"); - let mat_names: Vec = mesh.materials.iter().map(|m| identifier(m, &mut taken)).collect(); - let mat_path = |m: usize| mat_names.get(m).map(|id| format!("/{root_name}/Materials/{id}")); + let mut geometry = UsdPrim::new(&identifier(&format!("{name}_mesh"), &mut taken), "Mesh"); + let material_names: Vec = mesh.materials.iter().map(|m| identifier(m, &mut taken)).collect(); + let material_path = |m: usize| material_names.get(m).map(|id| format!("/{root_name}/Materials/{id}")); let (lo, hi) = mesh.bounds(); - // Faces in submesh order; subsets index them. - let mut tris: Vec = Vec::with_capacity(mesh.indices.len()); + + // Faces in submesh order; subsets index them + let mut indices: Vec = Vec::with_capacity(mesh.indices.len()); let mut faces_of: Vec> = vec![Vec::new(); mesh.materials.len()]; - for sm in parts(mesh, name) { - let range = mesh.indices.get(sm.start as usize..(sm.start as usize).saturating_add(sm.count as usize)).unwrap_or_default(); + for part in parts(mesh, name) { + let range = mesh.indices.get(part.start as usize..(part.start as usize).saturating_add(part.count as usize)).unwrap_or_default(); for t in range.as_chunks::<3>().0 { - if let Some(f) = faces_of.get_mut(sm.material) { - f.push(i32::try_from(tris.len() / 3).map_err(|_| FormatError::TooLarge("triangle count".into()))?); + if let Some(f) = faces_of.get_mut(part.material) { + f.push(i32::try_from(indices.len() / 3).map_err(|_| FormatError::TooLarge("triangle count".into()))?); } - tris.extend_from_slice(t); + indices.extend_from_slice(t); } } + let vertex = |mut a: UsdAttr| { a.interpolation = Some("vertex"); a }; - geo.attrs = vec![ + geometry.attrs = vec![ UsdAttr::new("extent", "float3[]", Some(UsdValue::Vec3fs(vec![lo.to_array(), hi.to_array()]))), - UsdAttr::new("faceVertexCounts", "int[]", Some(UsdValue::Ints(vec![3; tris.len() / 3]))), - UsdAttr::new("faceVertexIndices", "int[]", Some(UsdValue::Ints(ints(&tris)?))), + UsdAttr::new("faceVertexCounts", "int[]", Some(UsdValue::Ints(vec![3; indices.len() / 3]))), + UsdAttr::new("faceVertexIndices", "int[]", Some(UsdValue::Ints(ints(&indices)?))), UsdAttr::new("points", "point3f[]", Some(UsdValue::Vec3fs(mesh.positions.iter().map(|p| p.to_array()).collect()))), UsdAttr::new("subdivisionScheme", "token", Some(UsdValue::Token("none".into()))).uniform(), ]; - if mesh.normals.len() == n { - geo.attrs.push(vertex(UsdAttr::new("normals", "normal3f[]", Some(UsdValue::Vec3fs(mesh.normals.iter().map(|v| v.to_array()).collect()))))); + if mesh.normals.len() == vertex_count { + geometry.attrs.push(vertex(UsdAttr::new("normals", "normal3f[]", Some(UsdValue::Vec3fs(mesh.normals.iter().map(|v| v.to_array()).collect()))))); } - if mesh.uvs.len() == n { - // USD's st origin is bottom-left. + if mesh.uvs.len() == vertex_count { + // USD's st origin is bottom-left let st = mesh.uvs.iter().map(|t| [t.x, 1.0 - t.y]).collect(); - geo.attrs.push(vertex(UsdAttr::new("primvars:st", "texCoord2f[]", Some(UsdValue::Vec2fs(st))))); + geometry.attrs.push(vertex(UsdAttr::new("primvars:st", "texCoord2f[]", Some(UsdValue::Vec2fs(st))))); } + let used: Vec = (0..mesh.materials.len()).filter(|m| faces_of.get(*m).is_some_and(|f| !f.is_empty())).collect(); match used.as_slice() { [] => {} [m] => { - geo.binding_api = true; - geo.attrs.extend(mat_path(*m).map(|p| UsdAttr::rel("material:binding", p))); + geometry.binding_api = true; + geometry.attrs.extend(material_path(*m).map(|p| UsdAttr::rel("material:binding", p))); } _ => { for &m in &used { - let (Some(id), Some(path)) = (mat_names.get(m), mat_path(m)) else { continue }; + let (Some(id), Some(path)) = (material_names.get(m), material_path(m)) else { continue }; let mut subset = UsdPrim::new(id, "GeomSubset"); subset.binding_api = true; subset.attrs = vec![ @@ -228,18 +232,20 @@ fn scene(mesh: &Mesh, name: &str, files: &[Vec<(usize, String)>]) -> Result Ogawa<'a> { } /// The first sample of a scalar or array property as numbers (`extent` per item). - fn values(&mut self, p: &Prop) -> Result> { - let samples = self.group(p.group)?; + fn values(&mut self, property: &Prop) -> Result> { + let samples = self.group(property.group)?; let Some(&first) = samples.first() else { return Ok(Vec::new()) }; + let raw = self.data(first)?; let raw = if raw.is_empty() { raw } else { - raw.get(KEY_BYTES..).ok_or_else(|| malformed(KIND, format!("sample of \"{}\" is shorter than its key", p.name)))? + raw.get(KEY_BYTES..).ok_or_else(|| malformed(KIND, format!("sample of \"{}\" is shorter than its key", property.name)))? }; - let size = match p.pod { + + let value_bytes = match property.pod { 0..=2 => 1, 3 | 4 => 2, 5 | 6 | 10 => 4, 7 | 8 | 11 => 8, - other => return Err(FormatError::Unsupported(format!("Alembic property \"{}\" of data type {other}", p.name))), + other => return Err(FormatError::Unsupported(format!("Alembic property \"{}\" of data type {other}", property.name))), }; - self.charge((raw.len() / size).saturating_mul(8))?; - fn le(c: &[u8]) -> [u8; N] { - <[u8; N]>::try_from(c).unwrap_or([0; N]) - } - Ok(match p.pod { + self.charge((raw.len() / value_bytes).saturating_mul(8))?; + + Ok(match property.pod { 0 | 1 => raw.iter().map(|v| *v as f64).collect(), 2 => raw.iter().map(|v| *v as i8 as f64).collect(), - 3 => raw.as_chunks::<2>().0.iter().map(|c| u16::from_le_bytes(le(c)) as f64).collect(), - 4 => raw.as_chunks::<2>().0.iter().map(|c| i16::from_le_bytes(le(c)) as f64).collect(), - 5 => raw.as_chunks::<4>().0.iter().map(|c| u32::from_le_bytes(le(c)) as f64).collect(), - 6 => raw.as_chunks::<4>().0.iter().map(|c| i32::from_le_bytes(le(c)) as f64).collect(), - 7 => raw.as_chunks::<8>().0.iter().map(|c| u64::from_le_bytes(le(c)) as f64).collect(), - 8 => raw.as_chunks::<8>().0.iter().map(|c| i64::from_le_bytes(le(c)) as f64).collect(), - 10 => raw.as_chunks::<4>().0.iter().map(|c| f32::from_le_bytes(le(c)) as f64).collect(), - _ => raw.as_chunks::<8>().0.iter().map(|c| f64::from_le_bytes(le(c))).collect(), + 3 => raw.as_chunks::<2>().0.iter().map(|c| u16::from_le_bytes(*c) as f64).collect(), + 4 => raw.as_chunks::<2>().0.iter().map(|c| i16::from_le_bytes(*c) as f64).collect(), + 5 => raw.as_chunks::<4>().0.iter().map(|c| u32::from_le_bytes(*c) as f64).collect(), + 6 => raw.as_chunks::<4>().0.iter().map(|c| i32::from_le_bytes(*c) as f64).collect(), + 7 => raw.as_chunks::<8>().0.iter().map(|c| u64::from_le_bytes(*c) as f64).collect(), + 8 => raw.as_chunks::<8>().0.iter().map(|c| i64::from_le_bytes(*c) as f64).collect(), + 10 => raw.as_chunks::<4>().0.iter().map(|c| f32::from_le_bytes(*c) as f64).collect(), + _ => raw.as_chunks::<8>().0.iter().map(|c| f64::from_le_bytes(*c)).collect(), }) } @@ -491,21 +491,23 @@ impl Walk<'_, '_> { } fn mesh(&mut self, r: u64, world: Mat4, sets: &[(String, Vec)]) -> Result<()> { - let props = self.o.compound(r)?; + let properties = self.o.compound(r)?; let get = |o: &mut Ogawa, name: &str| -> Result> { - match find(&props, name) { + match find(&properties, name) { Some(p) => o.values(p), None => Err(malformed(KIND, format!("PolyMesh has no {name}"))), } }; + let p = get(&mut self.o, "P")?; let indices = get(&mut self.o, ".faceIndices")?; let counts = get(&mut self.o, ".faceCounts")?; check_vertices(p.len() / 3)?; let points: Vec = p.as_chunks::<3>().0.iter().map(|c| world.transform_point3(Vec3::new(c[0] as f32, c[1] as f32, c[2] as f32))).collect(); let n = [points.len(), counts.len(), indices.len()]; - let normals = self.param(&props, "N", n)?; - let uvs = self.param(&props, "uv", n)?; + let normals = self.param(&properties, "N", n)?; + let uvs = self.param(&properties, "uv", n)?; + let mut material = vec![None::; counts.len()]; for (s, (_, faces)) in sets.iter().enumerate() { for f in faces { @@ -514,19 +516,26 @@ impl Walk<'_, '_> { } } } - let nm = Mat3::from_mat4(world).inverse().transpose(); - // Alembic winds polygons clockwise; a mirroring transform flips them once more. + let normal_transform = Mat3::from_mat4(world).inverse().transpose(); + + // Alembic winds polygons clockwise; a mirroring transform flips them once more let keep_order = world.determinant() < 0.0; let (mut k, mut corners, mut bad_uvs) = (0usize, Vec::new(), 0usize); for (f, &count) in counts.iter().enumerate() { let end = (count >= 0.0).then(|| k.checked_add(count as usize)).flatten().filter(|e| *e <= indices.len()); let end = end.ok_or_else(|| malformed(KIND, format!("face {f} has {count} corners past the index list")))?; corners.clear(); - for (kk, &pi) in indices.iter().enumerate().take(end).skip(k) { - let p = points.get(pi as usize).filter(|_| pi >= 0.0).ok_or_else(|| malformed(KIND, format!("point index {pi} out of range")))?; - let pi = pi as usize; - let n = normals.as_ref().and_then(|l| l.get::<3>(kk, pi, f)).map(|[x, y, z]| nm * Vec3::new(x as f32, y as f32, z as f32)); - let uv = uvs.as_ref().map(|l| match l.get::<2>(kk, pi, f) { + for (corner_index, &point_index) in indices.iter().enumerate().take(end).skip(k) { + let p = points + .get(point_index as usize) + .filter(|_| point_index >= 0.0) + .ok_or_else(|| malformed(KIND, format!("point index {point_index} out of range")))?; + let point_index = point_index as usize; + let n = normals + .as_ref() + .and_then(|l| l.get::<3>(corner_index, point_index, f)) + .map(|[x, y, z]| normal_transform * Vec3::new(x as f32, y as f32, z as f32)); + let uv = uvs.as_ref().map(|l| match l.get::<2>(corner_index, point_index, f) { Some([u, v]) => Vec2::new(u as f32, 1.0 - v as f32), None => { bad_uvs += 1; @@ -542,9 +551,11 @@ impl Walk<'_, '_> { let name = material.get(f).copied().flatten().and_then(|s| sets.get(s)).map_or(DEFAULT_MATERIAL, |(n, _)| n.as_str()); self.sink.polygon(name, &corners)?; } + if bad_uvs > 0 { self.sink.warn(format!("{bad_uvs} polygon corners have no UV in the Alembic uv parameter (set to 0, 0)")); } + Ok(()) } } diff --git a/crates/formats/src/mesh_import/fbx.rs b/crates/formats/src/mesh_import/fbx.rs index 19d8cdad..5e975ba2 100644 --- a/crates/formats/src/mesh_import/fbx.rs +++ b/crates/formats/src/mesh_import/fbx.rs @@ -254,39 +254,39 @@ impl<'a> Binary<'a> { }) } - fn array(&mut self, ty: u8) -> Result> { + fn array(&mut self, value_type: u8) -> Result> { let (count, encoding, stored) = (self.u32()?, self.u32()?, self.u32()?); - let size = match ty { + let value_bytes = match value_type { b'd' | b'l' => 8, b'f' | b'i' => 4, _ => 1, }; - let len = count.checked_mul(size).ok_or_else(|| malformed(KIND, "array too large"))?; + let decoded_bytes = count.checked_mul(value_bytes).ok_or_else(|| malformed(KIND, "array too large"))?; self.budget.charge(count.saturating_mul(8))?; + let data = self.take(stored)?; let raw: Cow<[u8]> = match encoding { - 0 if stored == len => Cow::Borrowed(data), + 0 if stored == decoded_bytes => Cow::Borrowed(data), 1 => { let mut out = Vec::new(); flate2::read::ZlibDecoder::new(data) - .take(len as u64 + 1) + .take(decoded_bytes as u64 + 1) .read_to_end(&mut out) .map_err(|e| malformed(KIND, format!("bad compressed array: {e}")))?; - if out.len() != len { + if out.len() != decoded_bytes { return Err(malformed(KIND, "compressed array has the wrong length")); } + Cow::Owned(out) } _ => return Err(malformed(KIND, format!("array encoding {encoding} with {stored} bytes for {count} items"))), }; - fn le(c: &[u8]) -> [u8; N] { - <[u8; N]>::try_from(c).unwrap_or([0; N]) - } - Ok(match ty { - b'd' => raw.as_chunks::<8>().0.iter().map(|c| f64::from_le_bytes(le(c))).collect(), - b'l' => raw.as_chunks::<8>().0.iter().map(|c| i64::from_le_bytes(le(c)) as f64).collect(), - b'f' => raw.as_chunks::<4>().0.iter().map(|c| f32::from_le_bytes(le(c)) as f64).collect(), - b'i' => raw.as_chunks::<4>().0.iter().map(|c| i32::from_le_bytes(le(c)) as f64).collect(), + + Ok(match value_type { + b'd' => raw.as_chunks::<8>().0.iter().map(|c| f64::from_le_bytes(*c)).collect(), + b'l' => raw.as_chunks::<8>().0.iter().map(|c| i64::from_le_bytes(*c) as f64).collect(), + b'f' => raw.as_chunks::<4>().0.iter().map(|c| f32::from_le_bytes(*c) as f64).collect(), + b'i' => raw.as_chunks::<4>().0.iter().map(|c| i32::from_le_bytes(*c) as f64).collect(), _ => raw.iter().map(|b| *b as f64).collect(), }) } @@ -783,29 +783,34 @@ impl Layer<'_> { } } -fn add_geometry(sink: &mut PolygonSink, g: &Node, m: Mat4, slots: &[String]) -> Result<()> { - let verts = g.child("Vertices").map(Node::arr).unwrap_or_default(); - check_vertices(verts.len() / 3)?; - let points: Vec = verts.as_chunks::<3>().0.iter().map(|c| m.transform_point3(Vec3::new(c[0] as f32, c[1] as f32, c[2] as f32))).collect(); - let pvi = g.child("PolygonVertexIndex").map(Node::arr).unwrap_or_default(); - let normals = Layer::read(g, "LayerElementNormal", "Normals", "NormalsIndex"); - let uvs = Layer::read(g, "LayerElementUV", "UV", "UVIndex"); - let mats = Layer::read(g, "LayerElementMaterial", "Materials", ""); - let nm = Mat3::from_mat4(m).inverse().transpose(); - let flip = m.determinant() < 0.0; - let (mut corners, mut poly, mut bad_normals, mut bad_uvs) = (Vec::new(), 0usize, 0usize, 0usize); - for (k, &v) in pvi.iter().enumerate() { - // The last corner of each polygon is stored as -(index + 1). - let (cp, last) = if v < 0.0 { (-v - 1.0, true) } else { (v, false) }; - let p = points.get(cp as usize).filter(|_| cp.fract() == 0.0).ok_or_else(|| malformed(KIND, format!("polygon vertex index {v} out of range")))?; - let cp = cp as usize; +fn add_geometry(sink: &mut PolygonSink, geometry: &Node, transform: Mat4, slots: &[String]) -> Result<()> { + let vertices = geometry.child("Vertices").map(Node::arr).unwrap_or_default(); + check_vertices(vertices.len() / 3)?; + let points: Vec = vertices.as_chunks::<3>().0.iter().map(|c| transform.transform_point3(Vec3::new(c[0] as f32, c[1] as f32, c[2] as f32))).collect(); + let polygon_indices = geometry.child("PolygonVertexIndex").map(Node::arr).unwrap_or_default(); + let normals = Layer::read(geometry, "LayerElementNormal", "Normals", "NormalsIndex"); + let uvs = Layer::read(geometry, "LayerElementUV", "UV", "UVIndex"); + let materials = Layer::read(geometry, "LayerElementMaterial", "Materials", ""); + let normal_transform = Mat3::from_mat4(transform).inverse().transpose(); + let flip = transform.determinant() < 0.0; + let (mut corners, mut polygon_index, mut bad_normals, mut bad_uvs) = (Vec::new(), 0usize, 0usize, 0usize); + + for (k, &v) in polygon_indices.iter().enumerate() { + // The last corner of each polygon is stored as -(index + 1) + let (control_point, last) = if v < 0.0 { (-v - 1.0, true) } else { (v, false) }; + let p = points + .get(control_point as usize) + .filter(|_| control_point.fract() == 0.0) + .ok_or_else(|| malformed(KIND, format!("polygon vertex index {v} out of range")))?; + let control_point = control_point as usize; let n = normals.as_ref().and_then(|l| { - let n = l.get(k, cp, poly).map(|[x, y, z]| nm * Vec3::new(x as f32, y as f32, z as f32)); + let n = l.get(k, control_point, polygon_index).map(|[x, y, z]| normal_transform * Vec3::new(x as f32, y as f32, z as f32)); bad_normals += usize::from(n.is_none()); n }); - // A UV layer with holes keeps its layout: missing items read as 0, 0. - let uv = uvs.as_ref().map(|l| match l.get(k, cp, poly) { + + // A UV layer with holes keeps its layout: missing items read as 0, 0 + let uv = uvs.as_ref().map(|l| match l.get(k, control_point, polygon_index) { Some([u, v]) => Vec2::new(u as f32, 1.0 - v as f32), None => { bad_uvs += 1; @@ -813,22 +818,24 @@ fn add_geometry(sink: &mut PolygonSink, g: &Node, m: Mat4, slots: &[String]) -> } }); corners.push(Corner { p: *p, n, uv }); - if last || k + 1 == pvi.len() { + if last || k + 1 == polygon_indices.len() { if flip { corners.reverse(); } - let slot = mats.as_ref().and_then(|l| l.get(poly, poly, poly)).map_or(0.0, |[s]| s); + let slot = materials.as_ref().and_then(|l| l.get(polygon_index, polygon_index, polygon_index)).map_or(0.0, |[s]| s); let name = slots.get(slot as usize).filter(|_| slot >= 0.0).map_or("Default", String::as_str); sink.polygon(name, &corners)?; corners.clear(); - poly += 1; + polygon_index += 1; } } + if bad_normals > 0 { sink.warn(format!("{bad_normals} polygon corners have no normal in the FBX normal layer; normals were recomputed")); } if bad_uvs > 0 { sink.warn(format!("{bad_uvs} polygon corners have no UV in the FBX UV layer (set to 0, 0)")); } + Ok(()) } diff --git a/crates/formats/src/mesh_import/gltf.rs b/crates/formats/src/mesh_import/gltf.rs index 92f64077..21658033 100644 --- a/crates/formats/src/mesh_import/gltf.rs +++ b/crates/formats/src/mesh_import/gltf.rs @@ -96,33 +96,36 @@ struct Attrs { color_seen: bool, } -fn add_primitive(raw: &mut RawMesh, attrs: &mut Attrs, prim: &gltf::Primitive, m: Mat4, buffers: &[gltf::buffer::Data], part: &str) -> Result<()> { - if prim.mode() != Mode::Triangles { - raw.warnings.push(format!("skipped a primitive drawn as {:?} (only triangles are supported)", prim.mode())); +fn add_primitive(raw: &mut RawMesh, attrs: &mut Attrs, primitive: &gltf::Primitive, transform: Mat4, buffers: &[gltf::buffer::Data], part: &str) -> Result<()> { + if primitive.mode() != Mode::Triangles { + raw.warnings.push(format!("skipped a primitive drawn as {:?} (only triangles are supported)", primitive.mode())); return Ok(()); } - let Some(pacc) = prim.get(&Semantic::Positions) else { + + let Some(position_accessor) = primitive.get(&Semantic::Positions) else { raw.warnings.push("skipped a primitive without positions".into()); return Ok(()); }; - check_accessor(&pacc, buffers, Dimensions::Vec3, &[DataType::F32], "position")?; - let nacc = prim.get(&Semantic::Normals); - if let Some(a) = &nacc { + + check_accessor(&position_accessor, buffers, Dimensions::Vec3, &[DataType::F32], "position")?; + let normal_accessor = primitive.get(&Semantic::Normals); + if let Some(a) = &normal_accessor { check_accessor(a, buffers, Dimensions::Vec3, &[DataType::F32], "normal")?; } - let tacc = prim.get(&Semantic::TexCoords(0)); - if let Some(a) = &tacc { + let texcoord_accessor = primitive.get(&Semantic::TexCoords(0)); + if let Some(a) = &texcoord_accessor { check_accessor(a, buffers, Dimensions::Vec2, &[DataType::F32, DataType::U8, DataType::U16], "texcoord")?; } - let cacc = prim.get(&Semantic::Colors(0)); - if let Some(a) = &cacc { + let color_accessor = primitive.get(&Semantic::Colors(0)); + if let Some(a) = &color_accessor { let dims = if a.dimensions() == Dimensions::Vec3 { Dimensions::Vec3 } else { Dimensions::Vec4 }; check_accessor(a, buffers, dims, &[DataType::F32, DataType::U8, DataType::U16], "color")?; } - if let Some(a) = prim.indices() { + if let Some(a) = primitive.indices() { check_accessor(&a, buffers, Dimensions::Scalar, &[DataType::U8, DataType::U16, DataType::U32], "index")?; } - let reader = prim.reader(|b| buffers.get(b.index()).map(|d| &d.0[..])); + + let reader = primitive.reader(|b| buffers.get(b.index()).map(|d| &d.0[..])); let positions: Vec = reader.read_positions().ok_or_else(|| malformed(KIND, "unreadable positions"))?.map(Vec3::from).collect(); let n = positions.len(); check_vertices(raw.positions.len().saturating_add(n))?; @@ -134,38 +137,40 @@ fn add_primitive(raw: &mut RawMesh, attrs: &mut Attrs, prim: &gltf::Primitive, m if let Some(bad) = indices.iter().find(|i| **i as usize >= n) { return Err(malformed(KIND, format!("index {bad} out of range ({n} vertices)"))); } + check_triangles(raw.triangle_count(), indices.len() / 3)?; - let normals: Option> = nacc.and_then(|_| reader.read_normals()).map(|it| it.map(Vec3::from).collect()); - let texcoords: Option> = tacc.and_then(|_| reader.read_tex_coords(0)).map(|t| t.into_f32().map(Vec2::from).collect()); + let normals: Option> = normal_accessor.and_then(|_| reader.read_normals()).map(|it| it.map(Vec3::from).collect()); + let texcoords: Option> = texcoord_accessor.and_then(|_| reader.read_tex_coords(0)).map(|t| t.into_f32().map(Vec2::from).collect()); let colors: Option> = - cacc.and_then(|_| reader.read_colors(0)).map(|c| c.into_rgba_f32().map(Vec4::from).collect()).filter(|c: &Vec| c.len() == n); + color_accessor.and_then(|_| reader.read_colors(0)).map(|c| c.into_rgba_f32().map(Vec4::from).collect()).filter(|c: &Vec| c.len() == n); attrs.color_seen |= colors.is_some(); let color_of = |i: usize| colors.as_ref().and_then(|c| c.get(i)).copied().unwrap_or(Vec4::ONE); - let m3 = Mat3::from_mat4(m); - let nm = m3.inverse().transpose(); - let flip = m3.determinant() < 0.0; - let world: Vec = positions.iter().map(|p| m.transform_point3(*p)).collect(); - let name = match prim.material().index() { + let linear_transform = Mat3::from_mat4(transform); + let normal_transform = linear_transform.inverse().transpose(); + let flip = linear_transform.determinant() < 0.0; + let world: Vec = positions.iter().map(|p| transform.transform_point3(*p)).collect(); + let name = match primitive.material().index() { None => "Default".to_string(), - Some(i) => prim.material().name().map(str::to_string).unwrap_or_else(|| format!("Material_{i}")), + Some(i) => primitive.material().name().map(str::to_string).unwrap_or_else(|| format!("Material_{i}")), }; if !raw.base_colors.iter().any(|c| c.material == name) { - base_color(raw, &prim.material(), &name, buffers); + base_color(raw, &primitive.material(), &name, buffers); } let base = raw.positions.len() as u32; - let tex_ok = texcoords.as_ref().is_some_and(|t| t.len() == n); - if tex_ok { + let has_texcoords = texcoords.as_ref().is_some_and(|t| t.len() == n); + if has_texcoords { attrs.uv_seen.0 = true } else { attrs.uv_seen.1 = true } + let uv_of = |i: usize| texcoords.as_ref().and_then(|t| t.get(i)).copied().unwrap_or_default(); let raw_normals = raw.normals.get_or_insert_with(Vec::new); match normals.filter(|v| v.len() == n) { Some(nrm) => { raw.positions.extend_from_slice(&world); - raw_normals.extend(nrm.iter().map(|v| (nm * *v).try_normalize().unwrap_or(Vec3::Y))); + raw_normals.extend(nrm.iter().map(|v| (normal_transform * *v).try_normalize().unwrap_or(Vec3::Y))); attrs.uvs.extend((0..n).map(uv_of)); attrs.colors.extend((0..n).map(color_of)); let group = raw.group(&name, part); @@ -175,23 +180,24 @@ fn add_primitive(raw: &mut RawMesh, attrs: &mut Attrs, prim: &gltf::Primitive, m } } None => { - // glTF: flat normals when none are given, so every triangle gets its own corners. - let mut tris = Vec::with_capacity(indices.len()); + // glTF: flat normals when none are given, so every triangle gets its own corners + let mut triangles = Vec::with_capacity(indices.len()); for t in indices.as_chunks::<3>().0 { let order = if flip { [t[0], t[2], t[1]] } else { [t[0], t[1], t[2]] }; let p = order.map(|i| world.get(i as usize).copied().unwrap_or_default()); let face = (p[1] - p[0]).cross(p[2] - p[0]).try_normalize().unwrap_or(Vec3::Y); for (k, i) in order.iter().enumerate() { - tris.push(raw.positions.len() as u32); + triangles.push(raw.positions.len() as u32); raw.positions.push(p[k]); raw_normals.push(face); attrs.uvs.push(uv_of(*i as usize)); attrs.colors.push(color_of(*i as usize)); } } - raw.group(&name, part).extend_from_slice(&tris); + raw.group(&name, part).extend_from_slice(&triangles); } } + Ok(()) } diff --git a/crates/formats/src/mesh_import/mod.rs b/crates/formats/src/mesh_import/mod.rs index 7fd9b113..42497364 100644 --- a/crates/formats/src/mesh_import/mod.rs +++ b/crates/formats/src/mesh_import/mod.rs @@ -379,6 +379,7 @@ fn geometry(raw: RawMesh) -> Result<(Mesh, Vec, Option>)> { let RawMesh { positions, normals, uvs, colors, groups, warnings, diagonals, .. } = raw; check_vertices(positions.len())?; check_triangles(0, groups.iter().map(|(_, _, g)| g.len() / 3).sum())?; + let mut mesh = Mesh { positions, ..Mesh::default() }; let mut groups: Vec<(usize, String, Vec)> = groups .into_iter() @@ -398,9 +399,11 @@ fn geometry(raw: RawMesh) -> Result<(Mesh, Vec, Option>)> { mesh.indices.extend_from_slice(tris.get(..count as usize).unwrap_or_default()); mesh.submeshes.push(SubMesh { name, material, start, count }); } + if mesh.indices.is_empty() { return Err(FormatError::Invalid("the file contains no triangles".into())); } + if !diagonals.is_empty() { let diagonal = |a: u32, b: u32| diagonals.contains(&(a.min(b), a.max(b))); mesh.diagonals = mesh.indices.as_chunks::<3>().0.iter().map(|t| (0..3).map(|i| u8::from(diagonal(t[i], t[(i + 1) % 3])) << i).sum()).collect(); @@ -408,12 +411,15 @@ fn geometry(raw: RawMesh) -> Result<(Mesh, Vec, Option>)> { if let Some(bad) = mesh.indices.iter().find(|i| **i as usize >= mesh.positions.len()) { return Err(FormatError::Invalid(format!("vertex index {bad} out of range ({} vertices)", mesh.positions.len()))); } + if mesh.positions.iter().any(|p| !p.is_finite()) { return Err(FormatError::Invalid("the mesh has non-finite vertex positions".into())); } + if all_triangles_degenerate(&mesh) { return Err(FormatError::Invalid("every triangle of the mesh is degenerate (zero area)".into())); } + mesh.normals = match normals { Some(n) if n.len() == mesh.positions.len() => n.into_iter().map(|v| v.try_normalize().unwrap_or(Vec3::Y)).collect(), _ => smooth_normals(&mesh), @@ -421,6 +427,7 @@ fn geometry(raw: RawMesh) -> Result<(Mesh, Vec, Option>)> { if let Some(c) = colors.filter(|c| c.len() == mesh.positions.len()) { mesh.colors = c.into_iter().map(|v| if v.is_finite() { v.clamp(Vec4::ZERO, Vec4::ONE) } else { Vec4::ONE }).collect(); } + Ok((mesh, warnings, uvs)) } @@ -482,18 +489,19 @@ fn orbit_cameras(raw: &[RawCamera], mesh: &Mesh) -> Vec Vec { - let weld = weld_ids(&mesh.positions); - let mut acc = vec![Vec3::ZERO; mesh.positions.len()]; - for t in mesh.indices.as_chunks::<3>().0 { + let welded_vertices = weld_ids(&mesh.positions); + let mut normals = vec![Vec3::ZERO; mesh.positions.len()]; + for triangle in mesh.indices.as_chunks::<3>().0 { let p = |i: u32| mesh.positions.get(i as usize).copied().unwrap_or_default(); - let face = (p(t[1]) - p(t[0])).cross(p(t[2]) - p(t[0])); - for v in t { - if let Some(a) = weld.get(*v as usize).and_then(|w| acc.get_mut(*w as usize)) { + let face = (p(triangle[1]) - p(triangle[0])).cross(p(triangle[2]) - p(triangle[0])); + for v in triangle { + if let Some(a) = welded_vertices.get(*v as usize).and_then(|w| normals.get_mut(*w as usize)) { *a += face; } } } - weld.iter().map(|w| acc.get(*w as usize).and_then(|n| n.try_normalize()).unwrap_or(Vec3::Y)).collect() + + welded_vertices.iter().map(|w| normals.get(*w as usize).and_then(|n| n.try_normalize()).unwrap_or(Vec3::Y)).collect() } /// Inspects `mesh` and generates its UV report (overlaps, out-of-range UVs, warnings). diff --git a/crates/formats/src/mesh_import/obj.rs b/crates/formats/src/mesh_import/obj.rs index d6cc9eb8..44277208 100644 --- a/crates/formats/src/mesh_import/obj.rs +++ b/crates/formats/src/mesh_import/obj.rs @@ -13,8 +13,8 @@ pub(crate) fn read(bytes: &[u8]) -> Result { fn read_inner(bytes: &[u8]) -> Result { let text = String::from_utf8_lossy(bytes); - // Material names come from `usemtl` (MTL files are never read): tobj only assigns a face's - // material when a library defines it, so every library request gets a synthetic one. + + // A synthetic library lets tobj assign usemtl names without reading external MTL files let mut names: Vec<&str> = Vec::new(); for line in text.lines().map(str::trim) { if line.split_whitespace().next() == Some("usemtl") @@ -25,57 +25,64 @@ fn read_inner(bytes: &[u8]) -> Result { names.push(name.trim()); } } - let library: String = names.iter().map(|n| format!("newmtl {n}\n")).collect(); + + let library: String = names.iter().map(|name| format!("newmtl {name}\n")).collect(); let source = format!("mtllib texturecraft-usemtl.mtl\n{text}"); - // Polygons stay whole so the wireframe can show them; `RawMesh::polygon` triangulates. - let opts = tobj::LoadOptions { single_index: true, triangulate: false, ignore_points: true, ignore_lines: true }; + + // Polygons stay whole so the wireframe can show them; `RawMesh::polygon` triangulates + let options = tobj::LoadOptions { single_index: true, triangulate: false, ignore_points: true, ignore_lines: true }; let (models, materials) = - tobj::load_obj_buf(&mut source.as_bytes(), &opts, |_| tobj::load_mtl_buf(&mut library.as_bytes())).map_err(|e| malformed(KIND, e))?; + tobj::load_obj_buf(&mut source.as_bytes(), &options, |_| tobj::load_mtl_buf(&mut library.as_bytes())).map_err(|e| malformed(KIND, e))?; let materials = materials.unwrap_or_default(); let mut raw = RawMesh::default(); let (mut normals, mut uvs, mut colors) = (Some(Vec::new()), Some(Vec::new()), Vec::new()); let mut partial_uvs = false; for model in &models { - let m = &model.mesh; - let n = m.positions.len() / 3; - check_vertices(raw.positions.len().saturating_add(n))?; - // Corners per face; without arities every face is a triangle. - let arities: Vec = if m.face_arities.is_empty() { vec![3; m.indices.len() / 3] } else { m.face_arities.iter().map(|a| *a as usize).collect() }; + let mesh = &model.mesh; + let vertex_count = mesh.positions.len() / 3; + check_vertices(raw.positions.len().saturating_add(vertex_count))?; + + // Corners per face; without arities every face is a triangle + let arities: Vec = + if mesh.face_arities.is_empty() { vec![3; mesh.indices.len() / 3] } else { mesh.face_arities.iter().map(|a| *a as usize).collect() }; check_triangles(raw.triangle_count(), arities.iter().map(|a| a.saturating_sub(2)).sum())?; let base = raw.positions.len() as u32; - raw.positions.extend(m.positions.as_chunks::<3>().0.iter().map(|p| Vec3::new(p[0], p[1], p[2]))); - if m.normals.len() == n * 3 { + raw.positions.extend(mesh.positions.as_chunks::<3>().0.iter().map(|p| Vec3::new(p[0], p[1], p[2]))); + if mesh.normals.len() == vertex_count * 3 { if let Some(v) = &mut normals { - v.extend(m.normals.as_chunks::<3>().0.iter().map(|p| Vec3::new(p[0], p[1], p[2]))); + v.extend(mesh.normals.as_chunks::<3>().0.iter().map(|p| Vec3::new(p[0], p[1], p[2]))); } } else { normals = None; } - if m.texcoords.len() == n * 2 { + if mesh.texcoords.len() == vertex_count * 2 { if let Some(v) = &mut uvs { - // OBJ UVs have their origin bottom-left. - v.extend(m.texcoords.as_chunks::<2>().0.iter().map(|t| Vec2::new(t[0], 1.0 - t[1]))); + // OBJ UVs have their origin bottom-left + v.extend(mesh.texcoords.as_chunks::<2>().0.iter().map(|t| Vec2::new(t[0], 1.0 - t[1]))); } } else { - partial_uvs |= n > 0 && !m.indices.is_empty(); + partial_uvs |= vertex_count > 0 && !mesh.indices.is_empty(); uvs = None; } - // `v x y z r g b`: objects without colors are white. - match m.vertex_color.len() == n * 3 { - true => colors.extend(m.vertex_color.as_chunks::<3>().0.iter().map(|c| Vec4::new(c[0], c[1], c[2], 1.0))), - false => colors.extend(std::iter::repeat_n(Vec4::ONE, n)), + + // `v x y z r g b`: objects without colors are white + match mesh.vertex_color.len() == vertex_count * 3 { + true => colors.extend(mesh.vertex_color.as_chunks::<3>().0.iter().map(|c| Vec4::new(c[0], c[1], c[2], 1.0))), + false => colors.extend(std::iter::repeat_n(Vec4::ONE, vertex_count)), } - let name = match m.material_id { + + let name = match mesh.material_id { Some(id) => materials.get(id).map(|mat| mat.name.clone()).filter(|s| !s.is_empty()).unwrap_or_else(|| format!("Material_{id}")), None => "Default".to_string(), }; - if let Some(i) = m.indices.iter().find(|i| **i as usize >= n) { + if let Some(i) = mesh.indices.iter().find(|i| **i as usize >= vertex_count) { return Err(malformed(KIND, format!("face index {i} out of range"))); } - // tobj names models without `o`/`g` "unnamed_object"; an empty name takes the file stem. + + // tobj names models without `o`/`g` "unnamed_object"; an empty name takes the file stem let part = if model.name == "unnamed_object" { "" } else { model.name.as_str() }; - let (mut rest, mut corners) = (m.indices.as_slice(), Vec::new()); + let (mut rest, mut corners) = (mesh.indices.as_slice(), Vec::new()); for arity in arities { let Some((face, tail)) = rest.split_at_checked(arity) else { break }; rest = tail; @@ -86,11 +93,14 @@ fn read_inner(bytes: &[u8]) -> Result { } } } - if partial_uvs && models.iter().any(|m| !m.mesh.texcoords.is_empty()) { + + if partial_uvs && models.iter().any(|model| !model.mesh.texcoords.is_empty()) { raw.warnings.push("some objects have no UVs; the whole mesh was unwrapped automatically".into()); } + raw.normals = normals; raw.uvs = uvs; - raw.colors = models.iter().any(|m| !m.mesh.vertex_color.is_empty()).then_some(colors); + raw.colors = models.iter().any(|model| !model.mesh.vertex_color.is_empty()).then_some(colors); + Ok(raw) } diff --git a/crates/formats/src/mesh_import/usd/usdc.rs b/crates/formats/src/mesh_import/usd/usdc.rs index 9d3cc55d..221c7b4a 100644 --- a/crates/formats/src/mesh_import/usd/usdc.rs +++ b/crates/formats/src/mesh_import/usd/usdc.rs @@ -224,17 +224,19 @@ impl<'a> Crate<'a> { Ok(()) } - fn read_fields(&mut self, mut s: Cur, budget: &mut Budget) -> Result<()> { - let n = s.count(0)?; - let tokens = s.ints(n, 4, budget)?; - let size = s.u64()?; - let comp = s.bytes(usize::try_from(size).map_err(|_| truncated())?)?; - budget.take(n.saturating_mul(24))?; - let reps = codec::decompress(comp, n.saturating_mul(8))?; - if reps.len() != n * 8 { + fn read_fields(&mut self, mut section: Cur, budget: &mut Budget) -> Result<()> { + let count = section.count(0)?; + let tokens = section.ints(count, 4, budget)?; + let size = section.u64()?; + let compressed = section.bytes(usize::try_from(size).map_err(|_| truncated())?)?; + budget.take(count.saturating_mul(24))?; + let representations = codec::decompress(compressed, count.saturating_mul(8))?; + if representations.len() != count * 8 { return Err(malformed(KIND, "field values are truncated")); } - self.fields = tokens.iter().zip(reps.as_chunks::<8>().0.iter()).map(|(t, r)| (*t as u32, u64::from_le_bytes(*r))).collect(); + + self.fields = tokens.iter().zip(representations.as_chunks::<8>().0.iter()).map(|(t, r)| (*t as u32, u64::from_le_bytes(*r))).collect(); + Ok(()) } diff --git a/crates/formats/src/project_file/mod.rs b/crates/formats/src/project_file/mod.rs index 39f79583..0e1db163 100644 --- a/crates/formats/src/project_file/mod.rs +++ b/crates/formats/src/project_file/mod.rs @@ -293,44 +293,54 @@ fn expect_end(r: &mut impl Read, what: &str) -> Result<()> { } } -fn read_tiles(r: &mut impl Read, size: (u32, u32), comps: usize, budget: &mut Budget, what: &str) -> Result { - let (w, h, c, count) = read_header(r, what)?; - if (w, h) != size || c != comps { - return Err(malformed(KIND, format!("{what}: {w}×{h}×{c} does not match the texture set ({}×{}×{comps})", size.0, size.1))); +fn read_tiles(reader: &mut impl Read, size: (u32, u32), components: usize, budget: &mut Budget, what: &str) -> Result { + let (width, height, stored_components, count) = read_header(reader, what)?; + if (width, height) != size || stored_components != components { + return Err(malformed( + KIND, + format!("{what}: {width}×{height}×{stored_components} does not match the texture set ({}×{}×{components})", size.0, size.1), + )); } - let mut img = TileImage::new(w, h, comps); - if count > (img.tiles_x() as usize) * (img.tiles_y() as usize) { + + let mut image = TileImage::new(width, height, components); + if count > (image.tiles_x() as usize) * (image.tiles_y() as usize) { return Err(malformed(KIND, format!("{what}: {count} tiles is more than the image holds"))); } - let mut buf = vec![0u8; TILE_AREA * comps * 2]; - let mut pos = [0u8; 8]; + + let mut bytes = vec![0u8; TILE_AREA * components * 2]; + let mut position_bytes = [0u8; 8]; for _ in 0..count { - read_exact(r, &mut pos, what)?; - let (tx, ty) = (u32_at(&pos, 0), u32_at(&pos, 1)); - if tx >= img.tiles_x() || ty >= img.tiles_y() || img.is_allocated(tx, ty) { + read_exact(reader, &mut position_bytes, what)?; + let (tx, ty) = (u32_at(&position_bytes, 0), u32_at(&position_bytes, 1)); + if tx >= image.tiles_x() || ty >= image.tiles_y() || image.is_allocated(tx, ty) { return Err(malformed(KIND, format!("{what}: bad or repeated tile ({tx}, {ty})"))); } - read_exact(r, &mut buf, what)?; - budget.take(buf.len() as u64)?; - let data: Vec = buf.as_chunks::<2>().0.iter().map(|b| u16::from_le_bytes([b[0], b[1]])).collect(); - img.set_tile(tx, ty, Some(Arc::new(data))); + + read_exact(reader, &mut bytes, what)?; + budget.take(bytes.len() as u64)?; + let data: Vec = bytes.as_chunks::<2>().0.iter().map(|b| u16::from_le_bytes(*b)).collect(); + image.set_tile(tx, ty, Some(Arc::new(data))); } - expect_end(r, what)?; - Ok(img) + + expect_end(reader, what)?; + + Ok(image) } /// A baked map: (width, height, data). -fn read_baked(r: &mut impl Read, comps: usize, budget: &mut Budget, what: &str) -> Result<(u32, u32, Vec)> { - let (w, h, c, _) = read_header(r, what)?; - if w == 0 || h == 0 || u64::from(w) * u64::from(h) > MAX_TEXELS || c != comps { - return Err(malformed(KIND, format!("{what}: bad size {w}×{h}×{c}"))); +fn read_baked(reader: &mut impl Read, components: usize, budget: &mut Budget, what: &str) -> Result<(u32, u32, Vec)> { + let (width, height, stored_components, _) = read_header(reader, what)?; + if width == 0 || height == 0 || u64::from(width) * u64::from(height) > MAX_TEXELS || stored_components != components { + return Err(malformed(KIND, format!("{what}: bad size {width}×{height}×{stored_components}"))); } - let len = (w as usize) * (h as usize) * comps; - budget.take(len as u64 * 4)?; - let mut bytes = vec![0u8; len * 4]; - read_exact(r, &mut bytes, what)?; - expect_end(r, what)?; - Ok((w, h, bytes.as_chunks::<4>().0.iter().map(|b| f32::from_le_bytes([b[0], b[1], b[2], b[3]])).collect())) + + let value_count = (width as usize) * (height as usize) * components; + budget.take(value_count as u64 * 4)?; + let mut bytes = vec![0u8; value_count * 4]; + read_exact(reader, &mut bytes, what)?; + expect_end(reader, what)?; + + Ok((width, height, bytes.as_chunks::<4>().0.iter().map(|b| f32::from_le_bytes(*b)).collect())) } /// Texture set holding a paint layer, a content effect or a mask effect id. diff --git a/crates/geom/src/mesh.rs b/crates/geom/src/mesh.rs index 63c0bb71..5680a499 100644 --- a/crates/geom/src/mesh.rs +++ b/crates/geom/src/mesh.rs @@ -199,18 +199,19 @@ impl Mesh { /// Area-weighted smooth normals over the index buffer. pub fn compute_normals(&mut self) { - let mut n = vec![Vec3::ZERO; self.positions.len()]; + let mut normals = vec![Vec3::ZERO; self.positions.len()]; for &[a, b, c] in self.indices.as_chunks::<3>().0 { let (a, b, c) = (a as usize, b as usize, c as usize); let (Some(pa), Some(pb), Some(pc)) = (self.positions.get(a), self.positions.get(b), self.positions.get(c)) else { continue }; let face = (*pb - *pa).cross(*pc - *pa); for v in [a, b, c] { - if let Some(x) = n.get_mut(v) { + if let Some(x) = normals.get_mut(v) { *x += face; } } } - self.normals = n.into_iter().map(|v| v.try_normalize().unwrap_or(Vec3::Y)).collect(); + + self.normals = normals.into_iter().map(|v| v.try_normalize().unwrap_or(Vec3::Y)).collect(); } /// MikkTSpace tangents (falls back to per-triangle tangents if generation fails). @@ -237,25 +238,27 @@ impl Mesh { } fn simple_tangents(&mut self) { - let mut acc = vec![Vec3::ZERO; self.positions.len()]; + let mut tangents = vec![Vec3::ZERO; self.positions.len()]; for &[a, b, c] in self.indices.as_chunks::<3>().0 { let (a, b, c) = (a as usize, b as usize, c as usize); let (Some(pa), Some(pb), Some(pc)) = (self.positions.get(a), self.positions.get(b), self.positions.get(c)) else { continue }; let (Some(ua), Some(ub), Some(uc)) = (self.uvs.get(a), self.uvs.get(b), self.uvs.get(c)) else { continue }; let (e1, e2) = (*pb - *pa, *pc - *pa); let (d1, d2) = (*ub - *ua, *uc - *ua); - let r = d1.x * d2.y - d2.x * d1.y; - if r.abs() < 1e-12 { + let determinant = d1.x * d2.y - d2.x * d1.y; + if determinant.abs() < 1e-12 { continue; } - let tan = (e1 * d2.y - e2 * d1.y) / r; + + let tangent = (e1 * d2.y - e2 * d1.y) / determinant; for v in [a, b, c] { - if let Some(x) = acc.get_mut(v) { - *x += tan; + if let Some(x) = tangents.get_mut(v) { + *x += tangent; } } } - self.tangents = acc.into_iter().map(|t| t.try_normalize().unwrap_or(Vec3::X).extend(1.0)).collect(); + + self.tangents = tangents.into_iter().map(|t| t.try_normalize().unwrap_or(Vec3::X).extend(1.0)).collect(); } /// The UV tiles material `m` covers: integer parts of its triangles' UV centroids (v down), @@ -280,39 +283,44 @@ impl Mesh { /// material's triangles using the vertex: piecewise maps (UV tiles of different sizes) then /// place a vertex on a tile border with its own triangle's tile. pub fn map_material_uvs_with(&mut self, m: usize, f: impl Fn(Vec2, Vec2) -> Vec2) { - let mine: Vec = self.triangles_of(m).collect(); - let mut is_mine = vec![false; self.triangle_count()]; - for t in &mine { - if let Some(x) = is_mine.get_mut(*t) { + let material_triangles: Vec = self.triangles_of(m).collect(); + let mut in_material = vec![false; self.triangle_count()]; + for t in &material_triangles { + if let Some(x) = in_material.get_mut(*t) { *x = true; } } + let mut shared = vec![false; self.positions.len()]; - for (_, tri) in self.indices.as_chunks::<3>().0.iter().enumerate().filter(|(t, _)| !is_mine.get(*t).copied().unwrap_or(false)) { + for (_, tri) in self.indices.as_chunks::<3>().0.iter().enumerate().filter(|(t, _)| !in_material.get(*t).copied().unwrap_or(false)) { for v in tri { if let Some(s) = shared.get_mut(*v as usize) { *s = true; } } } - let mut copies = std::collections::HashMap::new(); - for k in mine.iter().flat_map(|t| t * 3..t * 3 + 3) { + + let mut duplicates = std::collections::HashMap::new(); + for k in material_triangles.iter().flat_map(|t| t * 3..t * 3 + 3) { let Some(&v) = self.indices.get(k) else { continue }; - let v = if shared.get(v as usize).copied().unwrap_or(false) { *copies.entry(v).or_insert_with(|| self.duplicate_vertex(v as usize)) } else { v }; + let v = + if shared.get(v as usize).copied().unwrap_or(false) { *duplicates.entry(v).or_insert_with(|| self.duplicate_vertex(v as usize)) } else { v }; if let Some(i) = self.indices.get_mut(k) { *i = v; } } - // (vertex, centroid of its first triangle), each vertex once. - let mut verts = Vec::with_capacity(mine.len() * 3); - for t in &mine { + + // (vertex, centroid of its first triangle), each vertex once + let mut vertices = Vec::with_capacity(material_triangles.len() * 3); + for t in &material_triangles { let Some(tri) = self.tri(*t) else { continue }; let centroid = tri.iter().map(|v| self.uvs.get(*v).copied().unwrap_or_default()).sum::() / 3.0; - verts.extend(tri.map(|v| (v, centroid))); + vertices.extend(tri.map(|v| (v, centroid))); } - verts.sort_by_key(|(v, _)| *v); - verts.dedup_by_key(|(v, _)| *v); - for (v, centroid) in verts { + + vertices.sort_by_key(|(v, _)| *v); + vertices.dedup_by_key(|(v, _)| *v); + for (v, centroid) in vertices { if let Some(uv) = self.uvs.get_mut(v) { *uv = f(centroid, *uv); } diff --git a/crates/paint/src/particles.rs b/crates/paint/src/particles.rs index ad81732e..2bdb122f 100644 --- a/crates/paint/src/particles.rs +++ b/crates/paint/src/particles.rs @@ -78,16 +78,16 @@ mod tests { #[test] fn particles_slide_down_a_wall_deterministically() { - // A vertical wall: the plane rotated to face +Z. - let mut m = primitives::plane(2.0, 8); - for p in &mut m.positions { - *p = Vec3::new(p.x, -p.z, 0.0); + // A vertical wall: the plane rotated to face +Z + let mut mesh = primitives::plane(2.0, 8); + for position in &mut mesh.positions { + *position = Vec3::new(position.x, -position.z, 0.0); } - m.normals.fill(Vec3::Z); - let bvh = Bvh::new(&m); - let cam = OrbitCamera::default(); - let ctx = PickCtx { mesh: &m, bvh: &bvh, camera: &cam, viewport: Vec2::new(100.0, 100.0) }; - let s = Stamp { + mesh.normals.fill(Vec3::Z); + let bvh = Bvh::new(&mesh); + let camera = OrbitCamera::default(); + let context = PickCtx { mesh: &mesh, bvh: &bvh, camera: &camera, viewport: Vec2::new(100.0, 100.0) }; + let stamp = Stamp { center: Vec3::ZERO, normal: Vec3::Z, tangent: Vec3::X, @@ -99,12 +99,14 @@ mod tests { seed: 3, copy: false, }; - let p = Particles { enabled: true, count: 4, lifetime: 20, gravity: 1.0 }; - let a = emit(&ctx, &p, &s); - assert_eq!(a, emit(&ctx, &p, &s)); - assert_eq!(a.len(), 80); - let lowest = a.iter().map(|d| d.center.y).fold(f32::MAX, f32::min); + let particles = Particles { enabled: true, count: 4, lifetime: 20, gravity: 1.0 }; + + let dabs = emit(&context, &particles, &stamp); + + assert_eq!(dabs, emit(&context, &particles, &stamp)); + assert_eq!(dabs.len(), 80); + let lowest = dabs.iter().map(|d| d.center.y).fold(f32::MAX, f32::min); assert!(lowest < -0.4, "{lowest}"); - assert!(a.iter().all(|d| d.center.z.abs() < 1e-3)); + assert!(dabs.iter().all(|d| d.center.z.abs() < 1e-3)); } } diff --git a/crates/render/src/subdivide.rs b/crates/render/src/subdivide.rs index 3da5e465..283759a4 100644 --- a/crates/render/src/subdivide.rs +++ b/crates/render/src/subdivide.rs @@ -65,29 +65,31 @@ fn on_edge(verts: &[Vertex], (p, q): (u32, u32), k: u32, n: u32) -> Option (Vec, Vec, Vec) { - let n = 1u32 << level.min(MAX_LEVEL); - let (mut out_v, mut out_i, mut out_d) = (Vec::new(), Vec::new(), Vec::new()); +pub(crate) fn subdivide(vertices: &[Vertex], indices: &[u32], draws: &[Draw], level: u32) -> (Vec, Vec, Vec) { + let segments = 1u32 << level.min(MAX_LEVEL); + let (mut output_vertices, mut output_indices, mut output_draws) = (Vec::new(), Vec::new(), Vec::new()); + for &(start, count, material) in draws { - let first = out_i.len() as u32; - let tris = indices.get(start as usize..(start as usize).saturating_add(count as usize)).unwrap_or_default(); - for t in tris.as_chunks::<3>().0 { - let (Some(a), Some(b), Some(c)) = (verts.get(t[0] as usize), verts.get(t[1] as usize), verts.get(t[2] as usize)) else { continue }; - let base = out_v.len() as u32; - // Grid point (i, j), i + j <= n, row by row: row j holds n + 1 - j points. Points on - // the edges are computed the same way from both triangles sharing the edge (no cracks). - for j in 0..=n { - for i in 0..=n - j { + let first = output_indices.len() as u32; + let triangles = indices.get(start as usize..(start as usize).saturating_add(count as usize)).unwrap_or_default(); + for t in triangles.as_chunks::<3>().0 { + let (Some(a), Some(b), Some(c)) = (vertices.get(t[0] as usize), vertices.get(t[1] as usize), vertices.get(t[2] as usize)) else { continue }; + let base = output_vertices.len() as u32; + + // Row j holds segments + 1 - j points inside the triangle + // Shared edges use identical interpolation in both triangles to prevent cracks + for j in 0..=segments { + for i in 0..=segments - j { let edge = match (i, j) { (_, 0) => Some(((t[0], t[1]), i)), (0, _) => Some(((t[0], t[2]), j)), - _ if i + j == n => Some(((t[1], t[2]), j)), + _ if i + j == segments => Some(((t[1], t[2]), j)), _ => None, }; - let p = match edge.and_then(|(ends, k)| on_edge(verts, ends, k, n)) { + let p = match edge.and_then(|(ends, k)| on_edge(vertices, ends, k, segments)) { Some(p) => p, None => { - let w = [1.0 - (i + j) as f32 / n as f32, i as f32 / n as f32, j as f32 / n as f32]; + let w = [1.0 - (i + j) as f32 / segments as f32, i as f32 / segments as f32, j as f32 / segments as f32]; Vertex { pos: mix(a.pos, b.pos, c.pos, w), nrm: mix(a.nrm, b.nrm, c.nrm, w), @@ -96,39 +98,42 @@ pub(crate) fn subdivide(verts: &[Vertex], indices: &[u32], draws: &[Draw], level } } }; - out_v.push(Vertex { tan: [p.tan[0], p.tan[1], p.tan[2], a.tan[3]], ..p }); + output_vertices.push(Vertex { tan: [p.tan[0], p.tan[1], p.tan[2], a.tan[3]], ..p }); } } - let at = |i: u32, j: u32| base + j * (n + 1) - j * j.saturating_sub(1) / 2 + i; - for j in 0..n { - for i in 0..n - j { - out_i.extend_from_slice(&[at(i, j), at(i + 1, j), at(i, j + 1)]); - if i + j + 1 < n { - out_i.extend_from_slice(&[at(i + 1, j), at(i + 1, j + 1), at(i, j + 1)]); + + let at = |i: u32, j: u32| base + j * (segments + 1) - j * j.saturating_sub(1) / 2 + i; + for j in 0..segments { + for i in 0..segments - j { + output_indices.extend_from_slice(&[at(i, j), at(i + 1, j), at(i, j + 1)]); + if i + j + 1 < segments { + output_indices.extend_from_slice(&[at(i + 1, j), at(i + 1, j + 1), at(i, j + 1)]); } } } } - out_d.push((first, out_i.len() as u32 - first, material)); + output_draws.push((first, output_indices.len() as u32 - first, material)); } - (out_v, out_i, out_d) + + (output_vertices, output_indices, output_draws) } /// World length per unit of UV over the whole mesh (the square root of their area ratio): how /// far a height change moves the surface for the slope height-to-normal shows. -pub(crate) fn world_per_uv(verts: &[Vertex], indices: &[u32]) -> Option { - let (mut world, mut uv) = (0.0f64, 0.0f64); +pub(crate) fn world_per_uv(vertices: &[Vertex], indices: &[u32]) -> Option { + let (mut world_area, mut uv_area) = (0.0f64, 0.0f64); for t in indices.as_chunks::<3>().0 { - let (Some(a), Some(b), Some(c)) = (verts.get(t[0] as usize), verts.get(t[1] as usize), verts.get(t[2] as usize)) else { continue }; + let (Some(a), Some(b), Some(c)) = (vertices.get(t[0] as usize), vertices.get(t[1] as usize), vertices.get(t[2] as usize)) else { continue }; let d = |p: [f32; 3], q: [f32; 3]| [f64::from(q[0] - p[0]), f64::from(q[1] - p[1]), f64::from(q[2] - p[2])]; let (e1, e2) = (d(a.pos, b.pos), d(a.pos, c.pos)); let cross = [e1[1] * e2[2] - e1[2] * e2[1], e1[2] * e2[0] - e1[0] * e2[2], e1[0] * e2[1] - e1[1] * e2[0]]; - world += (cross[0] * cross[0] + cross[1] * cross[1] + cross[2] * cross[2]).sqrt() * 0.5; + world_area += (cross[0] * cross[0] + cross[1] * cross[1] + cross[2] * cross[2]).sqrt() * 0.5; let (u1, u2) = ([b.uv[0] - a.uv[0], b.uv[1] - a.uv[1]], [c.uv[0] - a.uv[0], c.uv[1] - a.uv[1]]); - uv += f64::from(u1[0] * u2[1] - u1[1] * u2[0]).abs() * 0.5; + uv_area += f64::from(u1[0] * u2[1] - u1[1] * u2[0]).abs() * 0.5; } - let r = (world / uv).sqrt() as f32; - (uv > 1e-12 && r.is_finite() && r > 0.0).then_some(r) + + let scale = (world_area / uv_area).sqrt() as f32; + (uv_area > 1e-12 && scale.is_finite() && scale > 0.0).then_some(scale) } #[cfg(test)]