astrelis-ui 0.2.4

UI Framework designed for Astrelis Game Engine
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
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
//! High-level retained draw list for UI rendering.
//!
//! This module implements Phase 5 of the UI refactor plan: retained-mode rendering.
//! The draw list is API-agnostic and can be encoded to different GPU backends.
//! It tracks which nodes contribute which draw commands for efficient updates.

use crate::clip::ClipRect;
use crate::dirty::DirtyRanges;
use crate::tree::NodeId;
use crate::widgets::{ImageTexture, ImageUV};
use astrelis_core::alloc::HashMap;
use astrelis_core::math::Vec2;
use astrelis_core::profiling::profile_function;
use astrelis_render::Color;
use astrelis_text::PipelineShapedTextResult as ShapedTextResult;
use astrelis_text::{TextEffects, TextRenderMode};
use std::sync::Arc;

/// Render layer for controlling which rendering pass a command belongs to.
///
/// Overlays, tooltips, and modals use `Overlay(n)` to escape parent clip bounds
/// and render above base content. The sub-order `u8` determines relative
/// ordering among overlay layers.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, PartialOrd, Ord, Default)]
pub enum RenderLayer {
    /// Normal UI content, subject to parent clip bounds.
    #[default]
    Base,
    /// Overlay content that escapes parent clipping.
    /// The `u8` sub-order determines relative ordering among overlays.
    Overlay(u8),
}

/// High-level draw command for a UI element.
#[derive(Debug, Clone)]
pub enum DrawCommand {
    /// Draw a filled or bordered rectangle
    Quad(QuadCommand),
    /// Draw shaped text
    Text(TextCommand),
    /// Draw a textured image
    Image(ImageCommand),
}

impl DrawCommand {
    /// Get the node ID that owns this command.
    pub fn node_id(&self) -> NodeId {
        match self {
            DrawCommand::Quad(q) => q.node_id,
            DrawCommand::Text(t) => t.node_id,
            DrawCommand::Image(i) => i.node_id,
        }
    }
}

impl DrawCommand {
    /// Get the z-index for sorting.
    pub fn z_index(&self) -> u16 {
        match self {
            DrawCommand::Quad(q) => q.z_index,
            DrawCommand::Text(t) => t.z_index,
            DrawCommand::Image(i) => i.z_index,
        }
    }

    /// Check if this is an opaque draw command.
    pub fn is_opaque(&self) -> bool {
        match self {
            DrawCommand::Quad(q) => q.color.a >= 1.0,
            DrawCommand::Text(t) => t.color.a >= 1.0,
            DrawCommand::Image(i) => i.tint.a >= 1.0,
        }
    }

    /// Set the node ID for this command.
    pub fn set_node_id(&mut self, node_id: NodeId) {
        match self {
            DrawCommand::Quad(q) => q.node_id = node_id,
            DrawCommand::Text(t) => t.node_id = node_id,
            DrawCommand::Image(i) => i.node_id = node_id,
        }
    }

    /// Get the render layer for this command.
    pub fn render_layer(&self) -> RenderLayer {
        match self {
            DrawCommand::Quad(q) => q.render_layer,
            DrawCommand::Text(t) => t.render_layer,
            DrawCommand::Image(i) => i.render_layer,
        }
    }

    /// Get the clip rectangle for this command.
    pub fn clip_rect(&self) -> &ClipRect {
        match self {
            DrawCommand::Quad(q) => &q.clip_rect,
            DrawCommand::Text(t) => &t.clip_rect,
            DrawCommand::Image(i) => &i.clip_rect,
        }
    }

    /// Set the clip rectangle for this command.
    pub fn set_clip_rect(&mut self, clip_rect: ClipRect) {
        match self {
            DrawCommand::Quad(q) => q.clip_rect = clip_rect,
            DrawCommand::Text(t) => t.clip_rect = clip_rect,
            DrawCommand::Image(i) => i.clip_rect = clip_rect,
        }
    }
}

