pinready 0.27.8

Cross-platform configurator and launcher supporting the adoption of Visual Pinball 10.8.1 — for testers and early adopters, not a replacement for a stable production setup
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
use super::*;
use crate::tilt::SENSOR_RANGES_G;

const NOTICE_AMBER_TILT: egui::Color32 = egui::Color32::from_rgb(255, 200, 80);
const RING_TILT: egui::Color32 = egui::Color32::from_rgb(255, 120, 120);
const RING_INTENT: egui::Color32 = egui::Color32::from_rgb(230, 160, 60);
const RING_DEADZONE: egui::Color32 = egui::Color32::from_rgb(80, 200, 80);
/// The sensor pinned at its own ceiling — not a level, a loss of information.
const RING_CLIPPED: egui::Color32 = egui::Color32::from_rgb(255, 210, 60);

/// How long a clipping mark stays on screen. A nudge is over in milliseconds,
/// long before anyone looks up from the cabinet.
const CLIP_MARK_LIFE: std::time::Duration = std::time::Duration::from_secs(4);

/// How many marks to keep. Enough to show where a shove saturates, few enough
/// that a violent session does not paint the whole rim.
const CLIP_MARKS_KEPT: usize = 24;

/// One place, and one moment, where the sensor ran out of range.
pub struct ClipMark {
    at: egui::Pos2,
    seen: std::time::Instant,
}
const STRENGTH_RED: egui::Color32 = egui::Color32::from_rgb(235, 90, 90);

impl App {
    /// Keep the dial's rings in step with the sliders. Placing them runs the
    /// cabinet physics a few dozen times — cheap, but not per-frame cheap.
    fn refresh_tilt_rings(&mut self) {
        let key = self.tilt.rings_key();
        if key != self.tilt_rings_key {
            self.tilt_rings = self.tilt.rings();
            self.tilt_rings_key = key;
        }
    }

