codecraft 0.1.2

A minimalist 3D game engine built on parts of Bevy (ECS, color) with wgpu and winit: OpenPBR materials, clustered lighting, a yakui-drawn UI, audio and gamepad haptics; its binary maps any folder, and the symbols of its Rust files, as a 3D wall of boxes
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
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
//! Cameras: [`Camera`] is the eye a frame is drawn from; [`OrbitCamera`] and [`Follow`] are rigs that drive it.
use glam::{Mat4, Vec2, Vec3};

use super::{Category, SceneObject};
use crate::ui::icons::path;

mod follow;
pub use follow::Follow;

use crate::ecs::{Component, Query, Res, ResMut, Resource};
use crate::hid::{Finger, GamepadState};
use crate::input::{KeyCode, Keys};
use crate::time::Time;
use crate::ui::MouseInput;

/// How the camera flattens the world onto the screen.
#[derive(Clone, Copy, PartialEq, Debug)]
pub enum Projection {
    Perspective {
        /// Vertical field of view, in radians.
        fov_y: f32,
    },
    /// Bounds are in view space: the width and height of world that fills the screen.
    Orthographic {
        left: f32,
        right: f32,
        bottom: f32,
        top: f32,
    },
}

/// The eye the 3D scene is drawn from.
#[derive(Resource, Clone, Copy, PartialEq, Debug)]
pub struct Camera {
    pub eye: Vec3,
    pub target: Vec3,
    /// Up on screen; ignored when it is the viewing direction (see [`Camera::orthographic`]).
    pub up: Vec3,
    pub projection: Projection,
    pub near: f32,
    pub far: f32,
}

impl Default for Camera {
    fn default() -> Self {
        Self {
            eye: Vec3::new(0.0, 1.0, 2.0),
            target: Vec3::ZERO,
            up: Vec3::Y,
            projection: Projection::Perspective {
                fov_y: 45f32.to_radians(),
            },
            near: 0.01,
            far: 100.0,
        }
    }
}

impl Camera {
    pub fn looking_at(eye: Vec3, target: Vec3) -> Self {
        Self {
            eye,
            target,
            ..Self::default()
        }
    }

    /// Orthographic projection through a view-space box, with `glOrtho`'s argument order.
    ///
    /// ```
    /// # use codecraft::{Camera, glam::{Vec3, vec3}};
    /// let half = 0.18;
    /// let camera = Camera::looking_at(vec3(0.0, 0.5, 0.0), Vec3::ZERO)
    ///     .orthographic(-half, half, -half, half, 0.01, 10.0);
    /// ```
    ///
    /// Looking straight down, the camera puts the far side of the world at the top; set [`Camera::up`] to turn it.
    pub fn orthographic(
        mut self,
        left: f32,
        right: f32,
        bottom: f32,
        top: f32,
        near: f32,
        far: f32,
    ) -> Self {
        self.projection = Projection::Orthographic {
            left,
            right,
            bottom,
            top,
        };
        self.near = near;
        self.far = far;
        self
    }

    /// Back to drawing through an eye, at `fov_y` radians of vertical view.
    pub fn perspective(mut self, fov_y: f32) -> Self {
        self.projection = Projection::Perspective { fov_y };
        self
    }

    /// Which way up the picture is.
    pub fn up(mut self, up: Vec3) -> Self {
        self.up = up;
        self
    }

    /// `up` with the degenerate case replaced: parallel to the view direction it would give a NaN matrix.
    fn screen_up(&self) -> Vec3 {
        let forward = self.forward();
        if forward.cross(self.up).length_squared() > 1e-8 {
            return self.up;
        }
        match forward.y.abs() > 0.99 {
            true => Vec3::NEG_Z,
            false => Vec3::Y,
        }
    }

    /// The ray under the cursor (pixels from the top-left), in world space.
    pub fn ray(&self, cursor: (f32, f32), width: f32, height: f32) -> Ray {
        let ndc = Vec2::new(
            2.0 * cursor.0 / width.max(1.0) - 1.0,
            1.0 - 2.0 * cursor.1 / height.max(1.0),
        );

        let inverse = self.view_proj(width / height.max(1.0)).inverse();
        // wgpu clip space: depth 0 is the near plane, 1 the far.
        let near = inverse * glam::Vec4::new(ndc.x, ndc.y, 0.0, 1.0);
        let far = inverse * glam::Vec4::new(ndc.x, ndc.y, 1.0, 1.0);
        let near = near.truncate() / near.w;
        let far = far.truncate() / far.w;

        Ray {
            origin: near,
            direction: (far - near).normalize_or(Vec3::NEG_Z),
        }
    }