/// Command to draw a quad (rectangle).
#[derive(Debug, Clone)]
pub struct QuadCommand {
    /// Node that owns this command
    pub node_id: NodeId,
    /// Position in screen space
    pub position: Vec2,
    /// Size of the quad
    pub size: Vec2,
    /// Fill or border color
    pub color: Color,
    /// Border radius for rounded corners (0 = sharp)
    pub border_radius: f32,
    /// Border thickness (0 = filled, >0 = outline)
    pub border_thickness: f32,
    /// Z-index for depth sorting
    pub z_index: u16,
    /// Clip rectangle for scissor clipping
    pub clip_rect: ClipRect,
    /// Render layer for overlay support
    pub render_layer: RenderLayer,
}

impl QuadCommand {
    /// Create a new filled quad command.
    pub fn filled(position: Vec2, size: Vec2, color: Color, z_index: u16) -> Self {
        Self {
            node_id: NodeId(0), // Will be set by DrawList
            position,
            size,
            color,
            border_radius: 0.0,
            border_thickness: 0.0,
            z_index,
            clip_rect: ClipRect::infinite(),
            render_layer: RenderLayer::Base,
        }
    }

    /// Create a new rounded quad command.
    pub fn rounded(
        position: Vec2,
        size: Vec2,
        color: Color,
        border_radius: f32,
        z_index: u16,
    ) -> Self {
        Self {
            node_id: NodeId(0), // Will be set by DrawList
            position,
            size,
            color,
            border_radius,
            border_thickness: 0.0,
            z_index,
            clip_rect: ClipRect::infinite(),
            render_layer: RenderLayer::Base,
        }
    }

    /// Create a new bordered quad command.
    pub fn bordered(
        position: Vec2,
        size: Vec2,
        color: Color,
        border_thickness: f32,
        border_radius: f32,
        z_index: u16,
    ) -> Self {
        Self {
            node_id: NodeId(0), // Will be set by DrawList
            position,
            size,
            color,
            border_radius,
            border_thickness,
            z_index,
            clip_rect: ClipRect::infinite(),
            render_layer: RenderLayer::Base,
        }
    }

    /// Set the clip rectangle for this quad.
    pub fn with_clip(mut self, clip_rect: ClipRect) -> Self {
        self.clip_rect = clip_rect;
        self
    }
}

/// Command to draw shaped text.
#[derive(Debug, Clone)]
pub struct TextCommand {
    /// Node that owns this command
    pub node_id: NodeId,
    /// Position in screen space
    pub position: Vec2,
    /// Shaped text result with glyphs
    pub shaped_text: Arc<ShapedTextResult>,
    /// Text color
    pub color: Color,
    /// Z-index for depth sorting
    pub z_index: u16,
    /// Optional text effects (shadows, outlines, glows)
    pub effects: Option<TextEffects>,
    /// Render mode (Bitmap or SDF) - auto-selected when effects are present
    pub render_mode: TextRenderMode,
    /// Clip rectangle for scissor clipping
    pub clip_rect: ClipRect,
    /// Render layer for overlay support
    pub render_layer: RenderLayer,
}

impl TextCommand {
    /// Create a new text command.
    pub fn new(
        position: Vec2,
        shaped_text: Arc<ShapedTextResult>,
        color: Color,
        z_index: u16,
    ) -> Self {
        Self {
            node_id: NodeId(0), // Will be set by DrawList
            position,
            shaped_text,
            color,
            z_index,
            effects: None,
            render_mode: TextRenderMode::Bitmap,
            clip_rect: ClipRect::infinite(),
            render_layer: RenderLayer::Base,
        }
    }

