pyrucast 0.4.0

Finite-element library in Rust, inspired by cast3m, exposed to Python
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
//! Field-coloured rendering overlay — the "current component" button.
//!
//! Drawn on top of the rendered scene whenever a node field is supplied
//! (file export AND interactive window). In the interactive window the
//! same rectangle doubles as a **clickable button** that cycles through
//! the field's components — click detection uses `button_rect` so the
//! geometry stays in one place.

use crate::error::Result;
use crate::viz::drawable::pl_err;
use plotters::coord::Shift;
use plotters::prelude::*;
use plotters::style::text_anchor::{HPos, Pos, VPos};

const BUTTON_MARGIN: i32 = 10;
const BUTTON_WIDTH: i32 = 260;
const BUTTON_HEIGHT: i32 = 26;
const BUTTON_FILL: RGBColor = RGBColor(245, 245, 245);
const BUTTON_BORDER: RGBColor = RGBColor(110, 110, 110);
const BUTTON_TEXT: RGBColor = RGBColor(20, 20, 20);

// ─── Colorbar geometry (right edge of the canvas) ───────────────────────────
const BAR_WIDTH: i32 = 16;
/// Space reserved to the right of the bar for tick marks + value labels.
const BAR_RIGHT_MARGIN: i32 = 58;
const BAR_TOP_MARGIN: i32 = 48;
const BAR_BOTTOM_MARGIN: i32 = 36;
const BAR_TICKS: usize = 5;
/// Number of constant-colour bands making up the gradient. Sampling it per
/// pixel costs one rectangle per row, which a vector backend writes as one
/// tag each — some 500 tags, tens of kilobytes, for a bar 16 px wide. At this
/// count a band is a few pixels tall and the ramp still reads as continuous.
const BAR_BANDS: i32 = 64;

/// Pixel-space rectangle `(x, y, width, height)` of the button, in the
/// drawing area's local coordinate system (top-left origin). Centred at
/// the top of the area.
pub(crate) fn button_rect(area_width: u32) -> (i32, i32, i32, i32) {
    let x = (area_width as i32 - BUTTON_WIDTH) / 2;
    let y = BUTTON_MARGIN;
    (x.max(BUTTON_MARGIN), y, BUTTON_WIDTH, BUTTON_HEIGHT)
}

/// Is the pixel `(px, py)` inside the button on a canvas of size `(w, h)`?
#[cfg(any(test, feature = "viz-interactive"))]
pub(crate) fn click_hits_button(px: f64, py: f64, area_width: u32) -> bool {
    let (bx, by, bw, bh) = button_rect(area_width);
    let inside_x = px >= bx as f64 && px <= (bx + bw) as f64;
    let inside_y = py >= by as f64 && py <= (by + bh) as f64;
    inside_x && inside_y
}

/// Draw the labelled button (component name + value range) onto `area`.
pub(crate) fn draw_field_overlay<DB: DrawingBackend>(
    area: &DrawingArea<DB, Shift>,
    component: &str,
    vmin: f64,
    vmax: f64,
) -> Result<()>
where
    DB::ErrorType: 'static,
{
    let (w, _) = area.dim_in_pixel();
    let (bx, by, bw, bh) = button_rect(w);

    // Filled background.
    let fill = ShapeStyle::from(&BUTTON_FILL).filled();
    area.draw(&Rectangle::new(
        [(bx, by), (bx + bw - 1, by + bh - 1)],
        fill,
    ))
    .map_err(pl_err)?;
    // Border (un-filled rectangle = stroke).
    let border = ShapeStyle::from(&BUTTON_BORDER);
    area.draw(&Rectangle::new(
        [(bx, by), (bx + bw - 1, by + bh - 1)],
        border,
    ))
    .map_err(pl_err)?;

    // Label centred vertically — plotters draws text with its top-left at
    // `pos`, so we shift down by ~6 px to feel centred for a 14-pt font.
    let label = format!("[{}]  min={:.3}  max={:.3}", component, vmin, vmax);
    let text_style = TextStyle::from(("sans-serif", 13).into_font()).color(&BUTTON_TEXT);
    area.draw_text(&label, &text_style, (bx + 10, by + 5))
        .map_err(pl_err)?;
    Ok(())
}

// ─── Figure title (bottom caption of a file export) ─────────────────────────