    /// World space into view space, looking down -z.
    pub fn view(&self) -> Mat4 {
        glam::camera::rh::view::look_at_mat4(self.eye, self.target, self.screen_up())
    }

    /// The lens, without the pose.
    pub fn projection(&self, aspect: f32) -> Mat4 {
        match self.projection {
            Projection::Perspective { fov_y } => glam::camera::rh::proj::directx::perspective(
                fov_y,
                aspect.max(0.001),
                self.near,
                self.far,
            ),
            // The box is deliberately not stretched to the window's aspect.
            Projection::Orthographic {
                left,
                right,
                bottom,
                top,
            } => glam::camera::rh::proj::directx::orthographic(
                left, right, bottom, top, self.near, self.far,
            ),
        }
    }

    pub fn view_proj(&self, aspect: f32) -> Mat4 {
        self.projection(aspect) * self.view()
    }

    /// Which way the camera is pointing.
    pub fn forward(&self) -> Vec3 {
        (self.target - self.eye).normalize_or(Vec3::NEG_Z)
    }
}

/// A ray in world space, for working out what the cursor is over.
#[derive(Clone, Copy, Debug)]
pub struct Ray {
    pub origin: Vec3,
    pub direction: Vec3,
}

impl Ray {
    /// Where the ray crosses the horizontal plane at height `y`; `None` if parallel or behind the viewer.
    pub fn plane_hit(&self, y: f32) -> Option<Vec3> {
        let distance = (y - self.origin.y) / self.direction.y;
        (distance.is_finite() && distance >= 0.0).then(|| self.origin + self.direction * distance)
    }
}

/// 89 degrees: past this `look_at` would be looking straight down its own up axis.
const PITCH_LIMIT: f32 = 1.5533431;

/// A camera that orbits a point: right-drag orbits, middle-drag pans, WASD/EQ walk, the wheel dollies, and optionally a controller touchpad.
/// Spawn one as a scene entity and [`orbit_camera_system`] drives the [`Camera`] resource from it.
#[derive(Component, Clone, Copy, Debug)]
pub struct OrbitCamera {
    pub focus: Vec3,
    /// Radians about the up axis; 0 puts the eye on +Z.
    pub yaw: f32,
    /// Radians; positive looks down.
    pub pitch: f32,
    pub distance: f32,
    /// Units a second at a range of one; scales with distance.
    pub move_speed: f32,
    /// Radians of orbit per raw mouse count, so the mouse's DPI sets how fine the drag is.
    pub sensitivity: f32,
    /// Off by default: a pad in someone's hands is easy to brush.
    pub touchpad: bool,
    /// Radians of orbit per sweep of the whole pad.
    pub touch_sensitivity: f32,
    /// Wheel clicks per full-pad change in the gap between two fingers.
    pub touch_zoom: f32,
    /// Factor the range is multiplied by per wheel click.
    pub zoom_step: f32,
    pub min_distance: f32,
    pub max_distance: f32,
    gesture: Option<Gesture>,
}

/// Last frame's touchpad gesture, so a finger landing or lifting is not read as an enormous drag.
#[derive(Clone, Copy, Debug)]
enum Gesture {
    /// One finger, and where it was.
    Drag(Finger),
    /// Ids in a fixed order: which slot a finger is reported in is not stable.
    Pinch { ids: (u8, u8), gap: f32 },
}

impl Gesture {
    fn read(fingers: [Option<Finger>; 2]) -> Option<Gesture> {
        match fingers {
            [Some(a), Some(b)] => Some(Gesture::Pinch {
                ids: (a.id.min(b.id), a.id.max(b.id)),
                gap: (a.at - b.at).length(),
            }),
            [Some(one), None] | [None, Some(one)] => Some(Gesture::Drag(one)),
            [None, None] => None,
        }
    }
}

impl Default for OrbitCamera {
    fn default() -> Self {
        Self {
            focus: Vec3::ZERO,
            yaw: 0.6,
            pitch: 0.45,
            distance: 6.0,
            move_speed: 0.9,
            sensitivity: 0.002,
            touchpad: false,
            touch_sensitivity: std::f32::consts::PI,
            touch_zoom: 7.0,
            zoom_step: 0.9,
            min_distance: 0.2,
            max_distance: 200.0,
            gesture: None,
        }
    }
}