    /// Create a text command with effects (automatically uses SDF rendering).
    ///
    /// Effects require SDF (Signed Distance Field) rendering to work properly.
    /// This constructor automatically sets the render mode to SDF.
    ///
    /// # Arguments
    ///
    /// * `position` - Top-left position to draw the text
    /// * `shaped_text` - Pre-shaped text buffer with glyph layout
    /// * `color` - Base text color
    /// * `z_index` - Depth sorting order
    /// * `effects` - Collection of text effects (shadows, outlines, glows)
    ///
    /// # Example
    ///
    /// ```ignore
    /// use astrelis_ui::{TextCommand, TextEffectsBuilder};
    /// use astrelis_core::math::Vec2;
    /// use astrelis_render::Color;
    ///
    /// let effects = TextEffectsBuilder::new()
    ///     .shadow(Vec2::new(2.0, 2.0), Color::BLACK)
    ///     .outline(1.5, Color::WHITE)
    ///     .build();
    ///
    /// let cmd = TextCommand::with_effects(
    ///     Vec2::new(100.0, 100.0),
    ///     shaped_text,
    ///     Color::WHITE,
    ///     1,
    ///     effects
    /// );
    /// ```
    pub fn with_effects(
        position: Vec2,
        shaped_text: Arc<ShapedTextResult>,
        color: Color,
        z_index: u16,
        effects: TextEffects,
    ) -> Self {
        Self {
            node_id: NodeId(0),
            position,
            shaped_text,
            color,
            z_index,
            effects: Some(effects),
            render_mode: TextRenderMode::SDF { spread: 4.0 },
            clip_rect: ClipRect::infinite(),
            render_layer: RenderLayer::Base,
        }
    }

    /// Check if this text command requires SDF rendering.
    ///
    /// Returns `true` if:
    /// - The render mode is explicitly set to SDF, OR
    /// - The text has effects (which require SDF)
    ///
    /// This is used by the renderer to select the appropriate rendering pipeline.
    ///
    /// # Example
    ///
    /// ```ignore
    /// let cmd = TextCommand::new(...);
    /// assert!(!cmd.requires_sdf());  // Bitmap by default
    ///
    /// let cmd = TextCommand::with_effects(..., effects);
    /// assert!(cmd.requires_sdf());  // SDF required for effects
    /// ```
    pub fn requires_sdf(&self) -> bool {
        self.render_mode.is_sdf() || self.effects.is_some()
    }

    /// Set the clip rectangle for this text.
    pub fn with_clip(mut self, clip_rect: ClipRect) -> Self {
        self.clip_rect = clip_rect;
        self
    }
}

/// Command to draw an image (textured quad).
#[derive(Clone)]
pub struct ImageCommand {
    /// Node that owns this command
    pub node_id: NodeId,
    /// Position in screen space
    pub position: Vec2,
    /// Size of the image
    pub size: Vec2,
    /// The texture to draw
    pub texture: ImageTexture,
    /// UV coordinates for sprite regions
    pub uv: ImageUV,
    /// Tint color (multiplied with texture)
    pub tint: Color,
    /// Border radius for rounded corners
    pub border_radius: f32,
    /// Sampling mode for texture filtering
    pub sampling: astrelis_render::ImageSampling,
    /// Z-index for depth sorting
    pub z_index: u16,
    /// Clip rectangle for scissor clipping
    pub clip_rect: ClipRect,
    /// Render layer for overlay support
    pub render_layer: RenderLayer,
}

impl std::fmt::Debug for ImageCommand {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        f.debug_struct("ImageCommand")
            .field("node_id", &self.node_id)
            .field("position", &self.position)
            .field("size", &self.size)
            .field("uv", &self.uv)
            .field("tint", &self.tint)
            .field("border_radius", &self.border_radius)
            .field("sampling", &self.sampling)
            .field("z_index", &self.z_index)
            .field("clip_rect", &self.clip_rect)
            .finish()
    }
}

impl ImageCommand {
    /// Create a new image command.
    #[allow(clippy::too_many_arguments)]
    pub fn new(
        position: Vec2,
        size: Vec2,
        texture: ImageTexture,
        uv: ImageUV,
        tint: Color,
        border_radius: f32,
        sampling: astrelis_render::ImageSampling,
        z_index: u16,
    ) -> Self {
        Self {
            node_id: NodeId(0), // Will be set by DrawList
            position,
            size,
            texture,
            uv,
            tint,
            border_radius,
            sampling,
            z_index,
            clip_rect: ClipRect::infinite(),
            render_layer: RenderLayer::Base,
        }
    }