    pub(super) fn render_tilt_page(&mut self, ui: &mut egui::Ui) {
        theme::page_header(ui, &t!("tilt_heading"), Some(&t!("tilt_desc")));

        // Request repaint for live accelerometer data
        ui.ctx().request_repaint();

        // --- Nudge section ---
        theme::section(ui, &t!("tilt_nudge"), Some(&t!("tilt_nudge_intro")), |ui| {
            // Sensor range — read from the board, not asked. The firmware knows it
            // (Pinscape config variable 4) and the user generally does not, so the
            // detected value is adopted and the choice stays available for boards
            // that will not answer.
            if let Some(rx) = &self.pinscape_cfg_rx
                && let Ok(cfg) = rx.try_recv()
            {
                self.pinscape_cfg_rx = None;
                if let Some(range) = cfg.and_then(|c| c.accel_range_g) {
                    self.tilt.nudge_range_g = range;
                }
                self.pinscape_cfg = cfg;
            }
            let detected_range = self.pinscape_cfg.and_then(|c| c.accel_range_g);
            self.refresh_tilt_rings();

            ui.horizontal(|ui| {
                ui.label(t!("tilt_range"));
                help_marker(ui, &t!("tilt_range_help"));
            });
            ui.horizontal(|ui| {
                for range in SENSOR_RANGES_G {
                    let selected = (self.tilt.nudge_range_g - range).abs() < 0.01;
                    if ui
                        .selectable_label(selected, format!("{range:.0} G"))
                        .clicked()
                    {
                        self.tilt.nudge_range_g = range;
                    }
                }
            });
            match detected_range {
                Some(detected) if (detected - self.tilt.nudge_range_g).abs() < 0.01 => {
                    ui.label(
                        egui::RichText::new(t!(
                            "tilt_range_matches",
                            range = format!("{detected:.0}")
                        ))
                        .color(egui::Color32::from_rgb(120, 200, 120)),
                    );
                }
                // A range that disagrees with the firmware is the single most
                // damaging setting on this page: it is a unit conversion, so it
                // scales nudge and tilt together, and nothing downstream can undo
                // it. Name the factor — that is what makes the symptom
                // recognisable.
                Some(detected) => {
                    let factor = self.tilt.nudge_range_g / detected;
                    ui.colored_label(
                        egui::Color32::from_rgb(255, 140, 60),
                        t!(
                            if factor > 1.0 {
                                "tilt_range_mismatch_high"
                            } else {
                                "tilt_range_mismatch_low"
                            },
                            detected = format!("{detected:.0}"),
                            chosen = format!("{:.0}", self.tilt.nudge_range_g),
                            factor = if factor > 1.0 {
                                format!("×{factor:.0}")
                            } else {
                                format!("÷{:.0}", 1.0 / factor)
                            }
                        ),
                    );
                    if ui
                        .button(t!("tilt_range_adopt", range = format!("{detected:.0}")))
                        .clicked()
                    {
                        self.tilt.nudge_range_g = detected;
                    }
                }
                None => {
                    // Naming the board that stayed silent beats implying there is
                    // none.
                    ui.label(
                        egui::RichText::new(match self.pinscape_cfg.map(|c| c.board) {
                            Some(board) => t!(
                                "tilt_range_unsupported",
                                board = match board {
                                    crate::pinscape_config::Board::Kl25z => "Pinscape KL25Z",
                                    crate::pinscape_config::Board::Pico => "Pinscape Pico",
                                    crate::pinscape_config::Board::Opaque(name) => name,
                                }
                            ),
                            None => t!("tilt_range_unknown"),
                        })
                        .weak(),
                    );
                }
            }
            // How the board is fitted. Not a setting — the firmware rotates its
            // readings into cabinet axes itself, so nothing here is written to the
            // ini. It is shown because a board declared one way and screwed down
            // another mirrors the nudge, and no other screen would ever say so.
            if let Some(key) = self.pinscape_cfg.and_then(|c| c.orientation_key()) {
                ui.label(egui::RichText::new(t!("tilt_orientation", side = t!(key))).weak());
            }
            self.render_range_tables(ui);
            ui.add_space(8.0);

            // Strength — in practice the only setting worth touching once the
            // range is read off the board, so it is the one that stands out.
            ui.horizontal(|ui| {
                ui.label(
                    egui::RichText::new(t!("tilt_sensitivity"))
                        .strong()
                        .color(STRENGTH_RED),
                );
                help_marker(ui, &t!("tilt_sensitivity_help"));
            });
            ui.scope(|ui| {
                let visuals = &mut ui.style_mut().visuals;
                visuals.selection.bg_fill = STRENGTH_RED;
                visuals.widgets.inactive.fg_stroke.color = STRENGTH_RED;
                ui.add_sized(
                    [ui.available_width(), 24.0],
                    egui::Slider::new(&mut self.tilt.nudge_scale_pct, 0.0..=200.0)
                        .custom_formatter(|v, _| format!("{v:.0}%")),
                );
            });
            ui.add_space(4.0);

            ui.horizontal(|ui| {
                ui.label(t!("tilt_deadzone"));
                help_marker(ui, &t!("tilt_deadzone_help"));
            });
            let full_scale = self.tilt.full_scale_ms2();
            ui.add_sized(
                [ui.available_width(), 24.0],
                // VPX caps this at 0.3 of the axis range ("relative amount of
                // the axis range to nullify to avoid noise at rest position"), so
                // offering more would write values its own UI cannot show. The
                // m/s² is not decoration: this is the one setting whose real
                // effect changes with the sensor range.
                egui::Slider::new(&mut self.tilt.nudge_deadzone_pct, 0.0..=30.0).custom_formatter(
                    move |v, _| format!("{v:.0}% ({:.2} m/s²)", (v as f32 / 100.0) * full_scale),
                ),
            );
            ui.add_space(8.0);

            ui.add_enabled_ui(false, |ui| {
                egui::Frame::group(ui.style()).show(ui, |ui| {
                    // Peak of |x|,|y| since entering the page, as a share of full
                    // scale: a shake that never passes ~20 % means the board is
                    // set wider than the cabinet ever exercises. It doubles as a
                    // presence test — an axis that never leaves zero is either
                    // unmapped or has nothing wired to it, and telling that apart
                    // from "badly scaled" is the first question to answer.
                    let peak = self.accel_x.abs().max(self.accel_y.abs());
                    self.nudge_peak = self.nudge_peak.max(peak);
                    ui.label(if self.nudge_peak > 0.004 {
                        egui::RichText::new(t!("tilt_accel_present"))
                            .color(egui::Color32::from_rgb(120, 200, 120))
                    } else {
                        egui::RichText::new(t!("tilt_accel_absent")).color(NOTICE_AMBER_TILT)
                    });
                    ui.label(
                        egui::RichText::new(t!(
                            "tilt_peak",
                            pct = format!("{:.0}", self.nudge_peak * 100.0),
                            accel = format!("{:.2}", self.nudge_peak * self.tilt.full_scale_ms2())
                        ))
                        .weak(),
                    );
                });
            });
            if ui.small_button(t!("tilt_peak_reset")).clicked() {
                self.nudge_peak = 0.0;
            }
            ui.add_space(8.0);

            // What the three modes actually mean, and in what order the filters
            // apply — none of which VPX documents, and all of which decides
            // whether a nudge reaches the ball.
            ui.collapsing(t!("tilt_modes_title"), |ui| {
                ui.label(t!("tilt_modes_gamepad"));
                ui.add_space(4.0);
                ui.label(t!("tilt_modes_intent"));
                ui.add_space(4.0);
                ui.label(t!("tilt_modes_cabinet"));
                ui.add_space(8.0);
                ui.label(egui::RichText::new(t!("tilt_modes_chain")).strong());
                ui.label(t!("tilt_modes_chain_detail"));
            });
            ui.add_space(6.0);

            // Nudge sensor type (VPX new sensor schema: Mapping.Nudge0.Type).
            let sensor_types = [
                (0_i32, t!("tilt_nudge_type_game")),
                (1, t!("tilt_nudge_type_intent")),
                (2, t!("tilt_nudge_type_cabinet")),
            ];
            ui.horizontal(|ui| {
                ui.label(t!("tilt_nudge_type"));
                help_marker(ui, &t!("tilt_nudge_type_help"));
            });
            let selected = sensor_types
                .iter()
                .find(|(v, _)| *v == self.tilt.nudge_sensor_type)
                .map(|(_, l)| l.clone())
                .unwrap_or_default();
            egui::ComboBox::from_id_salt("nudge_sensor_type")
                .selected_text(selected)
                .width(ui.available_width())
                .show_ui(ui, |ui| {
                    for (val, label) in &sensor_types {
                        ui.selectable_value(&mut self.tilt.nudge_sensor_type, *val, label.clone());
                    }
                });
        });

        // --- Virtual plumb: recommended, and on by default ---
        theme::section(
            ui,
            &t!("tilt_plumb_section"),
            Some(&t!("tilt_plumb_intro")),
            |ui| {
                ui.horizontal(|ui| {
                    ui.checkbox(&mut self.tilt.plumb_enabled, t!("tilt_plumb_toggle"));
                    ui.label(
                        egui::RichText::new(t!("tilt_plumb_recommended"))
                            .color(egui::Color32::from_rgb(120, 200, 120))
                            .strong(),
                    );
                });
                ui.label(egui::RichText::new(t!("tilt_plumb_help")).weak());
                if !self.tilt.plumb_enabled {
                    ui.add_space(4.0);
                    ui.colored_label(theme::pal(ui.ctx()).warning, t!("tilt_plumb_off_warning"));
                }
                ui.add_space(10.0);
                ui.horizontal(|ui| {
                    ui.label(t!("tilt_visual_label"));
                    help_marker(ui, &t!("tilt_visual_help"));
                });
                ui.add_sized(
                    [ui.available_width(), 24.0],
                    egui::Slider::new(&mut self.tilt.visual_nudge_pct, 0.0..=200.0)
                        .custom_formatter(|v, _| format!("{v:.0}%")),
                );
            },
        );

        // --- Tilt section ---
        theme::section(
            ui,
            &t!("tilt_section"),
            Some(&t!("tilt_section_intro")),
            |ui| {
                ui.horizontal(|ui| {
                    ui.label(t!("tilt_threshold"));
                    help_marker(ui, &t!("tilt_threshold_help"));
                });
                ui.add_sized(
                    [ui.available_width(), 24.0],
                    // The percentage is ours; the degrees are what VPX stores and
                    // what its own UI shows, so print both rather than make anyone
                    // convert between the two.
                    egui::Slider::new(&mut self.tilt.tilt_sensitivity_pct, 0.0..=100.0)
                        .custom_formatter(|v, _| {
                            format!(
                                "{v:.0}% ({:.2}°)",
                                crate::tilt::TiltConfig::threshold_angle(v as f32)
                            )
                        }),
                );
                // The scale runs backwards from the angle it writes, so label both
                // ends rather than leave anyone to work out which way is which.
                ui.horizontal(|ui| {
                    ui.label(egui::RichText::new(t!("tilt_threshold_low")).weak().small());
                    ui.with_layout(egui::Layout::right_to_left(egui::Align::Center), |ui| {
                        ui.label(
                            egui::RichText::new(t!("tilt_threshold_high"))
                                .weak()
                                .small(),
                        );
                    });
                });
                ui.add_space(6.0);

                self.refresh_tilt_rings();
                // Comparable at last: both are accelerations now, so this says
                // something true. The old version compared a dead-zone percentage
                // against a sensitivity percentage — two different scales, and the
                // warning fired on settings that worked perfectly.
                if self.tilt_rings.deadzone >= self.tilt_rings.tilt {
                    ui.colored_label(theme::pal(ui.ctx()).warning, t!("tilt_deadzone_warning"));
                }
                self.render_out_of_reach_notice(ui);
                ui.add_space(4.0);

                self.render_tilt_dial(ui);
            },
        );
    }

