sim-engine 0.4.2

A validated high-performance visualization engine for simulations
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
//! Interactive visual oracle for stroke and frame-composition paths.
//!
//! Controls: 1-5 pages, Space pause, Left/Right scrub dash phase, +/- zoom,
//! R reset, Esc exit. Pass `--uncapped` to inspect throughput without FIFO pacing.

use std::{error::Error, sync::Arc, time::Instant};

use sim_engine::{
    Camera2d, Color, FrameBudget, FramePassOptions, LogicalPixels, LogicalScreenPosition,
    LogicalScreenVector, LogicalViewport, RenderStatus, RendererPresentMode, Scene, ScreenScene,
    ShapeStyle, StrokeCap2d, StrokeDashPattern2d, StrokeJoin2d, StrokeMarker2d,
    StrokeMarkerAnchor2d, StrokeStyle2d, Vec2, WgpuRenderer, WgpuRendererOptions, WorldLength,
};
use winit::{
    application::ApplicationHandler,
    dpi::LogicalSize,
    event::{ElementState, WindowEvent},
    event_loop::{ActiveEventLoop, ControlFlow, EventLoop},
    keyboard::{KeyCode, PhysicalKey},
    window::{Window, WindowId},
};

fn main() -> Result<(), Box<dyn Error>> {
    env_logger::init();
    let arguments = std::env::args().skip(1).collect::<Vec<_>>();
    let uncapped = arguments.iter().any(|argument| argument == "--uncapped");
    let initial_page = arguments
        .windows(2)
        .find(|pair| pair[0] == "--page")
        .and_then(|pair| match pair[1].as_str() {
            "1" => Some(GalleryPage::CapsAndJoins),
            "2" => Some(GalleryPage::AlphaContract),
            "3" => Some(GalleryPage::DashesAndMarkers),
            "4" => Some(GalleryPage::CameraAndEdges),
            "5" => Some(GalleryPage::ExactVectors),
            _ => None,
        })
        .unwrap_or(GalleryPage::CapsAndJoins);
    let frame_limit = arguments
        .windows(2)
        .find(|pair| pair[0] == "--frames")
        .map(|pair| pair[1].parse::<usize>())
        .transpose()?;
    if frame_limit == Some(0) {
        return Err("--frames must be positive".into());
    }
    let event_loop = EventLoop::new()?;
    event_loop.set_control_flow(ControlFlow::Poll);
    let mut application = GalleryApplication::new(uncapped, initial_page);
    application.frame_limit = frame_limit;
    event_loop.run_app(&mut application)?;
    if let Some(error) = application.failure {
        return Err(error.into());
    }
    Ok(())
}

#[derive(Debug, Clone, Copy, PartialEq, Eq)]
enum GalleryPage {
    CapsAndJoins,
    AlphaContract,
    DashesAndMarkers,
    CameraAndEdges,
    ExactVectors,
}

impl GalleryPage {
    const fn number(self) -> u8 {
        match self {
            Self::CapsAndJoins => 1,
            Self::AlphaContract => 2,
            Self::DashesAndMarkers => 3,
            Self::CameraAndEdges => 4,
            Self::ExactVectors => 5,
        }
    }

    const fn title(self) -> &'static str {
        match self {
            Self::CapsAndJoins => "caps + bevel/miter/round joins",
            Self::AlphaContract => "translucent joins: body and corner must match",
            Self::DashesAndMarkers => "bounded dashes + outward arrow markers",
            Self::CameraAndEdges => "camera stress + short accepted geometry",
            Self::ExactVectors => {
                "exact tips at crosshairs: cyan logical width, orange world width"
            }
        }
    }
}

struct GalleryApplication {
    window: Option<Arc<Window>>,
    renderer: Option<WgpuRenderer>,
    camera: Camera2d,
    page: GalleryPage,
    paused: bool,
    uncapped: bool,
    animation: f32,
    last_frame: Instant,
    metrics_started: Instant,
    metric_frames: usize,
    metric_work_seconds: f64,
    metric_acquire_seconds: f64,
    frame_limit: Option<usize>,
    drawn_frames: usize,
    failure: Option<String>,
}