    /// Create a simple image command with default UV and sampling (full texture, linear filtering).
    pub fn simple(position: Vec2, size: Vec2, texture: ImageTexture, z_index: u16) -> Self {
        Self::new(
            position,
            size,
            texture,
            ImageUV::default(),
            Color::WHITE,
            0.0,
            astrelis_render::ImageSampling::default(),
            z_index,
        )
    }

    /// Set the clip rectangle for this image.
    pub fn with_clip(mut self, clip_rect: ClipRect) -> Self {
        self.clip_rect = clip_rect;
        self
    }
}

/// Retained draw list for efficient UI rendering.
///
/// Maintains a list of draw commands and tracks which nodes contribute
/// which commands. Supports incremental updates where only dirty nodes
/// need to be re-encoded.
pub struct DrawList {
    /// All draw commands in the list
    commands: Vec<DrawCommand>,
    /// Mapping from node ID to command indices
    node_to_commands: HashMap<NodeId, Vec<usize>>,
    /// Ranges of commands that have been modified
    dirty_ranges: DirtyRanges,
    /// Whether the entire list needs re-sorting
    needs_sort: bool,
    /// Total number of updates since creation
    update_count: u64,
    /// Index where overlay commands begin (base commands are [0..split), overlay are [split..len))
    overlay_split_index: usize,
}

impl DrawList {
    /// Create a new empty draw list.
    pub fn new() -> Self {
        Self {
            commands: Vec::new(),
            node_to_commands: HashMap::new(),
            dirty_ranges: DirtyRanges::new(),
            needs_sort: false,
            update_count: 0,
            overlay_split_index: 0,
        }
    }

    /// Create a draw list with initial capacity.
    pub fn with_capacity(capacity: usize) -> Self {
        Self {
            commands: Vec::with_capacity(capacity),
            node_to_commands: HashMap::with_capacity(capacity / 2),
            dirty_ranges: DirtyRanges::new(),
            needs_sort: false,
            update_count: 0,
            overlay_split_index: 0,
        }
    }

    /// Update commands for a node.
    ///
    /// Replaces all existing commands for the node with the new ones.
    /// Marks affected ranges as dirty for GPU update.
    pub fn update_node(&mut self, node_id: NodeId, mut new_commands: Vec<DrawCommand>) {
        self.update_count += 1;

        // Remove old commands for this node
        if let Some(old_indices) = self.node_to_commands.get(&node_id) {
            // Mark old ranges as dirty and clear them
            for &idx in old_indices.iter().rev() {
                if idx < self.commands.len() {
                    self.dirty_ranges.mark_dirty(idx, idx + 1);
                    // Don't remove yet - we'll compact later
                }
            }
        }

        if new_commands.is_empty() {
            // Node has no commands anymore
            self.node_to_commands.remove(&node_id);
            self.needs_sort = true; // May need to compact
            return;
        }

        // Add new commands
        let start_idx = self.commands.len();
        let mut new_indices = Vec::with_capacity(new_commands.len());

        for mut cmd in new_commands.drain(..) {
            cmd.set_node_id(node_id);
            let idx = self.commands.len();
            self.commands.push(cmd);
            new_indices.push(idx);
        }

        let end_idx = self.commands.len();

        // Mark new range as dirty
        self.dirty_ranges.mark_dirty(start_idx, end_idx);

        // Update mapping
        self.node_to_commands.insert(node_id, new_indices);

        // May need sorting if z-index changed
        self.needs_sort = true;
    }