    /// Warn — and offer the two ways out — when the configured tilt threshold
    /// needs a harder shove than the sensor can report. Raising the range is
    /// the honest fix and costs nothing; Strength only compensates.
    fn render_out_of_reach_notice(&mut self, ui: &mut egui::Ui) {
        if !self.tilt_rings.tilt_out_of_reach() {
            return;
        }
        // A range is a fact about the board. When the board has told us its own,
        // offering a wider one would only make VPX over-read every shake.
        let board_known = self.pinscape_cfg.and_then(|c| c.accel_range_g).is_some();
        let wider = SENSOR_RANGES_G
            .iter()
            .copied()
            .find(|r| !board_known && *r > self.tilt.nudge_range_g && self.reach_covers(*r));
        egui::Frame::group(ui.style())
            .fill(egui::Color32::from_rgb(70, 45, 20))
            .show(ui, |ui| {
                ui.label(
                    egui::RichText::new(t!(
                        "tilt_unreachable",
                        range = format!("{:.0}", self.tilt.nudge_range_g),
                        angle = format!("{:.2}", self.tilt.threshold_deg())
                    ))
                    .color(NOTICE_AMBER_TILT)
                    .strong(),
                );
                if let Some(range) = wider {
                    ui.label(t!("tilt_unreachable_range", range = format!("{range:.0}")));
                }
                ui.horizontal(|ui| {
                    if let Some(range) = wider
                        && ui
                            .button(t!("tilt_range_adopt", range = format!("{range:.0}")))
                            .clicked()
                    {
                        self.tilt.nudge_range_g = range;
                    }
                    if let Some(pct) = self.tilt_rings.strength_to_reach_pct
                        && ui
                            .button(t!("tilt_unreachable_strength", pct = format!("{pct:.0}")))
                            .clicked()
                    {
                        self.tilt.nudge_scale_pct = pct;
                    }
                });
            });
    }

