laser-dac 0.13.0

Unified laser DAC abstraction supporting multiple protocols
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
//! PresentationEngine and ColorDelayLine — core frame lifecycle internals.

use crate::point::LaserPoint;

use super::{Frame, TransitionFn, TransitionPlan};

// =============================================================================
// PresentationEngine
// =============================================================================

/// Core frame lifecycle manager.
///
/// Manages the current and pending frames, cursor position, and transition
/// point insertion. Provides two delivery modes:
///
/// - [`fill_chunk`](Self::fill_chunk): FIFO delivery for queue-based DACs.
///   Traverses the drawable, inserting transition points at frame boundaries.
/// - [`compose_hardware_frame`](Self::compose_hardware_frame): Frame-swap
///   delivery. Returns a complete composed frame with transition points.
#[cfg_attr(feature = "testutils", doc(hidden))]
#[cfg_attr(not(feature = "testutils"), allow(dead_code))]
pub struct PresentationEngine {
    /// The currently playing frame.
    pub(crate) current_base: Option<Frame>,
    /// The next frame to promote (latest-wins).
    pub(crate) pending_base: Option<Frame>,
    /// Working buffer: base-only frame points (FIFO) or composed frame (FrameSwap).
    drawable: Vec<LaserPoint>,
    /// Whether the drawable needs to be rebuilt from current_base.
    drawable_dirty: bool,
    /// Current read cursor within `drawable`.
    cursor: usize,
    /// Transition function for generating blanking between frames.
    transition_fn: TransitionFn,
    /// Buffer for transition points injected between frames.
    transition_buf: Vec<LaserPoint>,
    /// Read cursor within transition_buf.
    transition_cursor: usize,
    /// True when transition_buf holds self-loop points (can be discarded if
    /// a pending frame arrives before they are fully drained).
    transition_is_self_loop: bool,
    /// Length of the transition prefix in the last composed frame-swap drawable.
    frame_swap_transition_len: usize,
    /// Maximum hardware frame capacity (frame-swap only). When set, composed
    /// frames are clamped by first trimming the generated transition prefix,
    /// then—only if the authored points still exceed capacity—truncating the tail.
    frame_capacity: Option<usize>,
    /// Point emitted while the engine has no drawable content — no frame yet, or
    /// an empty ("clear the display") frame. Defaults to a blanked origin point;
    /// the pipeline sets it to the configured park position under
    /// [`IdlePolicy::Park`](crate::config::IdlePolicy) so armed-but-idle output
    /// holds park instead of snapping to (0,0).
    idle_blank: LaserPoint,
}

impl PresentationEngine {
    /// Create a new engine with the given transition function.
    pub fn new(transition_fn: TransitionFn) -> Self {
        Self {
            current_base: None,
            pending_base: None,
            drawable: Vec::new(),
            drawable_dirty: true,
            cursor: 0,
            transition_fn,
            transition_buf: Vec::new(),
            transition_cursor: 0,
            transition_is_self_loop: false,
            frame_swap_transition_len: 0,
            frame_capacity: None,
            idle_blank: LaserPoint::blanked(0.0, 0.0),
        }
    }

    /// Set the maximum hardware frame capacity for frame-swap clamping.
    pub fn set_frame_capacity(&mut self, cap: Option<usize>) {
        self.frame_capacity = cap;
    }

    /// Set the point held while the engine has no drawable content (see
    /// [`idle_blank`](Self::idle_blank)). Preserved across [`reset`](Self::reset)
    /// like `frame_capacity`, since it is configuration rather than runtime state.
    pub fn set_idle_blank_point(&mut self, point: LaserPoint) {
        self.idle_blank = point;
    }

    /// Reset all runtime state. Preserves the transition_fn and frame_capacity.
    pub fn reset(&mut self) {
        self.current_base = None;
        self.pending_base = None;
        self.drawable.clear();
        self.drawable_dirty = true;
        self.cursor = 0;
        self.transition_buf.clear();
        self.transition_cursor = 0;
        self.transition_is_self_loop = false;
        self.frame_swap_transition_len = 0;
    }

