codecraft 0.1.1

A minimalist 3D game engine built on parts of Bevy (ECS, color) with wgpu and winit: OpenPBR materials, clustered lighting, an immediate-mode UI, audio and gamepad haptics
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
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
//! Cameras: the eye the 3D scene is drawn from, and a rig for flying it.

//!
//! A sibling of [`lights`](super::lights) and under the same rule: a kind of
//! scene object is a module that owns the whole of its kind. A camera is not
//! yet an object the outliner lists -- [`Camera`] is a resource and the rig
//! is a component on whatever is driving it -- so this module has no
//! [`SceneObject`](super::SceneObject) implementation yet. It is here because
//! that is where it belongs when it does.
//!
//! [`Camera`] is the plain description a frame is rendered with: two points
//! and a field of view. [`OrbitCamera`] is the thing a person drives — hold
//! the right mouse button to swing around what you are looking at, WASD to
//! walk it, the wheel to come closer — and it writes a [`Camera`] out every
//! frame. Keeping them apart means a scene that places its own fixed shot
//! never has to know the rig exists.
use glam::{Mat4, Vec2, Vec3};

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::{CursorPosition, MouseInput};

/// How the camera flattens the world onto the screen.
#[derive(Clone, Copy, PartialEq, Debug)]
pub enum Projection {
    /// What an eye does: things further away are smaller, and parallel lines
    /// meet.
    Perspective {
        /// Vertical field of view, in radians.
        fov_y: f32,
    },
    /// A box of world, drawn at one scale however far away it is. A board
    /// seen straight down through one of these is a diagram: every square the
    /// same size and shape, nothing hidden behind a piece in front of it.
    ///
    /// The bounds are in view space — right of, above and in front of the
    /// camera — so `left`/`right` and `bottom`/`top` are the width and height
    /// of the world that fills the screen.
    Orthographic {
        left: f32,
        right: f32,
        bottom: f32,
        top: f32,
    },
}