impl OrbitCamera {
    /// This rig as something the outliner can list.
    pub fn object(name: impl Into<String>) -> SceneObject {
        SceneObject::new(name, path::CAMERA, Category::Camera)
    }

    /// A rig looking at `focus` from `distance` away.
    pub fn new(focus: Vec3, distance: f32) -> Self {
        Self {
            focus,
            distance,
            ..Self::default()
        }
    }

    pub fn yaw(mut self, radians: f32) -> Self {
        self.yaw = radians;
        self
    }

    pub fn pitch(mut self, radians: f32) -> Self {
        self.pitch = radians;
        self
    }

    /// How near and how far the rig may be wound.
    pub fn range(mut self, min: f32, max: f32) -> Self {
        self.min_distance = min.max(1e-4);
        self.max_distance = max.max(self.min_distance);
        self.distance = self.distance.clamp(self.min_distance, self.max_distance);
        self
    }

    pub fn move_speed(mut self, units_per_second: f32) -> Self {
        self.move_speed = units_per_second;
        self
    }

    /// How far the view turns per raw mouse count.
    pub fn sensitivity(mut self, radians_per_count: f32) -> Self {
        self.sensitivity = radians_per_count;
        self
    }

    /// Lets a controller's touchpad drive the rig: one finger orbits, two pinch the range.
    pub fn touchpad(mut self) -> Self {
        self.touchpad = true;
        self
    }

    /// How far the view turns for a finger taken all the way across the pad.
    pub fn touch_sensitivity(mut self, radians_per_sweep: f32) -> Self {
        self.touch_sensitivity = radians_per_sweep;
        self
    }

    /// Wheel clicks of zoom for a pinch opened across the whole pad.
    pub fn touch_zoom(mut self, clicks_per_pinch: f32) -> Self {
        self.touch_zoom = clicks_per_pinch;
        self
    }

    /// Where the eye sits, given the angles and the range.
    pub fn eye(&self) -> Vec3 {
        let (sin_pitch, cos_pitch) = self.pitch.sin_cos();
        let (sin_yaw, cos_yaw) = self.yaw.sin_cos();
        self.focus + Vec3::new(cos_pitch * sin_yaw, sin_pitch, cos_pitch * cos_yaw) * self.distance
    }

    /// The rig's shot, keeping the lens from `base`.
    pub fn camera(&self, base: Camera) -> Camera {
        Camera {
            eye: self.eye(),
            target: self.focus,
            up: Vec3::Y,
            ..base
        }
    }

    /// Slides the focus across the view so the world follows the mouse; a count moves a fixed
    /// fraction of the range, so panning feels the same near and far.
    fn pan(&mut self, motion: Vec2) {
        const PER_COUNT: f32 = 0.0015;
        let forward = (self.focus - self.eye()).normalize_or(Vec3::NEG_Z);
        let right = forward.cross(Vec3::Y).normalize_or(Vec3::X);
        let up = right.cross(forward);
        let step = (up * motion.y - right * motion.x) * (self.distance * PER_COUNT);
        self.focus += step;
    }

    /// Drag right moves the world right (the eye goes left); drag down climbs to look down.
    fn orbit(&mut self, drag: Vec2, scale: f32) {
        self.yaw -= drag.x * scale;
        self.pitch = (self.pitch + drag.y * scale).clamp(-PITCH_LIMIT, PITCH_LIMIT);
    }

    fn zoom(&mut self, clicks: f32) {
        if clicks == 0.0 {
            return;
        }
        self.distance = (self.distance * self.zoom_step.powf(clicks))
            .clamp(self.min_distance, self.max_distance);
    }

    fn drive_touchpad(&mut self, fingers: [Option<Finger>; 2]) {
        if !self.touchpad {
            self.gesture = None;
            return;
        }

        let now = Gesture::read(fingers);
        match (self.gesture, now) {
            (Some(Gesture::Drag(before)), Some(Gesture::Drag(after))) if before.id == after.id => {
                self.orbit(after.at - before.at, self.touch_sensitivity);
            }
            (
                Some(Gesture::Pinch { ids: before, gap }),
                Some(Gesture::Pinch {
                    ids: after,
                    gap: now,
                }),
            ) if before == after => self.zoom((now - gap) * self.touch_zoom),
            // A gesture changing (finger landing or lifting) must move nothing.
            _ => {}
        }
        self.gesture = now;
    }