    /// Returns true once a logical frame has been submitted to the engine.
    pub fn has_logical_frame(&self) -> bool {
        self.current_base.is_some()
    }

    /// Submit a new frame. Latest-wins: multiple calls before consumption
    /// keep only the most recent frame.
    ///
    /// If no current frame exists, the pending is immediately promoted.
    pub fn set_pending(&mut self, frame: Frame) {
        if self.current_base.is_none() {
            self.current_base = Some(frame);
            self.drawable_dirty = true;
            self.cursor = 0;
        } else {
            self.pending_base = Some(frame);
            // Don't mark dirty yet — we compose on promotion
        }
    }

    /// FIFO delivery: fill `buffer[..max_points]` from the current frame.
    ///
    /// Traverses the base frame points cyclically. At each seam (cursor
    /// wrap), the transition function is called dynamically against the
    /// latest pending frame (if any) or the current frame (self-loop).
    /// This ensures the seam always reflects the most recent state — no
    /// stale self-loop transition is emitted before a real frame change.
    ///
    /// Returns the number of points written (always `max_points` if a
    /// frame is available, 0 if no frame has been submitted).
    pub fn fill_chunk(&mut self, buffer: &mut [LaserPoint], max_points: usize) -> usize {
        let max_points = max_points.min(buffer.len());

        // Rebuild drawable if dirty (no-op when current_base is None)
        if self.drawable_dirty {
            self.refresh_drawable();
        }

        // No frame yet or empty frame: hold the idle-blank point (origin by
        // default, or the configured park position).
        if self.current_base.is_none() || self.drawable.is_empty() {
            buffer[..max_points].fill(self.idle_blank);
            return max_points;
        }

        let mut written = 0;
        while written < max_points {
            // Drain pending transition points — but if they are stale
            // self-loop points and a pending frame has arrived, discard
            // them and promote immediately. Only safe when nothing has been
            // emitted yet (cursor == 0); a partial emission has already
            // started moving toward `current.last`'s self-loop destination,
            // and promoting now would compute a fresh transition starting
            // at `current.last` — creating a backward jump in the output
            // stream that downstream motion safety will slew-limit.
            if self.transition_cursor < self.transition_buf.len() {
                if self.transition_is_self_loop
                    && self.pending_base.is_some()
                    && self.transition_cursor == 0
                {
                    self.transition_buf.clear();
                    self.transition_is_self_loop = false;
                    self.promote_pending();

                    if self.drawable.is_empty() {
                        buffer[written..max_points].fill(self.idle_blank);
                        return max_points;
                    }
                    continue;
                }

                // Batch-drain as many transition points as fit in the output.
                let src = &self.transition_buf[self.transition_cursor..];
                let n = src.len().min(max_points - written);
                buffer[written..written + n].copy_from_slice(&src[..n]);
                written += n;
                self.transition_cursor += n;
                continue;
            }

            // Batch-copy drawable points until the next seam or buffer full.
            let src = &self.drawable[self.cursor..];
            let n = src.len().min(max_points - written);
            buffer[written..written + n].copy_from_slice(&src[..n]);
            written += n;
            self.cursor += n;

            // At the seam: compute transition dynamically against pending or self
            if self.cursor >= self.drawable.len() {
                if self.pending_base.is_some() {
                    self.promote_pending();

                    if self.drawable.is_empty() {
                        buffer[written..max_points].fill(self.idle_blank);
                        return max_points;
                    }
                } else {
                    // Self-loop: compute seam dynamically using drawable first/last.
                    // drawable is non-empty here (checked above) and is always a
                    // direct copy of current_base.points(), so these unwraps are safe.
                    let last = self.drawable.last().unwrap();
                    let first = self.drawable.first().unwrap();
                    match (self.transition_fn)(last, first) {
                        TransitionPlan::Transition(points) => {
                            self.transition_buf = points;
                            self.transition_cursor = 0;
                            self.transition_is_self_loop = true;
                            self.cursor = 0;
                        }
                        TransitionPlan::Coalesce => {
                            self.cursor = if self.drawable.len() > 1 { 1 } else { 0 };
                        }
                    }
                }
            }
        }

        written
    }

