threers 0.1.0

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
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
//! Bindings split out of `wasm.rs` by area (see the `mod` list there): the
//! shim's `Curve` hierarchy — three.js r165's `Curve`, `CurvePath` and every
//! built-in curve — over [`crate::curves::three`], in `f64` as JavaScript
//! computes it.
//!
//! One [`WebCurve`] backs one JavaScript curve object. The shim keeps the
//! three.js-visible properties (`v1`, `points`, `closed`, …) on the JS object
//! and pushes them here before each call; the arc-length tables and their
//! `needsUpdate` live here, cached exactly as three.js caches them.
//!
//! A JavaScript `Curve` subclass that overrides `getPoint` becomes a custom
//! curve: the base-class algorithms run here and call back into that
//! `getPoint` (a `js_sys::Function`), so `getPointAt`, `getSpacedPoints`,
//! `computeFrenetFrames` and the Tube/Extrude sweeps all work on it.
#![allow(unused_imports)]

use super::*;
use crate::curves::shapes::{ShapeCurve, Vec2d};
use crate::curves::three::{
    CatmullRomType, CurveDef, CustomCurve, CustomRole, PointFn, ThreeCurve, Vec3d,
};
use std::cell::RefCell;
use std::rc::Rc;

thread_local! {
    /// The exception a JavaScript `getPoint` threw during the current
    /// evaluation; further callbacks are skipped until it is reported.
    static CALLBACK_ERROR: RefCell<Option<JsValue>> = const { RefCell::new(None) };
}

/// A JS `(t) => boolean` that writes the point into `out` (false = null).
fn js_point_fn(f: js_sys::Function, out: js_sys::Float64Array) -> PointFn {
    Rc::new(move |t| {
        if CALLBACK_ERROR.with(|e| e.borrow().is_some()) {
            return None;
        }
        match f.call1(&JsValue::NULL, &JsValue::from_f64(t)) {
            Ok(v) if v.is_truthy() => Some([out.get_index(0), out.get_index(1), out.get_index(2)]),
            Ok(_) => None,
            Err(e) => {
                CALLBACK_ERROR.with(|s| *s.borrow_mut() = Some(e));
                None
            }
        }
    })
}

/// Run `f`, rethrowing anything a JS callback threw during it (and dropping
/// the caches it may have filled with NaN).
fn checked<T>(node: &ThreeCurve, f: impl FnOnce() -> T) -> Result<T, JsValue> {
    let outer = CALLBACK_ERROR.with(|e| e.borrow_mut().take());
    let r = f();
    let err = CALLBACK_ERROR.with(|e| std::mem::replace(&mut *e.borrow_mut(), outer));
    match err {
        Some(e) => {
            node.clear_caches();
            Err(e)
        }
        None => Ok(r),
    }
}

fn v2(a: &[f64], i: usize) -> Vec2d {
    Vec2d::new(a[i], a[i + 1])
}

fn v3(a: &[f64], i: usize) -> Vec3d {
    [a[i], a[i + 1], a[i + 2]]
}

fn flat_points(points: Vec<Option<Vec3d>>) -> Vec<f64> {
    points
        .into_iter()
        .flat_map(|p| p.unwrap_or([f64::NAN; 3]))
        .collect()
}

fn bad_len(what: &str, n: usize) -> JsValue {
    js_sys::TypeError::new(&format!("{what}: unexpected {n} numbers")).into()
}

/// One three.js curve object (see the module docs).
#[wasm_bindgen]
pub struct WebCurve {
    node: Rc<ThreeCurve>,
}

impl WebCurve {
    pub(crate) fn node(&self) -> &Rc<ThreeCurve> {
        &self.node
    }
}

#[wasm_bindgen]
impl WebCurve {
    /// A curve to be defined by one of the `set*` calls (a zero-length
    /// `LineCurve3` until then).
    #[wasm_bindgen(constructor)]
    pub fn new() -> WebCurve {
        WebCurve {
            node: ThreeCurve::line3([0.0; 3], [0.0; 3]),
        }
    }

