diff --git a/assets/locales/pending/point-cloud-edges-and-faces.json b/assets/locales/pending/point-cloud-edges-and-faces.json new file mode 100644 index 000000000..bfca9e3d6 --- /dev/null +++ b/assets/locales/pending/point-cloud-edges-and-faces.json @@ -0,0 +1,26 @@ +{ + "en": { + "ui.point_cloud_dots": "Dots" + }, + "fr": { + "ui.point_cloud_dots": "Points isolés" + }, + "de": { + "ui.point_cloud_dots": "Einzelpunkte" + }, + "ja": { + "ui.point_cloud_dots": "単独の点" + }, + "zh": { + "ui.point_cloud_dots": "独立点" + }, + "ar": { + "ui.point_cloud_dots": "نقاط منفردة" + }, + "he": { + "ui.point_cloud_dots": "נקודות בודדות" + }, + "vi": { + "ui.point_cloud_dots": "Điểm đơn lẻ" + } +} diff --git a/assets/shaders/viewport.wgsl b/assets/shaders/viewport.wgsl index 6f52b8de3..d3172ece8 100644 --- a/assets/shaders/viewport.wgsl +++ b/assets/shaders/viewport.wgsl @@ -883,10 +883,10 @@ fn fs_line_all(i: LOut) -> @location(0) vec4 { return out_color(i.c); } -// Point clouds (`view/clouds.rs`): each point is a round dot a few pixels across, facing the -// screen, depth-tested and written like the model's faces, so the model hides the points behind -// it and they hide it. The cloud's style colours them by their own colour, a ramp or a palette, -// and shows only those whose filtered values lie in its ranges or sets. +// Point clouds and their cells (`view/clouds.rs`): dots, segments as beads (or lines when they +// have no size) and triangles, from one record per element. The cloud's style colours them by +// their own colour, a ramp or a palette, and shows only those whose filtered values lie in its +// ranges or sets; values vary across an element, so a range cuts it where its value crosses an end. struct Cloud { style: vec4, // x: colour (0 own, 1 ramp, 2 palette), y: dot size (px), z, w: ramp range @@ -895,43 +895,88 @@ struct Cloud { @group(1) @binding(3) var cloud: Cloud; struct CIn { - @location(0) p: vec3, - @location(1) v: f32, - @location(2) f: vec4, - @location(3) rgb: vec4, + @location(0) a: vec3, + @location(1) b: vec3, + @location(2) c: vec3, + @location(8) before: vec3, + @location(9) after: vec3, + @location(3) v: vec3, + @location(4) f0: vec3, + @location(5) f1: vec3, + @location(10) f2: vec3, + @location(11) f3: vec3, + @location(6) size: vec2, + @location(7) rgb: vec4, }; struct COut { @builtin(position) pos: vec4, @location(0) wp: vec3, - @location(1) v: f32, - @location(2) f: vec4, - @location(3) rgb: vec3, - @location(4) at: vec2, // the place on its disc - @location(5) @interpolate(flat) has: u32, + @location(1) n: vec3, // zero: not lit + @location(2) v: f32, + @location(3) f: vec4, + @location(4) rgb: vec3, + @location(5) at: vec2, // a dot's place on its disc + @location(6) @interpolate(flat) has: u32, }; +fn cloud_out(i: CIn, w: vec3, wp: vec3, pos: vec4, n: vec3) -> COut { + var o: COut; + o.pos = pos; + o.wp = wp; + o.n = n; + o.v = dot(w, i.v); + o.f = vec4(dot(w, i.f0), dot(w, i.f1), dot(w, i.f2), dot(w, i.f3)); + o.rgb = i.rgb.rgb; + o.at = vec2(0.0); + o.has = u32(round(i.rgb.a * 255.0)); + return o; +} + +fn behind(c: vec4) -> bool { + return near_z(c) < 0.0; +} + @vertex fn vs_cloud_dot(@builtin(vertex_index) vi: u32, i: CIn) -> COut { var xs = array(-1.0, 1.0, 1.0, -1.0, 1.0, -1.0); var ys = array(-1.0, -1.0, 1.0, -1.0, 1.0, 1.0); let at = vec2(xs[vi], ys[vi]); let size = max(cloud.style.y, 1.0); - let centre = u.vp * vec4(i.p, 1.0); - var o: COut; - o.pos = vec4(centre.xy + at * size / u.screen.xy * centre.w, centre.z, centre.w); - // Behind the eye: nothing. - if (near_z(centre) < 0.0) { o.pos = vec4(0.0, 0.0, 0.0, -1.0); } - o.wp = i.p; - o.v = i.v; - o.f = i.f; - o.rgb = i.rgb.rgb; - o.has = u32(round(i.rgb.a * 255.0)); + let centre = u.vp * vec4(i.a, 1.0); + var pos = vec4(centre.xy + at * size / u.screen.xy * centre.w, centre.z, centre.w); + if (behind(centre)) { pos = vec4(0.0, 0.0, 0.0, -1.0); } + var o = cloud_out(i, vec3(1.0, 0.0, 0.0), i.a, pos, vec3(0.0)); // Dots under two pixels are squares: a disc that small loses its centre pixel. o.at = at * select(1.0, 0.0, size < 2.0); return o; } +/// The least half-width of a segment on screen, in pixels. +const MIN_HALF_PX: f32 = 0.75; + +/// The frame of a bead along `d`: along it, across it level, and up, its height axis. +fn bead_frame(d: vec3) -> mat3x3 { + var t = vec3(1.0, 0.0, 0.0); + if (length(d) > 1e-9) { t = d / length(d); } + var side = cross(vec3(0.0, 0.0, 1.0), t); + if (length(side) < 1e-6) { side = vec3(1.0, 0.0, 0.0); } + side = normalize(side); + return mat3x3(t, side, cross(t, side)); +} + +/// Corner `j` (0…9) of a bead's cross-section, a stadium: its place across and up, and its +/// normal. Corners 0…4 go up the right half-disc, 5…9 down the left one, so 4–5 is the flat top +/// and 9–0 the flat bottom. +fn stadium(j: u32, size: vec2) -> vec4 { + let k = j % 10u; + let right = k < 5u; + let a = -1.5707963 + 0.7853982 * f32(k % 5u) + select(3.1415927, 0.0, right); + let r = 0.5 * size.y; + let flat_half = 0.5 * max(size.x - size.y, 0.0); + return vec4(select(-flat_half, flat_half, right) + r * cos(a), r * sin(a), cos(a), sin(a)); +} + /// Whether filter `f` keeps the value `v`. fn cloud_keeps(f: vec4, v: f32) -> bool { if (f.x < 0.5) { return true; } @@ -940,6 +985,101 @@ fn cloud_keeps(f: vec4, v: f32) -> bool { return k >= 0 && k < 32 && ((bitcast(f.w) >> u32(k)) & 1u) != 0u; } +/// Whether filter `f` leaves out a whole element with values `v` at its corners: all on one +/// side of a range, or one value at every corner, not kept. A set of values with corners that +/// differ may keep part of the element: its fragments decide. +fn cloud_drops(f: vec4, v: vec3) -> bool { + if (f.x > 1.5) { return all(v == vec3(v.x)) && !cloud_keeps(f, v.x); } + return f.x > 0.5 && (all(v < vec3(f.y)) || all(v > vec3(f.z))); +} + +/// Whether a filter leaves out the whole element. +fn filtered_out(i: CIn) -> bool { + let has = u32(round(i.rgb.a * 255.0)); + let values = array, 4>(i.f0, i.f1, i.f2, i.f3); + for (var k = 0u; k < 4u; k++) { + if (((has >> k) & 1u) != 0u && cloud_drops(cloud.filters[k], values[k])) { return true; } + } + return false; +} + +/// The part in front of the near plane of the segment between clip-space `a` and `b`, as +/// fractions of it from `a`; empty (first above second) when all of it is behind. Clip-space +/// coordinates are affine along a line, so the crossing is exact. +fn in_front(a: vec4, b: vec4) -> vec2 { + let za = near_z(a); + let zb = near_z(b); + if (za < 0.0 && zb < 0.0) { return vec2(1.0, 0.0); } + let t = za / (za - zb); + return vec2(select(0.0, t, za < 0.0), select(1.0, t, zb < 0.0)); +} + +@vertex +fn vs_cloud_segment(@builtin(vertex_index) vi: u32, i: CIn) -> COut { + // Corner `vi % 10` of the cross-section at the start (`vi < 10`) or the end; the index + // buffer joins them into the bead's sides. + let pa = u.vp * vec4(i.a, 1.0); + let pb = u.vp * vec4(i.b, 1.0); + let part = in_front(pa, pb); + if (filtered_out(i) || part.x > part.y) { + return cloud_out(i, vec3(1.0, 0.0, 0.0), i.a, vec4(0.0, 0.0, 0.0, -1.0), vec3(0.0)); + } + // Where the near plane cuts it, the bead ends there, square; its numbers are exact at `e`. + let at_end = vi >= 10u; + let e = select(part.x, part.y, at_end); + let cut = e != select(0.0, 1.0, at_end); + let f = bead_frame(i.b - i.a); + let c = stadium(vi % 10u, i.size); + let axis = mix(i.a, i.b, e); + // Where it meets the next or the previous bead, the cross-section lies in the plane halfway + // between their directions, stretched across to keep its width: both beads end on the same + // section. A turn sharper than 120° ends square instead. + let other = select(i.a - i.before, i.after - i.b, at_end); + var across_dir = f[1]; + var stretch = 1.0; + if (!cut && length(other) > 1e-9) { + let g = bead_frame(other); + let mid = f[1] + g[1]; + if (length(mid) > 1e-6 && dot(normalize(mid), f[1]) > 0.5) { + across_dir = normalize(mid); + stretch = 1.0 / dot(across_dir, f[1]); + } + } + let wp = axis + across_dir * (c.x * stretch) + f[2] * c.y; + let ca = u.vp * vec4(axis, 1.0); + let cw = u.vp * vec4(wp, 1.0); + let half = u.screen.xy * 0.5; + var pos = cw; + // At least a pixel and a half across: a bead seen from afar, or a line without size. A corner + // behind the eye has no place on the screen and needs no widening: the rasteriser clips it. + if (cw.w > 0.0) { + let c0 = mix(pa, pb, part.x); + let c1 = mix(pa, pb, part.y); + let along = (c1.xy / c1.w - c0.xy / c0.w) * half; + var across = vec2(-along.y, along.x); + if (length(across) < 1e-6) { across = vec2(1.0, 0.0); } + across = normalize(across); + var px = (cw.xy / cw.w - ca.xy / ca.w) * half; + if (length(px) < MIN_HALF_PX * abs(c.z)) { + px = across * c.z * MIN_HALF_PX; + pos = vec4((ca.xy / ca.w + px / half) * cw.w, cw.z, cw.w); + } + } + let n = select(f[1] * c.z + f[2] * c.w, vec3(0.0), i.size.y <= 0.0); + return cloud_out(i, vec3(1.0 - e, e, 0.0), wp, pos, n); +} + +@vertex +fn vs_cloud_triangle(@builtin(vertex_index) vi: u32, i: CIn) -> COut { + // Not `w[vi] = 1.0`: the Windows D3D12 shader compiler cannot write through a dynamic vector index. + let w = vec3(f32(vi == 0u), f32(vi == 1u), f32(vi == 2u)); + let wp = i.a * w.x + i.b * w.y + i.c * w.z; + var n = cross(i.b - i.a, i.c - i.a); + if (length(n) > 0.0) { n = normalize(n); } + // The true clip-space corner, even behind the eye: the rasteriser clips a triangle exactly. + return cloud_out(i, w, wp, u.vp * vec4(wp, 1.0), n); +} + fn cloud_ramp(t: f32) -> vec3 { var stops = array, 5>( vec3(40.0, 70.0, 200.0), vec3(30.0, 170.0, 230.0), vec3(60.0, 200.0, 90.0), @@ -974,5 +1114,8 @@ fn fs_cloud(o: COut) -> @location(0) vec4 { } else if ((o.has & 16u) != 0u && mode > 0.5) { c = cloud_ramp((o.v - cloud.style.z) / max(cloud.style.w - cloud.style.z, 1e-12)); } + if (length(o.n) > 0.5) { + c = c * (0.45 + 0.55 * abs(dot(normalize(o.n), normalize(u.back.xyz)))); + } return out_color(vec4(c, 1.0)); } diff --git a/crates/doc/src/format/pending/point-cloud-segments-and-triangles.rs b/crates/doc/src/format/pending/point-cloud-segments-and-triangles.rs new file mode 100644 index 000000000..219f4df9a --- /dev/null +++ b/crates/doc/src/format/pending/point-cloud-segments-and-triangles.rs @@ -0,0 +1,6 @@ +//! A point cloud keeps the segments and triangles its file draws over its points (#8817): +//! `segments` and `triangles` in its `complex`, the indices of their points, and a column of named +//! numbers may lie on them (`on`: `segment` or `triangle`; a column that does not say is on the +//! points, as every design saved before this has it). Older designs need no transformation: their +//! clouds are points alone. The last release refuses a design saved with this (the newer format +//! number) instead of opening its clouds as loose points without their edges and faces. diff --git a/crates/doc/src/point_cloud.rs b/crates/doc/src/point_cloud.rs index ab174333d..a1ad8d959 100644 --- a/crates/doc/src/point_cloud.rs +++ b/crates/doc/src/point_cloud.rs @@ -12,7 +12,7 @@ use serde::{Deserialize, Deserializer, Serialize, Serializer}; use solidcore_record::Vec3; use crate::canvas::{base64_decode, base64_encode}; -pub use crate::point_cloud_complex::{Column, Complex, Filter, Floats, Keep, MAX_COLUMNS, MAX_NAMES, Names}; +pub use crate::point_cloud_complex::{Column, Complex, Filter, Floats, Indices, Keep, MAX_CELLS, MAX_COLUMNS, MAX_NAMES, Names, On}; use crate::{DocError, IDENTITY, Mat, Result}; /// Most points one cloud may hold. @@ -71,24 +71,26 @@ pub struct PointCloud { pub height_range: Option<[f64; 2]>, #[serde(default = "yes")] pub visible: bool, - /// The file's other properties of the points. + /// Segments and triangles over the points, and the file's other properties. #[serde(default, skip_serializing_if = "Complex::is_empty")] pub complex: Complex, /// The property `color_by: property` colours by. #[serde(default, skip_serializing_if = "Option::is_none")] pub color_property: Option, - /// Only the points every filter keeps are shown. + /// Only the elements within every filter's range are shown. #[serde(default, skip_serializing_if = "Vec::is_empty")] pub filters: Vec, } -/// Where a property's values come from. +/// Where a property's values come from on one kind of element. #[derive(Clone, Copy, Debug)] pub enum Source<'a> { - /// A coordinate of each point in the design. + /// A coordinate of each corner in the design. Coordinate(usize), - /// A column of the file: each point's. - Column(&'a [f32]), + /// A column on the points: each corner's. + Corners(&'a [f32]), + /// A column on the element itself. + Element(&'a [f32]), } /// How a cloud's points are coloured. @@ -239,16 +241,21 @@ impl PointCloud { ColorBy::File | ColorBy::Single => None, } } - /// Where the values of `name` are: a coordinate of each point or a column of the file. - pub fn source(&self, name: &str) -> Option> { + /// Where the values of `name` are on elements of kind `on`: a coordinate of each corner, a + /// column on the points (each corner's, varying across the element) or one on the element. + pub fn source(&self, name: &str, on: On) -> Option> { if let Some(k) = COORDINATES.iter().position(|n| *n == name) { return Some(Source::Coordinate(k)); } - self.complex.column(name).map(|col| Source::Column(&col.values.0)) + if let Some(col) = self.complex.column(name, on) { + return Some(Source::Element(&col.values.0)); + } + self.complex.column(name, On::Point).map(|col| Source::Corners(&col.values.0)) } /// Every property the cloud can be coloured and filtered by: its coordinates, then its columns. pub fn property_names(&self) -> impl Iterator { - COORDINATES.into_iter().chain(self.complex.columns.iter().map(|c| c.name.as_str())) + let mut seen = std::collections::BTreeSet::new(); + COORDINATES.into_iter().chain(self.complex.columns.iter().map(|c| c.name.as_str())).filter(move |n| seen.insert(*n)) } /// The smallest and largest value of a property, the coordinates in the design. pub fn span(&self, property: &str) -> Option<[f64; 2]> { @@ -273,6 +280,19 @@ impl PointCloud { self.filters.iter().filter(|f| f.property == property).filter_map(Filter::range).fold(span, |[lo, hi], [a, b]| [lo.max(a), hi.min(b)]); Some(if shown[0] <= shown[1] { crate::point_cloud_distribution::ramp_range(shown) } else { span }) } + /// Points no segment or triangle ends on: those drawn as dots. + pub fn isolated_points(&self) -> usize { + if self.complex.segments.is_empty() && self.complex.triangles.is_empty() { + return self.len(); + } + let mut used = vec![false; self.len()]; + for i in self.complex.segments.0.iter().chain(self.complex.triangles.0.iter()) { + if let Some(u) = used.get_mut(*i as usize) { + *u = true; + } + } + used.iter().filter(|u| !**u).count() + } /// The heights the height ramp runs between now: the cloud's own, else the automatic ones. pub fn height_range_now(&self) -> Option<[f64; 2]> { self.height_range.or_else(|| self.auto_height_range()) @@ -281,7 +301,7 @@ impl PointCloud { pub fn shade(&self, range: Option<[f64; 2]>) -> impl Fn(usize) -> [u8; 3] + '_ { let single = self.color.unwrap_or(PLAIN).map(byte); let plain = PLAIN.map(byte); - let column = self.color_property.as_deref().and_then(|n| self.complex.column(n)); + let column = self.color_property.as_deref().and_then(|n| self.complex.column(n, On::Point)); move |i| match self.color_by { ColorBy::File => self.colors.get(i).unwrap_or(plain), ColorBy::Single => single, @@ -558,9 +578,10 @@ mod tests { } #[test] - fn the_ramp_spans_what_is_shown_unless_set() { + fn the_ramp_spans_what_is_shown_unless_set_and_isolated_points_are_counted() { let mut c = cloud(vec![0.0; 9], Vec::new()); - c.complex.columns.push(Column { name: "t".into(), integer: false, values: Floats(vec![0.0, 10.0, 20.0].into()) }); + c.complex.segments = Indices(vec![0, 1].into()); + c.complex.columns.push(Column { name: "t".into(), on: On::Point, integer: false, values: Floats(vec![0.0, 10.0, 20.0].into()) }); (c.color_by, c.color_property) = (ColorBy::Property, Some("t".into())); assert_eq!(c.color_range(), Some([0.0, 20.0]), "the whole span"); c.filters = vec![Filter { property: "t".into(), keep: Keep::Range { range: [5.0, 50.0] } }]; @@ -569,6 +590,7 @@ mod tests { assert_eq!(c.color_range(), Some([5.0, 20.0]), "another property's filter changes nothing"); c.height_range = Some([1.0, 2.0]); assert_eq!(c.color_range(), Some([1.0, 2.0]), "a range set is kept"); + assert_eq!(c.isolated_points(), 1, "point 2 ends no segment"); } #[test] diff --git a/crates/doc/src/point_cloud_complex.rs b/crates/doc/src/point_cloud_complex.rs index 6635996c7..fe26dc12d 100644 --- a/crates/doc/src/point_cloud_complex.rs +++ b/crates/doc/src/point_cloud_complex.rs @@ -1,5 +1,8 @@ -//! What a point cloud holds besides its points' places and colours: named numbers on its points -//! (a PLY file's other vertex properties), to colour the cloud by and to filter it with. Whole +//! What a point cloud holds besides its points: segments and triangles between them, and named +//! numbers on its points, segments and triangles (a PLY file's properties), to colour the cloud +//! by and to filter it with. A point's numbers vary along the segments and across the triangles +//! that meet there; a segment's or a triangle's are constant on it. A segment with `width` and +//! `height` numbers is drawn as a bead of that cross-section; without them, as a line. Whole //! numbers may have names (`role: 0 outer wall, 1 inner wall` in a PLY file's comments): they //! are labels, filtered by a set of values rather than a range. @@ -11,13 +14,41 @@ use crate::canvas::{base64_decode, base64_encode}; use crate::point_cloud::MAX_POINTS; use crate::{DocError, Result}; -/// Most named numbers per point. +/// Most segments or triangles in one cloud. +pub const MAX_CELLS: usize = 20_000_000; +/// Most named numbers per point, segment and triangle together. pub const MAX_COLUMNS: usize = 64; -/// One named number on every point. +/// The elements a column of numbers is on. +#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Serialize, Deserialize)] +#[serde(rename_all = "lowercase")] +pub enum On { + #[default] + Point, + Segment, + Triangle, +} + +impl On { + fn is_point(&self) -> bool { + *self == On::Point + } + pub fn name(self) -> &'static str { + match self { + On::Point => "point", + On::Segment => "segment", + On::Triangle => "triangle", + } + } +} + +/// One named number on every element of a kind. #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] pub struct Column { pub name: String, + /// Points unless said: a design saved with numbers on points alone says nothing. + #[serde(default, skip_serializing_if = "On::is_point")] + pub on: On, /// Whole numbers (labels, counts): coloured by a palette rather than a ramp. #[serde(default)] pub integer: bool, @@ -33,10 +64,16 @@ impl Column { } } -/// The complex a cloud's points form: named numbers on the points, and the names of -/// whole-numbered ones. Points alone are a complex of dimension 0. +/// The complex a cloud's points span: segments and triangles over them, and named numbers on +/// all three. Without segments or triangles, the points alone are a complex of dimension 0. #[derive(Clone, Debug, Default, PartialEq, Serialize, Deserialize)] pub struct Complex { + /// Point indices, two per segment. + #[serde(default, skip_serializing_if = "Indices::is_empty")] + pub segments: Indices, + /// Point indices, three per triangle, counter-clockwise seen from its front. + #[serde(default, skip_serializing_if = "Indices::is_empty")] + pub triangles: Indices, #[serde(default, skip_serializing_if = "Vec::is_empty")] pub columns: Vec, #[serde(default, skip_serializing_if = "Vec::is_empty")] @@ -78,33 +115,95 @@ impl Names { impl Complex { pub fn is_empty(&self) -> bool { - self.columns.is_empty() && self.names.is_empty() + self.segments.is_empty() && self.triangles.is_empty() && self.columns.is_empty() && self.names.is_empty() } - /// The column named `name`. - pub fn column(&self, name: &str) -> Option<&Column> { - self.columns.iter().find(|c| c.name == name) + /// The subcomplex spanned by the points `kept` marks: those points, numbered in order, with + /// their numbers, and the segments and triangles all of whose corners are among them, with + /// theirs. Also how many segments and triangles it leaves out. + pub fn induced(&self, kept: &[bool]) -> (Complex, u64) { + let mut next = 0u32; + let renumbered: Vec> = kept + .iter() + .map(|k| { + k.then(|| { + next += 1; + next - 1 + }) + }) + .collect(); + let restrict = |indices: &Indices, n: usize| { + let (mut ids, mut whole) = (Vec::new(), Vec::new()); + for corners in indices.0.chunks_exact(n) { + let new: Option> = corners.iter().map(|i| renumbered.get(*i as usize).copied().flatten()).collect(); + whole.push(new.is_some()); + ids.extend(new.unwrap_or_default()); + } + (Indices(ids.into()), whole) + }; + let (segments, on_segments) = restrict(&self.segments, 2); + let (triangles, on_triangles) = restrict(&self.triangles, 3); + let left_out = on_segments.iter().chain(&on_triangles).filter(|whole| !**whole).count() as u64; + let columns = self + .columns + .iter() + .map(|c| { + let mask = match c.on { + On::Point => kept, + On::Segment => &on_segments, + On::Triangle => &on_triangles, + }; + let values: Vec = c.values.0.iter().zip(mask).filter(|(_, k)| **k).map(|(v, _)| *v).collect(); + Column { values: Floats(values.into()), ..c.clone() } + }) + .collect(); + (Complex { segments, triangles, columns, names: self.names.clone() }, left_out) } - /// The smallest and largest value named `name`. + pub fn segment_count(&self) -> usize { + self.segments.0.len() / 2 + } + pub fn triangle_count(&self) -> usize { + self.triangles.0.len() / 3 + } + /// The column named `name` on elements of kind `on`: a name may be on several kinds. + pub fn column(&self, name: &str, on: On) -> Option<&Column> { + self.columns.iter().find(|c| c.name == name && c.on == on) + } + /// The smallest and largest value named `name`, on whichever elements carry it. pub fn span(&self, name: &str) -> Option<[f64; 2]> { - self.column(name).and_then(Column::span) + self.columns.iter().filter(|c| c.name == name).filter_map(Column::span).reduce(|[a, b], [c, d]| [a.min(c), b.max(d)]) } /// The names of `property`'s values, when it is a label. pub fn names(&self, property: &str) -> Option<&Names> { self.names.iter().find(|n| n.property == property).filter(|_| self.integer(property)) } - /// Whether the values named `name` are whole numbers. + /// Whether the values named `name` are whole numbers wherever they are. pub fn integer(&self, name: &str) -> bool { - self.column(name).is_some_and(|c| c.integer) + let mut named = self.columns.iter().filter(|c| c.name == name).peekable(); + named.peek().is_some() && named.all(|c| c.integer) } - /// Every column has one number per point, the cloud having `points` points. + /// How many elements of a kind there are, the cloud having `points` points. + pub fn count(&self, on: On, points: usize) -> usize { + match on { + On::Point => points, + On::Segment => self.segment_count(), + On::Triangle => self.triangle_count(), + } + } + /// Every index names a point, and every column has one number per element. pub fn check(&self, points: usize) -> Result<()> { - let bad = |what: String| Err(DocError::Invalid(format!("point cloud properties: {what}"))); - if self.columns.len() > MAX_COLUMNS { - return bad("too many properties".into()); + let bad = |what: String| Err(DocError::Invalid(format!("point cloud complex: {what}"))); + if !self.segments.0.len().is_multiple_of(2) || !self.triangles.0.len().is_multiple_of(3) { + return bad("segments are not pairs or triangles not triples".into()); + } + if self.segment_count() > MAX_CELLS || self.triangle_count() > MAX_CELLS || self.columns.len() > MAX_COLUMNS { + return bad("too many segments, triangles or properties".into()); + } + if self.segments.0.iter().chain(self.triangles.0.iter()).any(|i| *i as usize >= points) { + return bad("an index names a missing point".into()); } for c in &self.columns { - if c.values.0.len() != points { - return bad(format!("property `{}` does not have one number per point", c.name)); + if c.values.0.len() != self.count(c.on, points) { + return bad(format!("property `{}` does not have one number per {}", c.name, c.on.name())); } } if self.names.len() > MAX_COLUMNS || self.names.iter().any(|n| n.values.is_empty() || n.values.len() > MAX_NAMES) { @@ -114,8 +213,8 @@ impl Complex { } } -/// Which points are shown: those whose property lies in a range (both ends included), or, for a -/// label, is one of a set of values. +/// Which elements are shown: those whose property lies in a range (both ends included), or, for +/// a label, is one of a set of values. #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] pub struct Filter { pub property: String, @@ -140,10 +239,26 @@ impl Filter { } } +/// Indices into a cloud's points, shared between copies of the design. +#[derive(Clone, Debug, Default)] +pub struct Indices(pub Arc<[u32]>); + +impl Indices { + pub fn is_empty(&self) -> bool { + self.0.is_empty() + } +} + /// Numbers, shared between copies of the design. #[derive(Clone, Debug, Default)] pub struct Floats(pub Arc<[f32]>); +impl PartialEq for Indices { + fn eq(&self, other: &Self) -> bool { + Arc::ptr_eq(&self.0, &other.0) || self.0 == other.0 + } +} + impl PartialEq for Floats { fn eq(&self, other: &Self) -> bool { Arc::ptr_eq(&self.0, &other.0) || self.0.iter().map(|v| v.to_bits()).eq(other.0.iter().map(|v| v.to_bits())) @@ -167,6 +282,18 @@ fn words<'de, D: Deserializer<'de>>(d: D, max: usize) -> std::result::Result().0.to_vec()) } +impl Serialize for Indices { + fn serialize(&self, s: S) -> std::result::Result { + s.serialize_str(&base64_encode(&self.0.iter().flat_map(|v| v.to_le_bytes()).collect::>())) + } +} + +impl<'de> Deserialize<'de> for Indices { + fn deserialize>(d: D) -> std::result::Result { + Ok(Indices(words(d, 3 * MAX_CELLS)?.into_iter().map(u32::from_le_bytes).collect())) + } +} + impl Serialize for Floats { fn serialize(&self, s: S) -> std::result::Result { s.serialize_str(&base64_encode(&self.0.iter().flat_map(|v| v.to_le_bytes()).collect::>())) @@ -175,7 +302,7 @@ impl Serialize for Floats { impl<'de> Deserialize<'de> for Floats { fn deserialize>(d: D) -> std::result::Result { - Ok(Floats(words(d, MAX_POINTS)?.into_iter().map(f32::from_le_bytes).collect())) + Ok(Floats(words(d, MAX_POINTS.max(MAX_CELLS))?.into_iter().map(f32::from_le_bytes).collect())) } } @@ -184,20 +311,26 @@ mod tests { use super::*; #[test] - fn properties_round_trip_and_are_checked_against_the_points() { + fn a_complex_round_trips_and_is_checked_against_its_points() { let complex = Complex { + segments: Indices(vec![0, 1, 1, 2].into()), + triangles: Indices(vec![0, 1, 2].into()), columns: vec![ - Column { name: "t".into(), integer: false, values: Floats(vec![0.0, 0.5, 1.0].into()) }, - Column { name: "role".into(), integer: true, values: Floats(vec![0.0, 4.0, 4.0].into()) }, + Column { name: "t".into(), on: On::Point, integer: false, values: Floats(vec![0.0, 0.5, 1.0].into()) }, + Column { name: "role".into(), on: On::Segment, integer: true, values: Floats(vec![0.0, 4.0].into()) }, ], names: Vec::new(), }; let back: Complex = serde_json::from_str(&serde_json::to_string(&complex).unwrap()).unwrap(); assert_eq!(back, complex); + let points: Column = serde_json::from_str(r#"{"name": "t", "values": ""}"#).unwrap(); + assert!(!serde_json::to_string(&points).unwrap().contains("\"on\""), "a column on the points does not say so"); + assert_eq!(points.on, On::Point, "a column without `on` is on the points"); complex.check(3).unwrap(); - assert!(complex.check(2).is_err(), "three numbers for two points"); + assert!(complex.check(2).is_err(), "index 2 names a missing point"); assert_eq!(complex.span("role"), Some([0.0, 4.0])); assert!(complex.integer("role") && !complex.integer("t") && !complex.integer("nope")); + assert!(complex.column("role", On::Segment).is_some() && complex.column("role", On::Point).is_none()); // Named values make a label, and a filter keeps a range or a set of them. let names = Names::parse("role: 0 outer wall, 4 bridge, -1 none").unwrap(); assert_eq!((names.name(4), names.name(-1), names.name(2)), (Some("bridge"), Some("none"), None)); @@ -211,5 +344,8 @@ mod tests { let range: Filter = serde_json::from_str(r#"{"property": "t", "range": [1, 3]}"#).unwrap(); assert_eq!((set.range(), range.range()), (None, Some([1.0, 3.0]))); assert_eq!(serde_json::to_value(&set).unwrap(), serde_json::json!({"property": "role", "values": [0, 4]})); + let mut short = complex.clone(); + short.columns[1].values = Floats(vec![0.0].into()); + assert!(short.check(3).is_err(), "one role for two segments"); } } diff --git a/crates/doc/src/point_cloud_distribution.rs b/crates/doc/src/point_cloud_distribution.rs index 4d9e052f8..ce44b6331 100644 --- a/crates/doc/src/point_cloud_distribution.rs +++ b/crates/doc/src/point_cloud_distribution.rs @@ -3,30 +3,79 @@ //! colours the view draws, and the values where a label changes along a property, which the //! tracks snap to. //! -//! Each point weighs the same, the cloud weighing 1. A range filter keeps the points between its -//! ends, as the view does; a filter by values keeps those whose rounded value it holds; the -//! colour sorts the points kept into the colours they are drawn in. The values the points kept -//! take, from the least to the greatest, are the ramp's automatic range: the colours span exactly -//! what is shown. +//! Each element weighs its measure: a dot 1, a segment its length, a triangle its area, each kind +//! divided by its own total so that kinds of different dimension weigh alike. On an element every +//! property is linear (the same everywhere, or its corners' values interpolated), so filters, +//! colours and the histogram all cut it the same way, where a linear function crosses a value. A +//! range filter keeps the part between its ends, as the view does; a filter by values keeps the +//! parts whose rounded value it holds; the colour sorts the parts into the colours they are drawn +//! in. Each part spreads its measure exactly over the values it covers of the histogram's +//! property: a dot's at one value, a segment's evenly, a triangle's as the tent its corners' +//! values make. The values the parts kept take, from the least to the greatest, are the ramp's +//! automatic range: the colours span exactly what is shown. -use crate::point_cloud::{ColorBy, Filter, Keep, PALETTE, PointCloud, Source}; +use crate::point_cloud::{ColorBy, Filter, Keep, On, PALETTE, PointCloud, Source}; /// Most bins of one histogram. pub const MAX_BINS: usize = 8192; +/// How far past its first band one part of an element is split by one cut. A ramp of [`MAX_BINS`] +/// bands, with the one below it and the one above it, has no more than this to cross, so its +/// measure is whole; only the whole numbers have more (a hostile file's values may cross billions). +const MAX_BANDS: usize = MAX_BINS + 1; +/// Most corners of a part of a triangle: each cut adds at most one to its three. +const MAX_CORNERS: usize = 24; -/// What the histograms need of a cloud's geometry, worked out once for its points. +/// What the histograms need of a cloud's geometry, worked out once for its points and cells. #[derive(Clone, Debug, Default)] pub struct Geometry { /// Each point in the design. world: Vec<[f64; 3]>, + /// The points drawn as dots: those no segment or triangle ends on. + dots: Vec, + /// Each segment's share of all segments' length, and each triangle's of their area. + segments: Vec, + triangles: Vec, } impl Geometry { pub fn of(c: &PointCloud) -> Geometry { - Geometry { world: (0..c.len()).map(|i| c.world_point(i).map_or([0.0; 3], |p| [p.x, p.y, p.z])).collect() } + let world: Vec<[f64; 3]> = (0..c.len()).map(|i| c.world_point(i).map_or([0.0; 3], |p| [p.x, p.y, p.z])).collect(); + let mut used = vec![false; world.len()]; + for i in c.complex.segments.0.iter().chain(c.complex.triangles.0.iter()) { + if let Some(u) = used.get_mut(*i as usize) { + *u = true; + } + } + let dots = (0..world.len() as u32).filter(|i| !used.get(*i as usize).copied().unwrap_or(true)).collect(); + let at = |i: u32| world.get(i as usize).copied().unwrap_or_default(); + let sub = |a: [f64; 3], b: [f64; 3]| [b[0] - a[0], b[1] - a[1], b[2] - a[2]]; + let norm = |v: [f64; 3]| (v[0] * v[0] + v[1] * v[1] + v[2] * v[2]).sqrt(); + let segments = c.complex.segments.0.as_chunks::<2>().0.iter().map(|[a, b]| norm(sub(at(*a), at(*b)))).collect(); + let triangles = c + .complex + .triangles + .0 + .as_chunks::<3>() + .0 + .iter() + .map(|[a, b, d]| { + let (u, v) = (sub(at(*a), at(*b)), sub(at(*a), at(*d))); + 0.5 * norm([u[1] * v[2] - u[2] * v[1], u[2] * v[0] - u[0] * v[2], u[0] * v[1] - u[1] * v[0]]) + }) + .collect(); + Geometry { world, dots, segments: shares(segments), triangles: shares(triangles) } } } +/// Each measure over their total (none for a total that is not a positive number). +fn shares(mut m: Vec) -> Vec { + let total: f64 = m.iter().filter(|v| v.is_finite()).sum(); + for v in &mut m { + *v = if total > 0.0 && v.is_finite() { *v / total } else { 0.0 }; + } + m +} + /// How a histogram is split by colour, into slots; the last slot holds what has no value to be /// coloured by. #[derive(Clone, Copy, Debug, PartialEq)] @@ -82,11 +131,11 @@ pub struct Histogram { pub bins: usize, /// `slots[s][b]`: the measure of slot `s` in bin `b`. pub slots: Vec>, - /// The least and the greatest value the points kept take, within the axis or not. + /// The least and the greatest value the parts kept take, within the axis or not. pub extent: Option<[f64; 2]>, } -/// Where values are cut into bands, by increasing values. +/// Where a linear function is cut into bands, by increasing values. #[derive(Clone, Copy, Debug)] enum Cut { /// Below (band 0), within (1, both ends included) and above (2) a range. @@ -115,6 +164,123 @@ impl Cut { } } } + /// The values band `k` holds, from and to (`None`: without end). + fn bounds(&self, k: usize) -> (Option, Option) { + match *self { + Cut::Range([a, b]) => match k { + 0 => (None, Some(a)), + 1 => (Some(a), Some(b)), + _ => (Some(b), None), + }, + Cut::Grid { start, step, count } => { + ((k > 0).then_some(start + k.saturating_sub(1) as f64 * step), (k < count).then_some(start + k as f64 * step)) + } + } + } +} + +/// A part of an element in its own coordinates: a dot, a stretch `[s₀, s₁]` of a segment (0 at +/// its first point), or a convex polygon in a triangle (each corner the weights of the +/// triangle's second and third points). +// Parts live in two buffers reused element after element: boxing a polygon would allocate per +// triangle. +#[allow(clippy::large_enum_variant)] +#[derive(Clone, Copy, Debug)] +enum Part { + Dot, + Stretch([f64; 2]), + Polygon(Polygon), +} + +#[derive(Clone, Copy, Debug)] +struct Polygon { + at: [[f64; 2]; MAX_CORNERS], + len: usize, +} + +impl Polygon { + fn triangle() -> Polygon { + let mut at = [[0.0; 2]; MAX_CORNERS]; + at[1] = [1.0, 0.0]; + at[2] = [0.0, 1.0]; + Polygon { at, len: 3 } + } + fn corners(&self) -> &[[f64; 2]] { + self.at.get(..self.len).unwrap_or(&[]) + } + /// The part where `g ≥ 0`. + fn clip(&self, g: impl Fn([f64; 2]) -> f64) -> Polygon { + let mut out = Polygon { at: [[0.0; 2]; MAX_CORNERS], len: 0 }; + let mut push = |p: [f64; 2]| { + if let Some(slot) = out.at.get_mut(out.len) { + *slot = p; + out.len += 1; + } + }; + let c = self.corners(); + for (k, p) in c.iter().enumerate() { + let q = c.get((k + 1) % c.len()).copied().unwrap_or(*p); + let (gp, gq) = (g(*p), g(q)); + if gp >= 0.0 { + push(*p); + } + if (gp >= 0.0) != (gq >= 0.0) { + let f = gp / (gp - gq); + push([p[0] + (q[0] - p[0]) * f, p[1] + (q[1] - p[1]) * f]); + } + } + out + } +} + +/// A linear function on an element: its values at the corners. +fn at(f: [f64; 3], p: [f64; 2]) -> f64 { + f[0] + (f[1] - f[0]) * p[0] + (f[2] - f[0]) * p[1] +} + +/// The bands of `cut` that `part` meets where `f` takes its values, each with the part in it. +fn split(part: &Part, f: [f64; 3], cut: Cut, mut visit: impl FnMut(usize, Part)) { + match part { + Part::Dot => visit(cut.band(f[0]), Part::Dot), + Part::Stretch([s0, s1]) => { + let (a, b) = (at(f, [*s0, 0.0]), at(f, [*s1, 0.0])); + let (lo, hi) = (a.min(b), a.max(b)); + let (k0, k1) = (cut.band(lo), cut.band(hi)); + if k0 == k1 || !(hi > lo) { + return visit(k0, *part); + } + let s = |x: f64| s0 + (x - a) / (b - a) * (s1 - s0); + for k in k0..=k1.min(k0 + MAX_BANDS) { + let (from, to) = cut.bounds(k); + let (x0, x1) = (from.map_or(lo, |v| v.max(lo)), to.map_or(hi, |v| v.min(hi))); + if x1 > x0 { + let (t0, t1) = (s(x0), s(x1)); + visit(k, Part::Stretch([t0.min(t1), t0.max(t1)])); + } + } + } + Part::Polygon(p) => { + let values = p.corners().iter().map(|c| at(f, *c)); + let (lo, hi) = values.fold((f64::INFINITY, f64::NEG_INFINITY), |(lo, hi), v| (lo.min(v), hi.max(v))); + let (k0, k1) = (cut.band(lo), cut.band(hi)); + if k0 == k1 || !(hi > lo) { + return visit(k0, *part); + } + for k in k0..=k1.min(k0 + MAX_BANDS) { + let (from, to) = cut.bounds(k); + let mut q = *p; + if let Some(v) = from { + q = q.clip(|c| at(f, c) - v); + } + if let Some(v) = to { + q = q.clip(|c| v - at(f, c)); + } + if q.len >= 3 { + visit(k, Part::Polygon(q)); + } + } + } + } } /// A filter as a cut and the bands it keeps. @@ -130,8 +296,7 @@ impl Kept<'_> { Keep::Values { values } => Kept { cut: INTEGERS, values: Some(values) }, } } - fn keeps(&self, v: f64) -> bool { - let band = self.cut.band(v); + fn keeps(&self, band: usize) -> bool { match self.values { None => band == 1, Some(values) => integer(band).is_some_and(|v| values.iter().any(|k| i64::from(*k) == v)), @@ -139,14 +304,133 @@ impl Kept<'_> { } } -/// The value of `s` at point `i`. -fn value(s: Source, i: usize, world: &[[f64; 3]]) -> f64 { +/// The values of `s` at an element's corners: element `e` of a kind, on points `ids`. +fn corners(s: Source, e: usize, ids: [u32; 3], world: &[[f64; 3]]) -> [f64; 3] { match s { - Source::Coordinate(k) => world.get(i).and_then(|p| p.get(k)).copied().unwrap_or(f64::NAN), - Source::Column(v) => v.get(i).map_or(f64::NAN, |x| f64::from(*x)), + Source::Coordinate(k) => ids.map(|i| world.get(i as usize).and_then(|p| p.get(k)).copied().unwrap_or(f64::NAN)), + Source::Corners(v) => ids.map(|i| v.get(i as usize).map_or(f64::NAN, |x| f64::from(*x))), + Source::Element(v) => [v.get(e).map_or(f64::NAN, |x| f64::from(*x)); 3], } } +/// Measure spread over bins: what falls in a bin directly, and evenly spread measure as ramps +/// (`k·max(0, x − c)` summed into its distribution function at each bin edge). +struct Bins { + lo: f64, + hi: f64, + width: f64, + n: usize, + direct: Vec, + slope: Vec, + offset: Vec, +} + +impl Bins { + fn new([lo, hi]: [f64; 2], n: usize, slots: usize) -> Bins { + Bins { + lo, + hi, + width: (hi - lo) / n as f64, + n, + direct: vec![0.0; slots * n], + slope: vec![0.0; slots * (n + 2)], + offset: vec![0.0; slots * (n + 2)], + } + } + fn edge(&self, j: usize) -> f64 { + if j >= self.n { self.hi } else { self.lo + j as f64 * self.width } + } + /// The bin holding `x`, the last bin holding its upper end too. + fn bin(&self, x: f64) -> Option { + if !(x >= self.lo && x <= self.hi) { + return None; + } + Some((((x - self.lo) / self.width).floor() as usize).min(self.n - 1)) + } + fn add(&mut self, slot: usize, j: usize, m: f64) { + if let Some(d) = self.direct.get_mut(slot * self.n + j) { + *d += m; + } + } + fn point(&mut self, slot: usize, x: f64, m: f64) { + if let Some(j) = self.bin(x) { + self.add(slot, j, m); + } + } + /// A ramp of slope `k` from `c`: it reaches the first edge at or after `c`. + fn ramp(&mut self, slot: usize, c: f64, k: f64) { + let j = ((c - self.lo) / self.width).ceil().clamp(0.0, (self.n + 1) as f64) as usize; + let at = slot * (self.n + 2) + j; + if let (Some(s), Some(o)) = (self.slope.get_mut(at), self.offset.get_mut(at)) { + *s += k; + *o += k * c; + } + } + /// `m` spread evenly over `[a, b]`. + fn even(&mut self, slot: usize, a: f64, b: f64, m: f64) { + if !(b > a) { + return self.point(slot, a, m); + } + let k = m / (b - a); + self.ramp(slot, a, k); + self.ramp(slot, b, -k); + } + /// `m` spread as a triangle's measure over its corners' values `q₀ ≤ q₁ ≤ q₂`: rising to + /// `q₁` and falling to `q₂`. + fn tent(&mut self, slot: usize, [q0, q1, q2]: [f64; 3], m: f64) { + if !(q2 > q0) { + return self.point(slot, q0, m); + } + let below = |x: f64| { + if x <= q0 { + 0.0 + } else if x >= q2 { + m + } else if x <= q1 { + m * (x - q0) * (x - q0) / ((q2 - q0) * (q1 - q0)) + } else { + m * (1.0 - (q2 - x) * (q2 - x) / ((q2 - q0) * (q2 - q1))) + } + }; + let (Some(j0), Some(j1)) = (self.bin(q0.max(self.lo)), self.bin(q2.min(self.hi))) else { return }; + for j in j0..=j1 { + let (a, b) = (self.edge(j).max(q0), self.edge(j + 1).min(q2)); + self.add(slot, j, below(b) - below(a)); + } + } + fn finish(self, slots: usize) -> Vec> { + (0..slots) + .map(|s| { + let (mut slope, mut offset, mut before) = (0.0, 0.0, 0.0); + (0..=self.n) + .filter_map(|j| { + let at = s * (self.n + 2) + j; + slope += self.slope.get(at).copied().unwrap_or(0.0); + offset += self.offset.get(at).copied().unwrap_or(0.0); + let f = slope * self.edge(j) - offset; + let spread = (j > 0).then_some(f - before); + before = f; + spread.map(|d| d + self.direct.get(s * self.n + j - 1).copied().unwrap_or(0.0)) + }) + .collect() + }) + .collect() + } +} + +/// The kinds of element, each with its elements' points and shares of measure. +fn kinds<'a>(c: &'a PointCloud, g: &'a Geometry) -> [(On, Box + 'a>); 3] { + let dot = if g.dots.is_empty() { 0.0 } else { 1.0 / g.dots.len() as f64 }; + [ + (On::Point, Box::new(g.dots.iter().map(move |i| (*i as usize, [*i; 3], dot)))), + ( + On::Segment, + Box::new(c.complex.segments.0.as_chunks::<2>().0.iter().zip(&g.segments).enumerate().map(|(e, ([a, b], m))| (e, [*a, *b, *b], *m))), + ), + (On::Triangle, Box::new(c.complex.triangles.0.as_chunks::<3>().0.iter().zip(&g.triangles).enumerate().map(|(e, (ids, m))| (e, *ids, *m)))), + ] +} + /// How much of the cloud lies in each of `bins` bins over `axis` of `property`, by `colour`, /// within every one of `filters`; `None` for an axis or a number of bins it can't have. pub fn histogram( @@ -167,39 +451,68 @@ pub fn histogram( return None; } let slots = colour.slots(); - let mut out = vec![vec![0.0; bins]; slots]; - let mut extent = None; - let Some(p) = c.source(property) else { return Some(Histogram { bins, slots: out, extent }) }; - // A point is not filtered by a property the cloud doesn't have, as in the view. - let kept: Vec<(Kept, Source)> = filters.iter().filter_map(|f| Some((Kept::of(f), c.source(&f.property)?))).collect(); - let coloured = colour.property().and_then(|n| c.source(n)); + let mut out = Bins::new(axis, bins, slots); + let kept: Vec = filters.iter().map(Kept::of).collect(); let (colour_cut, plain) = (colour.cut(), slots - 1); - let m = 1.0 / g.world.len().max(1) as f64; - let width = (axis[1] - axis[0]) / bins as f64; - for i in 0..g.world.len() { - if !kept.iter().all(|(k, s)| k.keeps(value(*s, i, &g.world))) { - continue; - } - let v = value(p, i, &g.world); - if !v.is_finite() { - continue; - } - extent = Some(extent.map_or([v, v], |[lo, hi]: [f64; 2]| [lo.min(v), hi.max(v)])); - if !(v >= axis[0] && v <= axis[1]) { - continue; - } - let slot = match (colour_cut, coloured) { - (Some(cut), Some(s)) => colour.slot(cut.band(value(s, i, &g.world))), - (Some(_), None) => plain, - (None, _) => 0, + let (mut parts, mut next) = (Vec::new(), Vec::new()); + let mut extent = None; + for (on, elements) in kinds(c, g) { + let Some(p) = c.source(property, on) else { continue }; + let filtered: Vec> = filters.iter().map(|f| c.source(&f.property, on)).collect(); + let coloured = colour.property().and_then(|n| c.source(n, on)); + let start = match on { + On::Point => Part::Dot, + On::Segment => Part::Stretch([0.0, 1.0]), + On::Triangle => Part::Polygon(Polygon::triangle()), }; - // The last bin holds the axis' upper end too. - let bin = (((v - axis[0]) / width).floor() as usize).min(bins - 1); - if let Some(b) = out.get_mut(slot).and_then(|s| s.get_mut(bin)) { - *b += m; + for (e, ids, m) in elements { + if m <= 0.0 { + continue; + } + parts.clear(); + parts.push(start); + for (k, s) in kept.iter().zip(&filtered) { + // An element without the filtered property is not filtered by it, as in the view. + let Some(s) = s else { continue }; + let f = corners(*s, e, ids, &g.world); + next.clear(); + for part in &parts { + split(part, f, k.cut, |band, q| { + if k.keeps(band) { + next.push(q); + } + }); + } + std::mem::swap(&mut parts, &mut next); + } + let pv = corners(p, e, ids, &g.world); + let colour_values = coloured.map(|s| corners(s, e, ids, &g.world)); + for part in &parts { + // A linear function is least and greatest at a part's corners. + for v in part_values(part, pv) { + if v.is_finite() { + extent = Some(extent.map_or([v, v], |[lo, hi]: [f64; 2]| [lo.min(v), hi.max(v)])); + } + } + match (colour_cut, colour_values) { + (Some(cut), Some(f)) => split(part, f, cut, |band, q| spread(&mut out, colour.slot(band), &q, pv, m)), + (Some(_), None) => spread(&mut out, plain, part, pv, m), + (None, _) => spread(&mut out, 0, part, pv, m), + } + } } } - Some(Histogram { bins, slots: out, extent }) + Some(Histogram { bins, slots: out.finish(slots), extent }) +} + +/// The values a linear function `f` takes at a part's corners. +fn part_values(part: &Part, f: [f64; 3]) -> impl Iterator + '_ { + let (ends, corners): (Option<[f64; 2]>, &[[f64; 2]]) = match part { + Part::Dot => (Some([f[0], f[0]]), &[]), + Part::Stretch([s0, s1]) => (Some([at(f, [*s0, 0.0]), at(f, [*s1, 0.0])]), &[]), + Part::Polygon(p) => (None, p.corners()), + }; + ends.into_iter().flatten().chain(corners.iter().map(move |c| at(f, *c))) } /// A range for a ramp from the values it spans: a single value gets one unit around it. @@ -225,16 +538,50 @@ pub fn color_range_by(c: &PointCloud, extent: impl FnOnce(&str, [f64; 2]) -> Opt extent(property, axis).map(ramp_range).or_else(|| c.color_range()) } -/// The values of `property` where the whole-numbered `label` changes, point after point in order -/// of `property`, lowest first. +/// Spread a part's measure (`m`, the whole element's share) over the values `f` takes on it. +fn spread(out: &mut Bins, slot: usize, part: &Part, f: [f64; 3], m: f64) { + match part { + Part::Dot => out.point(slot, f[0], m), + Part::Stretch([s0, s1]) => { + let (a, b) = (at(f, [*s0, 0.0]), at(f, [*s1, 0.0])); + out.even(slot, a.min(b), a.max(b), m * (s1 - s0)); + } + Part::Polygon(p) => { + let c = p.corners(); + let Some(first) = c.first() else { return }; + for w in c.get(1..).unwrap_or(&[]).windows(2) { + let [b, d] = [w[0], w[1]]; + // The share of the triangle's area: twice the area in its own coordinates. + let area = ((b[0] - first[0]) * (d[1] - first[1]) - (b[1] - first[1]) * (d[0] - first[0])).abs(); + let mut q = [at(f, *first), at(f, b), at(f, d)]; + q.sort_by(f64::total_cmp); + out.tent(slot, q, m * area); + } + } + } +} + +/// The values of `property` where the whole-numbered `label` changes, element after element in +/// order of `property` (each element at its smallest value, with its label there), lowest first. pub fn label_changes(c: &PointCloud, g: &Geometry, label: &str, property: &str) -> Vec { - let (Some(p), Some(l)) = (c.source(property), c.source(label)) else { return Vec::new() }; - let mut at: Vec<(f64, i64)> = (0..g.world.len()) - .filter_map(|i| { - let (v, l) = (value(p, i, &g.world), value(l, i, &g.world)); - v.is_finite().then(|| (v, if l.is_finite() { l.round() as i64 } else { i64::MIN })) - }) - .collect(); + let mut at: Vec<(f64, i64)> = Vec::new(); + for (on, elements) in kinds(c, g) { + let (Some(p), Some(l)) = (c.source(property, on), c.source(label, on)) else { continue }; + let n = match on { + On::Point => 1, + On::Segment => 2, + On::Triangle => 3, + }; + for (e, ids, _) in elements { + let (pv, lv) = (corners(p, e, ids, &g.world), corners(l, e, ids, &g.world)); + let lowest = (0..n).min_by(|i, j| pv[*i].total_cmp(&pv[*j])).unwrap_or(0); + let v = pv[lowest]; + if v.is_finite() { + let l = lv[lowest]; + at.push((v, if l.is_finite() { l.round() as i64 } else { i64::MIN })); + } + } + } at.sort_by(|a, b| a.0.total_cmp(&b.0)); let mut out: Vec = at.windows(2).filter(|w| w[0].1 != w[1].1).map(|w| w[1].0).collect(); out.dedup(); diff --git a/crates/doc/src/point_cloud_distribution_tests.rs b/crates/doc/src/point_cloud_distribution_tests.rs index cee5d0044..522475947 100644 --- a/crates/doc/src/point_cloud_distribution_tests.rs +++ b/crates/doc/src/point_cloud_distribution_tests.rs @@ -2,10 +2,10 @@ use solidcore_record::Vec3; use super::*; use crate::IDENTITY; -use crate::point_cloud::{ColorBy, Colors, Column, Complex, Floats, Points}; +use crate::point_cloud::{ColorBy, Colors, Column, Complex, Floats, Indices, Points}; -/// A cloud of `points` with `columns` on them. -fn cloud(points: &[[f32; 3]], columns: Vec) -> PointCloud { +/// A cloud of `points`, with `segments` and `triangles` between them and `columns` on them. +fn cloud(points: &[[f32; 3]], segments: &[u32], triangles: &[u32], columns: Vec) -> PointCloud { PointCloud { id: 1, name: "c".into(), @@ -21,14 +21,14 @@ fn cloud(points: &[[f32; 3]], columns: Vec) -> PointCloud { color: None, height_range: None, visible: true, - complex: Complex { columns, names: Vec::new() }, + complex: Complex { segments: Indices(segments.to_vec().into()), triangles: Indices(triangles.to_vec().into()), columns, names: Vec::new() }, color_property: None, filters: Vec::new(), } } -fn column(name: &str, integer: bool, values: &[f32]) -> Column { - Column { name: name.into(), integer, values: Floats(values.to_vec().into()) } +fn column(name: &str, on: On, integer: bool, values: &[f32]) -> Column { + Column { name: name.into(), on, integer, values: Floats(values.to_vec().into()) } } fn range(property: &str, range: [f64; 2]) -> Filter { @@ -39,27 +39,19 @@ fn close(a: &[f64], b: &[f64]) -> bool { a.len() == b.len() && a.iter().zip(b).all(|(x, y)| (x - y).abs() < 1e-9) } -/// Ten points along x, `t` the same as x. -fn row() -> PointCloud { - let points: Vec<[f32; 3]> = (0..10).map(|i| [i as f32 + 0.5, 0.0, 0.0]).collect(); - let t: Vec = points.iter().map(|p| p[0]).collect(); - cloud(&points, vec![column("t", false, &t)]) -} - #[test] -fn each_point_weighs_alike_and_a_range_keeps_those_within_it() { - let c = row(); +fn a_segment_spreads_its_length_evenly_over_what_a_range_keeps() { + // t runs 0 to 10 along a segment 10 long. + let c = cloud(&[[0.0, 0.0, 0.0], [10.0, 0.0, 0.0]], &[0, 1], &[], vec![column("t", On::Point, false, &[0.0, 10.0])]); let g = Geometry::of(&c); - let all = histogram(&c, &g, "t", [0.0, 10.0], 5, &Colour::One, &[]).unwrap(); - assert!(close(&all.slots[0], &[0.2; 5])); - // Kept from t = 2 to 5: three points, ends included. - let kept = histogram(&c, &g, "t", [0.0, 10.0], 5, &Colour::One, &[range("t", [2.0, 5.0])]).unwrap(); - assert!(close(&kept.slots[0], &[0.0, 0.2, 0.1, 0.0, 0.0])); - // Filtered by another property: x from 0 to 4 keeps t from 0 to 4. + let all = histogram(&c, &g, "t", [0.0, 10.0], 10, &Colour::One, &[]).unwrap(); + assert!(close(&all.slots[0], &[0.1; 10])); + // Kept from t = 2.5 to 5: the part is cut at the iso-values, as the view cuts it. + let kept = histogram(&c, &g, "t", [0.0, 10.0], 10, &Colour::One, &[range("t", [2.5, 5.0])]).unwrap(); + assert!(close(&kept.slots[0], &[0.0, 0.0, 0.05, 0.1, 0.1, 0.0, 0.0, 0.0, 0.0, 0.0])); + // Filtered by another property along the same segment: x from 0 to 4 keeps t from 0 to 4. let by_x = histogram(&c, &g, "t", [0.0, 10.0], 5, &Colour::One, &[range("x", [0.0, 4.0])]).unwrap(); assert!(close(&by_x.slots[0], &[0.2, 0.2, 0.0, 0.0, 0.0])); - // A filter on a property the cloud doesn't have keeps everything, as in the view. - assert_eq!(histogram(&c, &g, "t", [0.0, 10.0], 5, &Colour::One, &[range("nope", [0.0, 1.0])]), Some(all)); // An axis or a number of bins it can't have. for (axis, bins) in [([1.0, 1.0], 4), ([0.0, f64::NAN], 4), ([0.0, 1.0], 0), ([0.0, 1.0], MAX_BINS + 1)] { assert!(histogram(&c, &g, "t", axis, bins, &Colour::One, &[]).is_none()); @@ -67,37 +59,82 @@ fn each_point_weighs_alike_and_a_range_keeps_those_within_it() { } #[test] -fn colours_split_what_is_kept() { - // Four points, roles 0, 3, 3 and -1, t from 0 to 3. - let c = cloud( - &[[0.0; 3], [1.0, 0.0, 0.0], [2.0, 0.0, 0.0], [3.0, 0.0, 0.0]], - vec![column("t", false, &[0.0, 1.0, 2.0, 3.0]), column("role", true, &[0.0, 3.0, 3.0, -1.0])], - ); +fn a_triangle_spreads_its_area_as_a_tent_over_its_corners_values() { + // t is 0, 1 and 2 at the corners: the measure rises to t = 1 and falls to 2. + let c = cloud(&[[0.0, 0.0, 0.0], [1.0, 0.0, 0.0], [0.0, 1.0, 0.0]], &[], &[0, 1, 2], vec![column("t", On::Point, false, &[0.0, 1.0, 2.0])]); let g = Geometry::of(&c); - let colour = Colour::Palette { property: "role" }; - let h = histogram(&c, &g, "t", [0.0, 4.0], 4, &colour, &[]).unwrap(); - assert_eq!(h.slots.len(), colour.slots()); - assert!(close(&h.slots[0], &[0.25, 0.0, 0.0, 0.0])); - assert!(close(&h.slots[3], &[0.0, 0.25, 0.25, 0.0])); - assert!(close(&h.slots[PALETTE.len()], &[0.0, 0.0, 0.0, 0.25]), "a negative label"); - // A filter by values keeps role 3 only. - let three = Filter { property: "role".into(), keep: Keep::Values { values: vec![3] } }; - let kept = histogram(&c, &g, "t", [0.0, 4.0], 4, &colour, &[three]).unwrap(); - let total: f64 = kept.slots.iter().flatten().sum(); - assert!((total - 0.5).abs() < 1e-9 && close(&kept.slots[3], &h.slots[3])); - // A ramp over t in two bands, and coloured by a property the cloud doesn't have: plain. - let ramp = Colour::Ramp { property: "t", range: [0.0, 4.0], bands: 2 }; - let r = histogram(&c, &g, "t", [0.0, 4.0], 4, &ramp, &[]).unwrap(); - assert!(close(&r.slots[0], &[0.25, 0.25, 0.0, 0.0]) && close(&r.slots[1], &[0.0, 0.0, 0.25, 0.25])); - let none = histogram(&c, &g, "t", [0.0, 4.0], 4, &Colour::Palette { property: "nope" }, &[]).unwrap(); - assert!(close(&none.slots[PALETTE.len() + 1], &[0.25; 4])); + let h = histogram(&c, &g, "t", [0.0, 2.0], 4, &Colour::One, &[]).unwrap(); + // The distribution function: x²/2 up to 1, then 1 − (2 − x)²/2. + assert!(close(&h.slots[0], &[0.125, 0.375, 0.375, 0.125])); + // Cut at t ≤ 1: half the area is left, all below 1. + let half = histogram(&c, &g, "t", [0.0, 2.0], 4, &Colour::One, &[range("t", [0.0, 1.0])]).unwrap(); + assert!(close(&half.slots[0], &[0.125, 0.375, 0.0, 0.0])); + // Cut by x across t: the part where x ≤ 0.5, its area 3/4 of the triangle's. + let x = histogram(&c, &g, "t", [0.0, 2.0], 1, &Colour::One, &[range("x", [0.0, 0.5])]).unwrap(); + assert!(close(&x.slots[0], &[0.75])); } #[test] -fn labels_change_where_the_next_point_has_another() { - // Six points in order of t, layers 0 0 1 1 2 2. +fn kinds_weigh_alike_and_colours_split_what_is_kept() { + // Two segments, roles 0 and 3, and a dot; t along each segment, the dot at t = 5. + let c = cloud( + &[[0.0, 0.0, 0.0], [1.0, 0.0, 0.0], [1.0, 0.0, 0.0], [4.0, 0.0, 0.0], [9.0, 9.0, 9.0]], + &[0, 1, 2, 3], + &[], + vec![ + column("t", On::Point, false, &[0.0, 1.0, 1.0, 4.0, 5.0]), + column("role", On::Segment, true, &[0.0, 3.0]), + column("role", On::Point, true, &[0.0, 0.0, 0.0, 0.0, 2.0]), + ], + ); + let g = Geometry::of(&c); + let colour = Colour::Palette { property: "role" }; + let h = histogram(&c, &g, "t", [0.0, 5.0], 5, &colour, &[]).unwrap(); + assert_eq!(h.slots.len(), colour.slots()); + // The segments share their kind's 1 by length (1 and 3), the dot has its kind's 1. + assert!(close(&h.slots[0], &[0.25, 0.0, 0.0, 0.0, 0.0])); + assert!(close(&h.slots[3], &[0.0, 0.25, 0.25, 0.25, 0.0])); + assert!(close(&h.slots[2], &[0.0, 0.0, 0.0, 0.0, 1.0])); + // A filter by values keeps role 3 only; the dot has a role too and is left out. + let three = Filter { property: "role".into(), keep: Keep::Values { values: vec![3] } }; + let kept = histogram(&c, &g, "t", [0.0, 5.0], 5, &colour, &[three]).unwrap(); + let total: f64 = kept.slots.iter().flatten().sum(); + assert!((total - 0.75).abs() < 1e-9 && close(&kept.slots[3], &h.slots[3])); + // A ramp over t in two bands splits the long segment where t crosses 2.5. + let ramp = Colour::Ramp { property: "t", range: [0.0, 5.0], bands: 2 }; + let r = histogram(&c, &g, "t", [0.0, 5.0], 5, &ramp, &[]).unwrap(); + assert!(close(&r.slots[0], &[0.25, 0.25, 0.125, 0.0, 0.0]) && close(&r.slots[1], &[0.0, 0.0, 0.125, 0.25, 1.0])); +} + +#[test] +fn a_ramp_of_the_most_bands_keeps_all_of_an_element() { + // Across every band of the finest ramp the API accepts, nothing is lost: a segment and a + // triangle, within the ramp and running past both its ends. + let t = |values: &[f32]| vec![column("t", On::Point, false, values)]; + let ramp = Colour::Ramp { property: "t", range: [0.0, 1.0], bands: MAX_BINS }; + for c in [ + cloud(&[[0.0, 0.0, 0.0], [1.0, 0.0, 0.0]], &[0, 1], &[], t(&[0.0, 1.0])), + cloud(&[[0.0, 0.0, 0.0], [1.0, 0.0, 0.0], [0.0, 1.0, 0.0]], &[], &[0, 1, 2], t(&[0.0, 1.0, 0.5])), + cloud(&[[0.0, 0.0, 0.0], [1.0, 0.0, 0.0]], &[0, 1], &[], t(&[-0.5, 1.5])), + cloud(&[[0.0, 0.0, 0.0], [1.0, 0.0, 0.0], [0.0, 1.0, 0.0]], &[], &[0, 1, 2], t(&[-0.5, 1.5, 0.5])), + ] { + let g = Geometry::of(&c); + let h = histogram(&c, &g, "t", [-1.0, 2.0], 4, &ramp, &[]).unwrap(); + let total: f64 = h.slots.iter().flatten().sum(); + assert!((total - 1.0).abs() < 1e-9, "{total}"); + } +} + +#[test] +fn labels_change_where_the_next_element_has_another() { + // Five segments in order of t, layers 0 0 1 1 2. let points: Vec<[f32; 3]> = (0..6).map(|i| [i as f32, 0.0, 0.0]).collect(); - let c = cloud(&points, vec![column("t", false, &[0.0, 1.0, 2.0, 3.0, 4.0, 5.0]), column("layer", true, &[0.0, 0.0, 1.0, 1.0, 2.0, 2.0])]); + let c = cloud( + &points, + &[0, 1, 1, 2, 2, 3, 3, 4, 4, 5], + &[], + vec![column("t", On::Point, false, &[0.0, 1.0, 2.0, 3.0, 4.0, 5.0]), column("layer", On::Segment, true, &[0.0, 0.0, 1.0, 1.0, 2.0])], + ); let g = Geometry::of(&c); assert_eq!(label_changes(&c, &g, "layer", "t"), vec![2.0, 4.0]); assert!(label_changes(&c, &g, "nope", "t").is_empty()); @@ -105,21 +142,21 @@ fn labels_change_where_the_next_point_has_another() { #[test] fn the_automatic_range_is_what_every_filter_keeps() { - // Filtered by x from 2 to 4, coloured by t: the range is what is kept of t, though no filter - // is on t (its span within filters on t would be all of it). - let mut c = cloud(&[[0.0, 0.0, 0.0], [2.0, 0.0, 0.0], [4.0, 0.0, 0.0], [20.0, 0.0, 0.0]], vec![column("t", false, &[0.0, 3.0, 5.0, 7.0])]); + // t runs 0 to 10 along x; filtered by x from 2 to 4, coloured by t: the range is 2 to 4, + // though no filter is on t (its span within filters on t would be 0 to 10). + let mut c = cloud(&[[0.0, 0.0, 0.0], [10.0, 0.0, 0.0], [20.0, 0.0, 0.0]], &[0, 1], &[], vec![column("t", On::Point, false, &[0.0, 10.0, 7.0])]); c.color_by = ColorBy::Property; c.color_property = Some("t".into()); let g = Geometry::of(&c); let x = [range("x", [2.0, 4.0])]; - assert_eq!(c.color_range(), Some([0.0, 7.0])); - assert_eq!(color_range(&c, &g, &x), Some([3.0, 5.0])); - // The point at x = 20 alone: one value, one unit wide. + assert_eq!(c.color_range(), Some([0.0, 10.0])); + assert_eq!(color_range(&c, &g, &x), Some([2.0, 4.0])); + // The dot at x = 20 is kept by nothing; by itself it would be one value, one unit wide. assert_eq!(color_range(&c, &g, &[range("x", [19.0, 21.0])]), Some([6.5, 7.5])); // Nothing kept: the cloud's own bound; a range set is kept as it is. - assert_eq!(color_range(&c, &g, &[range("x", [50.0, 60.0])]), Some([0.0, 7.0])); + assert_eq!(color_range(&c, &g, &[range("x", [50.0, 60.0])]), Some([0.0, 10.0])); c.height_range = Some([1.0, 2.0]); assert_eq!(color_range(&c, &g, &x), Some([1.0, 2.0])); let h = histogram(&c, &g, "t", [0.0, 1.0], 4, &Colour::One, &x).unwrap(); - assert_eq!(h.extent, Some([3.0, 5.0]), "the extent reaches past the axis"); + assert_eq!(h.extent, Some([2.0, 4.0]), "the extent reaches past the axis"); } diff --git a/crates/engine/src/cmd/point_cloud.rs b/crates/engine/src/cmd/point_cloud.rs index 78bfb0283..9bb560bce 100644 --- a/crates/engine/src/cmd/point_cloud.rs +++ b/crates/engine/src/cmd/point_cloud.rs @@ -15,7 +15,7 @@ pub static COMMANDS: &[CommandSpec] = &[ CommandSpec::new("pointcloud.insert", "Insert Point Cloud", insert) .at("SOLID", "INSERT") .icon("import") - .params("path: .ply, .xyz or .pts file (its points join the design as a point cloud: drawn as points, never a body; a PLY's red, green and blue are its colours, its other vertex properties can colour and filter it) → cloud, name, points, source_points, bounds, warnings; name?; units?: mm|cm|m|in|ft (the file's length unit, default mm); max_points?: most points kept (default 5000000, at most 20000000; a larger file is thinned evenly); center?: bool (move the cloud so the middle of its base sits at the origin); point_size?: pixels (0.5…16, default 2); color_by?: file|single|height or a property's name (the file's colours, the default; one colour; a ramp by height, blue low to red high; or by any property of the file, a ramp over its values or a palette for whole numbers); color?: [r, g, b] 0…1 (the single colour; given alone it sets color_by single, null sets color_by file); color_range?: [low, high] the ramp runs between (design Z in mm by height), or null for the automatic range (by height all but the lowest and highest 2 % of the points; by a property the values it takes over what the filters keep); height_range?: the same as color_range; filters?: [{property, range: [low, high]} or {property, values: [whole numbers]} for a property with named values], or null (only what every filter keeps is shown)"), + .params("path: .ply, .xyz or .pts file (its points join the design as a point cloud: drawn as points, never a body; a PLY's red, green and blue are its colours, its other properties can colour and filter it; its edge and face elements become segments and triangles, a segment with width and height properties drawn as a bead) → cloud, name, points, segments, triangles, source_points, bounds, warnings; name?; units?: mm|cm|m|in|ft (the file's length unit, default mm); max_points?: most points kept (default 5000000, at most 20000000; a larger file is thinned evenly); center?: bool (move the cloud so the middle of its base sits at the origin); point_size?: pixels (0.5…16, default 2); color_by?: file|single|height or a property's name (the file's colours, the default; one colour; a ramp by height, blue low to red high; or by any property of the file, a ramp over its values or a palette for whole numbers); color?: [r, g, b] 0…1 (the single colour; given alone it sets color_by single, null sets color_by file); color_range?: [low, high] the ramp runs between (design Z in mm by height), or null for the automatic range (by height all but the lowest and highest 2 % of the points; by a property the values it takes over what the filters keep); height_range?: the same as color_range; filters?: [{property, range: [low, high]} or {property, values: [whole numbers]} for a property with named values], or null (only what every filter keeps is shown)"), CommandSpec::new("pointcloud.edit", "Edit Point Cloud", edit) .icon("edit") .params("cloud: id or name; name?; visible?; point_size?: pixels (0.5…16); color_by?: file|single|height or a property's name (the file's colours, the default; one colour; a ramp by height, blue low to red high; or by any property of the file, a ramp over its values or a palette for whole numbers); color?: [r, g, b] 0…1 (the single colour; given alone it sets color_by single, null sets color_by file); color_range?: [low, high] the ramp runs between (design Z in mm by height), or null for the automatic range (by height all but the lowest and highest 2 % of the points; by a property the values it takes over what the filters keep); height_range?: the same as color_range; units?: mm|cm|m|in|ft (the file's length unit: the points are scaled from the unit they came in as); matrix?: [12 or 16 numbers] (where the cloud sits: a rigid row-major 3x4 or 4x4 matrix, as occurrence.move takes it); tolerance?; filters?: [{property, range: [low, high]} or {property, values: [whole numbers]} for a property with named values], or null (only what every filter keeps is shown) → cloud"), @@ -24,7 +24,7 @@ pub static COMMANDS: &[CommandSpec] = &[ .icon("list") .noundo() .doc_only() - .params("→ clouds: [{cloud, name, file, points, source_points, units, visible, point_size, color_by (file, single, height or a property's name), color, colored, properties: [{name, integer, span, names}], filters, color_range (the ramp's now, exact over what the filters keep), height_range (the ramp's own range or the automatic one by height), height_auto, bounds: [[x,y,z], [x,y,z]] in the design, matrix}]"), + .params("→ clouds: [{cloud, name, file, points, segments, triangles, source_points, units, visible, point_size, color_by (file, single, height or a property's name), color, colored, properties: [{name, integer, span, names}], filters, color_range (the ramp's now, exact over what the filters keep), height_range (the ramp's own range or the automatic one by height), height_auto, bounds: [[x,y,z], [x,y,z]] in the design, matrix}]"), ]; fn units_of(p: &Value, cmd: &str) -> Result> { @@ -205,13 +205,7 @@ fn insert(s: &mut Session, p: &Value) -> Result { let center = bool_(p, "center").unwrap_or(false); let bytes = solidcraft_io::vfs::read(path, solidcraft_io::MAX_POINT_CLOUD_BYTES).map_err(|e| EngineError::Other(format!("{path}: {e}")))?; let read = solidcraft_io::read_point_cloud(&bytes, path, scale, max_points).map_err(|e| EngineError::Other(format!("{path}: {e}")))?; - let mut warnings = read.warnings; - if solidcraft_io::is_ply_path(path) - && let Ok((_, faces)) = solidcraft_io::ply_counts(&bytes) - && faces > 0 - { - warnings.push(format!("the file also has {faces} faces: Insert Mesh (file.insert_mesh) reads it as a mesh")); - } + let warnings = read.warnings; drop(bytes); let file = std::path::Path::new(path).file_name().map(|n| n.to_string_lossy().to_string()).unwrap_or_else(|| path.to_string()); let stem = std::path::Path::new(path).file_stem().map(|n| n.to_string_lossy().trim().to_string()).filter(|n| !n.is_empty()); @@ -252,6 +246,8 @@ fn insert(s: &mut Session, p: &Value) -> Result { "cloud": id, "name": name, "points": cloud.len(), + "segments": cloud.complex.segment_count(), + "triangles": cloud.complex.triangle_count(), "source_points": cloud.source_points, "bounds": bounds(&cloud), "warnings": warnings, @@ -344,6 +340,8 @@ fn list(s: &mut Session, _: &Value) -> Result { "visible": c.visible, "point_size": c.point_size, "color_by": c.colored_property().filter(|_| c.color_by == ColorBy::Property).unwrap_or(c.color_by.name()), + "segments": c.complex.segment_count(), + "triangles": c.complex.triangle_count(), "properties": c .property_names() .map(|n| json!({"name": n, "integer": c.complex.integer(n), "span": c.span(n), "names": c.complex.names(n).map(|m| &m.values)})) diff --git a/crates/gpu/src/view.rs b/crates/gpu/src/view.rs index 07ff5a798..e8883b9c8 100644 --- a/crates/gpu/src/view.rs +++ b/crates/gpu/src/view.rs @@ -20,7 +20,7 @@ use wgpu::util::DeviceExt; mod ao; pub use ao::GroundAo; mod clouds; -pub use clouds::{CloudFilter, CloudStyle, ColorMode, DOT_SIZE, Dot, FILTERS, GpuCloud, cloud_dot}; +pub use clouds::{CELL_SIZE, Cell, CloudFilter, CloudStyle, ColorMode, FILTERS, GpuCloud, cloud_cell}; #[cfg(not(target_arch = "wasm32"))] mod msaa_check; mod oit; @@ -1035,7 +1035,7 @@ pub struct Frame { pub cap: [f32; 4], /// Canvases and decals. pub images: Vec, - /// Point clouds. + /// Point clouds and their cells. pub clouds: Vec, /// Surface analysis: (mode: 0 none, 1 zebra, 2 draft, 3 curvature, 4 environment, /// 5 accessibility; parameter; scale; size) and the pull / access direction. @@ -5265,19 +5265,30 @@ mod glass_tests { let format = wgpu::TextureFormat::Rgba8Unorm; let mut renderer = Renderer::new(&device, GpuTarget { format, depth: Some(depth), samples: 1, tess: false, oit: false }, None); let mut frame = test_frame(GpuScene::default(), 2.0); - // A dot labelled 2 (red in the palette) and a dot filtered by 5 (a range) and the label - // 2 (a set). + // A dot (labelled 2, red in the palette) and a bead across the view, filtered by 5 (a + // range) and the label 2 (a set). let mut dots = Vec::new(); - cloud_dot(&mut dots, &Dot { at: [5.0, 5.0, 0.0], rgb: [0, 0, 255], value: 2.0, has: 16, ..Default::default() }); - let filtered = Dot { at: [-3.0, -3.0, 0.0], value: 1.0, filtered: [5.0, 2.0, 0.0, 0.0], rgb: [0, 255, 0], has: 0b10011 }; - cloud_dot(&mut dots, &filtered); + cloud_cell(&mut dots, &Cell { corners: [[5.0, 5.0, 0.0]; 3], rgb: [0, 0, 255], value: [2.0; 3], has: 16, ..Default::default() }); + let mut segments = Vec::new(); + let ends = [[-3.0, -3.0, 0.0], [3.0, -3.0, 0.0], [3.0, -3.0, 0.0]]; + let bead = Cell { + corners: ends, + value: [1.0; 3], + filtered: [[5.0; 3], [2.0; 3], [0.0; 3], [0.0; 3]], + size: [0.2, 0.2], + rgb: [0, 255, 0], + has: 0b10011, + ..Default::default() + }; + cloud_cell(&mut segments, &bead); let style = CloudStyle { mode: ColorMode::Own, range: [0.0, 1.0], filters: Default::default(), point_size: 20.0 }; - frame.clouds.push(GpuCloud { id: 1, version: 1, dots: Arc::new(dots), style }); + let empty = Arc::new(Vec::new()); + frame.clouds.push(GpuCloud { id: 1, version: 1, dots: Arc::new(dots), segments: Arc::new(segments), triangles: empty, style }); let has = |img: &[u8], f: &dyn Fn(&[u8; 4]) -> bool| img.as_chunks::<4>().0.iter().any(f); let green = |p: &[u8; 4]| p[1] > 120 && p[0] < 30 && p[2] < 30; let own = render_frame(&mut renderer, &device, &queue, &frame, true); - assert!(has(&own, &|p| p[2] > 200 && p[0] < 30), "a dot in its own colour"); - assert!(has(&own, &green), "the other in its own colour"); + assert!(has(&own, &|p| p[2] > 200 && p[0] < 30), "the dot in its own colour"); + assert!(has(&own, &green), "the bead in its own colour"); // Values from -1: bit 3 is the label 2, bit 2 the label 1. frame.clouds[0].style.filters[1] = CloudFilter::Values { offset: -1, mask: 0b1000 }; assert!(has(&render_frame(&mut renderer, &device, &queue, &frame, true), &green), "label 2 kept"); @@ -5287,13 +5298,102 @@ mod glass_tests { frame.clouds[0].style.filters[0] = CloudFilter::Range([0.0, 4.0]); frame.clouds[0].style.mode = ColorMode::Palette; let filtered = render_frame(&mut renderer, &device, &queue, &frame, true); - assert!(!has(&filtered, &green), "its 5 lies outside the range"); - assert!(has(&filtered, &|p| p[0] > 200 && p[1] < 90 && p[2] < 90), "the first, without that value, in the palette's red"); + assert!(!has(&filtered, &green), "the bead's 5 lies outside the range"); + assert!(has(&filtered, &|p| p[0] > 200 && p[1] < 90 && p[2] < 90), "the dot, without that value, in the palette's red"); frame.clouds.clear(); let hidden = render_frame(&mut renderer, &device, &queue, &frame, true); assert!(!has(&hidden, &|p| p[0] > 200 && p[1] < 90 && p[2] < 90), "hiding the cloud removes it"); } + /// A set of values keeps the part of a bead where its rounded value is kept, as the range + /// tracks measure it, whichever end holds the kept value: the first end's value alone does + /// not decide for the whole bead. + #[test] + fn a_set_filter_keeps_the_part_of_a_bead_whose_ends_differ() { + let Some((_, device, queue)) = crate::open_headless().ok() else { return }; + let depth = crate::depth_format(&device, true); + let format = wgpu::TextureFormat::Rgba8Unorm; + let target = GpuTarget { format, depth: Some(depth), samples: 1, tess: false, oit: false }; + let mut renderer = Renderer::new(&device, target, None); + let mut draw = |version: u64, at_start: f32, at_end: f32, mask: u32| { + let mut frame = test_frame(GpuScene::default(), 1.0); + let ends = [[-3.0, -3.0, 0.0], [3.0, -3.0, 0.0], [3.0, -3.0, 0.0]]; + let bead = Cell { + corners: ends, + neighbours: [ends[0], ends[1]], + filtered: [[at_start, at_end, at_end], [0.0; 3], [0.0; 3], [0.0; 3]], + size: [0.5, 0.5], + rgb: [0, 255, 0], + has: 1, + ..Default::default() + }; + let mut segments = Vec::new(); + cloud_cell(&mut segments, &bead); + let mut filters: [CloudFilter; 4] = Default::default(); + filters[0] = CloudFilter::Values { offset: 0, mask }; + let style = CloudStyle { mode: ColorMode::Own, range: [0.0, 1.0], filters, point_size: 1.0 }; + let empty = Arc::new(Vec::new()); + frame.clouds.push(GpuCloud { id: 1, version, dots: empty.clone(), segments: Arc::new(segments), triangles: empty, style }); + let img = render_frame(&mut renderer, &device, &queue, &frame, true); + // The 64 by 64 picture, split down the middle. + let side = + |left: bool| img.as_chunks::<4>().0.iter().enumerate().any(|(i, p)| (i % 64 < 32) == left && p[1] > 60 && p[0] < 30 && p[2] < 30); + (side(true), side(false)) + }; + assert_eq!(draw(1, 0.0, 1.0, 0b10), (false, true), "1 is kept at the end only: the half towards the end"); + assert_eq!(draw(2, 1.0, 0.0, 0b10), (true, false), "1 is kept at the start only: the half towards the start"); + assert_eq!(draw(3, 0.0, 1.0, 0b11), (true, true), "both kept: the whole bead"); + assert_eq!(draw(4, 0.0, 1.0, 0b100), (false, false), "neither kept: nothing"); + assert_eq!(draw(5, 1.0, 1.0, 0b01), (false, false), "the same value at both ends, not kept: nothing"); + } + + /// A floor and a bead on it, one end far off to the side behind the eye: each is cut exactly at + /// the near plane. So what lies ahead shows where the perspective puts it, and nothing is + /// drawn straight below the eye, where an end moved to a made-up place would pull a wedge. + #[test] + fn a_cloud_element_crossing_the_near_plane_is_cut_there() { + let Some((_, device, queue)) = crate::open_headless().ok() else { return }; + let depth = crate::depth_format(&device, true); + let format = wgpu::TextureFormat::Rgba8Unorm; + let target = GpuTarget { format, depth: Some(depth), samples: 1, tess: false, oit: false }; + let mut renderer = Renderer::new(&device, target, None); + // Looking along -z from the origin: a point shows at x/d, y/d at distance d = -z. + let (near, far) = (0.1f32, 1000.0f32); + let (a, b) = (-far / (far - near), -far * near / (far - near)); + let view_proj = [[1.0, 0.0, 0.0, 0.0], [0.0, 1.0, 0.0, 0.0], [0.0, 0.0, a, -1.0], [0.0, 0.0, b, 0.0]]; + let mut draw = |version: u64, segments: Vec, triangles: Vec| { + let mut frame = test_frame(GpuScene::default(), 1.0); + frame.view_proj = view_proj; + let style = CloudStyle { mode: ColorMode::Own, range: [0.0, 1.0], filters: Default::default(), point_size: 1.0 }; + let dots = Arc::new(Vec::new()); + frame.clouds.push(GpuCloud { id: 1, version, dots, segments: Arc::new(segments), triangles: Arc::new(triangles), style }); + render_frame(&mut renderer, &device, &queue, &frame, true) + }; + // Green at pixel `x` of row `y`, counted from the top of the 64 by 64 picture. + let green = + |img: &[u8], x: usize, y: usize| img.get((y * 64 + x) * 4..(y * 64 + x) * 4 + 3).is_some_and(|p| p[1] > 60 && p[0] < 30 && p[2] < 30); + // Pixel 47 of row 43 is (0.48, -0.36). On y = -1 that is 2.78 away, where the path from + // (0, -1, -3) to (40, -1, 3) has come to x = 1.47: x/d = 0.53, within the floor (0.18 to + // 0.87 there) and the bead. Pixel 32 of row 56 is (0.0, -0.77): by that distance both have + // gone far off to the right. + let (ahead, below) = ((47, 43), (32, 56)); + + let mut triangles = Vec::new(); + let floor = [[-1.0, -1.0, -3.0], [1.0, -1.0, -3.0], [40.0, -1.0, 3.0]]; + cloud_cell(&mut triangles, &Cell { corners: floor, rgb: [0, 255, 0], ..Default::default() }); + let img = draw(1, Vec::new(), triangles); + assert!(green(&img, ahead.0, ahead.1), "the floor ahead"); + assert!(!green(&img, below.0, below.1), "no wedge of floor below the eye"); + + let (start, end) = ([40.0, -1.0, 3.0], [0.0, -1.0, -3.0]); + let mut segments = Vec::new(); + let bead = Cell { corners: [start, end, end], neighbours: [start, end], size: [0.5, 0.5], rgb: [0, 255, 0], ..Default::default() }; + cloud_cell(&mut segments, &bead); + let img = draw(2, segments, Vec::new()); + assert!(green(&img, ahead.0, ahead.1), "the bead ahead"); + assert!(!green(&img, below.0, below.1), "no wedge of bead below the eye"); + } + /// A still view shows the picture it drew last: a reused frame (whose filtered picture is /// cached once) draws the same pixels as the frame before it, and changing the camera draws /// again rather than keeping the cached picture. diff --git a/crates/gpu/src/view/clouds.rs b/crates/gpu/src/view/clouds.rs index 52c0f05a7..e7dd5d817 100644 --- a/crates/gpu/src/view/clouds.rs +++ b/crates/gpu/src/view/clouds.rs @@ -1,8 +1,8 @@ -//! Point clouds: each point a round dot a few pixels across, facing the screen, depth-tested and -//! written like the model's faces. Every point is uploaded once, with the values it is coloured -//! and filtered by; how they are coloured and which are shown is a [`CloudStyle`] of a few -//! numbers the shaders read, so a new colour range or filter range draws again at once without -//! uploading anything. +//! Point clouds and the cells between their points: dots, segments drawn as beads (or lines when +//! they have no size), and triangles. Every element is uploaded once, as one record of a single +//! layout whatever its kind; how they are coloured and which are shown is a [`CloudStyle`] of a +//! few numbers the shaders read, so a new colour range or filter range draws again at once +//! without uploading anything. use std::sync::Arc; @@ -14,18 +14,21 @@ pub struct GpuCloud { pub id: u64, /// Changes when the records change (they are uploaded again). pub version: u64, - /// [`DOT_SIZE`] bytes per point, written by [`cloud_dot`]. + /// [`CELL_SIZE`] bytes per element, written by [`cloud_cell`]: the points drawn as dots, + /// the segments and the triangles. pub dots: Arc>, + pub segments: Arc>, + pub triangles: Arc>, pub style: CloudStyle, } -/// How a cloud is coloured and which of its points are shown. +/// How a cloud is coloured and which of its elements are shown. #[derive(Clone, Copy, Debug, Default, PartialEq)] pub struct CloudStyle { pub mode: ColorMode, /// The ramp's range of values. pub range: [f32; 2], - /// A point is shown where every filter keeps its filtered value. + /// An element is shown where every filter keeps its filtered value. pub filters: [CloudFilter; FILTERS], /// A dot's size on screen, in pixels. pub point_size: f32, @@ -46,10 +49,10 @@ pub enum CloudFilter { Values { offset: i32, mask: u32 }, } -/// Where a point's colour comes from. +/// Where an element's colour comes from. #[derive(Clone, Copy, Debug, Default, PartialEq, Eq)] pub enum ColorMode { - /// Its own colour ([`Dot::rgb`]). + /// Its own colour ([`Cell::rgb`]). #[default] Own, /// The ramp over [`CloudStyle::range`] at its value. @@ -58,32 +61,64 @@ pub enum ColorMode { Palette, } -/// One point: where it is, the coloured value and the four filtered values, its own colour, and -/// which of the four filters and the value it has (bits 0 to 3, and 4, of `has`). +/// One element: its corners (a point repeats its own, a segment its second), the coloured value +/// and the four filtered values at each corner, a bead's width and height (zero: a line), its own +/// colour, and which of the four filters and the value it has (bits 0 to 3, and 4, of `has`). A +/// segment also has the points before and after it on its bead (its own ends where it has none), +/// so that two beads meet in the plane halfway between their directions. #[derive(Clone, Copy, Debug, Default, PartialEq)] -pub struct Dot { - pub at: [f32; 3], - pub value: f32, - pub filtered: [f32; FILTERS], +pub struct Cell { + pub corners: [[f32; 3]; 3], + pub neighbours: [[f32; 3]; 2], + pub value: [f32; 3], + pub filtered: [[f32; 3]; FILTERS], + pub size: [f32; 2], pub rgb: [u8; 3], pub has: u8, } -/// Bytes per [`Dot`]. -pub const DOT_SIZE: usize = 36; +/// Bytes per [`Cell`]. +pub const CELL_SIZE: usize = 132; -/// Append a dot's record. -pub fn cloud_dot(out: &mut Vec, d: &Dot) { - for v in d.at.iter().chain([&d.value]).chain(&d.filtered) { +/// Append a cell's record. +pub fn cloud_cell(out: &mut Vec, c: &Cell) { + let floats = c.corners.iter().flatten().chain(c.neighbours.iter().flatten()).chain(&c.value).chain(c.filtered.iter().flatten()).chain(&c.size); + for v in floats { out.extend_from_slice(&v.to_le_bytes()); } - out.extend_from_slice(&d.rgb); - out.push(d.has); + out.extend_from_slice(&c.rgb); + out.push(c.has); } -fn dot_layout() -> wgpu::VertexBufferLayout<'static> { - const A: [wgpu::VertexAttribute; 4] = wgpu::vertex_attr_array![0 => Float32x3, 1 => Float32, 2 => Float32x4, 3 => Unorm8x4]; - wgpu::VertexBufferLayout { array_stride: DOT_SIZE as u64, step_mode: wgpu::VertexStepMode::Instance, attributes: &A } +fn cell_layout() -> wgpu::VertexBufferLayout<'static> { + const A: [wgpu::VertexAttribute; 12] = wgpu::vertex_attr_array![ + 0 => Float32x3, 1 => Float32x3, 2 => Float32x3, 8 => Float32x3, 9 => Float32x3, + 3 => Float32x3, 4 => Float32x3, 5 => Float32x3, 10 => Float32x3, 11 => Float32x3, + 6 => Float32x2, 7 => Unorm8x4 + ]; + wgpu::VertexBufferLayout { array_stride: CELL_SIZE as u64, step_mode: wgpu::VertexStepMode::Instance, attributes: &A } +} + +/// Corners of a bead's cross-section: a stadium, each half-disc in four chords. +const SIDES: u32 = 10; +/// What each pipeline draws: the records of which kind, and vertices per record. A bead's are +/// indexed into its [`SIDES`] corners at each end, so each is worked out once: its sides, then +/// its two ends closed by fans of triangles. +const DRAWS: [(usize, u32); 3] = [(0, 6), (1, SIDES * 6 + 2 * (SIDES - 2) * 3), (2, 3)]; + +/// The bead as indices into its corners: corner `j` at its start is `j`, at its end `SIDES + j`. +/// Side `q` is the quad between corners `q` and `q + 1` at both ends. The corners turn +/// counter-clockwise seen from ahead, so every triangle turns counter-clockwise seen from +/// outside: the inside faces away and is not drawn. +fn bead_indices() -> Vec { + let n = SIDES as u16; + let sides = (0..n).flat_map(|q| { + let r = (q + 1) % n; + [q, r, n + r, q, n + r, n + q] + }); + let start = (1..n - 1).flat_map(|j| [0, j + 1, j]); + let end = (1..n - 1).flat_map(move |j| [n, n + j, n + j + 1]); + sides.chain(start).chain(end).collect() } /// The uniform a cloud's style is written to, bytes: the colouring, then a `vec4` per filter. @@ -111,10 +146,11 @@ fn style_bytes(s: &CloudStyle) -> [u8; STYLE_SIZE as usize] { out } -/// The pipeline that draws clouds' dots, and the layout of their styles. +/// The pipelines that draw clouds: dots, segments and triangles. pub(super) struct CloudPipes { layout: wgpu::BindGroupLayout, - dots: wgpu::RenderPipeline, + pipes: [wgpu::RenderPipeline; 3], + bead: wgpu::Buffer, } impl CloudPipes { @@ -139,35 +175,41 @@ impl CloudPipes { bind_group_layouts: &[Some(viewport), Some(&layout)], immediate_size: 0, }); - let dots = device.create_render_pipeline(&wgpu::RenderPipelineDescriptor { - label: Some("vs_cloud_dot"), - layout: Some(&pipeline_layout), - vertex: wgpu::VertexState { - module, - entry_point: Some("vs_cloud_dot"), - buffers: &[Some(dot_layout())], - compilation_options: Default::default(), - }, - primitive: wgpu::PrimitiveState { topology: wgpu::PrimitiveTopology::TriangleList, ..Default::default() }, - depth_stencil: depth, - multisample: wgpu::MultisampleState { count: target.samples.max(1), mask: !0, alpha_to_coverage_enabled: false }, - fragment: Some(wgpu::FragmentState { - module, - entry_point: Some("fs_cloud"), - targets: &[Some(wgpu::ColorTargetState { format: target.format, blend: None, write_mask: wgpu::ColorWrites::ALL })], - compilation_options: Default::default(), - }), - multiview_mask: None, - cache: None, - }); - CloudPipes { layout, dots } + let pipe = |vs: &str, cull: Option| { + device.create_render_pipeline(&wgpu::RenderPipelineDescriptor { + label: Some(vs), + layout: Some(&pipeline_layout), + vertex: wgpu::VertexState { module, entry_point: Some(vs), buffers: &[Some(cell_layout())], compilation_options: Default::default() }, + primitive: wgpu::PrimitiveState { topology: wgpu::PrimitiveTopology::TriangleList, cull_mode: cull, ..Default::default() }, + depth_stencil: depth.clone(), + multisample: wgpu::MultisampleState { count: target.samples.max(1), mask: !0, alpha_to_coverage_enabled: false }, + fragment: Some(wgpu::FragmentState { + module, + entry_point: Some("fs_cloud"), + targets: &[Some(wgpu::ColorTargetState { format: target.format, blend: None, write_mask: wgpu::ColorWrites::ALL })], + compilation_options: Default::default(), + }), + multiview_mask: None, + cache: None, + }) + }; + let indices: Vec = bead_indices().iter().flat_map(|i| i.to_le_bytes()).collect(); + let bead = wgpu::util::DeviceExt::create_buffer_init( + device, + &wgpu::util::BufferInitDescriptor { label: Some("sc_cloud_bead"), contents: &indices, usage: wgpu::BufferUsages::INDEX }, + ); + CloudPipes { + pipes: [pipe("vs_cloud_dot", None), pipe("vs_cloud_segment", Some(wgpu::Face::Back)), pipe("vs_cloud_triangle", None)], + layout, + bead, + } } } -/// A cloud on the GPU: its dots and its style's uniform. +/// A cloud on the GPU: its records by kind and its style's uniform. struct Uploaded { version: u64, - dots: Option, + kinds: [Option; 3], style: wgpu::Buffer, bind: wgpu::BindGroup, } @@ -193,8 +235,8 @@ impl CloudDraws { layout: &pipes.layout, entries: &[wgpu::BindGroupEntry { binding: 3, resource: style.as_entire_binding() }], }); - let dots = upload(device, "sc_cloud", &c.dots, DOT_SIZE); - self.0.insert(c.id, Uploaded { version: c.version, dots, style, bind }); + let kinds = [&c.dots, &c.segments, &c.triangles].map(|bytes| upload(device, "sc_cloud", bytes, CELL_SIZE)); + self.0.insert(c.id, Uploaded { version: c.version, kinds, style, bind }); } if let Some(u) = self.0.get(&c.id) { queue.write_buffer(&u.style, 0, &style_bytes(&c.style)); @@ -204,13 +246,20 @@ impl CloudDraws { pub(super) fn paint(&self, pass: &mut wgpu::RenderPass<'_>, pipes: &CloudPipes, tally: &Tally) { for u in self.0.values() { - let Some(batch) = &u.dots else { continue }; pass.set_bind_group(1, &u.bind, &[]); - pass.set_pipeline(&pipes.dots); - for (buffer, count) in &batch.parts { - pass.set_vertex_buffer(0, buffer.slice(..)); - pass.draw(0..6, 0..*count); - tally.triangles(6, *count); + for (pipe, (kind, vertices)) in pipes.pipes.iter().zip(DRAWS) { + let Some(Some(batch)) = u.kinds.get(kind) else { continue }; + pass.set_pipeline(pipe); + for (buffer, count) in &batch.parts { + pass.set_vertex_buffer(0, buffer.slice(..)); + if kind == 1 { + pass.set_index_buffer(pipes.bead.slice(..), wgpu::IndexFormat::Uint16); + pass.draw_indexed(0..vertices, 0, 0..*count); + } else { + pass.draw(0..vertices, 0..*count); + } + tally.triangles(vertices, *count); + } } } } diff --git a/crates/io/src/ply.rs b/crates/io/src/ply.rs index 83990961d..ca0f55afc 100644 --- a/crates/io/src/ply.rs +++ b/crates/io/src/ply.rs @@ -536,9 +536,9 @@ mod tests { assert_eq!((n, colored), (3, true)); assert_eq!(v[1], ([1.5, 0.0, 0.0], Some([10, 20, 255]))); assert_eq!(v[2].0, [0.0, 2.5, -3.0]); - // Every second vertex. - let (v, _, _) = vertices(&binary(big), 2).unwrap(); - assert_eq!(v.iter().map(|v| v.0[1]).collect::>(), [0.0, 2.5]); + // A thinned file leaves its face out: it would lose a corner. + let thin = crate::ply_complex::read_ply_cloud(&binary(big), 2).unwrap(); + assert_eq!((thin.positions.len(), thin.complex.triangle_count(), thin.cells_left_out), (2, 0, 1)); let (mesh, warnings) = read_ply_mesh(&binary(big), "Tri").unwrap(); assert!(warnings.is_empty()); assert_eq!(mesh[0].triangles, [[0, 1, 2]]); @@ -563,6 +563,9 @@ mod tests { let (v, n, colored) = vertices(points.as_bytes(), 2).unwrap(); assert_eq!((v.len(), n, colored), (2, 2, false)); assert_eq!(v[1], ([4.0, 5.0, 6.0], None)); + // Points alone are thinned: every second one. + let (v, _, _) = vertices(points.as_bytes(), 1).unwrap(); + assert_eq!(v, [([1.0, 2.0, 3.0], None)]); assert!(read_ply_mesh(points.as_bytes(), "x").is_err(), "a point cloud is not a mesh"); } diff --git a/crates/io/src/ply_complex.rs b/crates/io/src/ply_complex.rs index ff8c4c290..636780648 100644 --- a/crates/io/src/ply_complex.rs +++ b/crates/io/src/ply_complex.rs @@ -1,10 +1,12 @@ -//! A PLY file read with everything a point cloud can hold: its vertices with all their -//! properties. Positions are `x`, `y`, `z` and colours `red`, `green`, `blue`; every other scalar -//! property becomes a column named as in the file, whole-numbered when its type is an integer. A -//! comment `property: 0 name, 1 name` names the values of a whole-numbered property. Every -//! `stride`th vertex is kept. +//! A PLY file read with everything a point cloud can hold: the vertices with all their +//! properties, and the `edge` and `face` elements as segments and triangles (a face as a fan) +//! with theirs. Positions are `x`, `y`, `z` and colours `red`, `green`, `blue`; every other +//! scalar property becomes a column named as in the file, whole-numbered when its type is an +//! integer. A comment `property: 0 name, 1 name` names the values of a whole-numbered property. +//! A file whose vertices fit keeps them all, with its edges and faces. One with more keeps every +//! `stride`th vertex and leaves its edges and faces out, since thinning would cut them. -use solidcraft_doc::point_cloud::{Column, Complex, Floats, MAX_COLUMNS, Names}; +use solidcraft_doc::point_cloud::{Column, Complex, Floats, Indices, MAX_CELLS, MAX_COLUMNS, Names, On}; use crate::ply::{Element, Kind, Rows, Scalar, header}; use crate::{IoError, Result}; @@ -20,6 +22,10 @@ pub(crate) struct PlyCloud { pub complex: Complex, /// Vertices in the file. pub vertices: u64, + /// Faces whose indices could not be read. + pub bad_faces: usize, + /// Edges and faces in the file, left out because its vertices were thinned. + pub cells_left_out: u64, } fn integer(s: Scalar) -> bool { @@ -31,78 +37,149 @@ fn named(e: &Element, names: &[&str]) -> Option { } /// The columns an element's scalar properties fill, leaving out those at `taken`. -fn columns_of(e: &Element, taken: &[usize]) -> Vec<(usize, Column)> { +fn columns_of(e: &Element, on: On, taken: &[usize]) -> Vec<(usize, Column)> { e.properties .iter() .enumerate() .filter(|(i, _)| !taken.contains(i)) .filter_map(|(i, p)| match p.kind { - Kind::Scalar(s) => Some((i, Column { name: p.name.clone(), integer: integer(s), values: Floats::default() })), + Kind::Scalar(s) => Some((i, Column { name: p.name.clone(), on, integer: integer(s), values: Floats::default() })), Kind::List(..) => None, }) .collect() } -/// Read a PLY file's vertices, every `stride`th one of those beyond `max_points`. +/// An index into `n` vertices, or `None` for anything else. +fn index(v: f64, n: usize) -> Option { + (v >= 0.0 && v < n as f64 && v.fract() == 0.0).then(|| u32::try_from(v as u64).ok()).flatten() +} + +/// Read a PLY file: every vertex with the edges and faces when they fit in `max_points`, else +/// every `stride`th vertex alone. pub(crate) fn read_ply_cloud(bytes: &[u8], max_points: usize) -> Result { let h = header(bytes)?; let vertex = h.elements.iter().find(|e| e.name == "vertex").ok_or_else(|| invalid("no `vertex` element"))?; let stride = vertex.count.div_ceil(max_points.max(1) as u64).max(1); - let xyz = [named(vertex, &["x"]), named(vertex, &["y"]), named(vertex, &["z"])]; - let [Some(x), Some(y), Some(z)] = xyz else { return Err(invalid("the vertices have no `x`, `y` and `z`")) }; - let rgb = - [named(vertex, &["red", "r", "diffuse_red"]), named(vertex, &["green", "g", "diffuse_green"]), named(vertex, &["blue", "b", "diffuse_blue"])]; - let rgb = match rgb { - [Some(r), Some(g), Some(b)] => Some([r, g, b]), - _ => None, - }; - let mut taken = vec![x, y, z]; - taken.extend(rgb.into_iter().flatten()); - let mine = columns_of(vertex, &taken); - if mine.len() > MAX_COLUMNS { - return Err(invalid(format!("more than {MAX_COLUMNS} properties"))); - } + let whole = stride == 1; let body = bytes.len().saturating_sub(h.body) as u64; let mut rows = Rows::new(&h, bytes); - let mut out = PlyCloud { positions: Vec::new(), colors: rgb.map(|_| Vec::new()), complex: Complex::default(), vertices: vertex.count }; - let mut columns: Vec<(usize, Vec, Column)> = mine.into_iter().map(|(i, c)| (i, Vec::new(), c)).collect(); - let mut row = vec![0.0f64; vertex.properties.len()]; - // The elements before the vertices are read past. - for e in h.elements.iter().take_while(|e| e.name != "vertex").chain([vertex]) { + let mut out = + PlyCloud { positions: Vec::new(), colors: None, complex: Complex::default(), vertices: vertex.count, bad_faces: 0, cells_left_out: 0 }; + let mut columns: Vec<(On, Vec, Column)> = Vec::new(); + let (mut segments, mut triangles) = (Vec::new(), Vec::new()); + let mut row = vec![0.0f64; e_max(&h.elements)]; + let mut list: Vec = Vec::new(); + for e in &h.elements { if e.count > body { return Err(invalid(format!("the file is too short for its {} {}", e.count, e.name))); } - let vertices = std::ptr::eq(e, vertex); + if !whole && (e.name == "edge" || e.name == "face") { + out.cells_left_out = out.cells_left_out.saturating_add(e.count); + } + let (on, taken, xyz, rgb, ends, face) = match e.name.as_str() { + "vertex" => { + let xyz = [named(e, &["x"]), named(e, &["y"]), named(e, &["z"])]; + let [Some(x), Some(y), Some(z)] = xyz else { return Err(invalid("the vertices have no `x`, `y` and `z`")) }; + let rgb = + [named(e, &["red", "r", "diffuse_red"]), named(e, &["green", "g", "diffuse_green"]), named(e, &["blue", "b", "diffuse_blue"])]; + let rgb = match rgb { + [Some(r), Some(g), Some(b)] => Some([r, g, b]), + _ => None, + }; + let mut taken = vec![x, y, z]; + taken.extend(rgb.into_iter().flatten()); + (Some(On::Point), taken, Some([x, y, z]), rgb, None, None) + } + "edge" if whole => { + let (Some(a), Some(b)) = (named(e, &["vertex1"]), named(e, &["vertex2"])) else { + return Err(invalid("the edges have no `vertex1` and `vertex2`")); + }; + (Some(On::Segment), vec![a, b], None, None, Some([a, b]), None) + } + "face" if whole => { + let face = e + .properties + .iter() + .position(|p| matches!(p.name.as_str(), "vertex_indices" | "vertex_index") && matches!(p.kind, Kind::List(..))); + (face.map(|_| On::Triangle), Vec::new(), None, None, None, face) + } + _ => (None, Vec::new(), None, None, None, None), + }; + let mine: Vec<(usize, Column)> = on.map(|on| columns_of(e, on, &taken)).unwrap_or_default(); + if columns.len() + mine.len() > MAX_COLUMNS { + return Err(invalid(format!("more than {MAX_COLUMNS} properties"))); + } + let first = columns.len(); + let slots: Vec = mine.iter().map(|(i, _)| *i).collect(); + columns.extend(mine.into_iter().map(|(_, c)| (c.on, Vec::new(), c))); + if rgb.is_some() { + out.colors = Some(Vec::new()); + } for r in 0..e.count { + list.clear(); for (i, p) in e.properties.iter().enumerate() { match p.kind { Kind::Scalar(t) => { let v = rows.value(t)?; - if let Some(s) = row.get_mut(i).filter(|_| vertices) { + if let Some(s) = row.get_mut(i) { *s = v; } } Kind::List(c, t) => { - for _ in 0..rows.count(c)? { - rows.value(t)?; + let n = rows.count(c)?; + for _ in 0..n { + let v = rows.value(t)?; + if face == Some(i) { + list.push(v); + } } } } } - if !vertices || !r.is_multiple_of(stride) { - continue; - } let v = |i: usize| row.get(i).copied().unwrap_or(0.0); - out.positions.push([v(x), v(y), v(z)]); - if let (Some(c), Some(ks)) = (out.colors.as_mut(), rgb) { - let t = |i: usize| match vertex.properties.get(i).map(|p| p.kind) { - Some(Kind::Scalar(s)) => s.channel(v(i)), - _ => 0, - }; - c.push(ks.map(t)); + // How many elements this row stands for: a vertex kept, a segment, a fan's triangles. + let copies = if let Some([x, y, z]) = xyz { + if !r.is_multiple_of(stride) { + continue; + } + out.positions.push([v(x), v(y), v(z)]); + if let (Some(c), Some(ks)) = (out.colors.as_mut(), rgb) { + let t = |i: usize| match e.properties.get(i).map(|p| p.kind) { + Some(Kind::Scalar(s)) => s.channel(v(i)), + _ => 0, + }; + c.push(ks.map(t)); + } + 1 + } else if let Some([a, b]) = ends { + let n = vertex.count as usize; + let (Some(a), Some(b)) = (index(v(a), n), index(v(b), n)) else { return Err(invalid("an edge names a missing vertex")) }; + segments.extend([a, b]); + 1 + } else if face.is_some() { + let n = vertex.count as usize; + match list.iter().map(|x| index(*x, n)).collect::>>() { + Some(p) if p.len() >= 3 => { + for k in 1..p.len() - 1 { + triangles.extend([p[0], p[k], p[k + 1]]); + } + p.len() - 2 + } + _ => { + out.bad_faces += 1; + 0 + } + } + } else { + 0 + }; + for (k, slot) in slots.iter().enumerate() { + if let Some((_, values, _)) = columns.get_mut(first + k) { + values.extend(std::iter::repeat_n(v(*slot) as f32, copies)); + } } - for (slot, values, _) in &mut columns { - values.push(v(*slot) as f32); + if segments.len() / 2 > MAX_CELLS || triangles.len() / 3 > MAX_CELLS { + return Err(invalid(format!("more than {MAX_CELLS} edges or triangles"))); } } } @@ -110,38 +187,51 @@ pub(crate) fn read_ply_cloud(bytes: &[u8], max_points: usize) -> Result = Vec::new(); for n in h.comments.iter().filter_map(|c| Names::parse(c)) { - let label = columns.iter().any(|c| c.name == n.property && c.integer); + let label = columns.iter().any(|c| c.name == n.property) && columns.iter().filter(|c| c.name == n.property).all(|c| c.integer); if label && !names.iter().any(|m| m.property == n.property) && names.len() < MAX_COLUMNS { names.push(n); } } - out.complex = Complex { columns, names }; + out.complex = Complex { segments: Indices(segments.into()), triangles: Indices(triangles.into()), columns, names }; Ok(out) } +/// The most properties of any element: the row buffer's length. +fn e_max(elements: &[Element]) -> usize { + elements.iter().map(|e| e.properties.len()).max().unwrap_or(0) +} + #[cfg(test)] mod tests { use super::*; #[test] - fn every_vertex_property_is_kept() { - let text = "ply\nformat ascii 1.0\ncomment role: 7 wall, -1 none\ncomment t: seconds since the start\ncomment width: 0 thin\n\ - element vertex 4\nproperty float x\nproperty float y\nproperty float z\nproperty double t\nproperty int role\nproperty float width\n\ - element face 1\nproperty list uchar int vertex_indices\nend_header\n\ - 0 0 0 0.5 7 1\n1 0 0 1.5 7 1\n1 1 0 2.5 -1 2\n0 1 0 3.5 -1 2\n4 0 1 2 3\n"; + fn edges_faces_and_every_property_are_kept() { + let text = "ply\nformat ascii 1.0\ncomment role: 7 wall, -1 none\ncomment t: seconds since the start\ncomment width: 0 thin\nelement vertex 4\nproperty float x\nproperty float y\nproperty float z\nproperty double t\n\ + element edge 2\nproperty int vertex1\nproperty int vertex2\nproperty int role\nproperty double width\n\ + element face 1\nproperty list uchar int vertex_indices\nproperty int layer\nend_header\n\ + 0 0 0 0.5\n1 0 0 1.5\n1 1 0 2.5\n0 1 0 3.5\n0 1 7 0.42\n1 2 -1 0\n4 0 1 2 3 9\n"; let r = read_ply_cloud(text.as_bytes(), 10).unwrap(); assert_eq!(r.positions.len(), 4); - let col = |n: &str| r.complex.column(n).unwrap(); - assert_eq!(&*col("t").values.0, &[0.5, 1.5, 2.5, 3.5]); - assert!(col("role").integer && !col("width").integer); - assert_eq!(&*col("role").values.0, &[7.0, 7.0, -1.0, -1.0]); + assert_eq!(&*r.complex.segments.0, &[0, 1, 1, 2]); + assert_eq!(&*r.complex.triangles.0, &[0, 1, 2, 0, 2, 3], "a quad is a fan of two"); + let col = |n: &str, on| r.complex.column(n, on).unwrap(); + assert_eq!(&*col("t", On::Point).values.0, &[0.5, 1.5, 2.5, 3.5]); + assert!(col("role", On::Segment).integer && !col("width", On::Segment).integer); + assert_eq!(&*col("role", On::Segment).values.0, &[7.0, -1.0]); + assert_eq!(&*col("layer", On::Triangle).values.0, &[9.0, 9.0], "each triangle of the fan has the face's"); r.complex.check(4).unwrap(); // Names for the whole-numbered `role` only: `t` is no list and `width` is not whole. assert_eq!(r.complex.names.len(), 1); assert_eq!(r.complex.names("role").and_then(|n| n.name(-1)), Some("none")); - // Every second vertex, with its numbers. - let half = read_ply_cloud(text.as_bytes(), 2).unwrap(); - assert_eq!((half.positions.len(), &*half.complex.column("t").unwrap().values.0), (2, &[0.5f32, 2.5][..])); - half.complex.check(2).unwrap(); + // Too many vertices: thinned, with the edges and faces that thinning would cut left out. + let thin = read_ply_cloud(text.as_bytes(), 3).unwrap(); + assert_eq!((thin.positions.len(), thin.cells_left_out), (2, 3)); + assert!(thin.complex.segments.0.is_empty() && thin.complex.triangles.0.is_empty()); + assert_eq!(&*thin.complex.column("t", On::Point).unwrap().values.0, &[0.5, 2.5]); + assert!(thin.complex.column("role", On::Segment).is_none()); + thin.complex.check(2).unwrap(); + let bad = text.replace("1 2 -1 0", "1 9 -1 0"); + assert!(read_ply_cloud(bad.as_bytes(), 10).is_err(), "an edge to a missing vertex"); } } diff --git a/crates/io/src/point_cloud.rs b/crates/io/src/point_cloud.rs index 0e6e922c4..b03db8df8 100644 --- a/crates/io/src/point_cloud.rs +++ b/crates/io/src/point_cloud.rs @@ -34,7 +34,7 @@ pub struct CloudFile { pub colors: Vec, /// Points in the file. pub source_points: u64, - /// The file's other properties of the points (PLY). + /// Segments, triangles and the file's other properties (PLY). pub complex: solidcraft_doc::point_cloud::Complex, pub warnings: Vec, } @@ -91,15 +91,25 @@ pub fn read_point_cloud(bytes: &[u8], file: &str, scale: f64, max_points: usize) stride = r.vertices.div_ceil(r.positions.len().max(1) as u64).max(1); keep.colored = r.colors.is_some(); let colors = r.colors.unwrap_or_default(); + let mut read = Vec::with_capacity(r.positions.len()); for (i, p) in r.positions.iter().enumerate() { + let bad = keep.bad; keep.push(*p, colors.get(i).copied()); + read.push(keep.bad == bad); } - // A point left out would shift every number after it. - if keep.bad > 0 && !r.complex.is_empty() { - return Err(IoError::Invalid(format!("{} point(s) are not finite numbers within range", keep.bad))); + // A point left out takes with it its numbers and whatever ends on it. + let (complex, cut) = if keep.bad > 0 { r.complex.induced(&read) } else { (r.complex, 0) }; + if cut > 0 { + keep.out.warnings.push(format!("{cut} segment(s) and triangle(s) left out, since a point they end on could not be read")); + } + if r.bad_faces > 0 { + keep.out.warnings.push(format!("{} face(s) could not be read and were left out", r.bad_faces)); + } + if r.cells_left_out > 0 { + keep.out.warnings.push(format!("{} edge(s) and face(s) left out, since thinning the points would cut them", r.cells_left_out)); } keep.out.source_points = r.vertices; - keep.out.complex = r.complex; + keep.out.complex = complex; } else { stride = read_xyz(bytes, &mut keep)?; } @@ -191,6 +201,8 @@ fn read_xyz(bytes: &[u8], keep: &mut Keep) -> Result { #[cfg(test)] mod tests { + use solidcraft_doc::point_cloud::On; + use super::*; fn ply_points(n: usize) -> Vec { @@ -215,11 +227,43 @@ mod tests { assert_eq!(&c.points[3..6], &[2000.0, 0.0, 0.0]); assert!(c.colors.is_empty()); assert_eq!(c.warnings.len(), 1, "{:?}", c.warnings); + // A thinned file leaves out the edges thinning would cut, and says so. + let edged = "ply\nformat ascii 1.0\nelement vertex 4\nproperty float x\nproperty float y\nproperty float z\n\ + element edge 2\nproperty int vertex1\nproperty int vertex2\nend_header\n0 0 0\n1 0 0\n2 0 0\n3 0 0\n0 1\n2 3\n"; + let e = read_point_cloud(edged.as_bytes(), "path.ply", 1.0, 2).unwrap(); + assert_eq!((e.points.len(), e.complex.segment_count()), (6, 0)); + assert!(e.warnings.iter().any(|w| w.starts_with("2 edge(s) and face(s) left out")), "{:?}", e.warnings); let all = read_point_cloud(&ply_points(10), "scan.PLY", 1.0, DEFAULT_MAX_POINTS).unwrap(); assert_eq!((all.points.len(), all.warnings.len()), (30, 0)); assert!(read_point_cloud(&ply_points(10), "scan.ply", 0.0, 5).is_err()); } + #[test] + fn a_point_that_cannot_be_read_takes_only_what_ends_on_it() { + let text = "ply\nformat ascii 1.0\ncomment role: 7 wall\nelement vertex 5\nproperty float x\nproperty float y\nproperty float z\nproperty float t\n\ + element edge 3\nproperty int vertex1\nproperty int vertex2\nproperty int role\n\ + element face 2\nproperty list uchar int vertex_indices\nproperty int layer\nend_header\n\ + 0 0 0 10\nnan 0 0 11\n2 0 0 12\n3 0 0 13\n4 0 0 14\n0 1 7\n2 3 8\n3 4 9\n3 0 2 3 5\n3 1 2 3 6\n"; + let c = read_point_cloud(text.as_bytes(), "path.ply", 1.0, DEFAULT_MAX_POINTS).unwrap(); + assert_eq!(c.points, [0., 0., 0., 2., 0., 0., 3., 0., 0., 4., 0., 0.]); + assert_eq!(&*c.complex.segments.0, &[1, 2, 2, 3], "numbered among the points that are left"); + assert_eq!(&*c.complex.triangles.0, &[0, 1, 2]); + assert_eq!(&*c.complex.column("t", On::Point).unwrap().values.0, &[10., 12., 13., 14.]); + assert_eq!(&*c.complex.column("role", On::Segment).unwrap().values.0, &[8., 9.]); + assert_eq!(&*c.complex.column("layer", On::Triangle).unwrap().values.0, &[5.]); + assert_eq!(c.complex.names("role").and_then(|n| n.name(7)), Some("wall")); + c.complex.check(4).unwrap(); + assert_eq!( + c.warnings, + ["2 segment(s) and triangle(s) left out, since a point they end on could not be read", "1 point(s) could not be read and were left out"] + ); + // Edges alone, no numbers on the points: the same, not a refused file. + let edged = "ply\nformat ascii 1.0\nelement vertex 3\nproperty float x\nproperty float y\nproperty float z\n\ + element edge 2\nproperty int vertex1\nproperty int vertex2\nend_header\nnan 0 0\n1 0 0\n2 0 0\n0 1\n1 2\n"; + let e = read_point_cloud(edged.as_bytes(), "path.ply", 1.0, DEFAULT_MAX_POINTS).unwrap(); + assert_eq!((e.points.len(), &*e.complex.segments.0), (6, &[0u32, 1][..])); + } + #[test] fn xyz_and_pts_text() { let xyz = "# x y z r g b\n1 2 3 255 0 0\n4,5,6,0,255,0\n\n7\t8\t9\t0\t0\t255\nnot a point\n"; diff --git a/crates/ui-egui/src/browser/point_cloud_tracks.rs b/crates/ui-egui/src/browser/point_cloud_tracks.rs index 04e32694c..d9bb5aab6 100644 --- a/crates/ui-egui/src/browser/point_cloud_tracks.rs +++ b/crates/ui-egui/src/browser/point_cloud_tracks.rs @@ -51,11 +51,18 @@ pub(crate) struct Answer { pub extent: Option<[f64; 2]>, } -/// The cloud's data as far as the tracks are concerned: its points, columns and placement. +/// The cloud's data as far as the tracks are concerned: its points, cells, columns and placement. type DataKey = Vec; fn data_key(c: &PointCloud) -> DataKey { - let mut k = vec![Arc::as_ptr(c.points.values()).cast::() as u64, c.origin.x.to_bits(), c.origin.y.to_bits(), c.origin.z.to_bits()]; + let mut k = vec![ + Arc::as_ptr(c.points.values()).cast::() as u64, + Arc::as_ptr(&c.complex.segments.0).cast::() as u64, + Arc::as_ptr(&c.complex.triangles.0).cast::() as u64, + c.origin.x.to_bits(), + c.origin.y.to_bits(), + c.origin.z.to_bits(), + ]; k.extend(c.complex.columns.iter().map(|col| Arc::as_ptr(&col.values.0).cast::() as u64)); k.extend(c.transform.iter().flatten().map(|v| v.to_bits())); k diff --git a/crates/ui-egui/src/browser/point_clouds.rs b/crates/ui-egui/src/browser/point_clouds.rs index 294798e40..19e80a211 100644 --- a/crates/ui-egui/src/browser/point_clouds.rs +++ b/crates/ui-egui/src/browser/point_clouds.rs @@ -1,10 +1,10 @@ //! The Point Clouds folder of the Browser (#5151): an eye per cloud and for the folder, a menu, -//! and the Edit Point Cloud card: the file's units, the size of the dots, how the cloud is -//! coloured (its colours, one colour, a ramp over a property, its range on a track, or the -//! palette of a label, with its legend), and its filters (a range on a track, played with ▶ or -//! Space, or the values of a label picked in its legend). Each track shows how much of the cloud -//! lies at each value, over what the other filters keep. The live edits of one opening are one -//! undo step. +//! and the Edit Point Cloud card: the file's units, the size of the dots (when some points are +//! dots), how the cloud is coloured (its colours, one colour, a ramp over a property, its range +//! on a track, or the palette of a label, with its legend), and its filters (a range on a track, +//! played with ▶ or Space, or the values of a label picked in its legend). Each track shows how +//! much of the cloud lies at each value, over what the other filters keep. The live edits of +//! one opening are one undo step. use serde_json::{Value, json}; use solidcraft_engine::doc::point_cloud::{COORDINATES, ColorBy, Filter, Keep, MAX_FILTERS, Names, PLAIN, PointCloud, UNITS, byte, label_color}; @@ -26,12 +26,14 @@ use range_track::{Part, Track, range_track}; pub const DRAWN_FILTERS: usize = solidcraft_gpu::view::FILTERS; /// The Edit Point Cloud card: the cloud, the undo depth when it opened, what it worked out once -/// for the cloud's data (the automatic height range), its tracks' bars, and a filter playing. +/// for the cloud's data (the automatic height range, the number of dots), its tracks' bars, and +/// a filter playing. #[derive(Clone, Debug)] pub struct CloudPanel { pub cloud: u64, pub(crate) depth: usize, auto: Option<(usize, [u64; 16], Option<[f64; 2]>)>, + dots: Option<([usize; 3], usize)>, tracks: Tracks, pub play: Option, } @@ -94,7 +96,7 @@ impl Play { impl CloudPanel { pub fn new(app: &SolveApp, cloud: u64) -> Self { - CloudPanel { cloud, depth: app.session.undo.len(), auto: None, tracks: Tracks::default(), play: None } + CloudPanel { cloud, depth: app.session.undo.len(), auto: None, dots: None, tracks: Tracks::default(), play: None } } /// The cloud's automatic height range, worked out again only when its points or placement /// change. @@ -109,6 +111,22 @@ impl CloudPanel { } } } + /// How many points are drawn as dots, worked out again only when the cloud's data change. + fn dots(&mut self, c: &PointCloud) -> usize { + let key = [ + std::sync::Arc::as_ptr(c.points.values()).cast::() as usize, + std::sync::Arc::as_ptr(&c.complex.segments.0).cast::() as usize, + std::sync::Arc::as_ptr(&c.complex.triangles.0).cast::() as usize, + ]; + match self.dots { + Some((k, n)) if k == key => n, + _ => { + let n = c.isolated_points(); + self.dots = Some((key, n)); + n + } + } + } /// The range filter `k` of this card's cloud shows now, while it plays. pub fn playing(&self, cloud: u64, k: usize) -> Option<[f64; 2]> { self.play.as_ref().filter(|p| self.cloud == cloud && p.filter == k).map(|p| p.now) @@ -247,6 +265,7 @@ pub(crate) fn panel(app: &mut SolveApp, ctx: &egui::Context) { let mut edit: Option = None; let title = crate::i18n::format("browser.edit_point_cloud_title", &[("name", &c.name)]); let auto = if c.color_by == ColorBy::Height { m.auto_range(&c) } else { None }; + let dots = m.dots(&c); let now = ctx.input(|i| i.time); // A playing filter moves on; at the end of its span it stops, and is written once. let mut stop_play = false; @@ -276,9 +295,17 @@ pub(crate) fn panel(app: &mut SolveApp, ctx: &egui::Context) { .actions("", crate::i18n::tr("ui.close"), None) .show(ctx, true, |ui| { ui_kit::row(ui, crate::i18n::tr_label("Points"), |ui| ui.label(c.len().to_string())); - let mut size = c.point_size; - if ui_kit::row(ui, crate::i18n::tr("ui.point_cloud_size"), |ui| ui_kit::slider(ui, &mut size, 0.5..=16.0, Default::default())).changed() { - edit = Some(json!({ "cloud": c.id, "point_size": size })); + // The dots' size, where some points are dots: those no segment or triangle ends on. + if dots > 0 { + if dots < c.len() { + ui_kit::row(ui, crate::i18n::tr_label("Dots"), |ui| ui.label(dots.to_string())); + } + let mut size = c.point_size; + if ui_kit::row(ui, crate::i18n::tr("ui.point_cloud_size"), |ui| ui_kit::slider(ui, &mut size, 0.5..=16.0, Default::default())) + .changed() + { + edit = Some(json!({ "cloud": c.id, "point_size": size })); + } } let units: Vec<&str> = UNITS.iter().map(|(u, _)| *u).collect(); let was = units.iter().position(|u| *u == c.units).unwrap_or(0); @@ -567,15 +594,18 @@ mod tests { let _ = std::fs::remove_dir_all(dir); } - /// A PLY file of points along x, `t` running 0 to 10 by halves, a layer every 2: the layer - /// changes at t = 2, 4, 6 and 8. - fn layered_points(dir: &std::path::Path) -> std::path::PathBuf { + /// A PLY file of ten segments along x, `t` running 0 to 10 along them and two segments to a + /// layer: the layer changes at t = 2, 4, 6 and 8. + fn layered_segments(dir: &std::path::Path) -> std::path::PathBuf { let mut ply = String::from( - "ply\nformat ascii 1.0\nelement vertex 21\nproperty float x\nproperty float y\nproperty float z\nproperty float t\nproperty int layer\nend_header\n", + "ply\nformat ascii 1.0\nelement vertex 11\nproperty float x\nproperty float y\nproperty float z\nproperty float t\n\ + element edge 10\nproperty int vertex1\nproperty int vertex2\nproperty int layer\nend_header\n", ); - for i in 0..=20 { - let t = f64::from(i) / 2.0; - ply += &format!("{t} 0 0 {t} {}\n", (i / 4).min(4)); + for i in 0..=10 { + ply += &format!("{i} 0 0 {i}\n"); + } + for i in 0..10 { + ply += &format!("{i} {} {}\n", i + 1, i / 2); } let path = dir.join("layers.ply"); std::fs::write(&path, ply).unwrap(); @@ -588,7 +618,7 @@ mod tests { h.app.home.open = false; let dir = std::env::temp_dir().join(format!("solidcraft-browser-track-{}", std::process::id())); std::fs::create_dir_all(&dir).unwrap(); - let path = layered_points(&dir); + let path = layered_segments(&dir); let id = h.app.run("pointcloud.insert", json!({"path": path.to_string_lossy()})).unwrap()["cloud"].as_u64().unwrap(); h.app.run("pointcloud.edit", json!({"cloud": id, "color_by": "layer", "filters": [{"property": "t", "range": [2.0, 5.0]}]})).unwrap(); h.app.tree.cloud_panel = Some(super::CloudPanel::new(&h.app, id)); diff --git a/crates/ui-egui/src/point_clouds.rs b/crates/ui-egui/src/point_clouds.rs index 0b6f21a0a..b13c162ed 100644 --- a/crates/ui-egui/src/point_clouds.rs +++ b/crates/ui-egui/src/point_clouds.rs @@ -1,6 +1,6 @@ -//! Point clouds (#5151): with the GPU viewport their points are drawn in the 3D pass -//! (depth-tested with the model), coloured and filtered by the shaders; the CPU viewport draws -//! some of them over its image. +//! Point clouds (#5151): with the GPU viewport their points, segments and triangles are drawn in +//! the 3D pass (depth-tested with the model), coloured and filtered by the shaders; the CPU +//! viewport draws some of their points over its image. use std::cell::RefCell; use std::collections::HashMap; @@ -8,9 +8,9 @@ use std::sync::Arc; use egui::{Painter, Shape}; use solidcraft_engine::doc::point_cloud::Keep; -use solidcraft_engine::doc::point_cloud::{ColorBy, PLAIN, PointCloud, Source, byte}; +use solidcraft_engine::doc::point_cloud::{ColorBy, On, PLAIN, PointCloud, Source, byte}; use solidcraft_engine::doc::point_cloud_distribution::color_range_by; -use solidcraft_gpu::view::{CloudFilter, CloudStyle, ColorMode, Dot, FILTERS, GpuCloud, cloud_dot}; +use solidcraft_gpu::view::{Cell, CloudFilter, CloudStyle, ColorMode, FILTERS, GpuCloud, cloud_cell}; use crate::SolveApp; use crate::browser::point_cloud_tracks::{Ask, Paint, Tracks}; @@ -35,7 +35,12 @@ struct Key { impl Key { fn of(c: &PointCloud) -> Key { - let mut data = vec![Arc::as_ptr(c.points.values()).cast::() as usize, Arc::as_ptr(&c.colors.0).cast::() as usize]; + let mut data = vec![ + Arc::as_ptr(c.points.values()).cast::() as usize, + Arc::as_ptr(&c.colors.0).cast::() as usize, + Arc::as_ptr(&c.complex.segments.0).cast::() as usize, + Arc::as_ptr(&c.complex.triangles.0).cast::() as usize, + ]; data.extend(c.complex.columns.iter().map(|k| Arc::as_ptr(&k.values.0).cast::() as usize)); Key { data, @@ -50,9 +55,12 @@ impl Key { } } +/// Records of a cloud's dots, segments and triangles. +type Records = [Arc>; 3]; + thread_local! { /// Records by cloud id: what they were made from, their version and bytes. - static RECORDS: RefCell>)>> = RefCell::new(HashMap::new()); + static RECORDS: RefCell> = RefCell::new(HashMap::new()); static VERSION: std::cell::Cell = const { std::cell::Cell::new(0) }; /// By cloud id, the values its coloured property takes over what is kept, worked out off the /// frame (one worker a cloud, so that each keeps its own geometry). @@ -77,45 +85,107 @@ pub(crate) fn color_range(ctx: &egui::Context, c: &PointCloud) -> Option<[f64; 2 }) } -fn records(c: &PointCloud) -> Arc> { +fn records(c: &PointCloud) -> Records { + let world: Vec<[f32; 3]> = (0..c.len()) + .map(|i| { + // Placed in double precision: the cloud's origin may be far from the design's. + let w = c.world_point(i).unwrap_or_default(); + [w.x as f32, w.y as f32, w.z as f32] + }) + .collect(); let plain = PLAIN.map(byte); let single = c.color.unwrap_or(PLAIN).map(byte); - let own = |i: usize| match c.color_by { + let own = |i: u32| match c.color_by { ColorBy::Single => single, - ColorBy::File => c.colors.get(i).unwrap_or(plain), + ColorBy::File => c.colors.get(i as usize).unwrap_or(plain), ColorBy::Height | ColorBy::Property => plain, }; // The coloured property, then the filtered ones. - let sources: [Option; 1 + FILTERS] = std::array::from_fn(|k| { - let name = if k == 0 { c.colored_property() } else { c.filters.get(k - 1).map(|f| f.property.as_str()) }; - name.and_then(|n| c.source(n)) - }); - let mut out = Vec::with_capacity(c.len() * solidcraft_gpu::view::DOT_SIZE); - for i in 0..c.len() { - // Placed in double precision: the cloud's origin may be far from the design's. - let w = c.world_point(i).unwrap_or_default(); - let at = [w.x as f32, w.y as f32, w.z as f32]; + let names: [Option<&str>; 1 + FILTERS] = + std::array::from_fn(|k| if k == 0 { c.colored_property() } else { c.filters.get(k - 1).map(|f| f.property.as_str()) }); + let complex = &c.complex; + let width = complex.column("width", On::Segment).map(|k| &k.values.0[..]); + let height = complex.column("height", On::Segment).map(|k| &k.values.0[..]); + let mut out: [Vec; 3] = Default::default(); + let mut used = vec![false; c.len()]; + // Each point's one segment in and one segment out, when it has exactly one of each: a bead + // runs through it, and its two segments meet there mitred. + let (mut into, mut out_of) = (vec![None; c.len()], vec![None; c.len()]); + for ends in complex.segments.0.as_chunks::<2>().0 { + let [a, b] = ends.map(|i| i as usize); + if let Some(slot) = out_of.get_mut(a) { + *slot = if slot.is_none() { Some(Some(b)) } else { Some(None) }; + } + if let Some(slot) = into.get_mut(b) { + *slot = if slot.is_none() { Some(Some(a)) } else { Some(None) }; + } + } + let through = |links: &[Option>], at: u32| links.get(at as usize).copied().flatten().flatten().and_then(|k| world.get(k).copied()); + for (kind, on, n) in [(1usize, On::Segment, 2usize), (2, On::Triangle, 3)] { + let indices = if n == 2 { &complex.segments.0 } else { &complex.triangles.0 }; + let sources = names.map(|name| name.and_then(|n| c.source(n, on))); + for (e, ids) in indices.chunks_exact(n).enumerate() { + let at = |k: usize| ids.get(k.min(n - 1)).copied().unwrap_or(0); + let corners = [at(0), at(1), at(2)]; + for i in corners { + if let Some(u) = used.get_mut(i as usize) { + *u = true; + } + } + let mut cell = + Cell { corners: corners.map(|i| world.get(i as usize).copied().unwrap_or_default()), rgb: own(corners[0]), ..Default::default() }; + let values = sources.map(|s| { + s.map(|s| match s { + Source::Coordinate(k) => cell.corners.map(|p| p[k]), + Source::Corners(v) => corners.map(|i| v.get(i as usize).copied().unwrap_or(0.0)), + Source::Element(v) => [v.get(e).copied().unwrap_or(0.0); 3], + }) + }); + if on == On::Segment { + let [a, b] = [corners[0], corners[1]]; + // The point before `a` only when `a` is passed through, not where beads branch. + let joined = |at: u32| matches!((into.get(at as usize), out_of.get(at as usize)), (Some(Some(Some(_))), Some(Some(Some(_))))); + let before = through(&into, a).filter(|_| joined(a)); + let after = through(&out_of, b).filter(|_| joined(b)); + cell.neighbours = [before.unwrap_or(cell.corners[0]), after.unwrap_or(cell.corners[1])]; + cell.size = [width.and_then(|w| w.get(e)).copied().unwrap_or(0.0), height.and_then(|h| h.get(e)).copied().unwrap_or(0.0)]; + } + fill(&mut cell, values); + cloud_cell(&mut out[kind], &cell); + } + } + // The points drawn as dots: those no segment or triangle ends on. + let sources = names.map(|name| name.and_then(|n| c.source(n, On::Point))); + for (i, p) in world.iter().enumerate() { + if used.get(i).copied().unwrap_or(false) { + continue; + } + let mut cell = Cell { corners: [*p; 3], rgb: own(i as u32), ..Default::default() }; let values = sources.map(|s| { s.map(|s| match s { - Source::Coordinate(k) => at.get(k).copied().unwrap_or(0.0), - Source::Column(v) => v.get(i).copied().unwrap_or(0.0), + Source::Coordinate(k) => [p[k]; 3], + Source::Corners(v) | Source::Element(v) => [v.get(i).copied().unwrap_or(0.0); 3], }) }); - let mut dot = Dot { at, rgb: own(i), ..Default::default() }; - let [value, filtered @ ..] = values; - if let Some(v) = value { - dot.value = v; - dot.has |= 1 << FILTERS; - } - for (k, f) in filtered.into_iter().enumerate() { - if let (Some(f), Some(slot)) = (f, dot.filtered.get_mut(k)) { - *slot = f; - dot.has |= 1 << k; - } - } - cloud_dot(&mut out, &dot); + fill(&mut cell, values); + cloud_cell(&mut out[0], &cell); + } + out.map(Arc::new) +} + +/// The coloured value and the filtered values of a cell, where it has them. +fn fill(cell: &mut Cell, values: [Option<[f32; 3]>; 1 + FILTERS]) { + let [value, filtered @ ..] = values; + if let Some(v) = value { + cell.value = v; + cell.has |= 1 << FILTERS; + } + for (k, f) in filtered.into_iter().enumerate() { + if let Some(f) = f { + cell.filtered[k] = f; + cell.has |= 1 << k; + } } - Arc::new(out) } /// The cloud as it is drawn now: a filter `playing` in the Edit Point Cloud card at its range @@ -172,7 +242,7 @@ pub fn gpu_clouds(app: &SolveApp, ctx: &egui::Context) -> Vec { solidcraft_engine::view::shown_point_clouds(&app.session) .map(|c| { let key = Key::of(c); - let (version, dots) = match m.get(&c.id) { + let (version, [dots, segments, triangles]) = match m.get(&c.id) { Some((k, version, records)) if *k == key => (*version, records.clone()), _ => { let version = VERSION.with(|v| { @@ -185,7 +255,7 @@ pub fn gpu_clouds(app: &SolveApp, ctx: &egui::Context) -> Vec { } }; let playing = |k: usize| app.tree.cloud_panel.as_ref().and_then(|p| p.playing(c.id, k)); - GpuCloud { id: c.id, version, dots, style: style(ctx, c, playing) } + GpuCloud { id: c.id, version, dots, segments, triangles, style: style(ctx, c, playing) } }) .collect() }) @@ -234,8 +304,8 @@ mod tests { assert!(crate::browser::is_open(&h.app, "point_clouds", true)); let first = gpu_clouds(&h.app, &h.ctx); assert_eq!(first.len(), 1); - let size = solidcraft_gpu::view::DOT_SIZE; - assert_eq!(first[0].dots.len(), 2 * size); + let size = solidcraft_gpu::view::CELL_SIZE; + assert_eq!((first[0].dots.len(), first[0].segments.len()), (2 * size, 0)); // The second point: at x = 10, green. assert_eq!(&first[0].dots[size..size + 4], &10f32.to_le_bytes()); assert_eq!(&first[0].dots[2 * size - 4..2 * size - 1], &[0, 255, 0]); @@ -270,13 +340,9 @@ mod tests { let dir = std::env::temp_dir().join(format!("solidcraft-ui-cloud-play-{}", std::process::id())); std::fs::create_dir_all(&dir).unwrap(); let path = dir.join("t.ply"); - // Eleven points, x and t both running 0 to 10. - let mut ply = String::from( - "ply\nformat ascii 1.0\nelement vertex 11\nproperty float x\nproperty float y\nproperty float z\nproperty float t\nend_header\n", - ); - for i in 0..=10 { - ply += &format!("{i} 0 0 {i}\n"); - } + // One segment, x and t both running 0 to 10 along it. + let ply = "ply\nformat ascii 1.0\nelement vertex 2\nproperty float x\nproperty float y\nproperty float z\nproperty float t\n\ + element edge 1\nproperty int vertex1\nproperty int vertex2\nend_header\n0 0 0 0\n10 0 0 10\n0 1\n"; std::fs::write(&path, ply).unwrap(); let id = h.app.run("pointcloud.insert", serde_json::json!({"path": path.to_string_lossy()})).unwrap()["cloud"].as_u64().unwrap(); // Filtered by x, not by t: the range is what is kept of t, 2 to 4, once worked out. diff --git a/docs/point-clouds.md b/docs/point-clouds.md index 7f0600c80..42768d86c 100644 --- a/docs/point-clouds.md +++ b/docs/point-clouds.md @@ -9,11 +9,11 @@ depends on it. | Extension | What is read | |-----------|--------------| -| `.ply` | ASCII, binary little-endian and binary big-endian PLY: the `vertex` element's `x`, `y`, `z` (any numeric type) and its `red`, `green`, `blue` when present (bytes, 16-bit or 0…1 floats). Every other scalar vertex property (intensity, a class, a time…) is kept, by its name in the file, to colour and filter the cloud by; it is whole-numbered when its type is an integer. Other elements are passed over. | +| `.ply` | ASCII, binary little-endian and binary big-endian PLY: the `vertex` element's `x`, `y`, `z` (any numeric type) and its `red`, `green`, `blue` when present (bytes, 16-bit or 0…1 floats). Every other scalar vertex property (intensity, a class, a time…) is kept, by its name in the file, to colour and filter the cloud by; it is whole-numbered when its type is an integer. The `edge` element (`vertex1`, `vertex2`) and the `face` element (`vertex_indices`, a face as a fan of triangles) become segments and triangles between the points, with their own properties. Other elements are passed over. | | `.xyz`, `.pts` | Text, a point per line: `x y z`, optionally followed by `r g b` (six numbers) or by an intensity and `r g b` (seven or more, as PTS files write it). Spaces, tabs, commas or semicolons separate the numbers; `#` and `//` start comments; a PTS file's first line (its count) is skipped. | -A PLY file that also has faces can be inserted as a mesh body instead with **Insert Mesh** -(`file.insert_mesh`); **Insert Point Cloud** then mentions it in its warnings. +A PLY file with faces can also be inserted as a mesh body with **Insert Mesh** +(`file.insert_mesh`), which makes it solid geometry rather than a reference. Point cloud files say nothing about their length unit. `units` (`mm`, `cm`, `m`, `in`, `ft`) says what it is; the default is millimetres, as for every other import. Lidar and SLAM maps are @@ -42,6 +42,21 @@ A whole-numbered property may name its values with a PLY comment, `property: 0 n name, -1 none` (for example `comment role: 0 outer wall, 1 inner wall`). Coloured by it, the card shows a legend, a swatch and a name per value; clicking a name shows or hides that value. +## Edges and faces + +A cloud read from a PLY file with edges or faces draws them between its points: triangles +filled, segments as lines or, when they have `width` and `height` properties, as beads of that +stadium cross-section (a tube when the two are equal), meeting mitred where one runs into the +next. Points no segment or triangle ends on stay dots, of the cloud's point size. A point that +can't be read (not a finite number, or out of range) is left out with a warning, and so are the +segments and triangles that end on it. + +A property on the points varies along the segments and across the triangles that meet there; +one on the segments or triangles is constant on each. Colours follow the same rule, and a range +filter cuts an element exactly where its value crosses an end of the range, so a filter on a +time property replays a path as it was drawn. A range track weighs each element by its measure, +each kind over its own total: a dot counts 1, a segment its length, a triangle its area. + ## Filters A filter keeps the points whose property lies in a range (both ends included) or, for a @@ -76,7 +91,9 @@ it shows the property's whole span, with the part the track shows framed. ## Size A cloud keeps at most `max_points` points (5,000,000 unless asked, at most 20,000,000); a larger -file is thinned evenly, one point in *n*, and the result says how many were kept. Files up to +file is thinned evenly, one point in *n*, and the result says how many were kept. Thinning would +cut a file's edges and faces, so a thinned file leaves them out, with a warning; raise `max_points` +to keep them. A cloud holds at most 20,000,000 segments and as many triangles. Files up to 1 GiB are read. The points are stored single precision relative to the cloud's first point (kept double precision), so a scan far from the origin keeps its detail; they travel inside the design file as a binary part (12 bytes a point, 3 more with colours). @@ -93,7 +110,7 @@ file as a binary part (12 bytes a point, 3 more with colours). `color?`, `color_range?`, `filters?`, `units?`, `matrix?` (a rigid placement, as `occurrence.move` takes it). - `pointcloud.delete`. -- `pointcloud.list` — each cloud with its properties (name, whole-numbered or not, span, named +- `pointcloud.list` — each cloud with its segment and triangle counts, its properties (name, whole-numbered or not, span, named values), its filters and its ramp's range as drawn (`color_range`). - `doc.open` opens a point cloud file as a new design holding it; dropping one on the window adds it to the open design. diff --git a/xtask/src/mesh_decisions.rs b/xtask/src/mesh_decisions.rs index 123e7334b..ee45c6729 100644 --- a/xtask/src/mesh_decisions.rs +++ b/xtask/src/mesh_decisions.rs @@ -32,10 +32,14 @@ pub const CRATES: &[&str] = &["crates/doc", "crates/engine", "crates/kernel"]; const MODEL_BODY_CRATES: &[&str] = &["crates/doc", "crates/engine"]; /// Modules (a file, or a directory with everything below it) whose job is display, export, -/// previews or mesh bodies: their mesh use is what a mesh is for. +/// previews or mesh bodies: their mesh use is what a mesh is for. Or that hold no mesh at all, +/// only a field the check's syntactic pattern takes for one. pub const SKIPPED_MODULES: &[(&str, &str)] = &[ ("crates/doc/src/display_quality.rs", "the viewport's display quality levels"), ("crates/doc/src/placed_mesh.rs", "the display meshes and plans of bodies and placed parts"), + ("crates/doc/src/point_cloud.rs", "no mesh: the triangles of a point cloud's own complex"), + ("crates/doc/src/point_cloud_complex.rs", "no mesh: the triangles of a point cloud's own complex"), + ("crates/doc/src/point_cloud_distribution.rs", "no mesh: the triangles of a point cloud's own complex"), ("crates/engine/src/cmd/file_thumbnail.rs", "a design's thumbnail picture"), ("crates/engine/src/cmd/mesh.rs", "mesh bodies: repair, decimate and inspect imported meshes"), ("crates/engine/src/cmd/render", "rendered pictures"),