    /// Frame-swap delivery: compose and return a complete hardware frame.
    ///
    /// On frame change (A→B): computes `transition_fn(A.last, B.first)`,
    /// composes `[transition | B_points]`, then promotes B to current.
    /// The next call without a pending frame will recompute the self-loop.
    ///
    /// On self-loop (no pending): computes `transition_fn(A.last, A.first)`,
    /// composes `[transition | A_points]` (or coalesced).
    pub fn compose_hardware_frame(&mut self) -> &[LaserPoint] {
        if let Some(pending) = self.pending_base.take() {
            // Frame change: A→B transition.
            // Compute transition from current (A) to pending (B) BEFORE promoting.
            let plan = match (
                self.current_base.as_ref().and_then(|c| c.last_point()),
                pending.first_point(),
            ) {
                (Some(last), Some(first)) => (self.transition_fn)(last, first),
                _ => TransitionPlan::Transition(vec![]),
            };

            self.drawable.clear();
            match plan {
                TransitionPlan::Transition(transition) => {
                    self.frame_swap_transition_len = transition.len();
                    self.drawable.extend_from_slice(&transition);
                    self.drawable.extend_from_slice(pending.points());
                }
                TransitionPlan::Coalesce => {
                    self.frame_swap_transition_len = 0;
                    // A.last ≈ B.first — skip B's first point to avoid a
                    // duplicate logical seam sample in the hardware frame.
                    let pts = pending.points();
                    self.drawable
                        .extend_from_slice(if pts.len() > 1 { &pts[1..] } else { pts });
                }
            }

            // Empty frame submitted: send the idle-blank point to clear the display
            if self.drawable.is_empty() {
                self.drawable.push(self.idle_blank);
            }

            self.clamp_to_capacity();

            // Promote B to current. Mark dirty so next call builds self-loop.
            self.current_base = Some(pending);
            self.drawable_dirty = true;

            return &self.drawable;
        }

        // No pending: self-loop for current frame.
        if self.drawable_dirty {
            self.refresh_drawable_for_frame_swap();
        }

        &self.drawable
    }

    /// Rebuild drawable for frame-swap: includes self-loop transition.
    ///
    /// Frame-swap DACs send the entire drawable as one atomic frame, so the
    /// transition from last→first point is included for clean looping.
    /// For nearly-closed shapes (circles), `Coalesce` omits the last base
    /// point so the frame loops seamlessly without a duplicate seam point.
    fn refresh_drawable_for_frame_swap(&mut self) {
        self.drawable.clear();
        self.drawable_dirty = false;
        self.frame_swap_transition_len = 0;

        let Some(current) = &self.current_base else {
            return;
        };

        if current.is_empty() {
            self.drawable.push(self.idle_blank);
            return;
        }

        let points = current.points();
        self.frame_swap_transition_len =
            build_self_loop_drawable(&self.transition_fn, points, &mut self.drawable);
        self.clamp_to_capacity();
    }

