martensite-devtools 0.10.0

Tracing spans, Tracy/Chrome GPU timestamps, and in-app F12 developer HUD.
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
//! In-app diagnostic HUD overlay.
//!
//! Activating F12 toggles a zero-allocation diagnostic overlay that
//! displays:
//!
//! - A rolling 120-frame timing histogram (layout, paint, GPU wait).
//! - Real-time dirty rect visualization.
//! - Live `WidgetArena` slot utilization and compaction telemetry.
//!
//! # Example
//!
//! ```
//! use martensite_devtools::hud::{DiagnosticHud, FrameTiming, Rect};
//!
//! let mut hud = DiagnosticHud::new();
//! hud.toggle();
//! assert!(hud.is_enabled());
//!
//! hud.record_frame(FrameTiming {
//!     layout_time_ns: 500_000,
//!     paint_time_ns: 300_000,
//!     gpu_wait_time_ns: 100_000,
//!     total_time_ns: 900_000,
//! });
//!
//! hud.add_dirty_rect(Rect::new(0, 0, 100, 100));
//! ```

/// Number of frames retained in the rolling histogram.
const HISTOGRAM_SIZE: usize = 120;

/// Frame timing data for a single frame.
///
/// All times are in nanoseconds for consistent units.
///
/// # Example
///
/// ```
/// use martensite_devtools::hud::FrameTiming;
///
/// let timing = FrameTiming {
///     layout_time_ns: 500_000,
///     paint_time_ns: 300_000,
///     gpu_wait_time_ns: 100_000,
///     total_time_ns: 900_000,
/// };
/// assert_eq!(timing.total_time_ns, 900_000);
/// ```
#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)]
pub struct FrameTiming {
    /// Time spent in layout passes (nanoseconds).
    pub layout_time_ns: u64,
    /// Time spent encoding the paint list (nanoseconds).
    pub paint_time_ns: u64,
    /// Time spent waiting for the GPU (nanoseconds).
    pub gpu_wait_time_ns: u64,
    /// Total frame time (nanoseconds).
    pub total_time_ns: u64,
}

impl FrameTiming {
    /// Creates a `FrameTiming` from millisecond values.
    ///
    /// # Example
    ///
    /// ```
    /// use martensite_devtools::hud::FrameTiming;
    ///
    /// let t = FrameTiming::from_ms(0.5, 0.3, 0.1, 0.9);
    /// assert_eq!(t.layout_time_ns, 500_000);
    /// ```
    pub fn from_ms(layout: f64, paint: f64, gpu_wait: f64, total: f64) -> Self {
        Self {
            layout_time_ns: (layout * 1_000_000.0) as u64,
            paint_time_ns: (paint * 1_000_000.0) as u64,
            gpu_wait_time_ns: (gpu_wait * 1_000_000.0) as u64,
            total_time_ns: (total * 1_000_000.0) as u64,
        }
    }

    /// Adds two `FrameTiming` values component-wise.
    #[inline]
    pub fn add(&self, other: &Self) -> Self {
        Self {
            layout_time_ns: self.layout_time_ns.saturating_add(other.layout_time_ns),
            paint_time_ns: self.paint_time_ns.saturating_add(other.paint_time_ns),
            gpu_wait_time_ns: self.gpu_wait_time_ns.saturating_add(other.gpu_wait_time_ns),
            total_time_ns: self.total_time_ns.saturating_add(other.total_time_ns),
        }
    }

    /// Divides all components by a scalar.
    #[inline]
    pub fn div(&self, n: u64) -> Self {
        if n == 0 {
            return Self::default();
        }
        Self {
            layout_time_ns: self.layout_time_ns / n,
            paint_time_ns: self.paint_time_ns / n,
            gpu_wait_time_ns: self.gpu_wait_time_ns / n,
            total_time_ns: self.total_time_ns / n,
        }
    }
}