    /// A `Curve` subclass with its own `getPoint`: `get_point(t)` writes the
    /// point to `out[0..3]` and returns whether there was one. An overridden
    /// `getTangent` comes the same way. `role`: 0 plain, 1 line, 2 ellipse,
    /// 3 spline (of `spline_points` points) — what the object's three.js flags
    /// say it is.
    pub fn custom(
        get_point: js_sys::Function,
        out: js_sys::Float64Array,
        get_tangent: Option<js_sys::Function>,
        dims: u8,
        role: u8,
        spline_points: usize,
    ) -> WebCurve {
        let role = match role {
            1 => CustomRole::Line,
            2 => CustomRole::Ellipse,
            3 => CustomRole::Spline(spline_points),
            _ => CustomRole::Plain,
        };
        WebCurve {
            node: ThreeCurve::new(CurveDef::Custom(CustomCurve {
                get_point: js_point_fn(get_point, out.clone()),
                get_tangent: get_tangent.map(|f| js_point_fn(f, out)),
                dims,
                role,
            })),
        }
    }

    /// Update a custom curve's role (a spline subclass's point count moves).
    #[wasm_bindgen(js_name = setCustomRole)]
    pub fn set_custom_role(&self, dims: u8, role: u8, spline_points: usize) {
        self.node.with_def_mut(|d| {
            if let CurveDef::Custom(c) = d {
                c.dims = dims;
                c.role = match role {
                    1 => CustomRole::Line,
                    2 => CustomRole::Ellipse,
                    3 => CustomRole::Spline(spline_points),
                    _ => CustomRole::Plain,
                };
            }
        });
    }

    /// `LineCurve` (`[x1, y1, x2, y2]`) or `LineCurve3` (six numbers).
    #[wasm_bindgen(js_name = setLine)]
    pub fn set_line(&self, v: &[f64]) -> Result<(), JsValue> {
        let def = match v.len() {
            4 => CurveDef::Planar(ShapeCurve::Line {
                v1: v2(v, 0),
                v2: v2(v, 2),
            }),
            6 => CurveDef::Line3 {
                v1: v3(v, 0),
                v2: v3(v, 3),
            },
            n => return Err(bad_len("setLine", n)),
        };
        self.node.set_def(def);
        Ok(())
    }

    /// `QuadraticBezierCurve` (six numbers) or `QuadraticBezierCurve3` (nine).
    #[wasm_bindgen(js_name = setQuadraticBezier)]
    pub fn set_quadratic_bezier(&self, v: &[f64]) -> Result<(), JsValue> {
        let def = match v.len() {
            6 => CurveDef::Planar(ShapeCurve::QuadraticBezier {
                v0: v2(v, 0),
                v1: v2(v, 2),
                v2: v2(v, 4),
            }),
            9 => CurveDef::QuadraticBezier3 {
                v0: v3(v, 0),
                v1: v3(v, 3),
                v2: v3(v, 6),
            },
            n => return Err(bad_len("setQuadraticBezier", n)),
        };
        self.node.set_def(def);
        Ok(())
    }

    /// `CubicBezierCurve` (eight numbers) or `CubicBezierCurve3` (twelve).
    #[wasm_bindgen(js_name = setCubicBezier)]
    pub fn set_cubic_bezier(&self, v: &[f64]) -> Result<(), JsValue> {
        let def = match v.len() {
            8 => CurveDef::Planar(ShapeCurve::CubicBezier {
                v0: v2(v, 0),
                v1: v2(v, 2),
                v2: v2(v, 4),
                v3: v2(v, 6),
            }),
            12 => CurveDef::CubicBezier3 {
                v0: v3(v, 0),
                v1: v3(v, 3),
                v2: v3(v, 6),
                v3: v3(v, 9),
            },
            n => return Err(bad_len("setCubicBezier", n)),
        };
        self.node.set_def(def);
        Ok(())
    }

    /// `SplineCurve`, points flattened `[x0, y0, …]`.
    #[wasm_bindgen(js_name = setSpline)]
    pub fn set_spline(&self, points: &[f64]) {
        let points = points
            .as_chunks::<2>()
            .0
            .iter()
            .map(|c| Vec2d::new(c[0], c[1]))
            .collect();
        self.node
            .set_def(CurveDef::Planar(ShapeCurve::Spline { points }));
    }

    /// `EllipseCurve` / `ArcCurve`.
    #[wasm_bindgen(js_name = setEllipse)]
    #[allow(clippy::too_many_arguments)]
    pub fn set_ellipse(
        &self,
        x: f64,
        y: f64,
        x_radius: f64,
        y_radius: f64,
        start_angle: f64,
        end_angle: f64,
        clockwise: bool,
        rotation: f64,
    ) {
        self.node.set_def(CurveDef::Planar(ShapeCurve::Ellipse {
            x,
            y,
            x_radius,
            y_radius,
            start_angle,
            end_angle,
            clockwise,
            rotation,
        }));
    }