    /// Clamp the composed drawable to `frame_capacity`.
    ///
    /// Trims the leading transition prefix first (it is generated filler, safe
    /// to shorten). If the *authored* frame points alone still exceed capacity,
    /// truncate the tail as a last resort — an oversized frame is rejected by
    /// some encoders (the Helios SDK refuses > 4095 points) and undefined on
    /// others, so a clamped frame is strictly safer than an oversized one.
    ///
    /// Note: `current_base` retains the full authored frame, so the subsequent
    /// self-loop seam is still computed from the authored last point even after
    /// a tail truncation — the seam then launches from a point that isn't
    /// displayed. This is cosmetic and only reachable in the already-pathological
    /// oversized-frame case, so it is accepted rather than special-cased.
    fn clamp_to_capacity(&mut self) {
        if let Some(cap) = self.frame_capacity {
            if self.drawable.len() > cap {
                let excess = self.drawable.len() - cap;
                let trim = excess.min(self.frame_swap_transition_len);
                self.drawable.drain(..trim);
                self.frame_swap_transition_len -= trim;

                if self.drawable.len() > cap {
                    warn_oversized_frame(self.drawable.len(), cap);
                    self.drawable.truncate(cap);
                }
            }
        }
    }

    /// Promote pending frame to current for FIFO delivery.
    ///
    /// Computes the A→B transition, promotes the pending frame, rebuilds
    /// the drawable, and sets the cursor appropriately.
    fn promote_pending(&mut self) {
        let pending = self.pending_base.take().unwrap();

        let plan = match (
            self.current_base.as_ref().and_then(|f| f.last_point()),
            pending.first_point(),
        ) {
            (Some(last), Some(first)) => (self.transition_fn)(last, first),
            _ => TransitionPlan::Transition(vec![]),
        };

        self.current_base = Some(pending);
        self.refresh_drawable();

        match plan {
            TransitionPlan::Transition(points) => {
                self.transition_buf = points;
                self.transition_cursor = 0;
                self.transition_is_self_loop = false;
                self.cursor = 0;
            }
            TransitionPlan::Coalesce => {
                self.cursor = if self.drawable.len() > 1 { 1 } else { 0 };
            }
        }
    }

    /// Rebuild the FIFO drawable from the current base frame.
    ///
    /// Contains only the base frame points. Transition points are computed
    /// dynamically at seam time in `fill_chunk`.
    fn refresh_drawable(&mut self) {
        self.drawable.clear();
        self.drawable_dirty = false;

        let Some(current) = &self.current_base else {
            return;
        };

        if current.is_empty() {
            return;
        }

        self.drawable.extend_from_slice(current.points());
    }
}

/// Rate-limited (≤ once/sec) warning that an authored frame exceeded the
/// hardware frame capacity and was truncated. Runs on the single scheduler
/// thread, so a `thread_local` last-warn timestamp is sufficient.
fn warn_oversized_frame(len: usize, cap: usize) {
    use std::cell::Cell;
    use std::time::{Duration, Instant};
    thread_local! {
        static LAST_WARN: Cell<Option<Instant>> = const { Cell::new(None) };
    }
    LAST_WARN.with(|last| {
        let now = Instant::now();
        let emit = match last.get() {
            Some(t) => now.duration_since(t) >= Duration::from_secs(1),
            None => true,
        };
        if emit {
            last.set(Some(now));
            log::warn!(
                "authored frame has {len} points, exceeding hardware frame_capacity {cap}; truncating tail"
            );
        }
    });
}

/// Build a seam-adjusted drawable for a self-loop, applying the transition
/// function to the seam between the frame's last and first points.
///
/// For `Transition(points)`: places the transition as a prefix before the
/// base frame points (used by frame-swap delivery).
///
/// For `Coalesce`: omits the last base point so the loop represents the
/// seam point once. Single-point frames are kept unchanged.
///
/// Returns the number of transition points in the drawable.
fn build_self_loop_drawable(
    transition_fn: &TransitionFn,
    base: &[LaserPoint],
    drawable: &mut Vec<LaserPoint>,
) -> usize {
    let last = base.last().unwrap();
    let first = base.first().unwrap();
    let plan = transition_fn(last, first);

    match plan {
        TransitionPlan::Transition(pts) => {
            let transition_len = pts.len();
            drawable.extend_from_slice(&pts);
            drawable.extend_from_slice(base);
            transition_len
        }
        TransitionPlan::Coalesce => {
            // Omit the last base point for len > 1 — on wrap, cursor returns to
            // first which is the same logical point.
            let end = if base.len() > 1 {
                base.len() - 1
            } else {
                base.len()
            };
            drawable.extend_from_slice(&base[..end]);
            0
        }
    }
}