/// Height in pixels of the band reserved below a plot for its figure title.
pub(crate) const FIGURE_TITLE_BAND: u32 = 40;

/// Font size of the figure title.
const FIGURE_TITLE_FONT: i32 = 18;

/// Draw `title` centred (horizontally and vertically) in `area` — the band
/// reserved at the bottom of a file export by the render dispatch. The window
/// backend uses the same string as the OS window title instead.
pub(crate) fn draw_figure_title<DB: DrawingBackend>(
    area: &DrawingArea<DB, Shift>,
    title: &str,
) -> Result<()>
where
    DB::ErrorType: 'static,
{
    let (w, h) = area.dim_in_pixel();
    let style = TextStyle::from(("sans-serif", FIGURE_TITLE_FONT).into_font())
        .color(&BUTTON_TEXT)
        .pos(Pos::new(HPos::Center, VPos::Center));
    area.draw_text(title, &style, (w as i32 / 2, h as i32 / 2))
        .map_err(pl_err)?;
    Ok(())
}

/// Draw a vertical colorbar on the right edge of `area`: the `cmap`
/// gradient (same one painting the cells) annotated with evenly spaced
/// value ticks. `vmin` maps to the bottom, `vmax` to the top.
///
/// No-op on a canvas too small to host the bar with its labels.
pub(crate) fn draw_colorbar<DB: DrawingBackend>(
    area: &DrawingArea<DB, Shift>,
    cmap: crate::viz::Colormap,
    vmin: f64,
    vmax: f64,
) -> Result<()>
where
    DB::ErrorType: 'static,
{
    let (w, h) = area.dim_in_pixel();
    let (w, h) = (w as i32, h as i32);
    let bar_x = w - BAR_RIGHT_MARGIN - BAR_WIDTH;
    let bar_top = BAR_TOP_MARGIN;
    let bar_bottom = h - BAR_BOTTOM_MARGIN;
    let bar_h = bar_bottom - bar_top;
    if bar_x <= 0 || bar_h <= 1 {
        return Ok(());
    }

    // Gradient: a stack of constant-colour bands, each sampled at its own
    // middle. `colormap` with the same `cmap` / `(vmin, vmax)` as the cells
    // keeps the bar and the mesh consistent, including the degenerate
    // (vmax ≤ vmin) → midpoint case.
    let bands = BAR_BANDS.min(bar_h);
    for k in 0..bands {
        let y0 = bar_top + k * bar_h / bands;
        let y1 = bar_top + (k + 1) * bar_h / bands;
        if y1 <= y0 {
            continue;
        }
        let mid = (y0 + y1) as f64 / 2.0 - bar_top as f64;
        let t = 1.0 - mid / (bar_h - 1) as f64; // 1 at top, 0 at bottom
        let value = vmin + t * (vmax - vmin);
        let c = crate::viz::field_color::colormap(cmap, value, vmin, vmax);
        let style = ShapeStyle::from(&RGBColor(c.r, c.g, c.b)).filled();
        area.draw(&Rectangle::new(
            [(bar_x, y0), (bar_x + BAR_WIDTH - 1, y1)],
            style,
        ))
        .map_err(pl_err)?;
    }
    // Border around the bar.
    area.draw(&Rectangle::new(
        [(bar_x, bar_top), (bar_x + BAR_WIDTH - 1, bar_bottom - 1)],
        ShapeStyle::from(&BUTTON_BORDER),
    ))
    .map_err(pl_err)?;

    // Ticks + value labels, bottom (vmin) → top (vmax).
    let text_style = TextStyle::from(("sans-serif", 12).into_font()).color(&BUTTON_TEXT);
    let tick_style = ShapeStyle::from(&BUTTON_BORDER);
    for i in 0..BAR_TICKS {
        let frac = i as f64 / (BAR_TICKS - 1) as f64;
        let value = vmin + frac * (vmax - vmin);
        let y = bar_bottom - 1 - (frac * (bar_h - 1) as f64).round() as i32;
        area.draw(&PathElement::new(
            vec![(bar_x + BAR_WIDTH, y), (bar_x + BAR_WIDTH + 4, y)],
            tick_style,
        ))
        .map_err(pl_err)?;
        area.draw_text(
            &format!("{value:.3}"),
            &text_style,
            (bar_x + BAR_WIDTH + 8, y - 7),
        )
        .map_err(pl_err)?;
    }
    Ok(())
}