    /// `CatmullRomCurve3`, points flattened `[x0, y0, z0, …]`.
    #[wasm_bindgen(js_name = setCatmullRom)]
    pub fn set_catmull_rom(&self, points: &[f64], closed: bool, curve_type: &str, tension: f64) {
        self.node.set_def(CurveDef::CatmullRom3 {
            points: points
                .as_chunks::<3>()
                .0
                .iter()
                .map(|c| [c[0], c[1], c[2]])
                .collect(),
            closed,
            curve_type: CatmullRomType::parse(curve_type),
            tension,
        });
    }

    /// Make this a `CurvePath` with no curves yet (keeping its caches);
    /// `addCurve` then lists them.
    #[wasm_bindgen(js_name = setPath)]
    pub fn set_path(&self, auto_close: bool) {
        self.node.set_def(CurveDef::Path {
            curves: Vec::new(),
            auto_close,
        });
    }

    /// Append to a `CurvePath` (the same curve object, shared).
    #[wasm_bindgen(js_name = addCurve)]
    pub fn add_curve(&self, curve: &WebCurve) {
        let child = curve.node.clone();
        self.node.with_def_mut(|d| {
            if let CurveDef::Path { curves, .. } = d {
                curves.push(child);
            }
        });
    }

    #[wasm_bindgen(getter, js_name = arcLengthDivisions)]
    pub fn arc_length_divisions(&self) -> usize {
        self.node.arc_length_divisions()
    }

    #[wasm_bindgen(setter, js_name = arcLengthDivisions)]
    pub fn set_arc_length_divisions(&self, n: usize) {
        self.node.set_arc_length_divisions(n);
    }

    #[wasm_bindgen(getter, js_name = needsUpdate)]
    pub fn needs_update(&self) -> bool {
        self.node.needs_update()
    }

    #[wasm_bindgen(setter, js_name = needsUpdate)]
    pub fn set_needs_update(&self, v: bool) {
        self.node.set_needs_update(v);
    }

    /// `cacheArcLengths`, or undefined before the first `getLengths`.
    #[wasm_bindgen(js_name = cacheArcLengths)]
    pub fn cache_arc_lengths(&self) -> Option<Vec<f64>> {
        self.node.cache_arc_lengths().map(|c| c.to_vec())
    }

    /// 2 for a 2D curve (its points are `Vector2`s), 3 otherwise.
    #[wasm_bindgen(getter)]
    pub fn dims(&self) -> u8 {
        self.node.dims()
    }

    /// `getPoint(t)` as `[x, y, z]`, empty for null.
    #[wasm_bindgen(js_name = getPoint)]
    pub fn get_point(&self, t: f64) -> Result<Vec<f64>, JsValue> {
        checked(&self.node, || {
            self.node.get_point(t).map_or(Vec::new(), |p| p.to_vec())
        })
    }

    /// `getPointAt(u)` as `[x, y, z]`, empty for null.
    #[wasm_bindgen(js_name = getPointAt)]
    pub fn get_point_at(&self, u: f64) -> Result<Vec<f64>, JsValue> {
        checked(&self.node, || {
            self.node.get_point_at(u).map_or(Vec::new(), |p| p.to_vec())
        })
    }

    /// `getPoints(divisions)`, flattened xyz.
    #[wasm_bindgen(js_name = getPoints)]
    pub fn get_points(&self, divisions: usize) -> Result<Vec<f64>, JsValue> {
        checked(&self.node, || flat_points(self.node.get_points(divisions)))
    }

    /// `getSpacedPoints(divisions)`, flattened xyz.
    #[wasm_bindgen(js_name = getSpacedPoints)]
    pub fn get_spaced_points(&self, divisions: usize) -> Result<Vec<f64>, JsValue> {
        checked(&self.node, || {
            flat_points(self.node.get_spaced_points(divisions))
        })
    }

    #[wasm_bindgen(js_name = getLength)]
    pub fn get_length(&self) -> Result<f64, JsValue> {
        checked(&self.node, || self.node.get_length())
    }

    #[wasm_bindgen(js_name = getLengths)]
    pub fn get_lengths(&self, divisions: usize) -> Result<Vec<f64>, JsValue> {
        checked(&self.node, || self.node.get_lengths(divisions).to_vec())
    }

    #[wasm_bindgen(js_name = updateArcLengths)]
    pub fn update_arc_lengths(&self) -> Result<(), JsValue> {
        checked(&self.node, || self.node.update_arc_lengths())
    }