// =============================================================================
// ColorDelayLine
// =============================================================================

/// Stateful color delay that carries across chunk boundaries.
///
/// For FIFO DACs, color delay is applied per-chunk. Without carry-over state,
/// the first `delay` points of every chunk get blanked, causing periodic
/// micro-brightness drops at chunk boundaries. This struct maintains a ring
/// buffer of the last `delay` color values so they carry into the next chunk.
pub(crate) struct ColorDelayLine {
    delay: usize,
    /// Ring buffer of the last `delay` colors from the previous chunk.
    carry: Vec<(u16, u16, u16, u16)>,
    /// Pre-allocated buffer for current chunk colors (avoids per-chunk allocation).
    scratch: Vec<(u16, u16, u16, u16)>,
}

impl ColorDelayLine {
    pub fn new(delay: usize) -> Self {
        Self {
            delay,
            carry: vec![(0, 0, 0, 0); delay],
            scratch: Vec::new(),
        }
    }

    /// Current delay in points.
    #[allow(dead_code)]
    pub fn delay(&self) -> usize {
        self.delay
    }

    /// Reset the carry buffer (e.g., after reconnect).
    pub fn reset(&mut self) {
        self.carry.fill((0, 0, 0, 0));
    }

    /// Resize the delay line to a new point count.
    ///
    /// - **Grow**: pads the front of the carry buffer with black (oldest slots).
    /// - **Shrink**: keeps the most recent entries (trims from the front).
    /// - **Equal**: no-op.
    pub fn resize(&mut self, new_delay: usize) {
        if new_delay == self.delay {
            return;
        }
        if new_delay == 0 {
            self.delay = 0;
            self.carry.clear();
            return;
        }
        if new_delay > self.delay {
            // Grow: prepend black entries, keep existing carry at the end
            let extra = new_delay - self.delay;
            let mut new_carry = vec![(0, 0, 0, 0); extra];
            new_carry.extend_from_slice(&self.carry);
            self.carry = new_carry;
        } else {
            // Shrink: keep only the most recent (tail) entries
            self.carry.drain(..self.delay - new_delay);
        }
        self.delay = new_delay;
    }