// ─── Revolution toggle (interactive window only) ────────────────────────────
//
// Offered only on an axisymmetric plot, where sweeping the meridian section
// into its body of revolution is meaningful. Pinned to the top-left corner:
// the field button is centred and the view readout sits on the right.

#[cfg(any(test, feature = "viz-interactive"))]
const REVOLVE_WIDTH: i32 = 150;
#[cfg(any(test, feature = "viz-interactive"))]
const REVOLVE_HEIGHT: i32 = 26;
/// Fill of the button when the sweep is on (the state reads at a glance).
#[cfg(any(test, feature = "viz-interactive"))]
const REVOLVE_ON_FILL: RGBColor = RGBColor(198, 224, 250);

/// Pixel-space rectangle `(x, y, width, height)` of the revolution toggle.
#[cfg(any(test, feature = "viz-interactive"))]
pub(crate) fn revolve_button_rect() -> (i32, i32, i32, i32) {
    (BUTTON_MARGIN, BUTTON_MARGIN, REVOLVE_WIDTH, REVOLVE_HEIGHT)
}

/// Is the pixel `(px, py)` inside the revolution toggle?
#[cfg(any(test, feature = "viz-interactive"))]
pub(crate) fn click_hits_revolve_button(px: f64, py: f64) -> bool {
    let (bx, by, bw, bh) = revolve_button_rect();
    px >= bx as f64 && px <= (bx + bw) as f64 && py >= by as f64 && py <= (by + bh) as f64
}

/// Draw the revolution toggle, labelled with the state it is in.
#[cfg(any(test, feature = "viz-interactive"))]
pub(crate) fn draw_revolve_button<DB: DrawingBackend>(
    area: &DrawingArea<DB, Shift>,
    revolve: Option<crate::viz::Revolve>,
) -> Result<()>
where
    DB::ErrorType: 'static,
{
    let (bx, by, bw, bh) = revolve_button_rect();
    let fill = match revolve {
        Some(_) => REVOLVE_ON_FILL,
        None => BUTTON_FILL,
    };
    area.draw(&Rectangle::new(
        [(bx, by), (bx + bw - 1, by + bh - 1)],
        ShapeStyle::from(&fill).filled(),
    ))
    .map_err(pl_err)?;
    area.draw(&Rectangle::new(
        [(bx, by), (bx + bw - 1, by + bh - 1)],
        ShapeStyle::from(&BUTTON_BORDER),
    ))
    .map_err(pl_err)?;

    let label = match revolve {
        Some(rev) => format!("3D {:.0}deg  [R]", rev.angle()),
        None => "2D section  [R]".to_string(),
    };
    let text_style = TextStyle::from(("sans-serif", 13).into_font()).color(&BUTTON_TEXT);
    area.draw_text(&label, &text_style, (bx + 10, by + 5))
        .map_err(pl_err)?;
    Ok(())
}

// ─── View readout (interactive window only) ─────────────────────────────────

#[cfg(any(test, feature = "viz-interactive"))]
const READOUT_WIDTH: i32 = 210;
#[cfg(any(test, feature = "viz-interactive"))]
const READOUT_HEIGHT: i32 = 26;

/// Draw the current `(yaw, pitch, scale)` — same order as the `view=`
/// tuple accepted by `plot()` — as small text pinned to the top-right
/// corner. Interactive window only: it lets the user read back a camera
/// angle they rotated/zoomed to, to reuse as `view=(...)` later.
#[cfg(any(test, feature = "viz-interactive"))]
pub(crate) fn draw_view_readout<DB: DrawingBackend>(
    area: &DrawingArea<DB, Shift>,
    view: &crate::viz::View,
) -> Result<()>
where
    DB::ErrorType: 'static,
{
    let (w, _) = area.dim_in_pixel();
    let x = (w as i32 - READOUT_WIDTH - BUTTON_MARGIN).max(BUTTON_MARGIN);
    let y = BUTTON_MARGIN;

    // Filled background + border, same look as the field button, so the
    // text stays legible over any mesh colour behind it.
    area.draw(&Rectangle::new(
        [(x, y), (x + READOUT_WIDTH - 1, y + READOUT_HEIGHT - 1)],
        ShapeStyle::from(&BUTTON_FILL).filled(),
    ))
    .map_err(pl_err)?;
    area.draw(&Rectangle::new(
        [(x, y), (x + READOUT_WIDTH - 1, y + READOUT_HEIGHT - 1)],
        ShapeStyle::from(&BUTTON_BORDER),
    ))
    .map_err(pl_err)?;

    let label = format!(
        "view=({:.1}, {:.1}, {:.2})",
        view.yaw, view.pitch, view.scale
    );
    let text_style = TextStyle::from(("sans-serif", 13).into_font()).color(&BUTTON_TEXT);
    area.draw_text(&label, &text_style, (x + 6, y + 5))
        .map_err(pl_err)?;
    Ok(())
}