    /// `getUtoTmapping(u, distance)`.
    #[wasm_bindgen(js_name = getUtoTmapping)]
    pub fn get_u_to_t_mapping(&self, u: f64, distance: Option<f64>) -> Result<f64, JsValue> {
        checked(&self.node, || self.node.get_u_to_t_mapping(u, distance))
    }

    /// `getTangent(t)` as `[x, y, z]`.
    #[wasm_bindgen(js_name = getTangent)]
    pub fn get_tangent(&self, t: f64) -> Result<Vec<f64>, JsValue> {
        checked(&self.node, || self.node.get_tangent(t).to_vec())
    }

    /// `Curve.prototype.getTangent(t)`: the base class's (or a line's),
    /// never an override — what `super.getTangent` reaches.
    #[wasm_bindgen(js_name = getBaseTangent)]
    pub fn get_base_tangent(&self, t: f64) -> Result<Vec<f64>, JsValue> {
        checked(&self.node, || self.node.get_tangent_base(t).to_vec())
    }

    /// `getTangentAt(u)` as `[x, y, z]`.
    #[wasm_bindgen(js_name = getTangentAt)]
    pub fn get_tangent_at(&self, u: f64) -> Result<Vec<f64>, JsValue> {
        checked(&self.node, || self.node.get_tangent_at(u).to_vec())
    }

    /// `computeFrenetFrames(segments, closed)`: the tangents, then the
    /// normals, then the binormals, each `segments + 1` flattened xyz.
    #[wasm_bindgen(js_name = computeFrenetFrames)]
    pub fn compute_frenet_frames(
        &self,
        segments: usize,
        closed: bool,
    ) -> Result<Vec<f64>, JsValue> {
        checked(&self.node, || {
            let f = self.node.compute_frenet_frames(segments, closed);
            f.tangents
                .iter()
                .chain(f.normals.iter())
                .chain(f.binormals.iter())
                .flatten()
                .copied()
                .collect()
        })
    }

    /// `CurvePath.getCurveLengths()`.
    #[wasm_bindgen(js_name = getCurveLengths)]
    pub fn get_curve_lengths(&self) -> Result<Vec<f64>, JsValue> {
        checked(&self.node, || self.node.get_curve_lengths().to_vec())
    }
}

impl Default for WebCurve {
    fn default() -> Self {
        Self::new()
    }
}

/// `new TubeGeometry(path, …)`: the geometry and the frames three.js keeps
/// on it.
#[wasm_bindgen]
pub struct WebTubeResult {
    geometry: Option<WebGeometry>,
    frames: Vec<f64>,
}

#[wasm_bindgen]
impl WebTubeResult {
    /// The geometry (once).
    pub fn geometry(&mut self) -> Option<WebGeometry> {
        self.geometry.take()
    }

    /// Tangents, normals, binormals: each `tubularSegments + 1` xyz.
    pub fn frames(&self) -> Vec<f64> {
        self.frames.clone()
    }
}

#[wasm_bindgen]
impl WebGeometry {
    /// three.js r165 `new TubeGeometry(path, tubularSegments, radius,
    /// radialSegments, closed)`; `path` may be a custom (JavaScript) curve.
    #[wasm_bindgen(js_name = tubeFromCurve)]
    pub fn tube_from_curve(
        path: &WebCurve,
        tubular_segments: usize,
        radius: f64,
        radial_segments: usize,
        closed: bool,
    ) -> Result<WebTubeResult, JsValue> {
        let (g, f) = checked(&path.node, || {
            crate::geometries::TubeGeometry::from_curve(
                &path.node,
                tubular_segments,
                radius,
                radial_segments,
                closed,
            )
        })?;
        Ok(WebTubeResult {
            geometry: Some(WebGeometry { inner: Arc::new(g) }),
            frames: f
                .tangents
                .iter()
                .chain(f.normals.iter())
                .chain(f.binormals.iter())
                .flatten()
                .copied()
                .collect(),
        })
    }
}

/// `curve.getPoint` etc. errors a JS callback raised, for bindings elsewhere.
pub(crate) fn checked_curve<T>(
    curve: &WebCurve,
    f: impl FnOnce(&ThreeCurve) -> T,
) -> Result<T, JsValue> {
    checked(&curve.node, || f(&curve.node))
}

// ---- curves ----
// The three.js curve classes are `WebCurve`, in `src/wasm/curves.rs`.