    /// Apply color delay to a chunk, using carried state from the previous chunk.
    pub fn apply(&mut self, points: &mut [LaserPoint]) {
        if self.delay == 0 || points.is_empty() {
            return;
        }

        // Collect current colors into pre-allocated scratch buffer
        self.scratch.clear();
        self.scratch
            .extend(points.iter().map(|p| (p.r, p.g, p.b, p.intensity)));

        // Apply delay: for the first `delay` points use carry; for the rest, scratch.
        for (i, point) in points.iter_mut().enumerate() {
            (point.r, point.g, point.b, point.intensity) = if i < self.delay {
                self.carry[i]
            } else {
                self.scratch[i - self.delay]
            };
        }

        // Update carry buffer: keep the last `delay` colors from this chunk
        let n = self.scratch.len();
        if n >= self.delay {
            self.carry.clear();
            self.carry
                .extend_from_slice(&self.scratch[n - self.delay..]);
        } else {
            // Chunk smaller than delay: shift carry and append
            self.carry.drain(..n);
            self.carry.extend_from_slice(&self.scratch);
            debug_assert_eq!(self.carry.len(), self.delay);
        }
    }
}

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

    fn frame_of(n: usize) -> Frame {
        let pts: Vec<LaserPoint> = (0..n)
            .map(|i| LaserPoint::new(i as f32 * 0.0001, 0.0, 1000, 1000, 1000, 1000))
            .collect();
        Frame::new(pts)
    }

    /// An authored frame whose points alone exceed `frame_capacity` must be
    /// truncated (not sent oversized) once the transition prefix is exhausted.
    #[test]
    fn oversized_authored_frame_is_truncated_to_capacity() {
        const CAP: usize = 4_095;
        // Transition function returns a 10-point prefix.
        let mut engine = PresentationEngine::new(Box::new(|_, _| {
            TransitionPlan::Transition(vec![LaserPoint::blanked(0.0, 0.0); 10])
        }));
        engine.set_frame_capacity(Some(CAP));

        // Prime a current frame so the swap computes an A->B transition.
        engine.set_pending(frame_of(4));
        let _ = engine.compose_hardware_frame();

        // Now swap in an over-capacity authored frame.
        engine.set_pending(frame_of(5_000));
        let composed = engine.compose_hardware_frame();
        assert_eq!(
            composed.len(),
            CAP,
            "authored frame must be clamped to capacity"
        );
    }

    /// The configured idle-blank point is used both before any frame and for an
    /// empty ("clear the display") frame, including when an empty pending frame
    /// is promoted at the seam mid-chunk.
    #[test]
    fn idle_blank_point_used_for_no_content_and_empty_frame() {
        let mut engine =
            PresentationEngine::new(Box::new(|_, _| TransitionPlan::Transition(Vec::new())));
        let park = LaserPoint::blanked(0.25, -0.5);
        engine.set_idle_blank_point(park);

        // No frame yet: fill holds the idle-blank point.
        let mut buf = vec![LaserPoint::default(); 4];
        assert_eq!(engine.fill_chunk(&mut buf, 4), 4);
        assert!(buf.iter().all(|p| p.x == park.x && p.y == park.y));

        // Empty frame ("clear the display") reports a logical frame but no
        // drawable content, so it also holds the idle-blank point.
        engine.set_pending(Frame::new(Vec::new()));
        assert!(engine.has_logical_frame());
        let mut buf = vec![LaserPoint::default(); 4];
        assert_eq!(engine.fill_chunk(&mut buf, 4), 4);
        assert!(buf.iter().all(|p| p.x == park.x && p.y == park.y));
    }

    /// A pending empty frame promoted at the seam mid-chunk fills the remainder
    /// with the idle-blank point rather than the origin.
    #[test]
    fn idle_blank_point_used_for_midchunk_empty_promotion() {
        let mut engine = PresentationEngine::new(Box::new(|_, _| TransitionPlan::Coalesce));
        let park = LaserPoint::blanked(0.1, 0.2);
        engine.set_idle_blank_point(park);

        // Prime a 2-point frame, then queue an empty frame to promote at the seam.
        engine.set_pending(frame_of(2));
        engine.set_pending(Frame::new(Vec::new()));

        // Ask for more points than the current frame holds so the seam is hit
        // and the empty pending frame is promoted, blanking the tail to park.
        let mut buf = vec![LaserPoint::default(); 8];
        assert_eq!(engine.fill_chunk(&mut buf, 8), 8);
        // The tail (after the current frame drains) must be the idle-blank point.
        assert!(buf[2..].iter().all(|p| p.x == park.x && p.y == park.y));
    }

    /// The self-loop (no pending) refresh path must also clamp an over-capacity
    /// authored frame.
    #[test]
    fn oversized_self_loop_frame_is_truncated_to_capacity() {
        const CAP: usize = 4_095;
        let mut engine = PresentationEngine::new(Box::new(|_, _| {
            TransitionPlan::Transition(vec![LaserPoint::blanked(0.0, 0.0); 10])
        }));
        engine.set_frame_capacity(Some(CAP));

        engine.set_pending(frame_of(5_000));
        let _ = engine.compose_hardware_frame(); // frame-change path
        let composed = engine.compose_hardware_frame(); // self-loop refresh
        assert_eq!(composed.len(), CAP);
    }
}