/// Rolling 120-frame timing histogram.
///
/// Stores the last `120` frame timings in a fixed-size ring buffer
/// with zero heap allocation.
///
/// # Example
///
/// ```
/// use martensite_devtools::hud::{FrameHistogram, FrameTiming};
///
/// let mut hist = FrameHistogram::new();
/// hist.record(FrameTiming {
///     layout_time_ns: 500_000,
///     paint_time_ns: 300_000,
///     gpu_wait_time_ns: 100_000,
///     total_time_ns: 900_000,
/// });
/// assert_eq!(hist.len(), 1);
/// let avg = hist.average();
/// assert_eq!(avg.total_time_ns, 900_000);
/// ```
#[derive(Debug, Clone)]
pub struct FrameHistogram {
    frames: [FrameTiming; HISTOGRAM_SIZE],
    index: usize,
    count: usize,
}

impl Default for FrameHistogram {
    fn default() -> Self {
        Self::new()
    }
}

impl FrameHistogram {
    /// Creates a new empty histogram.
    ///
    /// # Example
    ///
    /// ```
    /// use martensite_devtools::hud::FrameHistogram;
    ///
    /// let hist = FrameHistogram::new();
    /// assert!(hist.is_empty());
    /// ```
    pub fn new() -> Self {
        Self {
            frames: [FrameTiming::default(); HISTOGRAM_SIZE],
            index: 0,
            count: 0,
        }
    }

    /// Records a frame timing into the ring buffer.
    ///
    /// # Example
    ///
    /// ```
    /// use martensite_devtools::hud::{FrameHistogram, FrameTiming};
    ///
    /// let mut hist = FrameHistogram::new();
    /// hist.record(FrameTiming { total_time_ns: 16_000_000, ..Default::default() });
    /// assert_eq!(hist.len(), 1);
    /// ```
    pub fn record(&mut self, timing: FrameTiming) {
        self.frames[self.index] = timing;
        self.index = (self.index + 1) % HISTOGRAM_SIZE;
        if self.count < HISTOGRAM_SIZE {
            self.count += 1;
        }
    }

    /// Returns the average frame timing across all recorded frames.
    ///
    /// # Example
    ///
    /// ```
    /// use martensite_devtools::hud::{FrameHistogram, FrameTiming};
    ///
    /// let mut hist = FrameHistogram::new();
    /// hist.record(FrameTiming { total_time_ns: 10_000_000, ..Default::default() });
    /// hist.record(FrameTiming { total_time_ns: 20_000_000, ..Default::default() });
    /// assert_eq!(hist.average().total_time_ns, 15_000_000);
    /// ```
    pub fn average(&self) -> FrameTiming {
        if self.count == 0 {
            return FrameTiming::default();
        }
        let mut sum = FrameTiming::default();
        for i in 0..self.count {
            sum = sum.add(&self.frames[i]);
        }
        sum.div(self.count as u64)
    }

    /// Returns the timing at the given percentile (0.0–100.0).
    ///
    /// `p=50` gives the median, `p=99` gives the 99th percentile.
    ///
    /// # Example
    ///
    /// ```
    /// use martensite_devtools::hud::{FrameHistogram, FrameTiming};
    ///
    /// let mut hist = FrameHistogram::new();
    /// for i in 1..=100 {
    ///     hist.record(FrameTiming { total_time_ns: i * 1_000_000, ..Default::default() });
    /// }
    /// let p50 = hist.percentile(50.0);
    /// assert!(p50.total_time_ns >= 49_000_000 && p50.total_time_ns <= 51_000_000);
    /// ```
    pub fn percentile(&self, p: f32) -> FrameTiming {
        if self.count == 0 {
            return FrameTiming::default();
        }
        let mut totals: Vec<u64> = self.frames[..self.count]
            .iter()
            .map(|f| f.total_time_ns)
            .collect();
        totals.sort_unstable();
        let idx = ((p.clamp(0.0, 100.0) / 100.0) * (self.count as f32 - 1.0)) as usize;
        let target = totals[idx];
        self.frames[..self.count]
            .iter()
            .find(|f| f.total_time_ns == target)
            .copied()
            .unwrap_or_default()
    }