// ─── Frame slider (evolution plots) ─────────────────────────────────────────
//
// The slider is drawn and grabbed only in the interactive window (file export
// shows a single static frame), so its helpers are gated like the rest of the
// interactive path — plus `test` so the unit tests below stay reachable.

#[cfg(any(test, feature = "viz-interactive"))]
const SLIDER_MARGIN_X: i32 = 60;
#[cfg(any(test, feature = "viz-interactive"))]
const SLIDER_BOTTOM_MARGIN: i32 = 20;
#[cfg(any(test, feature = "viz-interactive"))]
const SLIDER_HEIGHT: i32 = 8;
#[cfg(any(test, feature = "viz-interactive"))]
const SLIDER_KNOB_R: i32 = 7;
/// Vertical tolerance (px) around the track that still grabs the slider.
#[cfg(any(test, feature = "viz-interactive"))]
const SLIDER_HIT_PAD: i32 = 12;
#[cfg(any(test, feature = "viz-interactive"))]
const SLIDER_TRACK: RGBColor = RGBColor(210, 210, 210);
#[cfg(any(test, feature = "viz-interactive"))]
const SLIDER_FILL: RGBColor = RGBColor(70, 130, 200);

/// Pixel-space track rectangle `(x, y, width, height)` of the frame slider,
/// a horizontal bar near the bottom of a canvas of size `(w, h)`.
#[cfg(any(test, feature = "viz-interactive"))]
pub(crate) fn slider_rect(area_w: u32, area_h: u32) -> (i32, i32, i32, i32) {
    let x = SLIDER_MARGIN_X;
    let w = (area_w as i32 - 2 * SLIDER_MARGIN_X).max(1);
    let y = area_h as i32 - SLIDER_BOTTOM_MARGIN - SLIDER_HEIGHT;
    (x, y, w, SLIDER_HEIGHT)
}

/// The frame index a click at `(px, py)` selects on the slider, or `None`
/// if the click is outside the slider's grab band. With a single frame the
/// slider always reports frame 0.
#[cfg(any(test, feature = "viz-interactive"))]
pub(crate) fn slider_frame_at(
    px: f64,
    py: f64,
    area_w: u32,
    area_h: u32,
    n_frames: usize,
) -> Option<usize> {
    if n_frames == 0 {
        return None;
    }
    let (x, y, w, h) = slider_rect(area_w, area_h);
    let in_x = px >= (x - SLIDER_KNOB_R) as f64 && px <= (x + w + SLIDER_KNOB_R) as f64;
    let in_y = py >= (y - SLIDER_HIT_PAD) as f64 && py <= (y + h + SLIDER_HIT_PAD) as f64;
    if !in_x || !in_y {
        return None;
    }
    if n_frames == 1 {
        return Some(0);
    }
    let frac = ((px - x as f64) / w as f64).clamp(0.0, 1.0);
    Some((frac * (n_frames - 1) as f64).round() as usize)
}