    /// Update only the color of a node's commands (fast path for paint-only changes).
    ///
    /// This is much faster than full command replacement when only colors change.
    pub fn update_node_colors(&mut self, node_id: NodeId, color: Color) {
        if let Some(indices) = self.node_to_commands.get(&node_id) {
            for &idx in indices {
                if let Some(cmd) = self.commands.get_mut(idx) {
                    match cmd {
                        DrawCommand::Quad(q) => q.color = color,
                        DrawCommand::Text(t) => t.color = color,
                        DrawCommand::Image(i) => i.tint = color,
                    }
                    self.dirty_ranges.mark_dirty(idx, idx + 1);
                }
            }
            self.update_count += 1;
        }
    }

    /// Remove all commands for a node.
    pub fn remove_node(&mut self, node_id: NodeId) {
        if let Some(indices) = self.node_to_commands.remove(&node_id) {
            // Mark ranges as dirty
            for idx in indices {
                if idx < self.commands.len() {
                    self.dirty_ranges.mark_dirty(idx, idx + 1);
                }
            }
            self.needs_sort = true; // Need to compact
            self.update_count += 1;
        }
    }

    /// Sort commands by z-index and prepare for rendering.
    ///
    /// Should be called before encoding to GPU to ensure proper draw order.
    pub fn sort_if_needed(&mut self) {
        profile_function!();

        if !self.needs_sort {
            return;
        }

        // Compact: remove invalidated commands
        self.compact();

        // Sort by render layer, then z-index (stable sort preserves order for same z-index)
        self.commands
            .sort_by_key(|cmd| (cmd.render_layer(), cmd.z_index(), !cmd.is_opaque()));

        // Compute the split point between Base and Overlay commands
        self.overlay_split_index = self
            .commands
            .partition_point(|cmd| cmd.render_layer() == RenderLayer::Base);

        // Rebuild node mapping
        self.rebuild_node_mapping();

        // Mark entire list as dirty after sort
        if !self.commands.is_empty() {
            self.dirty_ranges.mark_dirty(0, self.commands.len());
        }

        self.needs_sort = false;
    }

    /// Compact the command list by removing invalidated entries.
    fn compact(&mut self) {
        // Collect all valid command indices
        let mut valid_indices: Vec<usize> = self
            .node_to_commands
            .values()
            .flat_map(|indices| indices.iter().copied())
            .collect();

        if valid_indices.len() == self.commands.len() {
            // No compaction needed
            return;
        }

        valid_indices.sort_unstable();
        valid_indices.dedup();

        // Build new command list with only valid commands
        let mut new_commands = Vec::with_capacity(valid_indices.len());
        for idx in valid_indices {
            if let Some(cmd) = self.commands.get(idx) {
                new_commands.push(cmd.clone());
            }
        }

        self.commands = new_commands;
    }

    /// Rebuild node-to-command mapping after sorting/compacting.
    fn rebuild_node_mapping(&mut self) {
        // Clear old mapping
        self.node_to_commands.clear();

        // Rebuild from commands (now that they track their node_id)
        for (idx, cmd) in self.commands.iter().enumerate() {
            self.node_to_commands
                .entry(cmd.node_id())
                .or_default()
                .push(idx);
        }
    }

    /// Get all commands for rendering.
    pub fn commands(&self) -> &[DrawCommand] {
        &self.commands
    }

    /// Get base-layer commands (everything before the overlay split).
    pub fn base_commands(&self) -> &[DrawCommand] {
        &self.commands[..self.overlay_split_index]
    }

    /// Get overlay-layer commands (everything from the overlay split onward).
    pub fn overlay_commands(&self) -> &[DrawCommand] {
        &self.commands[self.overlay_split_index..]
    }

    /// Get dirty ranges for partial GPU updates.
    pub fn dirty_ranges(&self) -> &DirtyRanges {
        &self.dirty_ranges
    }

    /// Clear all dirty ranges.
    pub fn clear_dirty(&mut self) {
        self.dirty_ranges.clear();
    }