    /// Advances the rig by one frame's worth of input; `fingers` is ignored unless [`OrbitCamera::touchpad`] asked for it.
    pub fn drive(
        &mut self,
        delta: f32,
        keys: &Keys,
        mouse: &MouseInput,
        fingers: [Option<Finger>; 2],
        taken: bool,
    ) {
        // Pointer over a panel: its wheel and drag are not meant for the world.
        let mouse = &match taken {
            true => MouseInput::default(),
            false => *mouse,
        };
        if mouse.right_down {
            self.orbit(mouse.motion, self.sensitivity);
        }
        if mouse.middle_down {
            self.pan(mouse.motion);
        }

        self.drive_touchpad(fingers);
        self.zoom(mouse.scroll);

        // Walk over the ground, not along the line of sight, so W never drives into the floor.
        let (sin_yaw, cos_yaw) = self.yaw.sin_cos();
        let forward = Vec3::new(-sin_yaw, 0.0, -cos_yaw);
        let right = Vec3::new(cos_yaw, 0.0, -sin_yaw);

        let mut step = Vec3::ZERO;
        if keys.pressed(KeyCode::KeyW) {
            step += forward;
        }
        if keys.pressed(KeyCode::KeyS) {
            step -= forward;
        }
        if keys.pressed(KeyCode::KeyD) {
            step += right;
        }
        if keys.pressed(KeyCode::KeyA) {
            step -= right;
        }
        if keys.pressed(KeyCode::KeyE) {
            step += Vec3::Y;
        }
        if keys.pressed(KeyCode::KeyQ) {
            step -= Vec3::Y;
        }

        if step != Vec3::ZERO {
            let speed = self.move_speed * self.distance;
            self.focus += step.normalize() * speed * delta;
        }
    }
}

