threers 0.0.7

Drop-in three.js replacement for Rust and WebAssembly (wgpu) — THREE.* API, scene graph, PBR, post-fx, mesh BVH, CSG, an OpenSCAD front end with a watertight exact-CSG kernel, headless render, and native media codecs
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
//! Wide lines, polylines and arcs.

use super::{Column, ColumnFormat, KindUniforms, Mark, MarkCommon, MarkKind, PrepareContext};

/// Lines of any width between pairs of points, straight or arched —
/// deck.gl's `LineLayer` and `ArcLayer`, and `PathLayer` through
/// [`set_paths`](Self::set_paths).
///
/// Each row is one segment from a source to a target. Width is per row (the
/// `widths` column) times [`MarkStyle::size_scale`](super::MarkStyle::size_scale),
/// in pixels or world units, and the colour runs from the row's source colour
/// to its target colour.
///
/// The GPU draws no line wider than one pixel by itself (WebGPU has no line
/// width at all), so every segment is a quad expanded in screen space, with
/// round caps and an antialiased edge computed per fragment.
///
/// Polylines become one segment per edge, each knowing its neighbours, and
/// meet at mitred joints: the two quads share the joint's bisector, so a
/// translucent line is not darker where they meet. Turns sharper than 120°
/// would make long spikes; there both ends get round caps instead, which
/// overlap. Closed rings (last point equal to the first) join all round.
#[derive(Debug)]
pub struct SegmentMarks {
    pub common: MarkCommon,
    sources: Column,
    targets: Column,
    widths: Column,
    colors: Column,
    target_colors: Column,
    /// Per row: the previous point of its path minus the source and the
    /// distance along the path to the source; the next point minus the
    /// target and the segment's length. Zero where the path ends. One buffer
    /// for all of it, to stay inside WebGPU's eight vertex buffers with both
    /// custom columns bound.
    neighbours: Column,
    /// Height of the arc's peak as a fraction of the segment's length. 0 is a
    /// straight line; 0.5 is a tall arch.
    pub arc_height: f32,
    /// Pieces each arc is drawn in. Ignored (one piece) when `arc_height` is 0.
    pub arc_segments: u32,
    /// The direction arcs rise in, world space.
    pub arc_up: [f32; 3],
    /// The centre of a globe the segments lie on: they then follow great
    /// circles (in [`arc_segments`](Self::arc_segments) pieces, even with no
    /// height) and arcs rise away from the centre instead of along
    /// [`arc_up`](Self::arc_up).
    pub globe: Option<[f64; 3]>,
    globe_rel: [f32; 3],
    /// Dashes along straight segments and paths: `[dash, gap]`, each in
    /// line widths, continuing across a path's joints.
    pub dash: Option<[f32; 2]>,
    /// The ends of lines and paths. Joints are mitred whatever this is.
    pub cap: LineCap,
    /// A casing this many pixels wide inside the line's edge, in
    /// [`outline_color`](Self::outline_color): roads, borders.
    pub outline_width: f32,
    /// sRGB, straight alpha.
    pub outline_color: [u8; 4],
    /// For segments made by [`set_paths`](Self::set_paths): the first segment
    /// of each path, so a segment's row maps back to its path.
    path_starts: Vec<u32>,
}

/// How a line ends.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
pub enum LineCap {
    /// Flat, at the end point.
    Butt,
    /// A half disc past the end point.
    #[default]
    Round,
    /// A half square past the end point.
    Square,
}

/// Polylines flattened to segments, as plain data, built on any thread —
/// what [`SegmentMarks::set_path_mesh`] uploads.
///
/// Each segment knows its neighbours (for mitred joints) and its distance
/// along its path (for dashes), and positions are local to `origin`.
#[derive(Debug, Clone, Default, PartialEq)]
pub struct PathMesh {
    pub origin: [f64; 3],
    pub sources: Vec<[f32; 3]>,
    pub targets: Vec<[f32; 3]>,
    /// Per segment: previous point minus source, distance along the path to
    /// the source; next point minus target, the segment's length.
    pub neighbours: Vec<[f32; 8]>,
    /// The first segment of each path.
    pub path_starts: Vec<u32>,
}

impl PathMesh {
    /// Flatten `paths`, local to the middle of their bounds.
    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)
    }

    /// Flatten `paths`, local to `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
    }

    /// As bytes for a Web Worker boundary, little-endian.
    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
    }

    /// [`to_bytes`](Self::to_bytes) back.
    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(),
        }
    }

    /// Source and target of every segment. Both must be the same length.
    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();
    }

    /// [`set_segments`](Self::set_segments) with both ends relative to
    /// `origin`, at half the memory.
    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();
    }

    /// [`set_paths`](Self::set_paths) with points relative to `origin`.
    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));
    }

    /// Polylines, one segment per edge. Colours and widths set afterwards are
    /// per *segment*; [`set_path_colors`](Self::set_path_colors) and
    /// [`set_path_widths`](Self::set_path_widths) set them per path.
    pub fn set_paths(&mut self, paths: &[Vec<[f64; 3]>]) {
        self.set_path_mesh(PathMesh::build(paths));
    }

    /// Paths prepared by [`PathMesh::build`], on any thread.
    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;
    }

    /// The path a segment row belongs to, when built with
    /// [`set_paths`](Self::set_paths).
    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
    }

    /// One colour per path, for paths from [`set_paths`](Self::set_paths).
    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);
    }

    /// One width per path.
    pub fn set_path_widths(&mut self, widths: &[f32]) {
        let w = self.per_path(widths);
        self.widths.set_f32(&w);
    }

    /// Pieces each segment is drawn in.
    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);
    }
    /// Colour at each segment's source — and at its target too, unless
    /// [`set_target_colors`](Self::set_target_colors) says otherwise.
    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],
            },
            // The casing's colour.
            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::*;

    /// The neighbours column as (prev, next), each a flat run of triples.
    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);
        // The first edge's predecessor is the last edge's source, and the
        // last edge's successor is the first edge's target.
        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));
        // The single-point path has no segments; row 2 is the third path.
        assert_eq!(s.path_of(2), Some(2));
        assert_eq!(s.path_of(3), None);
        // Neighbours: the first edge has none before it, the middle joint is
        // shared, and the second path's lone edge is free at both ends.
        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]
        );
    }
}