    /// Whether a given sensor range still reaches the configured threshold.
    fn reach_covers(&self, range_g: f32) -> bool {
        SENSOR_RANGES_G
            .iter()
            .position(|r| (*r - range_g).abs() < 0.01)
            .is_some_and(|i| self.tilt_rings.reach[i].1 >= self.tilt.threshold_deg())
    }

    /// The two tables that make the range choice decidable rather than a
    /// guess: what a wrong declaration does, and what each range can reach.
    fn render_range_tables(&mut self, ui: &mut egui::Ui) {
        ui.collapsing(t!("tilt_range_tables_title"), |ui| {
            ui.label(t!("tilt_range_table_mismatch_intro"));
            ui.add_space(4.0);
            egui::Grid::new("tilt_range_mismatch")
                .striped(true)
                .show(ui, |ui| {
                    ui.label("");
                    for vpx in SENSOR_RANGES_G {
                        ui.label(egui::RichText::new(format!("VPX {vpx:.0} G")).strong());
                    }
                    ui.end_row();
                    for firmware in SENSOR_RANGES_G {
                        ui.label(
                            egui::RichText::new(t!(
                                "tilt_range_table_firmware",
                                range = format!("{firmware:.0}")
                            ))
                            .strong(),
                        );
                        for vpx in SENSOR_RANGES_G {
                            let factor = vpx / firmware;
                            ui.label(if (factor - 1.0).abs() < 0.01 {
                                egui::RichText::new(t!("tilt_range_table_exact"))
                                    .color(egui::Color32::from_rgb(120, 200, 120))
                            } else if factor > 1.0 {
                                egui::RichText::new(format!("×{factor:.0}"))
                                    .color(egui::Color32::from_rgb(255, 140, 60))
                            } else {
                                egui::RichText::new(format!("÷{:.0}", 1.0 / factor))
                                    .color(NOTICE_AMBER_TILT)
                            });
                        }
                        ui.end_row();
                    }
                });
            ui.add_space(4.0);
            ui.label(t!("tilt_range_table_mismatch_read"));
            ui.add_space(10.0);

            ui.label(t!("tilt_range_table_reach_intro"));
            ui.add_space(4.0);
            egui::Grid::new("tilt_range_reach")
                .striped(true)
                .show(ui, |ui| {
                    ui.label("");
                    ui.label(egui::RichText::new(t!("tilt_range_table_full_scale")).strong());
                    ui.label(egui::RichText::new(t!("tilt_range_table_min")).strong());
                    ui.label(egui::RichText::new(t!("tilt_range_table_max")).strong());
                    ui.end_row();
                    for (i, range) in SENSOR_RANGES_G.into_iter().enumerate() {
                        let (min, max) = self.tilt_rings.reach[i];
                        let current = (range - self.tilt.nudge_range_g).abs() < 0.01;
                        let cell = |text: String| {
                            let rich = egui::RichText::new(text);
                            if current { rich.strong() } else { rich }
                        };
                        ui.label(cell(format!("{range:.0} G")));
                        ui.label(cell(format!("{:.1} m/s²", range * crate::tilt::GRAVITY)));
                        ui.label(cell(format!("{min:.2}°")));
                        ui.label(cell(format!("{max:.2}°")));
                        ui.end_row();
                    }
                });
            ui.add_space(4.0);
            ui.label(
                egui::RichText::new(t!(
                    "tilt_range_table_reach_note",
                    pct = format!("{:.0}", self.tilt.nudge_scale_pct)
                ))
                .weak(),
            );
        });
    }