    /// Clear the entire draw list.
    pub fn clear(&mut self) {
        self.commands.clear();
        self.node_to_commands.clear();
        self.dirty_ranges.clear();
        self.needs_sort = false;
        self.overlay_split_index = 0;
    }

    /// Get the number of commands in the list.
    pub fn len(&self) -> usize {
        self.commands.len()
    }

    /// Check if the draw list is empty.
    pub fn is_empty(&self) -> bool {
        self.commands.is_empty()
    }

    /// Get statistics about the draw list.
    pub fn stats(&self) -> DrawListStats {
        let mut num_quads = 0;
        let mut num_text = 0;
        let mut num_images = 0;
        let mut num_opaque = 0;
        let mut num_transparent = 0;

        for cmd in &self.commands {
            match cmd {
                DrawCommand::Quad(_) => num_quads += 1,
                DrawCommand::Text(_) => num_text += 1,
                DrawCommand::Image(_) => num_images += 1,
            }
            if cmd.is_opaque() {
                num_opaque += 1;
            } else {
                num_transparent += 1;
            }
        }

        DrawListStats {
            total_commands: self.commands.len(),
            num_quads,
            num_text,
            num_images,
            num_opaque,
            num_transparent,
            num_nodes: self.node_to_commands.len(),
            dirty_ranges: self.dirty_ranges.stats().num_ranges,
            needs_sort: self.needs_sort,
            update_count: self.update_count,
        }
    }

    /// Separate commands into opaque and transparent batches.
    ///
    /// Returns (opaque_commands, transparent_commands) for two-pass rendering.
    pub fn separate_by_opacity(&self) -> (Vec<&DrawCommand>, Vec<&DrawCommand>) {
        let mut opaque = Vec::new();
        let mut transparent = Vec::new();

        for cmd in &self.commands {
            if cmd.is_opaque() {
                opaque.push(cmd);
            } else {
                transparent.push(cmd);
            }
        }

        (opaque, transparent)
    }

    /// Get commands in a specific z-index range.
    pub fn commands_in_z_range(&self, min_z: u16, max_z: u16) -> Vec<&DrawCommand> {
        self.commands
            .iter()
            .filter(|cmd| {
                let z = cmd.z_index();
                z >= min_z && z <= max_z
            })
            .collect()
    }
}

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

/// Statistics about a draw list.
#[derive(Debug, Clone, Copy)]
pub struct DrawListStats {
    pub total_commands: usize,
    pub num_quads: usize,
    pub num_text: usize,
    pub num_images: usize,
    pub num_opaque: usize,
    pub num_transparent: usize,
    pub num_nodes: usize,
    pub dirty_ranges: usize,
    pub needs_sort: bool,
    pub update_count: u64,
}

#[cfg(test)]
mod tests {
    use super::*;
    use astrelis_text::PipelineShapedTextResult as ShapedTextResult;
    use astrelis_text::ShapedTextResult as BaseShapedTextResult;

    #[test]
    fn test_add_and_get_commands() {
        let mut draw_list = DrawList::new();
        let node_id = NodeId(1);

        let cmd = DrawCommand::Quad(QuadCommand::filled(
            Vec2::new(0.0, 0.0),
            Vec2::new(100.0, 50.0),
            Color::WHITE,
            0,
        ));

        draw_list.update_node(node_id, vec![cmd]);

        assert_eq!(draw_list.len(), 1);
        assert!(!draw_list.is_empty());
    }

    #[test]
    fn test_update_replaces_commands() {
        let mut draw_list = DrawList::new();
        let node_id = NodeId(1);

        // First update
        let cmd1 = DrawCommand::Quad(QuadCommand::filled(
            Vec2::new(0.0, 0.0),
            Vec2::new(100.0, 50.0),
            Color::WHITE,
            0,
        ));
        draw_list.update_node(node_id, vec![cmd1]);

        assert_eq!(draw_list.len(), 1);

        // Second update with different command
        let cmd2 = DrawCommand::Quad(QuadCommand::filled(
            Vec2::new(10.0, 10.0),
            Vec2::new(200.0, 100.0),
            Color::RED,
            0,
        ));
        draw_list.update_node(node_id, vec![cmd2]);

        // Should still be 2 commands (old ones not immediately removed)
        // Compaction happens on sort
        assert!(!draw_list.is_empty());
    }