    /// Returns the maximum recorded frame timing.
    ///
    /// # Example
    ///
    /// ```
    /// use martensite_devtools::hud::{FrameHistogram, FrameTiming};
    ///
    /// let mut hist = FrameHistogram::new();
    /// hist.record(FrameTiming { total_time_ns: 10_000_000, ..Default::default() });
    /// hist.record(FrameTiming { total_time_ns: 30_000_000, ..Default::default() });
    /// hist.record(FrameTiming { total_time_ns: 20_000_000, ..Default::default() });
    /// assert_eq!(hist.max().total_time_ns, 30_000_000);
    /// ```
    pub fn max(&self) -> FrameTiming {
        self.frames[..self.count]
            .iter()
            .copied()
            .max_by_key(|f| f.total_time_ns)
            .unwrap_or_default()
    }

    /// Returns a slice of all recorded frame timings.
    ///
    /// **Note**: After the ring buffer wraps (more than 120 frames recorded),
    /// the slice is in physical storage order, not chronological order. The
    /// newest frame may appear at any position. This is suitable for
    /// aggregation (average, max, percentile) but not for chronological
    /// display.
    ///
    /// # Example
    ///
    /// ```
    /// use martensite_devtools::hud::{FrameHistogram, FrameTiming};
    ///
    /// let mut hist = FrameHistogram::new();
    /// hist.record(FrameTiming::default());
    /// assert_eq!(hist.frames().len(), 1);
    /// ```
    pub fn frames(&self) -> &[FrameTiming] {
        &self.frames[..self.count]
    }

    /// Returns the number of recorded frames.
    #[inline]
    pub fn len(&self) -> usize {
        self.count
    }

    /// Returns `true` if no frames have been recorded.
    #[inline]
    pub fn is_empty(&self) -> bool {
        self.count == 0
    }

    /// Clears all recorded frames.
    pub fn clear(&mut self) {
        self.index = 0;
        self.count = 0;
    }
}

/// A rectangle for dirty rect tracking.
///
/// # Example
///
/// ```
/// use martensite_devtools::hud::Rect;
///
/// let r = Rect::new(10, 20, 100, 200);
/// assert_eq!(r.area(), 20_000);
/// ```
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
pub struct Rect {
    /// X coordinate (pixels from left).
    pub x: i32,
    /// Y coordinate (pixels from top).
    pub y: i32,
    /// Width in pixels.
    pub width: u32,
    /// Height in pixels.
    pub height: u32,
}

impl Rect {
    /// Creates a new rectangle.
    ///
    /// # Example
    ///
    /// ```
    /// use martensite_devtools::hud::Rect;
    ///
    /// let r = Rect::new(0, 0, 100, 100);
    /// assert_eq!(r.area(), 10_000);
    /// ```
    pub fn new(x: i32, y: i32, width: u32, height: u32) -> Self {
        Self {
            x,
            y,
            width,
            height,
        }
    }

    /// Returns the area of the rectangle in pixels.
    ///
    /// # Example
    ///
    /// ```
    /// use martensite_devtools::hud::Rect;
    ///
    /// assert_eq!(Rect::new(0, 0, 100, 50).area(), 5_000);
    /// ```
    pub fn area(&self) -> u64 {
        self.width as u64 * self.height as u64
    }

    /// Returns `true` if this rectangle intersects another.
    ///
    /// # Example
    ///
    /// ```
    /// use martensite_devtools::hud::Rect;
    ///
    /// let a = Rect::new(0, 0, 100, 100);
    /// let b = Rect::new(50, 50, 100, 100);
    /// let c = Rect::new(200, 200, 50, 50);
    /// assert!(a.intersects(&b));
    /// assert!(!a.intersects(&c));
    /// ```
    pub fn intersects(&self, other: &Rect) -> bool {
        let self_right = self.x + self.width as i32;
        let self_bottom = self.y + self.height as i32;
        let other_right = other.x + other.width as i32;
        let other_bottom = other.y + other.height as i32;
        self.x < other_right
            && self_right > other.x
            && self.y < other_bottom
            && self_bottom > other.y
    }