impl GalleryApplication {
    fn new(uncapped: bool, page: GalleryPage) -> Self {
        let now = Instant::now();
        Self {
            window: None,
            renderer: None,
            camera: Camera2d::new(Vec2::ZERO, 10_000.0).expect("gallery camera is valid"),
            page,
            paused: false,
            uncapped,
            animation: 0.0,
            last_frame: now,
            metrics_started: now,
            metric_frames: 0,
            metric_work_seconds: 0.0,
            metric_acquire_seconds: 0.0,
            frame_limit: None,
            drawn_frames: 0,
            failure: None,
        }
    }

    fn reset(&mut self) {
        self.animation = 0.0;
        self.paused = false;
        self.camera.set_zoom(10_000.0).expect("reset zoom is valid");
        self.camera
            .set_rotation(0.0)
            .expect("reset rotation is valid");
    }

    fn update_title(&mut self, now: Instant, work: f64, acquire: f64) {
        self.metric_frames = self.metric_frames.saturating_add(1);
        self.metric_work_seconds += work;
        self.metric_acquire_seconds += acquire;
        let elapsed = now.saturating_duration_since(self.metrics_started);
        if elapsed.as_secs_f64() < 1.0 {
            return;
        }
        let frames = self.metric_frames.max(1) as f64;
        let fps = frames / elapsed.as_secs_f64();
        let work_ms = self.metric_work_seconds * 1_000.0 / frames;
        let acquire_ms = self.metric_acquire_seconds * 1_000.0 / frames;
        if let Some(window) = &self.window {
            window.set_title(&format!(
                "Sim;Engine stroke gallery {} | {} | {fps:.1} FPS | work {work_ms:.3} ms | acquire {acquire_ms:.3} ms",
                self.page.number(),
                self.page.title(),
            ));
        }
        println!(
            "gallery page={} fps={fps:.1} renderer_work_ms={work_ms:.3} acquire_ms={acquire_ms:.3}",
            self.page.number()
        );
        self.metrics_started = now;
        self.metric_frames = 0;
        self.metric_work_seconds = 0.0;
        self.metric_acquire_seconds = 0.0;
    }
}

impl ApplicationHandler for GalleryApplication {
    fn resumed(&mut self, event_loop: &ActiveEventLoop) {
        if self.window.is_some() {
            return;
        }
        let window = Arc::new(
            event_loop
                .create_window(
                    Window::default_attributes()
                        .with_title("Sim;Engine stroke gallery")
                        .with_inner_size(LogicalSize::new(1280.0, 760.0)),
                )
                .expect("create gallery window"),
        );
        let size = window.inner_size();
        let present_mode = if self.uncapped {
            RendererPresentMode::NoVsync
        } else {
            RendererPresentMode::Vsync
        };
        let options = WgpuRendererOptions::new(present_mode, window.scale_factor())
            .expect("window scale factor is valid");
        let mut renderer = pollster::block_on(WgpuRenderer::new_with_options(
            Arc::clone(&window),
            size.width.max(1),
            size.height.max(1),
            options,
        ))
        .expect("create gallery renderer");
        let notify_window = Arc::clone(&window);
        renderer.set_pre_present_notify(move || notify_window.pre_present_notify());
        println!(
            "stroke gallery: 1 caps/joins, 2 alpha, 3 dash/markers, 4 camera edge cases, 5 exact scientific vectors; Space pause, Left/Right scrub, +/- zoom, R reset, Esc exit"
        );
        self.window = Some(window);
        self.renderer = Some(renderer);
    }

