use super::{Column, ColumnFormat, KindUniforms, Mark, MarkCommon, MarkKind, PrepareContext};
#[derive(Debug)]
pub struct SegmentMarks {
pub common: MarkCommon,
sources: Column,
targets: Column,
widths: Column,
colors: Column,
target_colors: Column,
neighbours: Column,
pub arc_height: f32,
pub arc_segments: u32,
pub arc_up: [f32; 3],
pub globe: Option<[f64; 3]>,
globe_rel: [f32; 3],
pub dash: Option<[f32; 2]>,
pub cap: LineCap,
pub outline_width: f32,
pub outline_color: [u8; 4],
path_starts: Vec<u32>,
}
#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
pub enum LineCap {
Butt,
#[default]
Round,
Square,
}
#[derive(Debug, Clone, Default, PartialEq)]
pub struct PathMesh {
pub origin: [f64; 3],
pub sources: Vec<[f32; 3]>,
pub targets: Vec<[f32; 3]>,
pub neighbours: Vec<[f32; 8]>,
pub path_starts: Vec<u32>,
}
impl PathMesh {
pub fn build(paths: &[Vec<[f64; 3]>]) -> Self {
let mut lo = [f64::INFINITY; 3];
let mut hi = [f64::NEG_INFINITY; 3];
for p in paths.iter().flatten() {
for k in 0..3 {
lo[k] = lo[k].min(p[k]);
hi[k] = hi[k].max(p[k]);
}
}
let origin = if lo[0].is_finite() {
[
(lo[0] + hi[0]) * 0.5,
(lo[1] + hi[1]) * 0.5,
(lo[2] + hi[2]) * 0.5,
]
} else {
[0.0; 3]
};
Self::build_around(paths, origin)
}
pub fn build_around(paths: &[Vec<[f64; 3]>], origin: [f64; 3]) -> Self {
let rel = |p: [f64; 3], from: [f64; 3]| {
[
(p[0] - from[0]) as f32,
(p[1] - from[1]) as f32,
(p[2] - from[2]) as f32,
]
};
let len = |a: [f64; 3], b: [f64; 3]| {
((b[0] - a[0]).powi(2) + (b[1] - a[1]).powi(2) + (b[2] - a[2]).powi(2)).sqrt()
};
let mut m = Self {
origin,
..Default::default()
};
for p in paths {
m.path_starts.push(m.sources.len() as u32);
let edges = p.len().saturating_sub(1);
let closed = edges >= 3 && p.first() == p.last();
let mut along = 0.0f64;
for k in 0..edges {
let (s, t) = (p[k], p[k + 1]);
m.sources.push(rel(s, origin));
m.targets.push(rel(t, origin));
let before = match k {
0 if closed => Some(p[edges - 1]),
0 => None,
_ => Some(p[k - 1]),
};
let after = match k + 2 {
j if j <= edges => Some(p[j]),
_ if closed => Some(p[1]),
_ => None,
};
let b = before.map_or([0.0; 3], |q| rel(q, s));
let a = after.map_or([0.0; 3], |q| rel(q, t));
let l = len(s, t);
m.neighbours
.push([b[0], b[1], b[2], along as f32, a[0], a[1], a[2], l as f32]);
along += l;
}
}
m
}
pub fn to_bytes(&self) -> Vec<u8> {
let mut out = Vec::new();
out.extend_from_slice(b"TPA1");
for v in self.origin {
out.extend_from_slice(&v.to_le_bytes());
}
out.extend_from_slice(&(self.sources.len() as u32).to_le_bytes());
out.extend_from_slice(&(self.path_starts.len() as u32).to_le_bytes());
let floats = self
.sources
.iter()
.flatten()
.chain(self.targets.iter().flatten())
.chain(self.neighbours.iter().flatten());
for f in floats {
out.extend_from_slice(&f.to_le_bytes());
}
for s in &self.path_starts {
out.extend_from_slice(&s.to_le_bytes());
}
out
}
pub fn from_bytes(b: &[u8]) -> Result<Self, String> {
let take = |at: &mut usize, n: usize| -> Result<&[u8], String> {
let s = b.get(*at..*at + n).ok_or("PathMesh bytes end early")?;
*at += n;
Ok(s)
};
let mut at = 0;
if take(&mut at, 4)? != b"TPA1" {
return Err("not a PathMesh".into());
}
let mut origin = [0.0; 3];
for o in &mut origin {
*o = f64::from_le_bytes(take(&mut at, 8)?.try_into().unwrap());
}
let n = u32::from_le_bytes(take(&mut at, 4)?.try_into().unwrap()) as usize;
let np = u32::from_le_bytes(take(&mut at, 4)?.try_into().unwrap()) as usize;
let mut f = |count: usize| -> Result<Vec<f32>, String> {
(0..count)
.map(|_| Ok(f32::from_le_bytes(take(&mut at, 4)?.try_into().unwrap())))
.collect()
};
let s = f(n * 3)?;
let t = f(n * 3)?;
let nb = f(n * 8)?;
let path_starts = (0..np)
.map(|_| Ok(u32::from_le_bytes(take(&mut at, 4)?.try_into().unwrap())))
.collect::<Result<Vec<_>, String>>()?;
if at != b.len() {
return Err("PathMesh bytes run on".into());
}
Ok(Self {
origin,
sources: s.chunks(3).map(|c| [c[0], c[1], c[2]]).collect(),
targets: t.chunks(3).map(|c| [c[0], c[1], c[2]]).collect(),
neighbours: nb.chunks(8).map(|c| c.try_into().unwrap()).collect(),
path_starts,
})
}
}
impl Default for SegmentMarks {
fn default() -> Self {
Self::new()
}
}
impl SegmentMarks {
pub fn new() -> Self {
let mut widths = Column::float(1);
widths.set_default_f32(&[1.0]);
Self {
common: MarkCommon::default(),
sources: Column::new(ColumnFormat::PositionF64),
targets: Column::new(ColumnFormat::PositionF64),
widths,
colors: Column::new(ColumnFormat::Unorm8x4),
target_colors: Column::new(ColumnFormat::Unorm8x4),
neighbours: Column::new(ColumnFormat::Float4x2),
arc_height: 0.0,
arc_segments: 32,
arc_up: [0.0, 1.0, 0.0],
globe: None,
globe_rel: [0.0; 3],
dash: None,
cap: LineCap::Round,
outline_width: 0.0,
outline_color: [0, 0, 0, 255],
path_starts: Vec::new(),
}
}
pub fn set_segments(&mut self, sources: &[[f64; 3]], targets: &[[f64; 3]]) {
assert_eq!(sources.len(), targets.len(), "one target per source");
self.common.local_origin = None;
self.sources.set_positions(sources);
self.targets.set_positions(targets);
self.neighbours.set_f32(&[]);
self.path_starts.clear();
}
pub fn set_local_segments(
&mut self,
origin: [f64; 3],
sources: &[[f32; 3]],
targets: &[[f32; 3]],
) {
assert_eq!(sources.len(), targets.len(), "one target per source");
self.common.local_origin = Some(origin);
self.sources.set_local_positions(sources);
self.targets.set_local_positions(targets);
self.neighbours.set_f32(&[]);
self.path_starts.clear();
}
pub fn set_local_paths(&mut self, origin: [f64; 3], paths: &[Vec<[f32; 3]>]) {
let abs: Vec<Vec<[f64; 3]>> = paths
.iter()
.map(|p| {
p.iter()
.map(|q| {
[
origin[0] + q[0] as f64,
origin[1] + q[1] as f64,
origin[2] + q[2] as f64,
]
})
.collect()
})
.collect();
self.set_path_mesh(PathMesh::build_around(&abs, origin));
}
pub fn set_paths(&mut self, paths: &[Vec<[f64; 3]>]) {
self.set_path_mesh(PathMesh::build(paths));
}
pub fn set_path_mesh(&mut self, mesh: PathMesh) {
self.common.local_origin = Some(mesh.origin);
self.sources.set_local_positions(&mesh.sources);
self.targets.set_local_positions(&mesh.targets);
self.neighbours
.set_f32(bytemuck::cast_slice::<[f32; 8], f32>(&mesh.neighbours));
self.path_starts = mesh.path_starts;
}
pub fn path_of(&self, segment: u32) -> Option<usize> {
if self.path_starts.is_empty() || segment as usize >= self.sources.len() {
return None;
}
Some(self.path_starts.partition_point(|&s| s <= segment) - 1)
}
fn per_path<T: Copy>(&self, values: &[T]) -> Vec<T> {
let n = self.sources.len();
let mut out = Vec::with_capacity(n);
for (i, &start) in self.path_starts.iter().enumerate() {
let end = self.path_starts.get(i + 1).copied().unwrap_or(n as u32);
let v = values[i.min(values.len() - 1)];
out.extend(std::iter::repeat_n(v, (end - start) as usize));
}
out
}
pub fn set_path_colors(&mut self, colors: &[[u8; 4]]) {
let c = self.per_path(colors);
self.colors.set_rgba(&c);
self.target_colors.set_rgba(&c);
}
pub fn set_path_widths(&mut self, widths: &[f32]) {
let w = self.per_path(widths);
self.widths.set_f32(&w);
}
fn pieces(&self) -> u32 {
if self.arc_height == 0.0 && self.globe.is_none() {
1
} else {
self.arc_segments.clamp(1, 512)
}
}
pub fn set_widths(&mut self, w: &[f32]) {
self.widths.set_f32(w);
}
pub fn update_widths(&mut self, start: usize, w: &[f32]) {
self.widths.update_f32(start, w);
}
pub fn set_colors(&mut self, c: &[[u8; 4]]) {
self.colors.set_rgba(c);
self.target_colors.set_rgba(c);
}
pub fn set_target_colors(&mut self, c: &[[u8; 4]]) {
self.target_colors.set_rgba(c);
}
pub fn update_colors(&mut self, start: usize, c: &[[u8; 4]]) {
self.colors.update_rgba(start, c);
self.target_colors.update_rgba(start, c);
}
pub fn set_default_color(&mut self, c: [u8; 4]) {
self.colors.set_default_rgba(c);
self.target_colors.set_default_rgba(c);
}
}
impl Mark for SegmentMarks {
fn kind(&self) -> MarkKind {
MarkKind::Segment
}
fn common(&self) -> &MarkCommon {
&self.common
}
fn common_mut(&mut self) -> &mut MarkCommon {
&mut self.common
}
fn instance_count(&self) -> usize {
self.sources.len().min(self.targets.len())
}
fn vertices_per_instance(&self) -> u32 {
6 * self.pieces()
}
fn kind_uniforms(&self) -> KindUniforms {
(
[self.arc_height, self.pieces() as f32, 0.0, 0.0],
match self.globe {
Some(_) => [self.globe_rel[0], self.globe_rel[1], self.globe_rel[2], 1.0],
None => [self.arc_up[0], self.arc_up[1], self.arc_up[2], 0.0],
},
super::points::srgb_u8_to_linear(self.outline_color),
)
}
fn kind_extra(&self) -> [f32; 4] {
let [dash, gap] = self.dash.unwrap_or([0.0, 0.0]);
let cap = match self.cap {
LineCap::Butt => 0.0,
LineCap::Round => 1.0,
LineCap::Square => 3.0,
};
[
dash.max(0.0),
gap.max(0.0),
self.outline_width.max(0.0),
cap,
]
}
fn prepare(&mut self, ctx: &PrepareContext) {
if let Some(c) = self.globe {
let o = ctx.view.origin.position;
self.globe_rel = [
(c[0] - o[0]) as f32,
(c[1] - o[1]) as f32,
(c[2] - o[2]) as f32,
];
}
}
fn columns(&mut self) -> Vec<&mut Column> {
vec![
&mut self.sources,
&mut self.targets,
&mut self.widths,
&mut self.colors,
&mut self.target_colors,
&mut self.neighbours,
]
}
}
#[cfg(test)]
mod tests {
use super::*;
fn split(s: &SegmentMarks) -> (Vec<f32>, Vec<f32>) {
let all: Vec<f32> = bytemuck::pod_collect_to_vec(s.neighbours.bytes());
let (mut prev, mut next) = (Vec::new(), Vec::new());
for row in all.chunks(8) {
prev.extend_from_slice(&row[..3]);
next.extend_from_slice(&row[4..7]);
}
(prev, next)
}
#[test]
fn closed_rings_join_all_round() {
let mut s = SegmentMarks::new();
let square = vec![
[0.0, 0.0, 0.0],
[1.0, 0.0, 0.0],
[1.0, 1.0, 0.0],
[0.0, 1.0, 0.0],
[0.0, 0.0, 0.0],
];
s.set_paths(&[square]);
let (prev, next) = split(&s);
assert_eq!(&prev[0..3], &[0.0, 1.0, 0.0]);
assert_eq!(&next[9..12], &[1.0, 0.0, 0.0]);
assert!(prev.chunks(3).chain(next.chunks(3)).all(|v| v != [0.0; 3]));
}
#[test]
fn paths_flatten_to_edges_and_map_back() {
let mut s = SegmentMarks::new();
s.set_paths(&[
vec![[0.0; 3], [1.0, 0.0, 0.0], [2.0, 0.0, 0.0]],
vec![[5.0; 3]],
vec![[0.0; 3], [0.0, 1.0, 0.0]],
]);
assert_eq!(s.instance_count(), 3);
assert_eq!(s.path_of(0), Some(0));
assert_eq!(s.path_of(1), Some(0));
assert_eq!(s.path_of(2), Some(2));
assert_eq!(s.path_of(3), None);
let (prev, next) = split(&s);
assert_eq!(prev, [0.0, 0.0, 0.0, -1.0, 0.0, 0.0, 0.0, 0.0, 0.0]);
assert_eq!(next, [1.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0]);
s.set_path_colors(&[[1, 0, 0, 255], [2, 0, 0, 255], [3, 0, 0, 255]]);
assert_eq!(
s.colors.bytes(),
&[1, 0, 0, 255, 1, 0, 0, 255, 3, 0, 0, 255]
);
}
}