    /// Returns the bounding union of two rectangles.
    ///
    /// # Example
    ///
    /// ```
    /// use martensite_devtools::hud::Rect;
    ///
    /// let a = Rect::new(0, 0, 100, 100);
    /// let b = Rect::new(50, 50, 100, 100);
    /// let u = a.union(&b);
    /// assert_eq!(u.x, 0);
    /// assert_eq!(u.y, 0);
    /// assert_eq!(u.width, 150);
    /// assert_eq!(u.height, 150);
    /// ```
    pub fn union(&self, other: &Rect) -> Rect {
        let x = self.x.min(other.x);
        let y = self.y.min(other.y);
        let right = (self.x + self.width as i32).max(other.x + other.width as i32);
        let bottom = (self.y + self.height as i32).max(other.y + other.height as i32);
        Rect::new(x, y, (right - x) as u32, (bottom - y) as u32)
    }
}

/// Dirty rectangle tracking for visualization.
///
/// Tracks repainted screen regions for the diagnostic HUD overlay.
///
/// # Example
///
/// ```
/// use martensite_devtools::hud::{DirtyRectTracker, Rect};
///
/// let mut tracker = DirtyRectTracker::new(64);
/// tracker.add(Rect::new(0, 0, 100, 100));
/// tracker.add(Rect::new(50, 50, 100, 100));
/// assert_eq!(tracker.rects().len(), 2);
/// assert!(tracker.total_area() > 0);
/// ```
#[derive(Debug, Clone)]
pub struct DirtyRectTracker {
    rects: Vec<Rect>,
    max_rects: usize,
}

impl DirtyRectTracker {
    /// Creates a new tracker with the given maximum number of rectangles.
    ///
    /// # Example
    ///
    /// ```
    /// use martensite_devtools::hud::DirtyRectTracker;
    ///
    /// let tracker = DirtyRectTracker::new(32);
    /// assert!(tracker.is_empty());
    /// ```
    pub fn new(max_rects: usize) -> Self {
        Self {
            rects: Vec::with_capacity(max_rects),
            max_rects,
        }
    }

    /// Adds a dirty rectangle. If the tracker is full, the oldest
    /// rectangle is dropped.
    ///
    /// # Example
    ///
    /// ```
    /// use martensite_devtools::hud::{DirtyRectTracker, Rect};
    ///
    /// let mut tracker = DirtyRectTracker::new(2);
    /// tracker.add(Rect::new(0, 0, 10, 10));
    /// tracker.add(Rect::new(10, 10, 10, 10));
    /// tracker.add(Rect::new(20, 20, 10, 10)); // drops oldest
    /// assert_eq!(tracker.rects().len(), 2);
    /// ```
    pub fn add(&mut self, rect: Rect) {
        if self.rects.len() >= self.max_rects {
            self.rects.remove(0);
        }
        self.rects.push(rect);
    }

    /// Returns the tracked rectangles.
    #[inline]
    pub fn rects(&self) -> &[Rect] {
        &self.rects
    }

    /// Clears all tracked rectangles.
    pub fn clear(&mut self) {
        self.rects.clear();
    }

    /// Returns the total area of all tracked rectangles.
    ///
    /// # Example
    ///
    /// ```
    /// use martensite_devtools::hud::{DirtyRectTracker, Rect};
    ///
    /// let mut tracker = DirtyRectTracker::new(10);
    /// tracker.add(Rect::new(0, 0, 100, 100));
    /// assert_eq!(tracker.total_area(), 10_000);
    /// ```
    pub fn total_area(&self) -> u64 {
        self.rects.iter().map(|r| r.area()).sum()
    }

    /// Returns `true` if no rectangles are tracked.
    #[inline]
    pub fn is_empty(&self) -> bool {
        self.rects.is_empty()
    }

    /// Returns the number of tracked rectangles.
    #[inline]
    pub fn len(&self) -> usize {
        self.rects.len()
    }
}