    fn window_event(
        &mut self,
        event_loop: &ActiveEventLoop,
        window_id: WindowId,
        event: WindowEvent,
    ) {
        let Some(window) = self.window.as_ref().map(Arc::clone) else {
            return;
        };
        if window.id() != window_id {
            return;
        }
        match event {
            WindowEvent::CloseRequested => event_loop.exit(),
            WindowEvent::Resized(size) => {
                if let Some(renderer) = self.renderer.as_mut() {
                    renderer
                        .resize_with_scale_factor(
                            size.width.max(1),
                            size.height.max(1),
                            window.scale_factor(),
                        )
                        .expect("gallery resize is valid");
                }
            }
            WindowEvent::ScaleFactorChanged { scale_factor, .. } => {
                if let Some(renderer) = self.renderer.as_mut() {
                    let size = window.inner_size();
                    renderer
                        .resize_with_scale_factor(
                            size.width.max(1),
                            size.height.max(1),
                            scale_factor,
                        )
                        .expect("gallery scale transition is valid");
                }
            }
            WindowEvent::KeyboardInput { event, .. } if event.state == ElementState::Pressed => {
                let PhysicalKey::Code(code) = event.physical_key else {
                    return;
                };
                match code {
                    KeyCode::Escape => event_loop.exit(),
                    KeyCode::Digit1 => self.page = GalleryPage::CapsAndJoins,
                    KeyCode::Digit2 => self.page = GalleryPage::AlphaContract,
                    KeyCode::Digit3 => self.page = GalleryPage::DashesAndMarkers,
                    KeyCode::Digit4 => self.page = GalleryPage::CameraAndEdges,
                    KeyCode::Digit5 => self.page = GalleryPage::ExactVectors,
                    KeyCode::Space => self.paused = !self.paused,
                    KeyCode::ArrowLeft => self.animation -= 0.15,
                    KeyCode::ArrowRight => self.animation += 0.15,
                    KeyCode::Equal | KeyCode::NumpadAdd => {
                        let zoom = (self.camera.zoom() * 1.25).min(100_000.0);
                        self.camera.set_zoom(zoom).expect("bounded zoom is valid");
                    }
                    KeyCode::Minus | KeyCode::NumpadSubtract => {
                        let zoom = (self.camera.zoom() / 1.25).max(1.0);
                        self.camera.set_zoom(zoom).expect("bounded zoom is valid");
                    }
                    KeyCode::KeyR => self.reset(),
                    _ => {}
                }
                window.request_redraw();
            }
            WindowEvent::RedrawRequested => {
                if let Err(error) = self.draw_frame() {
                    eprintln!("stroke gallery frame failed: {error}");
                    self.failure = Some(error.to_string());
                    event_loop.exit();
                } else if self
                    .frame_limit
                    .is_some_and(|limit| self.drawn_frames >= limit)
                {
                    println!(
                        "stroke gallery page {}: {} presented frames",
                        self.page.number(),
                        self.drawn_frames
                    );
                    event_loop.exit();
                }
            }
            _ => {}
        }
    }

    fn about_to_wait(&mut self, _event_loop: &ActiveEventLoop) {
        if let Some(window) = &self.window {
            window.request_redraw();
        }
    }
}