/// Draw the frame slider (track, filled portion, knob) plus a label
/// `frame k/n   x=…` just above it. No-op on a canvas too small.
#[cfg(any(test, feature = "viz-interactive"))]
pub(crate) fn draw_slider<DB: DrawingBackend>(
    area: &DrawingArea<DB, Shift>,
    frame: usize,
    n_frames: usize,
    abscissa_label: &str,
    abscissa: f64,
) -> Result<()>
where
    DB::ErrorType: 'static,
{
    if n_frames == 0 {
        return Ok(());
    }
    let (w, h) = area.dim_in_pixel();
    let (x, y, tw, th) = slider_rect(w, h);
    if tw < 4 * SLIDER_KNOB_R {
        return Ok(());
    }
    let frac = if n_frames > 1 {
        frame as f64 / (n_frames - 1) as f64
    } else {
        0.0
    };
    let knob_x = x + (frac * tw as f64).round() as i32;
    let cy = y + th / 2;

    // Track.
    area.draw(&Rectangle::new(
        [(x, y), (x + tw, y + th)],
        ShapeStyle::from(&SLIDER_TRACK).filled(),
    ))
    .map_err(pl_err)?;
    // Filled portion up to the knob.
    area.draw(&Rectangle::new(
        [(x, y), (knob_x, y + th)],
        ShapeStyle::from(&SLIDER_FILL).filled(),
    ))
    .map_err(pl_err)?;
    // Knob.
    area.draw(&Circle::new(
        (knob_x, cy),
        SLIDER_KNOB_R,
        ShapeStyle::from(&SLIDER_FILL).filled(),
    ))
    .map_err(pl_err)?;
    area.draw(&Circle::new(
        (knob_x, cy),
        SLIDER_KNOB_R,
        ShapeStyle::from(&BUTTON_BORDER),
    ))
    .map_err(pl_err)?;

    // Label above the track.
    let label = format!(
        "frame {}/{}   {}={:.4}",
        frame + 1,
        n_frames,
        abscissa_label,
        abscissa
    );
    let text_style = TextStyle::from(("sans-serif", 13).into_font()).color(&BUTTON_TEXT);
    area.draw_text(&label, &text_style, (x, y - 20))
        .map_err(pl_err)?;
    Ok(())
}

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

    #[test]
    fn button_rect_centred() {
        let (x, _y, w, _h) = button_rect(800);
        // Centred horizontally on an 800-px canvas.
        assert_eq!(x, (800 - BUTTON_WIDTH) / 2);
        assert_eq!(w, BUTTON_WIDTH);
    }

    #[test]
    fn click_hits_button_inside_and_outside() {
        let (bx, by, bw, bh) = button_rect(800);
        let cx = (bx + bw / 2) as f64;
        let cy = (by + bh / 2) as f64;
        assert!(click_hits_button(cx, cy, 800));
        // Far away: not inside.
        assert!(!click_hits_button(0.0, 0.0, 800));
        assert!(!click_hits_button(799.0, 599.0, 800));
    }

    #[test]
    fn draw_overlay_renders_label_in_svg() {
        let mut buf = String::new();
        {
            let backend = SVGBackend::with_string(&mut buf, (400, 100));
            let area = backend.into_drawing_area();
            area.fill(&WHITE).unwrap();
            draw_field_overlay(&area, "T", 0.0, 1.5).unwrap();
            area.present().unwrap();
        }
        // The label text should appear in the SVG output.
        assert!(buf.contains("[T]"));
        assert!(buf.contains("min=0.000"));
        assert!(buf.contains("max=1.500"));
    }

    #[test]
    fn draw_figure_title_renders_text_in_svg() {
        let mut buf = String::new();
        {
            let backend = SVGBackend::with_string(&mut buf, (400, 40));
            let area = backend.into_drawing_area();
            area.fill(&WHITE).unwrap();
            draw_figure_title(&area, "beam L=2m").unwrap();
            area.present().unwrap();
        }
        assert!(buf.contains("beam L=2m"));
    }

    #[test]
    fn draw_colorbar_renders_value_ticks() {
        let mut buf = String::new();
        {
            let backend = SVGBackend::with_string(&mut buf, (400, 300));
            let area = backend.into_drawing_area();
            area.fill(&WHITE).unwrap();
            draw_colorbar(&area, crate::viz::Colormap::Viridis, 0.0, 2.0).unwrap();
            area.present().unwrap();
        }
        // 5 evenly spaced ticks over [0, 2]: endpoints and midpoint.
        assert!(buf.contains("0.000"));
        assert!(buf.contains("1.000"));
        assert!(buf.contains("2.000"));
    }

    #[test]
    fn draw_colorbar_gradient_is_banded_not_per_pixel() {
        let mut buf = String::new();
        {
            let backend = SVGBackend::with_string(&mut buf, (400, 300));
            let area = backend.into_drawing_area();
            area.fill(&WHITE).unwrap();
            draw_colorbar(&area, crate::viz::Colormap::Viridis, 0.0, 2.0).unwrap();
            area.present().unwrap();
        }
        // The gradient rectangles, plus the canvas fill and the bar's border.
        let rects = buf.matches("<rect").count();
        assert!(
            rects <= BAR_BANDS as usize + 2,
            "gradient drawn in {rects} rectangles, expected at most {}",
            BAR_BANDS + 2
        );
        // Ends still carry the extremes of the colormap: Viridis runs from
        // dark violet at `vmin` to yellow at `vmax`.
        let top = crate::viz::field_color::colormap(crate::viz::Colormap::Viridis, 2.0, 0.0, 2.0);
        let bottom =
            crate::viz::field_color::colormap(crate::viz::Colormap::Viridis, 0.0, 0.0, 2.0);
        assert!(top.r > 200 && top.g > 200, "top band should be yellow");
        assert!(
            bottom.r < 100 && bottom.g < 100,
            "bottom band should be dark"
        );
    }

    #[test]
    fn slider_frame_at_maps_position_to_index() {
        let (x, y, w, h) = slider_rect(800, 600);
        let cy = (y + h / 2) as f64;
        // Far left → frame 0, far right → last, middle → middle.
        assert_eq!(slider_frame_at(x as f64, cy, 800, 600, 5), Some(0));
        assert_eq!(slider_frame_at((x + w) as f64, cy, 800, 600, 5), Some(4));
        assert_eq!(
            slider_frame_at((x + w / 2) as f64, cy, 800, 600, 5),
            Some(2)
        );
        // Click far above the track → no grab.
        assert_eq!(slider_frame_at((x + w / 2) as f64, 10.0, 800, 600, 5), None);
        // Single frame always reports 0.
        assert_eq!(slider_frame_at(x as f64, cy, 800, 600, 1), Some(0));
    }

    #[test]
    fn draw_slider_renders_label_in_svg() {
        let mut buf = String::new();
        {
            let backend = SVGBackend::with_string(&mut buf, (640, 480));
            let area = backend.into_drawing_area();
            area.fill(&WHITE).unwrap();
            draw_slider(&area, 1, 4, "x", 2.5).unwrap();
            area.present().unwrap();
        }
        assert!(buf.contains("frame 2/4"));
        assert!(buf.contains("x=2.5000"));
    }

    #[test]
    fn draw_view_readout_renders_values_in_svg() {
        let mut buf = String::new();
        {
            let backend = SVGBackend::with_string(&mut buf, (400, 100));
            let area = backend.into_drawing_area();
            area.fill(&WHITE).unwrap();
            let view = crate::viz::View {
                yaw: 45.0,
                pitch: 35.264_389_682_754_654,
                scale: 1.0,
                target: None,
                show_axes: true,
                revolve: None,
            };
            draw_view_readout(&area, &view).unwrap();
            area.present().unwrap();
        }
        assert!(buf.contains("view=(45.0, 35.3, 1.00)"));
    }

    #[test]
    fn revolve_button_hit_test_and_labels() {
        let (bx, by, bw, bh) = revolve_button_rect();
        assert!(click_hits_revolve_button(
            (bx + bw / 2) as f64,
            (by + bh / 2) as f64
        ));
        assert!(!click_hits_revolve_button(400.0, 300.0));

        // The label states which of the two modes is active.
        for (revolve, expected) in [
            (None, "2D section"),
            (Some(crate::viz::Revolve::full()), "3D 360deg"),
        ] {
            let mut buf = String::new();
            {
                let backend = SVGBackend::with_string(&mut buf, (400, 100));
                let area = backend.into_drawing_area();
                area.fill(&WHITE).unwrap();
                draw_revolve_button(&area, revolve).unwrap();
                area.present().unwrap();
            }
            assert!(buf.contains(expected), "{buf}");
        }
    }

    #[test]
    fn draw_colorbar_skips_tiny_canvas() {
        // Too small to host the bar + labels — must be a no-op, not panic.
        let mut buf = String::new();
        {
            let backend = SVGBackend::with_string(&mut buf, (20, 20));
            let area = backend.into_drawing_area();
            area.fill(&WHITE).unwrap();
            draw_colorbar(&area, crate::viz::Colormap::Viridis, 0.0, 1.0).unwrap();
            area.present().unwrap();
        }
    }
}