/// Arena memory telemetry data.
///
/// Tracks `WidgetArena` slot utilization and compaction statistics.
///
/// # Example
///
/// ```
/// use martensite_devtools::hud::ArenaTelemetry;
///
/// let telemetry = ArenaTelemetry {
///     total_slots: 1000,
///     used_slots: 750,
///     free_slots: 250,
///     utilization_pct: 75.0,
///     compaction_count: 3,
/// };
/// assert_eq!(telemetry.free_slots, 250);
/// ```
#[derive(Debug, Clone, Copy, Default, PartialEq)]
pub struct ArenaTelemetry {
    /// Total number of slots in the arena.
    pub total_slots: usize,
    /// Number of slots currently in use.
    pub used_slots: usize,
    /// Number of free (available) slots.
    pub free_slots: usize,
    /// Slot utilization as a percentage (0.0–100.0).
    pub utilization_pct: f32,
    /// Number of compaction passes performed.
    pub compaction_count: u64,
}

impl ArenaTelemetry {
    /// Creates telemetry from slot counts, computing derived fields.
    ///
    /// # Example
    ///
    /// ```
    /// use martensite_devtools::hud::ArenaTelemetry;
    ///
    /// let t = ArenaTelemetry::from_slots(1000, 750, 2);
    /// assert_eq!(t.free_slots, 250);
    /// assert_eq!(t.utilization_pct, 75.0);
    /// ```
    pub fn from_slots(total: usize, used: usize, compactions: u64) -> Self {
        let free = total.saturating_sub(used);
        let utilization_pct = if total > 0 {
            (used as f32 / total as f32) * 100.0
        } else {
            0.0
        };
        Self {
            total_slots: total,
            used_slots: used,
            free_slots: free,
            utilization_pct,
            compaction_count: compactions,
        }
    }
}

/// The diagnostic HUD state.
///
/// Aggregates frame timing, dirty rect, and arena telemetry data
/// for the F12 diagnostic overlay.
///
/// # Example
///
/// ```
/// use martensite_devtools::hud::{DiagnosticHud, FrameTiming, Rect, ArenaTelemetry};
///
/// let mut hud = DiagnosticHud::new();
/// hud.toggle();
/// assert!(hud.is_enabled());
///
/// hud.record_frame(FrameTiming {
///     layout_time_ns: 500_000,
///     paint_time_ns: 300_000,
///     gpu_wait_time_ns: 100_000,
///     total_time_ns: 900_000,
/// });
/// hud.add_dirty_rect(Rect::new(0, 0, 100, 100));
/// hud.update_arena_telemetry(ArenaTelemetry::from_slots(1000, 500, 0));
///
/// assert_eq!(hud.histogram().len(), 1);
/// assert_eq!(hud.dirty_rects().len(), 1);
/// ```
#[derive(Debug, Clone)]
pub struct DiagnosticHud {
    enabled: bool,
    histogram: FrameHistogram,
    dirty_rects: DirtyRectTracker,
    arena_telemetry: ArenaTelemetry,
}

impl Default for DiagnosticHud {
    fn default() -> Self {
        Self::new()
    }
}

impl DiagnosticHud {
    /// Creates a new disabled HUD.
    ///
    /// # Example
    ///
    /// ```
    /// use martensite_devtools::hud::DiagnosticHud;
    ///
    /// let hud = DiagnosticHud::new();
    /// assert!(!hud.is_enabled());
    /// ```
    pub fn new() -> Self {
        Self {
            enabled: false,
            histogram: FrameHistogram::new(),
            dirty_rects: DirtyRectTracker::new(256),
            arena_telemetry: ArenaTelemetry::default(),
        }
    }

    /// Toggles the HUD on/off (bound to F12 in the application).
    ///
    /// # Example
    ///
    /// ```
    /// use martensite_devtools::hud::DiagnosticHud;
    ///
    /// let mut hud = DiagnosticHud::new();
    /// hud.toggle();
    /// assert!(hud.is_enabled());
    /// hud.toggle();
    /// assert!(!hud.is_enabled());
    /// ```
    pub fn toggle(&mut self) {
        self.enabled = !self.enabled;
    }