    #[test]
    fn test_remove_node() {
        let mut draw_list = DrawList::new();
        let node_id = NodeId(1);

        let cmd = DrawCommand::Quad(QuadCommand::filled(
            Vec2::new(0.0, 0.0),
            Vec2::new(100.0, 50.0),
            Color::WHITE,
            0,
        ));
        draw_list.update_node(node_id, vec![cmd]);

        draw_list.remove_node(node_id);

        // Commands marked for removal but not compacted yet
        assert!(draw_list.needs_sort);
    }

    #[test]
    fn test_clear() {
        let mut draw_list = DrawList::new();
        draw_list.update_node(
            NodeId(1),
            vec![DrawCommand::Quad(QuadCommand::filled(
                Vec2::ZERO,
                Vec2::new(100.0, 100.0),
                Color::WHITE,
                0,
            ))],
        );

        draw_list.clear();

        assert_eq!(draw_list.len(), 0);
        assert!(draw_list.is_empty());
    }

    #[test]
    fn test_dirty_ranges() {
        let mut draw_list = DrawList::new();
        let node_id = NodeId(1);

        draw_list.update_node(
            node_id,
            vec![DrawCommand::Quad(QuadCommand::filled(
                Vec2::ZERO,
                Vec2::new(100.0, 100.0),
                Color::WHITE,
                0,
            ))],
        );

        assert!(!draw_list.dirty_ranges().is_empty());

        draw_list.clear_dirty();

        assert!(draw_list.dirty_ranges().is_empty());
    }

    #[test]
    fn test_update_colors_fast_path() {
        let mut draw_list = DrawList::new();
        let node_id = NodeId(1);

        draw_list.update_node(
            node_id,
            vec![DrawCommand::Quad(QuadCommand::filled(
                Vec2::ZERO,
                Vec2::new(100.0, 100.0),
                Color::WHITE,
                0,
            ))],
        );

        draw_list.clear_dirty();
        draw_list.update_node_colors(node_id, Color::RED);

        assert!(!draw_list.dirty_ranges().is_empty());
    }

    #[test]
    fn test_stats() {
        let mut draw_list = DrawList::new();

        draw_list.update_node(
            NodeId(1),
            vec![DrawCommand::Quad(QuadCommand::filled(
                Vec2::ZERO,
                Vec2::new(100.0, 100.0),
                Color::WHITE,
                0,
            ))],
        );

        let shaped = Arc::new(ShapedTextResult::new(
            1,
            BaseShapedTextResult::new((100.0, 20.0), vec![]),
        ));
        draw_list.update_node(
            NodeId(2),
            vec![DrawCommand::Text(TextCommand::new(
                Vec2::ZERO,
                shaped,
                Color::BLACK,
                0,
            ))],
        );

        let stats = draw_list.stats();
        assert_eq!(stats.num_quads, 1);
        assert_eq!(stats.num_text, 1);
        assert_eq!(stats.total_commands, 2);
    }

    #[test]
    fn test_opacity_separation() {
        let mut draw_list = DrawList::new();

        // Opaque quad
        draw_list.update_node(
            NodeId(1),
            vec![DrawCommand::Quad(QuadCommand::filled(
                Vec2::ZERO,
                Vec2::new(100.0, 100.0),
                Color::WHITE,
                0,
            ))],
        );

        // Transparent quad
        draw_list.update_node(
            NodeId(2),
            vec![DrawCommand::Quad(QuadCommand::filled(
                Vec2::ZERO,
                Vec2::new(100.0, 100.0),
                Color::rgba(1.0, 1.0, 1.0, 0.5),
                0,
            ))],
        );

        let (opaque, transparent) = draw_list.separate_by_opacity();
        assert_eq!(opaque.len(), 1);
        assert_eq!(transparent.len(), 1);
    }