/// The eye the 3D scene is drawn from.
///
/// What is shining on the scene is [`crate::sceneobjects::lights::Lighting`]'s business, not
/// this one's: a game moves the camera far more often than it moves the sun.
#[derive(Resource, Clone, Copy, PartialEq, Debug)]
pub struct Camera {
    pub eye: Vec3,
    pub target: Vec3,
    /// Which way is up on screen. Ignored when it is the way the camera is
    /// already looking, since that leaves the picture undefined — 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()
        }
    }

    /// Draws the world through a box rather than through an eye.
    ///
    /// The six numbers are the box in view space, the way `glOrtho` takes
    /// them: `left`/`right` across, `bottom`/`top` up, and `near`/`far` along
    /// the way the camera looks. Nothing outside the box is drawn, so `far`
    /// has to reach past the scene and `near` has to be in front of it.
    ///
    /// A board seen from straight above:
    ///
    /// ```
    /// # 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 leaves "up on screen" undecided, since the usual
    /// answer — the Y axis — is the direction being looked along. The camera
    /// falls back to pointing the far side of the world at the top of the
    /// screen; set [`Camera::up`] to turn the picture.
    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. `Vec3::Y` unless said otherwise, which is
    /// no use looking straight down — see [`Camera::orthographic`].
    pub fn up(mut self, up: Vec3) -> Self {
        self.up = up;
        self
    }

    /// Which way up the screen is, with the degenerate answer replaced.
    ///
    /// `up` pointing the way the camera looks — straight down at a board, in
    /// practice — gives no rotation at all and a matrix full of NaNs, so it
    /// is swapped for an axis across the view.
    fn screen_up(&self) -> Vec3 {
        let forward = self.forward();
        if forward.cross(self.up).length_squared() > 1e-8 {
            return self.up;
        }
        // Looking along the world's up: put what is furthest along -Z at the
        // top of the screen, which for a board is the far side of it.
        match forward.y.abs() > 0.99 {
            true => Vec3::NEG_Z,
            false => Vec3::Y,
        }
    }

    /// The ray under the cursor, in world space.
    ///
    /// `cursor` is in pixels from the top-left, the way the window reports
    /// it; `width` and `height` are the window's.
    pub fn ray(&self, cursor: (f32, f32), width: f32, height: f32) -> Ray {
        // Pixels to normalised device coordinates: x right, y *up*, which is
        // the flip between window space and clip space.
        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();
        // Depth 0 is the near plane and 1 the far one, per wgpu's clip space.
        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 the camera's own, looking down its -z.
    ///
    /// Split out from [`view_proj`](Self::view_proj) because the cluster grid
    /// is built in view space: a cell is a slab of the frustum, which is a
    /// simple box there and an awkward one anywhere else.
    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 the caller's: it is what they asked to see, and
            // stretching it to the window would show something else.
            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` when it runs parallel to the plane, or crosses it behind the
    /// viewer — looking away from the board is not a hit.
    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)
    }
}

/// How far the pitch may go before the rig would be looking straight down its
/// own up axis, where `look_at` has nothing left to work with. 89 degrees.
const PITCH_LIMIT: f32 = 1.5533431;

/// A camera that swings around a point, driven by mouse and keyboard.
///
/// Spawn one as a scene entity — `app.spawn_entity(OrbitCamera::new(..))` —
/// and [`orbit_camera_system`] drives the [`Camera`] resource -- and the
/// frame's view, when there is one -- from it every frame. Being an entity
/// rather than a resource means it goes away with the
/// scene that wanted it, and a scene that sets a fixed shot instead simply
/// never spawns one.
///
/// - Right mouse held: orbit. Dragging moves the world the way the mouse goes.
/// - WASD: walk the focus point over the ground, E/Q: raise and lower it.
/// - Wheel: closer and further, by a factor rather than a fixed distance, so
///   it takes the same number of clicks to halve the range wherever you are.
/// - A controller's touchpad, where a scene has switched it on with
///   [`OrbitCamera::touchpad`]: one finger orbits as the mouse does, two
///   pinch the range the way the wheel does.
#[derive(Component, Clone, Copy, Debug)]
pub struct OrbitCamera {
    /// The point being orbited, and what WASD walks around.
    pub focus: Vec3,
    /// Rotation about the up axis, in radians. 0 puts the eye on +Z.
    pub yaw: f32,
    /// Height of the eye as an angle, in radians. Positive looks down.
    pub pitch: f32,
    pub distance: f32,
    /// Units a second at a range of one; further out moves faster, so
    /// crossing the view takes about as long whatever the zoom.
    pub move_speed: f32,
    /// Radians of orbit per pixel dragged.
    pub sensitivity: f32,
    /// Whether a controller's touchpad drives the rig: one finger orbits,
    /// two pinch the range.
    ///
    /// Off unless a scene asks for it. A pad sitting in someone's hands is
    /// easy to brush, and a camera that swings when a scene never wanted it
    /// to reads as a bug rather than a feature.
    pub touchpad: bool,
    /// Radians of orbit per sweep of the whole pad, with one finger.
    pub touch_sensitivity: f32,
    /// Clicks of the wheel per full-pad change in the gap between two
    /// fingers. Spreading them apart comes closer, as a pinch does anywhere.
    pub touch_zoom: f32,
    /// Factor the range is multiplied by per click of the wheel.
    pub zoom_step: f32,
    pub min_distance: f32,
    pub max_distance: f32,
    /// Where the cursor was last frame, for turning positions into a drag.
    /// `None` until the button goes down, so picking the mouse up and putting
    /// it down elsewhere does not fling the view.
    dragging_from: Option<Vec2>,
    /// What the pad was doing last frame, for the same reason.
    gesture: Option<Gesture>,
}

/// A touchpad gesture in progress, as of the frame it was read.
///
/// Held so that a change *in* a gesture can be told from a change *of* one:
/// a finger landing or lifting rearranges what the pad is reporting, and
/// without this the rearrangement itself would read as an enormous drag.
#[derive(Clone, Copy, Debug)]
enum Gesture {
    /// One finger, and where it was.
    Drag(Finger),
    /// Two, and how far apart. The ids are kept in a fixed order, because
    /// which slot a finger is reported in is not stable.
    Pinch { ids: (u8, u8), gap: f32 },
}

impl Gesture {
    /// What the pad is doing now, or `None` if nothing is on it.
    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.005,
            touchpad: false,
            // A sweep of the pad is a half turn, and spreading two fingers
            // across it halves the range about once.
            touch_sensitivity: std::f32::consts::PI,
            touch_zoom: 7.0,
            zoom_step: 0.9,
            min_distance: 0.2,
            max_distance: 200.0,
            dragging_from: None,
            gesture: None,
        }
    }
}

impl OrbitCamera {
    /// 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. The defaults are made for
    /// a world measured in metres; a board is a third of one across.
    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
    }

    /// Lets a controller's touchpad drive the rig: one finger orbits as the
    /// right mouse button does, two pinch the range as the wheel does.
    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
    }

    /// How much the range changes for a pinch opened across the whole pad,
    /// in clicks of the wheel.
    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 everything else — lens, lighting — from
    /// `base`, so driving the camera does not reset how the scene is lit.
    pub fn camera(&self, base: Camera) -> Camera {
        Camera {
            eye: self.eye(),
            target: self.focus,
            up: Vec3::Y,
            ..base
        }
    }

    /// Turns the view by a drag, in whatever units `scale` converts to
    /// radians. Drag right and the world goes right, which means the eye goes
    /// left; drag down and it climbs to look down at things.
    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);
    }

    /// Changes the range by `clicks` of the wheel, or a pinch worth as much.
    /// A factor per click rather than a distance, so it takes the same number
    /// to halve the range wherever you already are.
    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);
    }

    /// Applies whatever the pad is doing, if a scene asked for the pad.
    ///
    /// A touchpad counts up and to the right the way a screen does, so a
    /// one-finger drag means the same thing as the mouse's without a flip.
    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) {
            // The same finger, moved: a drag.
            (Some(Gesture::Drag(before)), Some(Gesture::Drag(after))) if before.id == after.id => {
                self.orbit(after.at - before.at, self.touch_sensitivity);
            }
            // The same two fingers, further apart or closer together. Opening
            // the pinch comes closer, which is the sign the wheel uses.
            (
                Some(Gesture::Pinch { ids: before, gap }),
                Some(Gesture::Pinch {
                    ids: after,
                    gap: now,
                }),
            ) if before == after => self.zoom((now - gap) * self.touch_zoom),
            // Anything else is the gesture changing rather than continuing —
            // a finger landing, one lifting, a drag becoming a pinch. Only
            // the new starting point is kept, so the change moves nothing.
            _ => {}
        }
        self.gesture = now;
    }

    /// Advances the rig by one frame's worth of input.
    ///
    /// `fingers` is the touchpad, both slots as the pad reports them. It is
    /// ignored entirely unless [`OrbitCamera::touchpad`] asked for it.
    pub fn drive(
        &mut self,
        delta: f32,
        keys: &Keys,
        mouse: &MouseInput,
        cursor: Vec2,
        fingers: [Option<Finger>; 2],
        taken: bool,
    ) {
        // The pointer is over a panel: the wheel is scrolling a list and the
        // drag is moving a window, and neither is meant for the world.
        let mouse = &match taken {
            true => MouseInput::default(),
            false => *mouse,
        };
        if mouse.right_down {
            if let Some(previous) = self.dragging_from {
                self.orbit(cursor - previous, self.sensitivity);
            }
            self.dragging_from = Some(cursor);
        } else {
            self.dragging_from = None;
        }

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

        // Walk over the ground rather than along the line of sight: pointing
        // at the floor should not mean W drives you into it.
        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 {
            // Speed scales with the range so the view crosses in about the
            // same time whether you are on top of something or well back.
            let speed = self.move_speed * self.distance;
            self.focus += step.normalize() * speed * delta;
        }
    }
}

/// Drives the [`Camera`] resource from every [`OrbitCamera`] in the world.
///
/// Registered by [`crate::render3d::Render3dPlugin`], and does nothing at all
/// in a scene that has not spawned a rig.
pub fn orbit_camera_system(
    time: Res<Time>,
    keys: Res<Keys>,
    mouse: Res<MouseInput>,
    cursor: Res<CursorPosition>,
    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,
            Vec2::new(cursor.x, cursor.y),
            fingers,
            capture.taken(),
        );
        *camera = rig.camera(*camera);
        // The frame is drawn from the views, not from the camera resource --
        // which the renderer sets back to the first view's before it draws.
        // A rig that only wrote the resource would be undone every frame, so
        // it points the view itself, when there is one to point.
        views.set_camera(*camera);
    }
}

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

    fn dragged(from: Vec2, to: Vec2) -> OrbitCamera {
        let mut rig = OrbitCamera::new(Vec3::ZERO, 4.0).yaw(0.0).pitch(0.0);
        let held = MouseInput {
            right_down: true,
            ..MouseInput::default()
        };
        // The first frame only records where the drag started.
        rig.drive(0.016, &Keys::default(), &held, from, [None, None], false);
        rig.drive(0.016, &Keys::default(), &held, to, [None, None], false);
        rig
    }

    #[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}");

        // A quarter turn puts it on +X, still four units out.
        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 a_drag_only_counts_from_where_the_button_went_down() {
        // Without this the first frame of a drag would read the whole gap
        // between wherever the cursor was last seen and where it is now.
        let mut rig = OrbitCamera::new(Vec3::ZERO, 4.0).yaw(0.0).pitch(0.0);
        let held = MouseInput {
            right_down: true,
            ..MouseInput::default()
        };
        rig.drive(
            0.016,
            &Keys::default(),
            &held,
            Vec2::new(900.0, 900.0),
            [None, None],
            false,
        );
        assert_eq!(rig.yaw, 0.0, "the press itself must not turn anything");
    }

    #[test]
    fn dragging_moves_the_world_the_way_the_mouse_goes() {
        // Rightwards: the eye goes left, so what you are looking at swings right.
        let rig = dragged(Vec2::new(100.0, 100.0), Vec2::new(140.0, 100.0));
        assert!(rig.yaw < 0.0, "{}", rig.yaw);
        assert!(rig.eye().x < 0.0, "the eye came round to -X");

        // Downwards: the eye climbs, and looks down.
        let rig = dragged(Vec2::new(100.0, 100.0), Vec2::new(100.0, 140.0));
        assert!(rig.pitch > 0.0);
        assert!(rig.eye().y > 0.0);
    }

    #[test]
    fn the_pitch_stops_short_of_straight_down() {
        let rig = dragged(Vec2::new(0.0, 0.0), Vec2::new(0.0, 100_000.0));
        assert!(rig.pitch <= PITCH_LIMIT);
        // Still a usable up vector: look_at needs the two not to be parallel.
        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,
            Vec2::ZERO,
            [None, None],
            false,
        );
        assert!(
            (rig.distance - 10.0 * 0.9 * 0.9).abs() < 1e-4,
            "{}",
            rig.distance
        );

        // And never all the way onto the focus point.
        let mut rig = OrbitCamera::new(Vec3::ZERO, 10.0);
        let spun = MouseInput {
            scroll: 500.0,
            ..MouseInput::default()
        };
        rig.drive(
            0.016,
            &Keys::default(),
            &spun,
            Vec2::ZERO,
            [None, None],
            false,
        );
        assert_eq!(rig.distance, rig.min_distance);
    }

    /// A rig with the pad switched on, sat still at the origin.
    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),
        })
    }

    /// One frame of the pad reading `fingers`.
    fn touch(rig: &mut OrbitCamera, fingers: [Option<Finger>; 2]) {
        rig.drive(
            0.016,
            &Keys::default(),
            &MouseInput::default(),
            Vec2::ZERO,
            fingers,
            false,
        );
    }

    /// Runs a single finger from `from` to `to` across the pad.
    fn swiped(rig: &mut OrbitCamera, id: u8, from: Vec2, to: Vec2) {
        for at in [from, to] {
            touch(rig, [Some(Finger { id, at }), None]);
        }
    }

    /// Opens or closes a two-finger pinch from `from` to `to` wide, centred.
    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() {
        // The pad is in someone's hands whether or not the scene wants it
        // steering the camera.
        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);

        // Down the pad climbs the eye, exactly as dragging the mouse down does.
        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;

        // A new contact across the pad: without the id check this would read
        // as one enormous drag and spin the view right round.
        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]);
        // Same id back down, well away from where it left: a fresh drag.
        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}");
        // Half the range for half the pad, near enough to be worth checking:
        // the same gesture back the other way has to undo it exactly.
        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();
        // Two fingers sweeping together would be a drag if either counted.
        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() {
        // The frame a pinch starts, the pad goes from reporting one position
        // to reporting two. Nothing has moved; only what is being measured.
        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));

        // And lifting back to one does not resume the old drag either.
        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() {
        // Which slot a contact is reported in is not stable, so the pair has
        // to be matched as a set rather than in order.
        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(),
            Vec2::ZERO,
            [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");
    }
}