    /// Returns whether the HUD is currently visible.
    #[inline]
    pub fn is_enabled(&self) -> bool {
        self.enabled
    }

    /// Records a frame's timing data.
    ///
    /// # Example
    ///
    /// ```
    /// use martensite_devtools::hud::{DiagnosticHud, FrameTiming};
    ///
    /// let mut hud = DiagnosticHud::new();
    /// hud.record_frame(FrameTiming { total_time_ns: 16_000_000, ..Default::default() });
    /// assert_eq!(hud.histogram().len(), 1);
    /// ```
    pub fn record_frame(&mut self, timing: FrameTiming) {
        self.histogram.record(timing);
    }

    /// Adds a dirty rectangle for visualization.
    pub fn add_dirty_rect(&mut self, rect: Rect) {
        self.dirty_rects.add(rect);
    }

    /// Updates the arena telemetry data.
    pub fn update_arena_telemetry(&mut self, telemetry: ArenaTelemetry) {
        self.arena_telemetry = telemetry;
    }

    /// Returns the frame timing histogram.
    #[inline]
    pub fn histogram(&self) -> &FrameHistogram {
        &self.histogram
    }

    /// Returns the dirty rect tracker.
    #[inline]
    pub fn dirty_rects(&self) -> &DirtyRectTracker {
        &self.dirty_rects
    }

    /// Returns the arena telemetry.
    #[inline]
    pub fn arena_telemetry(&self) -> &ArenaTelemetry {
        &self.arena_telemetry
    }