impl GalleryApplication {
    fn draw_frame(&mut self) -> Result<(), Box<dyn Error>> {
        let now = Instant::now();
        let delta = now.saturating_duration_since(self.last_frame);
        self.last_frame = now;
        if !self.paused {
            self.animation += delta.as_secs_f32();
        }
        if matches!(
            self.page,
            GalleryPage::CameraAndEdges | GalleryPage::ExactVectors
        ) {
            self.camera
                .set_rotation((self.animation * 0.35).sin() * 0.22)?;
        }
        let renderer = self
            .renderer
            .as_mut()
            .ok_or("renderer is not initialized")?;
        let (width, height) = renderer.logical_size();
        let mut screen = build_screen_page(self.page, width, height, self.animation)?;
        let mut camera = self.camera;
        let world = match self.page {
            GalleryPage::CameraAndEdges => Some(build_world_edge_scene()?),
            GalleryPage::ExactVectors => {
                // Keep the complete illustrative vectors inside the target at
                // every window size. Zooming out still demonstrates world width.
                camera.set_zoom(camera.zoom().min(width.min(height) * 0.38 / 0.03).max(1.0))?;
                add_exact_vector_guides(&mut screen, camera, LogicalViewport::new(width, height)?)?;
                Some(build_exact_vector_scene()?)
            }
            _ => None,
        };
        let mut frame = renderer.begin_frame(screen.background(), FrameBudget::default())?;
        frame.draw_screen_scene(&screen, FramePassOptions::new(0))?;
        if let Some(world) = &world {
            frame.draw_scene(world, camera, FramePassOptions::new(1))?;
        }
        let report = frame.present()?;
        if report.status() != RenderStatus::Drawn {
            if self.frame_limit.is_some() {
                return Err("bounded gallery run requires every frame to be drawn".into());
            }
            return Ok(());
        }
        self.drawn_frames += 1;
        let metrics = report.metrics();
        self.update_title(
            now,
            metrics
                .total_cpu()
                .saturating_sub(metrics.surface_acquire())
                .as_secs_f64(),
            metrics.surface_acquire().as_secs_f64(),
        );
        Ok(())
    }
}

fn build_screen_page(
    page: GalleryPage,
    width: f32,
    height: f32,
    animation: f32,
) -> Result<ScreenScene, Box<dyn Error>> {
    let mut scene = ScreenScene::new(Color::rgb8(8, 11, 17))?;
    scene.try_rect(
        p(28.0, 28.0),
        LogicalScreenVector::new((width - 56.0).max(1.0), (height - 56.0).max(1.0)),
        px(18.0),
        ShapeStyle::fill_stroke(Color::rgb8(15, 21, 31), 1.0, Color::rgb8(52, 67, 84)),
    )?;
    match page {
        GalleryPage::CapsAndJoins => draw_caps_and_joins(&mut scene, width, height)?,
        GalleryPage::AlphaContract => draw_alpha_contract(&mut scene, width, height)?,
        GalleryPage::DashesAndMarkers => {
            draw_dashes_and_markers(&mut scene, width, height, animation)?
        }
        GalleryPage::CameraAndEdges => draw_camera_frame(&mut scene, width, height)?,
        GalleryPage::ExactVectors => {}
    }
    Ok(scene)
}

fn draw_caps_and_joins(
    scene: &mut ScreenScene,
    width: f32,
    _height: f32,
) -> Result<(), Box<dyn Error>> {
    let left = 110.0;
    let middle = width * 0.46;
    let right = width - 110.0;
    for (index, (cap, color)) in [
        (StrokeCap2d::Butt, Color::rgb8(65, 196, 255)),
        (StrokeCap2d::Square, Color::rgb8(255, 176, 70)),
        (StrokeCap2d::Round, Color::rgb8(106, 224, 142)),
    ]
    .into_iter()
    .enumerate()
    {
        let y = 150.0 + index as f32 * 150.0;
        scene.try_styled_line(
            p(left, y),
            p(middle - 70.0, y),
            StrokeStyle2d::logical(px(22.0), color).with_cap(cap),
        )?;
    }
    for (index, (join, color)) in [
        (StrokeJoin2d::Bevel, Color::rgb8(65, 196, 255)),
        (StrokeJoin2d::Miter, Color::rgb8(255, 176, 70)),
        (StrokeJoin2d::Round, Color::rgb8(106, 224, 142)),
    ]
    .into_iter()
    .enumerate()
    {
        let y = 150.0 + index as f32 * 150.0;
        scene.try_styled_polyline(
            &[
                p(middle + 40.0, y + 42.0),
                p((middle + right) * 0.5, y - 42.0),
                p(right, y + 42.0),
            ],
            StrokeStyle2d::logical(px(22.0), color)
                .with_cap(StrokeCap2d::Butt)
                .with_join(join),
        )?;
    }
    Ok(())
}