#[wasm_bindgen]
pub struct WebPath {
    pub(super) inner: crate::Path,
}
#[wasm_bindgen]
impl WebPath {
    #[wasm_bindgen(constructor)]
    pub fn new() -> WebPath {
        WebPath {
            inner: crate::Path::new(),
        }
    }
    #[wasm_bindgen(js_name = moveTo)]
    pub fn move_to(&mut self, x: f32, y: f32) {
        self.inner.move_to(crate::Vector2::new(x, y));
    }
    #[wasm_bindgen(js_name = lineTo)]
    pub fn line_to(&mut self, x: f32, y: f32) {
        self.inner.line_to(crate::Vector2::new(x, y));
    }

    #[wasm_bindgen(js_name = quadraticCurveTo)]
    pub fn quadratic_curve_to(&mut self, cpx: f32, cpy: f32, x: f32, y: f32) {
        self.inner
            .quadratic_curve_to(crate::Vector2::new(cpx, cpy), crate::Vector2::new(x, y));
    }

    #[wasm_bindgen(js_name = bezierCurveTo)]
    pub fn bezier_curve_to(&mut self, c1x: f32, c1y: f32, c2x: f32, c2y: f32, x: f32, y: f32) {
        self.inner.bezier_curve_to(
            crate::Vector2::new(c1x, c1y),
            crate::Vector2::new(c2x, c2y),
            crate::Vector2::new(x, y),
        );
    }

    pub fn arc(&mut self, cx: f32, cy: f32, radius: f32, start: f32, end: f32, clockwise: bool) {
        self.inner
            .arc(crate::Vector2::new(cx, cy), radius, start, end, clockwise);
    }

    /// Sample the path as a flat polyline — `divisions` points per sub-curve.
    #[wasm_bindgen(js_name = getPoints)]
    pub fn get_points(&self, divisions: usize) -> Vec<f32> {
        self.inner
            .get_points(divisions.max(1))
            .into_iter()
            .flat_map(|p| [p.x, p.y])
            .collect()
    }

    /// The path as an SVG `d` string, with its curves intact rather than
    /// flattened. Note that SVG's y axis points down and these coordinates are
    /// y-up, so a document usually wants a `scale(1,-1)` around them.
    #[wasm_bindgen(js_name = toSvgPathData)]
    pub fn to_svg_path_data(&self, precision: usize) -> String {
        self.inner.to_svg_path_data(precision)
    }

    /// Read an SVG `d` string — the inbound half, for turning artwork into
    /// geometry.
    #[wasm_bindgen(js_name = fromSvgPathData)]
    pub fn from_svg_path_data(d: &str) -> Result<WebPath, JsValue> {
        crate::Path::from_svg_path_data(d)
            .map(|inner| WebPath { inner })
            .map_err(|e| JsValue::from_str(&e.to_string()))
    }
}

#[wasm_bindgen]
pub struct WebShape {
    pub(crate) inner: crate::Shape,
}
#[wasm_bindgen]
impl WebShape {
    #[wasm_bindgen(constructor)]
    pub fn new() -> WebShape {
        WebShape {
            inner: crate::Shape::new(),
        }
    }

    #[wasm_bindgen(js_name = fromPath)]
    pub fn from_path(outline: &WebPath) -> WebShape {
        WebShape {
            inner: crate::Shape::from_path(
                crate::Path::from_svg_path_data(&outline.inner.to_svg_path_data(6))
                    .unwrap_or_default(),
            ),
        }
    }

    #[wasm_bindgen(js_name = addHole)]
    pub fn add_hole(&mut self, hole: &WebPath) {
        if let Ok(p) = crate::Path::from_svg_path_data(&hole.inner.to_svg_path_data(6)) {
            self.inner.add_hole(p);
        }
    }

    /// Outline then holes, as one `d` string. Fill it with
    /// `fill-rule="evenodd"` — see the Rust-side docs for why.
    #[wasm_bindgen(js_name = toSvgPathData)]
    pub fn to_svg_path_data(&self, precision: usize) -> String {
        self.inner.to_svg_path_data(precision)
    }

    /// Read SVG path data as an outline plus holes: first subpath is the
    /// outline, the rest are holes.
    #[wasm_bindgen(js_name = fromSvgPathData)]
    pub fn from_svg_path_data(d: &str) -> Result<WebShape, JsValue> {
        crate::Shape::from_svg_path_data(d)
            .map(|inner| WebShape { inner })
            .map_err(|e| JsValue::from_str(&e.to_string()))
    }
}