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
use super::PointerEvent;
use crate::cameras::PerspectiveCamera;
use crate::math::{Spherical, Vector3};

/// Spherical orbit camera controls — rotate, pan, zoom around `target`.
/// Mirrors three.js's `OrbitControls`.
#[derive(Debug, Clone, Copy)]
pub struct OrbitControls {
    pub target: Vector3,
    pub min_distance: f32,
    pub max_distance: f32,
    pub min_polar_angle: f32,
    pub max_polar_angle: f32,
    /// Azimuth limits (radians). When `min > max` wrapping is allowed (default).
    pub min_azimuth_angle: f32,
    pub max_azimuth_angle: f32,
    pub rotate_speed: f32,
    pub zoom_speed: f32,
    pub pan_speed: f32,
    /// Inertia factor in `0..1`. `0` = no damping (input applied immediately).
    /// Typical three.js value is `0.05` with `enable_damping = true`.
    pub damping: f32,
    /// When true, residual spherical / pan deltas decay each frame. Call
    /// [`update`](Self::update) / [`update_dt`](Self::update_dt) every frame.
    pub enable_damping: bool,
    /// Continuous azimuth spin when idle.
    pub auto_rotate: bool,
    /// Radians per second when `auto_rotate` is on. three.js default ≈ 2π / 30.
    pub auto_rotate_speed: f32,
    /// three.js `screenSpacePanning`: pan in the screen plane (`true`, the
    /// default) or across the plane orthogonal to the camera's up (`false`,
    /// `MapControls`' default — dragging moves over the ground).
    pub screen_space_panning: bool,
    /// three.js `zoomToCursor`: dolly toward the pointer (keeping the world
    /// point under it fixed) instead of toward `target`. Needs `PointerEvent.cursor`.
    pub zoom_to_cursor: bool,
    spherical: Spherical,
    /// Residual rotate deltas (theta, phi) for damping.
    spherical_delta: (f32, f32),
    pan_offset: Vector3,
    zoom_scale: f32,
    /// Pointer NDC captured on the last wheel, for dolly-to-cursor while the
    /// zoom eases under damping.
    zoom_cursor: (f32, f32),
}

impl OrbitControls {
    pub fn new(camera: &PerspectiveCamera) -> Self {
        let offset = camera.position - camera.target;
        let spherical = Spherical::from_vector3(offset);
        Self {
            target: camera.target,
            min_distance: 0.1,
            max_distance: 1000.0,
            min_polar_angle: 0.0,
            max_polar_angle: std::f32::consts::PI,
            min_azimuth_angle: f32::NEG_INFINITY,
            max_azimuth_angle: f32::INFINITY,
            rotate_speed: 1.0,
            zoom_speed: 1.0,
            pan_speed: 1.0,
            damping: 0.05,
            enable_damping: false,
            auto_rotate: false,
            auto_rotate_speed: std::f32::consts::TAU / 30.0,
            screen_space_panning: true,
            zoom_to_cursor: false,
            spherical,
            spherical_delta: (0.0, 0.0),
            pan_offset: Vector3::ZERO,
            zoom_scale: 1.0,
            zoom_cursor: (0.0, 0.0),
        }
    }

    /// Shift `target` so the world point under the cursor stays put as the
    /// radius goes `old → new` (three.js `zoomToCursor`). The cursor point on
    /// the focus plane is `target + k·radius`; keeping it fixed means
    /// `target += k·old·(1 − new/old)`.
    fn dolly_to_cursor(&mut self, camera: &PerspectiveCamera, old_radius: f32, new_radius: f32) {
        if !self.zoom_to_cursor || old_radius <= 0.0 {
            return;
        }
        let (cx, cy) = self.zoom_cursor;
        let offset = self.spherical.to_vector3(); // position − target
        let forward = (-offset).normalize();
        let right = forward.cross(Vector3::UP).normalize();
        let up = right.cross(forward).normalize();
        let tan_half = (camera.fov * 0.5).tan();
        let k = right * (cx * tan_half * camera.aspect) + up * (cy * tan_half);
        self.target = self.target + k * (old_radius * (1.0 - new_radius / old_radius));
    }