fn draw_alpha_contract(
    scene: &mut ScreenScene,
    width: f32,
    height: f32,
) -> Result<(), Box<dyn Error>> {
    let colors = [
        Color::rgba(1.0, 0.12, 0.08, 0.5),
        Color::rgba(0.08, 1.0, 0.24, 0.5),
        Color::rgba(0.08, 0.45, 1.0, 0.5),
    ];
    let joins = [
        StrokeJoin2d::Round,
        StrokeJoin2d::Bevel,
        StrokeJoin2d::Miter,
    ];
    for index in 0..3 {
        let center_x = width * (0.2 + index as f32 * 0.3);
        let center_y = height * 0.46;
        let mut style = StrokeStyle2d::logical(px(34.0), colors[index])
            .with_cap(StrokeCap2d::Round)
            .with_join(joins[index]);
        if joins[index] == StrokeJoin2d::Miter {
            style = style.with_miter_limit(1.0)?;
        }
        scene.try_styled_polyline(
            &[
                p(center_x - 105.0, center_y + 105.0),
                p(center_x, center_y - 95.0),
                p(center_x + 105.0, center_y + 105.0),
            ],
            style,
        )?;
        scene.try_rect(
            p(center_x - 105.0, center_y + 150.0),
            LogicalScreenVector::new(210.0, 34.0),
            px(17.0),
            ShapeStyle::filled(colors[index]),
        )?;
    }
    Ok(())
}

fn draw_dashes_and_markers(
    scene: &mut ScreenScene,
    width: f32,
    height: f32,
    animation: f32,
) -> Result<(), Box<dyn Error>> {
    let phase = (animation * 38.0).floor().rem_euclid(82.0);
    let dash = StrokeDashPattern2d::new(&[28.0, 22.0, 10.0, 22.0], phase, 2_048)?;
    let arrow = StrokeMarker2d::arrow(px(30.0), px(28.0));
    let rows = [
        (Color::rgb8(65, 196, 255), false, false, true),
        (Color::rgb8(255, 176, 70), true, false, false),
        (Color::rgba(0.2, 1.0, 0.45, 0.5), true, true, false),
    ];
    for (index, (color, start, end, dashed)) in rows.into_iter().enumerate() {
        let y = height * 0.28 + index as f32 * 155.0;
        let mut style = StrokeStyle2d::logical(px(14.0), color)
            .with_cap(StrokeCap2d::Round)
            .with_join(StrokeJoin2d::Round);
        if dashed {
            style = style.with_dash_pattern(dash);
        }
        if start {
            style = style.with_start_marker(arrow);
        }
        if end {
            style = style.with_end_marker(arrow);
        }
        scene.try_styled_polyline(
            &[
                p(100.0, y),
                p(width * 0.42, y - 55.0),
                p(width * 0.67, y + 45.0),
                p(width - 100.0, y),
            ],
            style,
        )?;
    }
    let short_center = width * 0.5;
    scene.try_styled_line(
        p(short_center - 2.0, height - 82.0),
        p(short_center + 2.0, height - 82.0),
        StrokeStyle2d::logical(px(14.0), Color::rgba(0.72, 0.42, 1.0, 0.5))
            .with_cap(StrokeCap2d::Round)
            .with_start_marker(arrow)
            .with_end_marker(arrow),
    )?;
    Ok(())
}

fn draw_camera_frame(
    scene: &mut ScreenScene,
    width: f32,
    height: f32,
) -> Result<(), Box<dyn Error>> {
    scene.try_rect(
        p(width * 0.24, height * 0.31),
        LogicalScreenVector::new(width * 0.52, height * 0.38),
        px(8.0),
        ShapeStyle::fill_stroke(
            Color::rgba(0.0, 0.0, 0.0, 0.25),
            2.0,
            Color::rgb8(82, 101, 124),
        ),
    )?;
    Ok(())
}