    #[test]
    fn test_text_command_new() {
        let shaped = Arc::new(ShapedTextResult::new(
            1,
            BaseShapedTextResult::new((100.0, 20.0), vec![]),
        ));
        let cmd = TextCommand::new(Vec2::new(10.0, 20.0), shaped, Color::BLACK, 5);

        assert_eq!(cmd.position, Vec2::new(10.0, 20.0));
        assert_eq!(cmd.color, Color::BLACK);
        assert_eq!(cmd.z_index, 5);
        assert!(cmd.effects.is_none());
        assert_eq!(cmd.render_mode, TextRenderMode::Bitmap);
        assert!(!cmd.requires_sdf());
    }

    #[test]
    fn test_text_command_with_effects() {
        use astrelis_text::{TextEffect, TextEffects};

        let mut effects = TextEffects::new();
        effects.add(TextEffect::shadow(Vec2::new(2.0, 2.0), Color::BLACK));

        let shaped = Arc::new(ShapedTextResult::new(
            1,
            BaseShapedTextResult::new((100.0, 20.0), vec![]),
        ));
        let cmd =
            TextCommand::with_effects(Vec2::new(10.0, 20.0), shaped, Color::WHITE, 5, effects);

        assert!(cmd.effects.is_some());
        assert_eq!(cmd.render_mode, TextRenderMode::SDF { spread: 4.0 });
        assert!(cmd.requires_sdf());
    }

    #[test]
    fn test_text_command_requires_sdf_with_effects() {
        use astrelis_text::{TextEffect, TextEffects};

        let mut effects = TextEffects::new();
        effects.add(TextEffect::outline(1.0, Color::BLACK));

        let shaped = Arc::new(ShapedTextResult::new(
            1,
            BaseShapedTextResult::new((100.0, 20.0), vec![]),
        ));
        let mut cmd = TextCommand::new(Vec2::ZERO, shaped, Color::WHITE, 0);
        cmd.effects = Some(effects);

        // Has effects, should require SDF
        assert!(cmd.requires_sdf());
    }

    #[test]
    fn test_text_command_requires_sdf_with_sdf_mode() {
        let shaped = Arc::new(ShapedTextResult::new(
            1,
            BaseShapedTextResult::new((100.0, 20.0), vec![]),
        ));
        let mut cmd = TextCommand::new(Vec2::ZERO, shaped, Color::WHITE, 0);
        cmd.render_mode = TextRenderMode::SDF { spread: 6.0 };

        // SDF mode set, should require SDF
        assert!(cmd.requires_sdf());
    }

    #[test]
    fn test_text_command_requires_sdf_bitmap_no_effects() {
        let shaped = Arc::new(ShapedTextResult::new(
            1,
            BaseShapedTextResult::new((100.0, 20.0), vec![]),
        ));
        let cmd = TextCommand::new(Vec2::ZERO, shaped, Color::WHITE, 0);

        // Bitmap mode, no effects, should not require SDF
        assert!(!cmd.requires_sdf());
    }

    #[test]
    fn test_text_command_multiple_effects() {
        use astrelis_text::{TextEffect, TextEffects};

        let mut effects = TextEffects::new();
        effects.add(TextEffect::shadow(Vec2::new(1.0, 1.0), Color::BLACK));
        effects.add(TextEffect::outline(1.0, Color::WHITE));
        effects.add(TextEffect::glow(3.0, Color::BLUE, 0.5));

        let shaped = Arc::new(ShapedTextResult::new(
            1,
            BaseShapedTextResult::new((100.0, 20.0), vec![]),
        ));
        let cmd = TextCommand::with_effects(Vec2::ZERO, shaped, Color::WHITE, 0, effects.clone());

        assert!(cmd.requires_sdf());
        assert_eq!(cmd.effects.as_ref().unwrap().effects().len(), 3);
    }
}