    /// Rebuild spherical state from the camera's current pose (parity orbit sync).
    pub fn reseed_from_camera(&mut self, camera: &PerspectiveCamera) {
        self.target = camera.target;
        self.spherical = Spherical::from_vector3(camera.position - camera.target);
        self.pan_offset = Vector3::ZERO;
        self.spherical_delta = (0.0, 0.0);
        self.zoom_scale = 1.0;
    }

    /// Apply one frame of input at a presumed 60 Hz step. Prefer
    /// [`update_dt`](Self::update_dt) when you have a real delta.
    pub fn update(
        &mut self,
        ev: PointerEvent,
        camera: &mut PerspectiveCamera,
        viewport: (f32, f32),
    ) {
        self.update_dt(ev, camera, viewport, 1.0 / 60.0);
    }

    /// Apply input + damping / auto-rotate for `dt` seconds.
    pub fn update_dt(
        &mut self,
        ev: PointerEvent,
        camera: &mut PerspectiveCamera,
        viewport: (f32, f32),
        dt: f32,
    ) {
        let (w, h) = viewport;
        let half_fov = camera.fov * 0.5;
        let dist = self.spherical.radius;
        let dt = if dt.is_finite() && dt > 0.0 {
            dt
        } else {
            1.0 / 60.0
        };

        if ev.rotating {
            let dtheta = -ev.dx / h * std::f32::consts::PI * 2.0 * self.rotate_speed;
            let dphi = -ev.dy / h * std::f32::consts::PI * 2.0 * self.rotate_speed;
            self.spherical_delta.0 += dtheta;
            self.spherical_delta.1 += dphi;
        }
        if ev.panning {
            let world_per_pixel = 2.0 * dist * half_fov.tan() / h;
            let offset = self.spherical.to_vector3();
            let forward = (-offset).normalize();
            let world_up = Vector3::UP;
            let right = forward.cross(world_up).normalize();
            // three.js `panUp`: the camera's own up, or (map-style) the
            // world up crossed with the camera's right — forward along the
            // ground.
            let up = if self.screen_space_panning {
                right.cross(forward).normalize()
            } else {
                world_up.cross(right)
            };
            self.pan_offset = self.pan_offset
                + right * (-ev.dx * world_per_pixel * self.pan_speed)
                + up * (ev.dy * world_per_pixel * self.pan_speed);
        }
        if ev.wheel != 0.0 {
            self.zoom_cursor = ev.cursor;
            let factor = (1.0 - ev.wheel * 0.001 * self.zoom_speed).clamp(0.1, 10.0);
            if self.enable_damping && self.damping > 0.0 {
                self.zoom_scale *= factor;
            } else {
                let old = self.spherical.radius;
                let new = (old * factor).clamp(self.min_distance, self.max_distance);
                self.spherical.radius = new;
                self.dolly_to_cursor(camera, old, new);
            }
        }

        if self.auto_rotate && !ev.rotating {
            self.spherical_delta.0 += self.auto_rotate_speed * dt;
        }

        let has_residual = self.spherical_delta.0.abs() > 1e-8
            || self.spherical_delta.1.abs() > 1e-8
            || self.pan_offset.length_sq() > 1e-12
            || (self.zoom_scale - 1.0).abs() > 1e-8;
        let has_input = ev.rotating || ev.panning || ev.wheel != 0.0;
        let needs_tick = has_input || has_residual || self.auto_rotate;

        // Idle frames must not rewrite the camera — external sync may have set
        // the wasm pose without updating our spherical state yet.
        if !needs_tick {
            return;
        }

        if self.enable_damping && self.damping > 0.0 {
            // three.js: each frame applies `damping` of the residual and keeps
            // the rest, so a gesture's total motion (Σ d·(1−d)^k = 1) equals the
            // input — applying the whole residual would multiply it by 1/d.
            let d = self.damping.clamp(0.0, 1.0);
            let damp = 1.0 - d;
            self.spherical.theta += self.spherical_delta.0 * d;
            self.spherical.phi += self.spherical_delta.1 * d;
            self.spherical_delta.0 *= damp;
            self.spherical_delta.1 *= damp;
            self.target = self.target + self.pan_offset * d;
            self.pan_offset = self.pan_offset * damp;
            if (self.zoom_scale - 1.0).abs() > 1e-8 {
                // The same split in log space: this frame takes zoom^d and
                // zoom^(1−d) remains, so the eased total is the wheel's factor.
                let step = self.zoom_scale.powf(d);
                let old = self.spherical.radius;
                let new = (old * step).clamp(self.min_distance, self.max_distance);
                self.spherical.radius = new;
                self.dolly_to_cursor(camera, old, new);
                self.zoom_scale /= step;
            }
            // Snap residuals to rest so damping does not hiss forever as
            // sub-pixel orbit jitter.
            const REST: f32 = 1e-6;
            if self.spherical_delta.0.abs() < REST {
                self.spherical_delta.0 = 0.0;
            }
            if self.spherical_delta.1.abs() < REST {
                self.spherical_delta.1 = 0.0;
            }
            if self.pan_offset.length_sq() < REST * REST {
                self.pan_offset = Vector3::ZERO;
            }
            if (self.zoom_scale - 1.0).abs() < REST {
                self.zoom_scale = 1.0;
            }
        } else {
            self.spherical.theta += self.spherical_delta.0;
            self.spherical.phi += self.spherical_delta.1;
            self.spherical_delta = (0.0, 0.0);
            self.target = self.target + self.pan_offset;
            self.pan_offset = Vector3::ZERO;
            if (self.zoom_scale - 1.0).abs() > 1e-8 {
                let old = self.spherical.radius;
                let new = (old * self.zoom_scale).clamp(self.min_distance, self.max_distance);
                self.spherical.radius = new;
                self.dolly_to_cursor(camera, old, new);
                self.zoom_scale = 1.0;
            }
        }

        const EPS: f32 = 1e-4;
        self.spherical.phi = self
            .spherical
            .phi
            .clamp(self.min_polar_angle, self.max_polar_angle)
            .clamp(EPS, std::f32::consts::PI - EPS);
        if self.min_azimuth_angle <= self.max_azimuth_angle {
            self.spherical.theta = self
                .spherical
                .theta
                .clamp(self.min_azimuth_angle, self.max_azimuth_angle);
        }
        self.spherical.radius = self
            .spherical
            .radius
            .clamp(self.min_distance, self.max_distance);

        let offset = self.spherical.to_vector3();
        camera.target = self.target;
        camera.position = self.target + offset;
        let _ = w;
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::controls::PointerEvent;

    #[test]
    fn idle_update_preserves_external_camera_pose() {
        let mut cam = PerspectiveCamera::new(50.0, 1.0, 0.1, 100.0);
        cam.position = Vector3::new(0.0, 0.0, 5.0);
        let mut orbit = OrbitControls::new(&cam);
        // External sync moves the camera without reseeding orbit.
        cam.position = Vector3::new(-3.8, 2.9, 1.25);
        cam.target = Vector3::ZERO;
        let idle = PointerEvent {
            dx: 0.0,
            dy: 0.0,
            wheel: 0.0,
            rotating: false,
            panning: false,
            cursor: (0.0, 0.0),
        };
        orbit.update(idle, &mut cam, (800.0, 600.0));
        assert!((cam.position.x + 3.8).abs() < 1e-4);
        assert!((cam.position.y - 2.9).abs() < 1e-4);
        assert!((cam.position.z - 1.25).abs() < 1e-4);
    }

    #[test]
    fn reseed_from_camera_refreshes_spherical() {
        let mut cam = PerspectiveCamera::new(50.0, 1.0, 0.1, 100.0);
        cam.position = Vector3::new(0.0, 0.0, 5.0);
        let mut orbit = OrbitControls::new(&cam);
        cam.position = Vector3::new(-3.8, 2.9, 1.25);
        orbit.reseed_from_camera(&cam);
        let idle = PointerEvent {
            dx: 0.0,
            dy: 0.0,
            wheel: 0.0,
            rotating: false,
            panning: false,
            cursor: (0.0, 0.0),
        };
        orbit.update(idle, &mut cam, (800.0, 600.0));
        assert!((cam.position.x + 3.8).abs() < 1e-4);
        let moved = PointerEvent {
            dx: 0.0,
            dy: 0.0,
            wheel: 0.0,
            rotating: false,
            panning: false,
            cursor: (0.0, 0.0),
        };
        orbit.update(moved, &mut cam, (800.0, 600.0));
        assert!((cam.position.x + 3.8).abs() < 1e-4);
    }

    #[test]
    fn damping_keeps_residual_motion() {
        let mut cam = PerspectiveCamera::new(50.0, 1.0, 0.1, 100.0);
        cam.position = Vector3::new(0.0, 0.0, 5.0);
        let mut orbit = OrbitControls::new(&cam);
        orbit.enable_damping = true;
        orbit.damping = 0.1;
        let flick = PointerEvent {
            dx: 40.0,
            dy: 0.0,
            wheel: 0.0,
            rotating: true,
            panning: false,
            cursor: (0.0, 0.0),
        };
        orbit.update_dt(flick, &mut cam, (800.0, 600.0), 1.0 / 60.0);
        let after_flick = cam.position;
        let idle = PointerEvent {
            dx: 0.0,
            dy: 0.0,
            wheel: 0.0,
            rotating: false,
            panning: false,
            cursor: (0.0, 0.0),
        };
        orbit.update_dt(idle, &mut cam, (800.0, 600.0), 1.0 / 60.0);
        assert!((cam.position - after_flick).length() > 1e-4);
    }

    #[test]
    fn damping_settles_without_endless_residual() {
        let mut cam = PerspectiveCamera::new(50.0, 1.0, 0.1, 100.0);
        cam.position = Vector3::new(0.0, 0.0, 5.0);
        let mut orbit = OrbitControls::new(&cam);
        orbit.enable_damping = true;
        orbit.damping = 0.15;
        let flick = PointerEvent {
            dx: 80.0,
            dy: 0.0,
            wheel: 0.0,
            rotating: true,
            panning: false,
            cursor: (0.0, 0.0),
        };
        orbit.update_dt(flick, &mut cam, (800.0, 600.0), 1.0 / 60.0);
        let idle = PointerEvent {
            dx: 0.0,
            dy: 0.0,
            wheel: 0.0,
            rotating: false,
            panning: false,
            cursor: (0.0, 0.0),
        };
        for _ in 0..300 {
            orbit.update_dt(idle, &mut cam, (800.0, 600.0), 1.0 / 60.0);
        }
        let settled = cam.position;
        orbit.update_dt(idle, &mut cam, (800.0, 600.0), 1.0 / 60.0);
        assert_eq!(
            cam.position, settled,
            "idle update after settle must not rewrite the camera"
        );
        assert_eq!(orbit.spherical_delta, (0.0, 0.0));
    }

    #[test]
    fn auto_rotate_spins_when_idle() {
        let mut cam = PerspectiveCamera::new(50.0, 1.0, 0.1, 100.0);
        cam.position = Vector3::new(0.0, 0.0, 5.0);
        let mut orbit = OrbitControls::new(&cam);
        orbit.auto_rotate = true;
        orbit.auto_rotate_speed = 1.0;
        let start_theta = orbit.spherical.theta;
        let idle = PointerEvent {
            dx: 0.0,
            dy: 0.0,
            wheel: 0.0,
            rotating: false,
            panning: false,
            cursor: (0.0, 0.0),
        };
        orbit.update_dt(idle, &mut cam, (800.0, 600.0), 0.5);
        assert!((orbit.spherical.theta - start_theta).abs() > 0.1);
    }

    #[test]
    fn damping_does_not_amplify_input() {
        let mut cam = PerspectiveCamera::new(50.0, 1.0, 0.1, 100.0);
        cam.position = Vector3::new(0.0, 0.0, 5.0);
        let mut orbit = OrbitControls::new(&cam);
        orbit.enable_damping = true;
        orbit.damping = 0.08;
        let idle = PointerEvent {
            dx: 0.0,
            dy: 0.0,
            wheel: 0.0,
            rotating: false,
            panning: false,
            cursor: (0.0, 0.0),
        };
        // a drag's total turn, once settled, is what it would be undamped
        let start = orbit.spherical.theta;
        orbit.update_dt(
            PointerEvent {
                dx: 60.0,
                rotating: true,
                ..idle
            },
            &mut cam,
            (800.0, 600.0),
            1.0 / 60.0,
        );
        for _ in 0..600 {
            orbit.update_dt(idle, &mut cam, (800.0, 600.0), 1.0 / 60.0);
        }
        let expect = -60.0 / 600.0 * std::f32::consts::TAU;
        assert!(
            (orbit.spherical.theta - start - expect).abs() < 1e-3,
            "turned {} not {expect}",
            orbit.spherical.theta - start
        );
        // and a wheel notch zooms by its factor, not that factor ^ (1 / damping)
        let r0 = orbit.spherical.radius;
        orbit.update_dt(
            PointerEvent {
                wheel: 100.0,
                ..idle
            },
            &mut cam,
            (800.0, 600.0),
            1.0 / 60.0,
        );
        for _ in 0..600 {
            orbit.update_dt(idle, &mut cam, (800.0, 600.0), 1.0 / 60.0);
        }
        assert!(
            (orbit.spherical.radius / r0 - 0.9).abs() < 1e-3,
            "zoomed ×{}",
            orbit.spherical.radius / r0
        );
        // auto-rotate settles at `auto_rotate_speed` rad/s
        orbit.auto_rotate = true;
        orbit.auto_rotate_speed = 0.5;
        for _ in 0..600 {
            orbit.update_dt(idle, &mut cam, (800.0, 600.0), 1.0 / 60.0);
        }
        let t0 = orbit.spherical.theta;
        for _ in 0..60 {
            orbit.update_dt(idle, &mut cam, (800.0, 600.0), 1.0 / 60.0);
        }
        assert!(
            (orbit.spherical.theta - t0 - 0.5).abs() < 1e-3,
            "{} rad/s",
            orbit.spherical.theta - t0
        );
    }

    #[test]
    fn zoom_to_cursor_shifts_target_toward_pointer() {
        let mut cam = PerspectiveCamera::new(50.0, 1.0, 0.1, 100.0);
        cam.position = Vector3::new(0.0, 0.0, 10.0);
        cam.target = Vector3::ZERO;
        let mut orbit = OrbitControls::new(&cam);
        orbit.zoom_to_cursor = true;
        // zoom IN (wheel > 0 shrinks radius) with the cursor to the right (+x NDC)
        let ev = PointerEvent {
            dx: 0.0,
            dy: 0.0,
            wheel: 200.0,
            rotating: false,
            panning: false,
            cursor: (0.5, 0.0),
        };
        orbit.update(ev, &mut cam, (800.0, 600.0));
        assert!(orbit.spherical.radius < 10.0, "zoom in shrinks radius");
        assert!(
            orbit.target.x > 0.01,
            "target shifts toward the +x cursor, got {}",
            orbit.target.x
        );
        assert!(
            orbit.target.y.abs() < 1e-4 && orbit.target.z.abs() < 1e-4,
            "no cross-axis drift"
        );

        // centred cursor must not move the target
        let mut cam2 = PerspectiveCamera::new(50.0, 1.0, 0.1, 100.0);
        cam2.position = Vector3::new(0.0, 0.0, 10.0);
        let mut orbit2 = OrbitControls::new(&cam2);
        orbit2.zoom_to_cursor = true;
        orbit2.update(
            PointerEvent {
                wheel: 200.0,
                cursor: (0.0, 0.0),
                ..Default::default()
            },
            &mut cam2,
            (800.0, 600.0),
        );
        assert!(
            orbit2.target.length() < 1e-4,
            "centred zoom keeps the target put"
        );
    }
}