    /// Clears all dirty rects (call after each frame).
    pub fn clear_dirty_rects(&mut self) {
        self.dirty_rects.clear();
    }
}

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

    #[test]
    fn frame_timing_from_ms() {
        let t = FrameTiming::from_ms(0.5, 0.3, 0.1, 0.9);
        assert_eq!(t.layout_time_ns, 500_000);
        assert_eq!(t.paint_time_ns, 300_000);
        assert_eq!(t.gpu_wait_time_ns, 100_000);
        assert_eq!(t.total_time_ns, 900_000);
    }

    #[test]
    fn frame_timing_add_and_div() {
        let a = FrameTiming {
            total_time_ns: 10,
            ..Default::default()
        };
        let b = FrameTiming {
            total_time_ns: 20,
            ..Default::default()
        };
        let sum = a.add(&b);
        assert_eq!(sum.total_time_ns, 30);
        let avg = sum.div(2);
        assert_eq!(avg.total_time_ns, 15);
        let div_zero = sum.div(0);
        assert_eq!(div_zero.total_time_ns, 0);
    }

    #[test]
    fn histogram_new_is_empty() {
        let hist = FrameHistogram::new();
        assert!(hist.is_empty());
        assert_eq!(hist.len(), 0);
    }

    #[test]
    fn histogram_record_and_average() {
        let mut hist = FrameHistogram::new();
        hist.record(FrameTiming {
            total_time_ns: 10_000_000,
            ..Default::default()
        });
        hist.record(FrameTiming {
            total_time_ns: 20_000_000,
            ..Default::default()
        });
        assert_eq!(hist.len(), 2);
        let avg = hist.average();
        assert_eq!(avg.total_time_ns, 15_000_000);
    }

    #[test]
    fn histogram_max() {
        let mut hist = FrameHistogram::new();
        hist.record(FrameTiming {
            total_time_ns: 10,
            ..Default::default()
        });
        hist.record(FrameTiming {
            total_time_ns: 30,
            ..Default::default()
        });
        hist.record(FrameTiming {
            total_time_ns: 20,
            ..Default::default()
        });
        assert_eq!(hist.max().total_time_ns, 30);
    }

    #[test]
    fn histogram_percentile() {
        let mut hist = FrameHistogram::new();
        for i in 1..=100 {
            hist.record(FrameTiming {
                total_time_ns: i * 1_000_000,
                ..Default::default()
            });
        }
        let p50 = hist.percentile(50.0);
        assert!(p50.total_time_ns >= 49_000_000 && p50.total_time_ns <= 51_000_000);
        let p99 = hist.percentile(99.0);
        assert!(p99.total_time_ns >= 98_000_000);
    }

    #[test]
    fn histogram_ring_buffer_wrap() {
        let mut hist = FrameHistogram::new();
        for i in 0..150 {
            hist.record(FrameTiming {
                total_time_ns: i,
                ..Default::default()
            });
        }
        assert_eq!(hist.len(), 120);
    }

    #[test]
    fn histogram_clear() {
        let mut hist = FrameHistogram::new();
        hist.record(FrameTiming::default());
        hist.clear();
        assert!(hist.is_empty());
    }

    #[test]
    fn rect_area() {
        assert_eq!(Rect::new(0, 0, 100, 50).area(), 5_000);
        assert_eq!(Rect::new(10, 20, 0, 100).area(), 0);
    }

    #[test]
    fn rect_intersects() {
        let a = Rect::new(0, 0, 100, 100);
        let b = Rect::new(50, 50, 100, 100);
        let c = Rect::new(200, 200, 50, 50);
        assert!(a.intersects(&b));
        assert!(!a.intersects(&c));
    }

    #[test]
    fn rect_union() {
        let a = Rect::new(0, 0, 100, 100);
        let b = Rect::new(50, 50, 100, 100);
        let u = a.union(&b);
        assert_eq!(u.x, 0);
        assert_eq!(u.y, 0);
        assert_eq!(u.width, 150);
        assert_eq!(u.height, 150);
    }

    #[test]
    fn dirty_rect_tracker_basic() {
        let mut tracker = DirtyRectTracker::new(64);
        assert!(tracker.is_empty());
        tracker.add(Rect::new(0, 0, 100, 100));
        tracker.add(Rect::new(50, 50, 100, 100));
        assert_eq!(tracker.len(), 2);
        assert!(!tracker.is_empty());
        assert!(tracker.total_area() > 0);
        tracker.clear();
        assert!(tracker.is_empty());
    }

    #[test]
    fn dirty_rect_tracker_eviction() {
        let mut tracker = DirtyRectTracker::new(2);
        tracker.add(Rect::new(0, 0, 10, 10));
        tracker.add(Rect::new(10, 10, 10, 10));
        tracker.add(Rect::new(20, 20, 10, 10));
        assert_eq!(tracker.len(), 2);
        assert_eq!(tracker.rects()[0], Rect::new(10, 10, 10, 10));
    }

    #[test]
    fn arena_telemetry_from_slots() {
        let t = ArenaTelemetry::from_slots(1000, 750, 3);
        assert_eq!(t.total_slots, 1000);
        assert_eq!(t.used_slots, 750);
        assert_eq!(t.free_slots, 250);
        assert_eq!(t.utilization_pct, 75.0);
        assert_eq!(t.compaction_count, 3);
    }

    #[test]
    fn arena_telemetry_zero_total() {
        let t = ArenaTelemetry::from_slots(0, 0, 0);
        assert_eq!(t.utilization_pct, 0.0);
    }

    #[test]
    fn hud_toggle() {
        let mut hud = DiagnosticHud::new();
        assert!(!hud.is_enabled());
        hud.toggle();
        assert!(hud.is_enabled());
        hud.toggle();
        assert!(!hud.is_enabled());
    }

    #[test]
    fn hud_record_frame_and_dirty_rect() {
        let mut hud = DiagnosticHud::new();
        hud.record_frame(FrameTiming {
            total_time_ns: 16_000_000,
            ..Default::default()
        });
        hud.add_dirty_rect(Rect::new(0, 0, 100, 100));
        assert_eq!(hud.histogram().len(), 1);
        assert_eq!(hud.dirty_rects().len(), 1);
        hud.clear_dirty_rects();
        assert_eq!(hud.dirty_rects().len(), 0);
    }

    #[test]
    fn hud_arena_telemetry_update() {
        let mut hud = DiagnosticHud::new();
        hud.update_arena_telemetry(ArenaTelemetry::from_slots(500, 250, 1));
        assert_eq!(hud.arena_telemetry().used_slots, 250);
    }
}