fn build_world_edge_scene() -> Result<Scene, Box<dyn Error>> {
    let mut scene = Scene::new(Color::BLACK)?;
    scene.try_styled_line(
        Vec2::new(-0.0025, 0.0),
        Vec2::new(0.0025, 0.0),
        StrokeStyle2d::logical(px(8.0), Color::rgb8(65, 196, 255)).with_cap(StrokeCap2d::Round),
    )?;
    let arrow = StrokeMarker2d::arrow(px(18.0), px(16.0));
    scene.try_styled_polyline(
        vec![
            Vec2::new(-0.015, -0.012),
            Vec2::new(0.0, 0.014),
            Vec2::new(0.015, -0.012),
        ],
        StrokeStyle2d::logical(px(7.0), Color::rgba(1.0, 0.58, 0.08, 0.65))
            .with_cap(StrokeCap2d::Round)
            .with_join(StrokeJoin2d::Miter)
            .with_miter_limit(1.0)?
            .with_end_marker(arrow),
    )?;
    Ok(scene)
}

const fn p(x: f32, y: f32) -> LogicalScreenPosition {
    LogicalScreenPosition::new(x, y)
}

const EXACT_VECTORS: [(Vec2, Vec2); 5] = [
    (Vec2::new(-0.020, 0.020), Vec2::new(0.020, 0.020)),
    (Vec2::new(0.020, 0.010), Vec2::new(-0.020, 0.010)),
    (Vec2::new(-0.020, 0.001), Vec2::new(0.020, -0.009)),
    (Vec2::new(-0.010, -0.020), Vec2::new(-0.0096, -0.020)),
    (Vec2::new(0.0104, -0.020), Vec2::new(0.010, -0.020)),
];

fn build_exact_vector_scene() -> Result<Scene, Box<dyn Error>> {
    let mut scene = Scene::new(Color::BLACK)?;
    let marker =
        StrokeMarker2d::arrow(px(30.0), px(20.0)).with_anchor(StrokeMarkerAnchor2d::TipAtEndpoint);
    for (index, (start, end)) in EXACT_VECTORS.into_iter().enumerate() {
        let style = if matches!(index, 1 | 4) {
            StrokeStyle2d::world(
                WorldLength::new(0.0012)?,
                Color::rgb8(255, 176, 70).with_alpha(0.5),
            )
        } else {
            StrokeStyle2d::logical(px(12.0), Color::rgb8(65, 196, 255).with_alpha(0.5))
        };
        scene.try_styled_line(
            start,
            end,
            style.with_start_marker(marker).with_end_marker(marker),
        )?;
    }
    Ok(scene)
}

fn add_exact_vector_guides(
    scene: &mut ScreenScene,
    camera: Camera2d,
    viewport: LogicalViewport,
) -> Result<(), Box<dyn Error>> {
    let guide = StrokeStyle2d::logical(px(1.0), Color::rgb8(180, 190, 210).with_alpha(0.5))
        .with_cap(StrokeCap2d::Butt);
    for (start, end) in EXACT_VECTORS {
        for world in [start, end] {
            let point = camera.world_to_screen(world, viewport)?.to_vec2();
            scene.try_styled_line(
                p(point.x() - 9.0, point.y()),
                p(point.x() + 9.0, point.y()),
                guide,
            )?;
            scene.try_styled_line(
                p(point.x(), point.y() - 9.0),
                p(point.x(), point.y() + 9.0),
                guide,
            )?;
        }
    }
    Ok(())
}

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

    #[test]
    fn exact_vector_page_accepts_both_widths_reversed_and_short_segments() {
        assert_eq!(build_exact_vector_scene().unwrap().command_count(), 5);
        for (width, height) in [(640.0, 480.0), (1280.0, 760.0)] {
            let mut scene =
                build_screen_page(GalleryPage::ExactVectors, width, height, 0.0).unwrap();
            let camera = Camera2d::new(Vec2::ZERO, 6000.0).unwrap();
            add_exact_vector_guides(
                &mut scene,
                camera,
                LogicalViewport::new(width, height).unwrap(),
            )
            .unwrap();
        }
    }
}

fn px(value: f32) -> LogicalPixels {
    LogicalPixels::new(value).expect("gallery uses positive finite logical pixels")
}