/// Drives the [`Camera`] resource from every [`OrbitCamera`] in the world.
pub fn orbit_camera_system(
    time: Res<Time>,
    keys: Res<Keys>,
    mouse: Res<MouseInput>,
    capture: Res<crate::ui::PointerCapture>,
    pad: Res<GamepadState>,
    mut camera: ResMut<Camera>,
    mut views: ResMut<crate::views::Views>,
    mut rigs: Query<&mut OrbitCamera>,
) {
    let fingers = pad.fingers();
    for mut rig in &mut rigs {
        rig.drive(time.delta, &keys, &mouse, fingers, capture.taken());
        *camera = rig.camera(*camera);
        // The renderer resets the camera resource from the first view before drawing, so point the view too.
        views.set_camera(*camera);
    }
}

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

    fn dragged(motion: Vec2) -> OrbitCamera {
        let mut rig = OrbitCamera::new(Vec3::ZERO, 4.0).yaw(0.0).pitch(0.0);
        let held = MouseInput {
            right_down: true,
            motion,
            ..MouseInput::default()
        };
        rig.drive(0.016, &Keys::default(), &held, [None, None], false);
        rig
    }

    #[test]
    fn a_middle_drag_slides_the_world_with_the_mouse() {
        let mut rig = OrbitCamera::new(Vec3::ZERO, 4.0).yaw(0.0).pitch(0.0);
        let held = MouseInput {
            middle_down: true,
            motion: Vec2::new(100.0, 50.0),
            ..MouseInput::default()
        };
        rig.drive(0.016, &Keys::default(), &held, [None, None], false);
        // The eye is on +Z looking down -Z: dragging right and down moves the world that way,
        // so the focus goes left and up.
        assert!(rig.focus.x < 0.0, "{}", rig.focus);
        assert!(rig.focus.y > 0.0, "{}", rig.focus);
        assert!(rig.focus.z.abs() < 1e-5, "no drift along the line of sight");
        assert_eq!((rig.yaw, rig.pitch), (0.0, 0.0), "panning does not turn");

        let mut far = OrbitCamera::new(Vec3::ZERO, 40.0).yaw(0.0).pitch(0.0);
        far.drive(0.016, &Keys::default(), &held, [None, None], false);
        assert!(
            (far.focus.x / rig.focus.x - 10.0).abs() < 1e-3,
            "ten times the range, ten times the slide"
        );
    }

    #[test]
    fn the_eye_starts_on_the_far_side_and_swings_round() {
        let rig = OrbitCamera::new(Vec3::ZERO, 4.0).yaw(0.0).pitch(0.0);
        let eye = rig.eye();
        assert!((eye - Vec3::new(0.0, 0.0, 4.0)).length() < 1e-4, "{eye}");

        let quarter = OrbitCamera {
            yaw: std::f32::consts::FRAC_PI_2,
            ..rig
        };
        let eye = quarter.eye();
        assert!((eye - Vec3::new(4.0, 0.0, 0.0)).length() < 1e-3, "{eye}");
    }

    #[test]
    fn moving_the_mouse_without_the_button_turns_nothing() {
        let mut rig = OrbitCamera::new(Vec3::ZERO, 4.0).yaw(0.0).pitch(0.0);
        let loose = MouseInput {
            motion: Vec2::new(900.0, 900.0),
            ..MouseInput::default()
        };
        rig.drive(0.016, &Keys::default(), &loose, [None, None], false);
        assert_eq!(rig.yaw, 0.0);
        assert_eq!(rig.pitch, 0.0);
    }

    #[test]
    fn dragging_moves_the_world_the_way_the_mouse_goes() {
        let rig = dragged(Vec2::new(40.0, 0.0));
        assert!(rig.yaw < 0.0, "{}", rig.yaw);
        assert!(rig.eye().x < 0.0, "the eye came round to -X");

        let rig = dragged(Vec2::new(0.0, 40.0));
        assert!(rig.pitch > 0.0);
        assert!(rig.eye().y > 0.0);
    }

    #[test]
    fn a_count_turns_the_same_amount_whatever_the_frame_rate() {
        let one = dragged(Vec2::new(10.0, 0.0));
        let mut ten = OrbitCamera::new(Vec3::ZERO, 4.0).yaw(0.0).pitch(0.0);
        let held = MouseInput {
            right_down: true,
            motion: Vec2::new(1.0, 0.0),
            ..MouseInput::default()
        };
        for _ in 0..10 {
            ten.drive(0.001, &Keys::default(), &held, [None, None], false);
        }
        assert!(
            (one.yaw - ten.yaw).abs() < 1e-6,
            "{} vs {}",
            one.yaw,
            ten.yaw
        );
    }

    #[test]
    fn the_pitch_stops_short_of_straight_down() {
        let rig = dragged(Vec2::new(0.0, 100_000.0));
        assert!(rig.pitch <= PITCH_LIMIT);
        assert!(rig.eye().normalize().dot(Vec3::Y) < 0.9999);
    }

    #[test]
    fn the_wheel_scales_the_range_rather_than_stepping_it() {
        let mut rig = OrbitCamera::new(Vec3::ZERO, 10.0);
        let wheel = MouseInput {
            scroll: 2.0,
            ..MouseInput::default()
        };
        rig.drive(0.016, &Keys::default(), &wheel, [None, None], false);
        assert!(
            (rig.distance - 10.0 * 0.9 * 0.9).abs() < 1e-4,
            "{}",
            rig.distance
        );

        let mut rig = OrbitCamera::new(Vec3::ZERO, 10.0);
        let spun = MouseInput {
            scroll: 500.0,
            ..MouseInput::default()
        };
        rig.drive(0.016, &Keys::default(), &spun, [None, None], false);
        assert_eq!(rig.distance, rig.min_distance);
    }

    fn with_touchpad() -> OrbitCamera {
        OrbitCamera::new(Vec3::ZERO, 4.0)
            .yaw(0.0)
            .pitch(0.0)
            .touchpad()
            .touch_sensitivity(4.0)
    }

    fn finger(id: u8, x: f32, y: f32) -> Option<Finger> {
        Some(Finger {
            id,
            at: Vec2::new(x, y),
        })
    }

    fn touch(rig: &mut OrbitCamera, fingers: [Option<Finger>; 2]) {
        rig.drive(
            0.016,
            &Keys::default(),
            &MouseInput::default(),
            fingers,
            false,
        );
    }

    fn swiped(rig: &mut OrbitCamera, id: u8, from: Vec2, to: Vec2) {
        for at in [from, to] {
            touch(rig, [Some(Finger { id, at }), None]);
        }
    }

    fn pinched(rig: &mut OrbitCamera, from: f32, to: f32) {
        for gap in [from, to] {
            let (left, right) = (0.5 - gap * 0.5, 0.5 + gap * 0.5);
            touch(rig, [finger(1, left, 0.5), finger(2, right, 0.5)]);
        }
    }

    #[test]
    fn the_touchpad_is_ignored_unless_a_scene_asks_for_it() {
        let mut rig = OrbitCamera::new(Vec3::ZERO, 4.0).yaw(0.0).pitch(0.0);
        swiped(&mut rig, 1, Vec2::new(0.2, 0.5), Vec2::new(0.8, 0.5));
        assert_eq!(rig.yaw, 0.0);

        pinched(&mut rig, 0.2, 0.8);
        assert_eq!(rig.distance, 4.0);
    }

    #[test]
    fn a_touch_drag_orbits_the_way_a_right_drag_does() {
        let mut rig = with_touchpad();
        swiped(&mut rig, 1, Vec2::new(0.2, 0.5), Vec2::new(0.45, 0.5));
        assert!((rig.yaw - -1.0).abs() < 1e-5, "{}", rig.yaw);

        let mut rig = with_touchpad();
        swiped(&mut rig, 1, Vec2::new(0.5, 0.2), Vec2::new(0.5, 0.6));
        assert!(rig.pitch > 0.0);
        assert!(rig.eye().y > 0.0);
    }

    #[test]
    fn putting_a_finger_down_somewhere_else_starts_a_new_drag() {
        let mut rig = with_touchpad();
        swiped(&mut rig, 1, Vec2::new(0.1, 0.5), Vec2::new(0.2, 0.5));
        let after_first = rig.yaw;

        swiped(&mut rig, 2, Vec2::new(0.9, 0.5), Vec2::new(0.9, 0.5));
        assert_eq!(rig.yaw, after_first, "landing again turns nothing");
    }

    #[test]
    fn lifting_a_finger_ends_the_drag() {
        let mut rig = with_touchpad();
        swiped(&mut rig, 1, Vec2::new(0.1, 0.5), Vec2::new(0.2, 0.5));
        let after_first = rig.yaw;

        touch(&mut rig, [None, None]);
        swiped(&mut rig, 1, Vec2::new(0.9, 0.5), Vec2::new(0.9, 0.5));
        assert_eq!(rig.yaw, after_first);
    }

    #[test]
    fn opening_a_pinch_comes_closer_and_closing_it_backs_off() {
        let mut rig = with_touchpad().touch_zoom(7.0);
        pinched(&mut rig, 0.2, 0.7);
        let opened = rig.distance;
        assert!(opened < 4.0, "spreading two fingers zooms in: {opened}");
        pinched(&mut rig, 0.7, 0.2);
        assert!((rig.distance - 4.0).abs() < 1e-4, "{}", rig.distance);
    }

    #[test]
    fn a_pinch_does_not_orbit_and_a_drag_does_not_zoom() {
        let mut rig = with_touchpad();
        touch(&mut rig, [finger(1, 0.2, 0.5), finger(2, 0.4, 0.5)]);
        touch(&mut rig, [finger(1, 0.6, 0.5), finger(2, 0.8, 0.5)]);
        assert_eq!(rig.yaw, 0.0, "a pinch is not a drag");
        assert!(
            (rig.distance - 4.0).abs() < 1e-5,
            "and the gap never changed: {}",
            rig.distance
        );

        let mut rig = with_touchpad();
        swiped(&mut rig, 1, Vec2::new(0.2, 0.5), Vec2::new(0.8, 0.5));
        assert_eq!(rig.distance, 4.0, "a drag is not a pinch");
    }

    #[test]
    fn a_second_finger_landing_neither_orbits_nor_zooms() {
        let mut rig = with_touchpad();
        touch(&mut rig, [finger(1, 0.2, 0.5), None]);
        touch(&mut rig, [finger(1, 0.2, 0.5), finger(2, 0.9, 0.5)]);
        assert_eq!((rig.yaw, rig.distance), (0.0, 4.0));

        touch(&mut rig, [finger(1, 0.2, 0.5), None]);
        assert_eq!((rig.yaw, rig.distance), (0.0, 4.0));
    }

    #[test]
    fn a_pinch_survives_its_fingers_swapping_slots() {
        let mut rig = with_touchpad();
        touch(&mut rig, [finger(1, 0.3, 0.5), finger(2, 0.7, 0.5)]);
        touch(&mut rig, [finger(2, 0.8, 0.5), finger(1, 0.2, 0.5)]);
        assert!(rig.distance < 4.0, "the gap opened: {}", rig.distance);
    }

    #[test]
    fn walking_stays_on_the_ground_however_the_camera_is_tilted() {
        let mut rig = OrbitCamera::new(Vec3::ZERO, 4.0).yaw(0.0).pitch(1.2);
        let mut keys = Keys::default();
        keys.press(KeyCode::KeyW, false);
        rig.drive(0.5, &keys, &MouseInput::default(), [None, None], false);

        assert_eq!(rig.focus.y, 0.0, "W must not fly into the floor");
        assert!(rig.focus.z < 0.0, "forward at yaw 0 is -Z");
    }
}