    /// The dial. Everything on it — dead zone, intent gate, tilt threshold,
    /// live reading — is drawn in one unit, acceleration as the sensor reads
    /// it, so distances on screen mean the same thing everywhere. The rim is
    /// full scale, which is the hard ceiling: a ring outside it names a
    /// setting the sensor can never satisfy.
    fn render_tilt_dial(&mut self, ui: &mut egui::Ui) {
        ui.label(t!("tilt_visualization"));
        ui.add_space(4.0);
        let viz_size = egui::vec2(260.0, 260.0);
        let (rect, _response) = ui.allocate_exact_size(viz_size, egui::Sense::hover());
        let painter = ui.painter_at(rect);
        // Snap to the pixel grid: a centre landing on a half pixel smears the
        // 1px crosshair over two rows and the rings read as off-centre.
        let center = {
            use egui::emath::GuiRounding as _;
            rect.center().round_to_pixel_center(ui.pixels_per_point())
        };
        let radius = 118.0;
        let rings = self.tilt_rings;
        let to_radius = |accel: f32| radius * (accel / rings.full_scale).clamp(0.0, 1.0);

        // Rim: full scale.
        painter.circle_stroke(center, radius, egui::Stroke::new(2.0, egui::Color32::GRAY));
        for (dx, dy) in [(1.0, 0.0), (0.0, 1.0)] {
            painter.line_segment(
                [
                    center - egui::vec2(radius * dx, radius * dy),
                    center + egui::vec2(radius * dx, radius * dy),
                ],
                egui::Stroke::new(1.0, egui::Color32::DARK_GRAY),
            );
        }

        // Tilt threshold. Beyond the rim it is unreachable, so it is drawn on
        // the rim as a dashed ring rather than silently clamped — the ring has
        // to say "no shove gets here", not "shove this hard".
        if rings.tilt_out_of_reach() {
            painter.circle_stroke(
                center,
                radius - 2.0,
                egui::Stroke::new(2.0, RING_TILT.gamma_multiply(0.55)),
            );
            for step in 0..48 {
                let angle = std::f32::consts::TAU * (step as f32 + 0.25) / 48.0;
                let dir = egui::vec2(angle.cos(), angle.sin());
                painter.line_segment(
                    [center + dir * (radius - 8.0), center + dir * (radius - 2.0)],
                    egui::Stroke::new(1.5, RING_TILT),
                );
            }
        } else {
            painter.circle_stroke(
                center,
                to_radius(rings.tilt),
                egui::Stroke::new(2.0, RING_TILT),
            );
        }

        // Intent gate — fixed at 1 m/s² on the strength-scaled vector, so
        // raising Strength moves it inwards. It is not a circle: VPX scales the
        // side axis by 4/3 (so it reaches 3/4 as far as the front one), and it
        // keeps only the push on the front axis — a pull is never a nudge. Hence
        // a half ellipse, closed along the side axis.
        if let Some(intent) = rings.intent {
            let side = to_radius(intent);
            let front = to_radius(intent * 4.0 / 3.0);
            let mut points: Vec<egui::Pos2> = (0..=48)
                .map(|step| {
                    let angle = std::f32::consts::PI * step as f32 / 48.0;
                    egui::pos2(
                        center.x + side * angle.cos(),
                        center.y - front * angle.sin(),
                    )
                })
                .collect();
            points.push(points[0]);
            painter.add(egui::Shape::line(
                points,
                egui::Stroke::new(2.0, RING_INTENT),
            ));
        }

        // Dead zone, innermost by nature: it gates the raw signal first.
        let deadzone_radius = to_radius(rings.deadzone);
        if deadzone_radius > 1.0 {
            painter.circle_filled(
                center,
                deadzone_radius,
                egui::Color32::from_rgba_unmultiplied(80, 200, 80, 40),
            );
            painter.circle_stroke(
                center,
                deadzone_radius,
                egui::Stroke::new(2.0, RING_DEADZONE),
            );
        }

        // The live sensor reading, thin and translucent — a laser dot that
        // shows movement everywhere, including inside the dead zone, which is
        // the one place the plumb can never show anything.
        let dot_pos = egui::pos2(
            center.x + self.accel_x.clamp(-1.05, 1.05) * radius,
            center.y + self.accel_y.clamp(-1.05, 1.05) * radius,
        );

        // The rim is the sensor's own ceiling: an axis reading its full scale
        // is a reading that was cut off there, and the board cannot say how
        // hard the real shove was. Sitting exactly on the rim and being clipped
        // by it look identical otherwise — the dot simply stops moving — so
        // clipping gets its own colour, and a mark that outlives the shove.
        let clipped = self.accel_x.abs() >= 1.0 || self.accel_y.abs() >= 1.0;
        if clipped {
            self.clip_marks.push(ClipMark {
                at: dot_pos,
                seen: std::time::Instant::now(),
            });
            if self.clip_marks.len() > CLIP_MARKS_KEPT {
                self.clip_marks.remove(0);
            }
        }

        // Marks fade out on their own: a nudge lasts a few milliseconds, far
        // less than it takes to look up from the cabinet.
        self.clip_marks
            .retain(|mark| mark.seen.elapsed() < CLIP_MARK_LIFE);
        for mark in &self.clip_marks {
            let left = 1.0 - mark.seen.elapsed().as_secs_f32() / CLIP_MARK_LIFE.as_secs_f32();
            painter.circle_stroke(
                mark.at,
                6.0,
                egui::Stroke::new(1.5, RING_CLIPPED.gamma_multiply(left.clamp(0.0, 1.0))),
            );
        }

        let laser = if clipped {
            RING_CLIPPED
        } else {
            egui::Color32::from_rgba_unmultiplied(255, 60, 60, 210)
        };
        painter.circle_filled(
            dot_pos,
            if clipped { 9.0 } else { 7.0 },
            laser.gamma_multiply(0.18),
        );
        painter.circle_filled(dot_pos, if clipped { 3.0 } else { 2.0 }, laser);

        // A legend, because a ring nobody can name is decoration.
        ui.add_space(2.0);
        let legend =
            |ui: &mut egui::Ui, color: egui::Color32, text: String, what: Option<String>| {
                ui.horizontal(|ui| {
                    let (rect, _) =
                        ui.allocate_exact_size(egui::vec2(12.0, 12.0), egui::Sense::hover());
                    ui.painter()
                        .circle_stroke(rect.center(), 5.0, egui::Stroke::new(2.0, color));
                    ui.label(egui::RichText::new(text).small());
                });
                if let Some(what) = what {
                    ui.label(egui::RichText::new(what).small().weak());
                }
            };
        legend(
            ui,
            egui::Color32::GRAY,
            t!(
                "tilt_legend_rim",
                accel = format!("{:.1}", rings.full_scale),
                range = format!("{:.0}", self.tilt.nudge_range_g)
            )
            .to_string(),
            None,
        );
        // Only worth a line when it has actually happened: a legend entry for
        // something nobody ever sees is noise.
        if !self.clip_marks.is_empty() {
            legend(
                ui,
                RING_CLIPPED,
                t!("tilt_legend_clipped").to_string(),
                None,
            );
        }
        legend(
            ui,
            RING_TILT,
            if rings.tilt_out_of_reach() {
                t!(
                    "tilt_legend_tilt_unreachable",
                    angle = format!("{:.2}", self.tilt.threshold_deg())
                )
                .to_string()
            } else {
                t!(
                    "tilt_legend_tilt",
                    angle = format!("{:.2}", self.tilt.threshold_deg()),
                    accel = format!("{:.1}", rings.tilt),
                    pct = format!("{:.0}", 100.0 * rings.tilt / rings.full_scale)
                )
                .to_string()
            },
            Some(t!("tilt_legend_tilt_what").to_string()),
        );
        if let Some(intent) = rings.intent {
            legend(
                ui,
                RING_INTENT,
                t!("tilt_legend_intent", accel = format!("{intent:.1}")).to_string(),
                Some(t!("tilt_legend_intent_what").to_string()),
            );
        }
        legend(
            ui,
            RING_DEADZONE,
            t!(
                "tilt_legend_deadzone",
                accel = format!("{:.2}", rings.deadzone),
                pct = format!("{:.0}", self.tilt.nudge_deadzone_pct)
            )
            .to_string(),
            Some(t!("tilt_legend_deadzone_what").to_string()),
        );

        // A banner naming what just happened. Rising is instant, falling
        // waits a second: a tilt that lasts one millisecond would otherwise
        // be gone before the eye arrives, and the point of shaking the
        // cabinet here is to see what the shake did.
        let now = std::time::Instant::now();
        let sensor_magnitude = self.accel_x.abs().max(self.accel_y.abs()) * rings.full_scale;
        let instant_state = if self.plumb_tilt_until.is_some_and(|t| now < t) {
            2
        } else if sensor_magnitude > rings.deadzone || self.nudge_sim.impulse_active() {
            // Either the raw signal cleared the dead zone, or the intent
            // detector recognised a nudge and is delivering its impulse.
            1
        } else {
            0
        };
        let calmed_down = self
            .nudge_state_since
            .is_none_or(|t| now.duration_since(t) >= std::time::Duration::from_secs(1));
        if instant_state >= self.nudge_state || calmed_down {
            self.nudge_state = instant_state;
            self.nudge_state_since = Some(now);
        }

        ui.add_space(6.0);
        let (bg, label) = match self.nudge_state {
            2 => (egui::Color32::from_rgb(200, 60, 60), t!("tilt_state_tilt")),
            1 => (
                egui::Color32::from_rgb(210, 140, 40),
                t!("tilt_state_nudge"),
            ),
            _ => (
                egui::Color32::from_rgb(70, 150, 70),
                t!("tilt_state_deadzone"),
            ),
        };
        egui::Frame::new()
            .fill(bg)
            .inner_margin(egui::Margin::symmetric(10, 6))
            .corner_radius(4)
            .show(ui, |ui| {
                ui.label(
                    egui::RichText::new(label)
                        .strong()
                        .color(egui::Color32::WHITE),
                );
            });
        ui.add_space(2.0);
        ui.label(
            egui::RichText::new(t!(
                "tilt_plumb_angle",
                angle = format!("{:.2}", self.plumb.angle_deg()),
                threshold = format!("{:.2}", self.tilt.threshold_deg())
            ))
            .weak(),
        );
    }
}