soorat 1.0.0

Soorat — GPU rendering engine for AGNOS
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
//! Sprite rendering pipeline.

//! Also re-exports batch functions from [`crate::batch`] for backward compatibility.

use crate::color::Color;
use crate::error::Result;
use crate::sprite::SpriteBatch;
use crate::vertex::Vertex2D;
use wgpu::util::DeviceExt;

// Re-export batch functions for backward compatibility
pub use crate::batch::{
    MAX_SPRITES_PER_BATCH, batch_to_vertices, batch_to_vertices_into, batch_to_vertices_u32,
    batch_to_vertices_u32_into,
};

/// Orthographic projection matrix for 2D rendering.
/// Maps screen coordinates (0,0 top-left) to clip space.
/// Origin at top-left, Y-axis points down, Z range [0, 1].
fn orthographic_projection(width: f32, height: f32) -> [f32; 16] {
    // Column-major 4x4: origin (0,0) top-left, right-handed, zero-to-one depth
    // Simplified from general ortho with l=0, t=0, n=-1, f=1
    [
        2.0 / width,
        0.0,
        0.0,
        0.0,
        0.0,
        -2.0 / height,
        0.0,
        0.0,
        0.0,
        0.0,
        -0.5,
        0.0,
        -1.0,
        1.0,
        0.5,
        1.0,
    ]
}

/// Persistent GPU buffers for sprite rendering. Reuse across frames to avoid per-frame allocation.
pub struct SpriteBuffers {
    vertex_buffer: wgpu::Buffer,
    index_buffer: wgpu::Buffer,
    vertex_capacity: usize,
    index_capacity: usize,
    // CPU-side staging
    vertices: Vec<Vertex2D>,
    indices: Vec<u16>,
}

impl SpriteBuffers {
    /// Create persistent buffers sized for the given sprite count.
    #[must_use]
    pub fn new(device: &wgpu::Device, sprite_capacity: usize) -> Self {
        let vert_cap = sprite_capacity.saturating_mul(4);
        let idx_cap = sprite_capacity.saturating_mul(6);
        let vertex_buffer = device.create_buffer(&wgpu::BufferDescriptor {
            label: Some("sprite_vertex_buffer_persistent"),
            size: (vert_cap * std::mem::size_of::<Vertex2D>()) as u64,
            usage: wgpu::BufferUsages::VERTEX | wgpu::BufferUsages::COPY_DST,
            mapped_at_creation: false,
        });
        let index_buffer = device.create_buffer(&wgpu::BufferDescriptor {
            label: Some("sprite_index_buffer_persistent"),
            size: (idx_cap * std::mem::size_of::<u16>()) as u64,
            usage: wgpu::BufferUsages::INDEX | wgpu::BufferUsages::COPY_DST,
            mapped_at_creation: false,
        });
        Self {
            vertex_buffer,
            index_buffer,
            vertex_capacity: vert_cap,
            index_capacity: idx_cap,
            vertices: Vec::with_capacity(vert_cap),
            indices: Vec::with_capacity(idx_cap),
        }
    }

    /// Prepare buffers for a batch. Grows GPU buffers if needed, then writes via queue.
    pub fn prepare(&mut self, device: &wgpu::Device, queue: &wgpu::Queue, batch: &SpriteBatch) {
        batch_to_vertices_into(batch, &mut self.vertices, &mut self.indices);

        // Regrow GPU buffers if CPU data exceeds capacity
        if self.vertices.len() > self.vertex_capacity {
            self.vertex_capacity = self.vertices.len();
            self.vertex_buffer = device.create_buffer(&wgpu::BufferDescriptor {
                label: Some("sprite_vertex_buffer_persistent"),
                size: (self.vertex_capacity * std::mem::size_of::<Vertex2D>()) as u64,
                usage: wgpu::BufferUsages::VERTEX | wgpu::BufferUsages::COPY_DST,
                mapped_at_creation: false,
            });
        }
        if self.indices.len() > self.index_capacity {
            self.index_capacity = self.indices.len();
            self.index_buffer = device.create_buffer(&wgpu::BufferDescriptor {
                label: Some("sprite_index_buffer_persistent"),
                size: (self.index_capacity * std::mem::size_of::<u16>()) as u64,
                usage: wgpu::BufferUsages::INDEX | wgpu::BufferUsages::COPY_DST,
                mapped_at_creation: false,
            });
        }

        queue.write_buffer(&self.vertex_buffer, 0, bytemuck::cast_slice(&self.vertices));
        queue.write_buffer(&self.index_buffer, 0, bytemuck::cast_slice(&self.indices));
    }

    /// Number of indices currently written.
    #[must_use]
    #[inline]
    pub fn index_count(&self) -> u32 {
        self.indices.len() as u32
    }
}

/// Per-frame rendering statistics.
#[derive(Debug, Clone, Copy, Default)]
pub struct FrameStats {
    pub draw_calls: u32,
    pub triangles: u32,
    pub sprites: u32,
}

/// Parameters for `SpritePipeline::draw_batched`.
pub struct SpriteBatchDrawParams<'a> {
    pub view: &'a wgpu::TextureView,
    pub batch: &'a SpriteBatch,
    pub texture_cache: &'a crate::texture::TextureCache,
    pub fallback_bind_group: &'a wgpu::BindGroup,
    pub clear_color: Option<Color>,
}

/// Sprite rendering pipeline — holds the wgpu pipeline, bind group layouts, and buffers.
///
/// Uses [`mabda::RenderPipeline`] for pipeline management and
/// [`mabda::create_uniform_buffer`] for uniform buffer creation.
pub struct SpritePipeline {
    pipeline: mabda::RenderPipeline,
    uniform_buffer: wgpu::Buffer,
    uniform_bind_group: wgpu::BindGroup,
}

impl SpritePipeline {
    /// Create a new sprite pipeline for the given surface format.
    pub fn new(device: &wgpu::Device, surface_format: wgpu::TextureFormat) -> Result<Self> {
        tracing::debug!(?surface_format, "creating sprite pipeline");
        let pipeline = mabda::RenderPipelineBuilder::new(
            device,
            include_str!("sprite.wgsl"),
            "vs_main",
            "fs_main",
        )
        .label("sprite_pipeline")
        .vertex_layout(Vertex2D::layout())
        .bind_group(
            mabda::BindGroupLayoutBuilder::new()
                .uniform_buffer(wgpu::ShaderStages::VERTEX)
                .into_entries(),
        )
        .bind_group(
            mabda::BindGroupLayoutBuilder::new()
                .texture_2d(wgpu::ShaderStages::FRAGMENT)
                .sampler(wgpu::ShaderStages::FRAGMENT)
                .into_entries(),
        )
        .color_target(surface_format, Some(wgpu::BlendState::ALPHA_BLENDING))
        .build()?;

        // Create uniform buffer with identity projection (updated per frame)
        let uniform_buffer = mabda::create_uniform_buffer(
            device,
            bytemuck::cast_slice(&[0.0_f32; 16]),
            "sprite_uniform_buffer",
        );

        let uniform_bind_group = device.create_bind_group(&wgpu::BindGroupDescriptor {
            label: Some("sprite_uniform_bind_group"),
            layout: pipeline.bind_group_layout(0).ok_or_else(|| {
                crate::error::RenderError::Pipeline(
                    "sprite pipeline missing bind group layout 0".into(),
                )
            })?,
            entries: &[wgpu::BindGroupEntry {
                binding: 0,
                resource: uniform_buffer.as_entire_binding(),
            }],
        });

        Ok(Self {
            pipeline,
            uniform_buffer,
            uniform_bind_group,
        })
    }

    /// Get the texture bind group layout for creating texture bind groups.
    pub fn texture_bind_group_layout(&self) -> Result<&wgpu::BindGroupLayout> {
        self.pipeline.bind_group_layout(1).ok_or_else(|| {
            crate::error::RenderError::Pipeline(
                "sprite pipeline missing bind group layout 1".into(),
            )
        })
    }

    /// Update the projection matrix for the current viewport size.
    pub fn update_projection(&self, queue: &wgpu::Queue, width: f32, height: f32) {
        if width <= 0.0 || height <= 0.0 {
            tracing::warn!(
                width,
                height,
                "zero or negative viewport size, skipping projection update"
            );
            return;
        }
        let proj = orthographic_projection(width, height);
        queue.write_buffer(&self.uniform_buffer, 0, bytemuck::cast_slice(&proj));
    }

    /// Draw a sprite batch with a single texture. The batch should already be sorted by z-order.
    ///
    /// `clear_color`: if Some, clears the render target first.
    /// `texture_bind_group`: the bind group for the texture to use.
    pub fn draw(
        &self,
        device: &wgpu::Device,
        queue: &wgpu::Queue,
        view: &wgpu::TextureView,
        batch: &SpriteBatch,
        texture_bind_group: &wgpu::BindGroup,
        clear_color: Option<Color>,
    ) -> FrameStats {
        let mut stats = FrameStats::default();
        tracing::debug!(
            sprite_count = batch.sprites.len(),
            has_clear = clear_color.is_some(),
            "drawing sprites"
        );

        if batch.is_empty() && clear_color.is_none() {
            return stats;
        }

        let (vertices, indices) = batch_to_vertices(batch);
        stats.sprites = batch.sprites.len() as u32;
        stats.triangles = indices.len() as u32 / 3;

        let (vertex_buffer, index_buffer) = Self::upload_buffers(device, &vertices, &indices);
        let mut encoder = device.create_command_encoder(&wgpu::CommandEncoderDescriptor {
            label: Some("sprite_encoder"),
        });

        {
            let mut render_pass = Self::begin_pass(&mut encoder, view, clear_color);

            if !batch.is_empty() {
                render_pass.set_pipeline(self.pipeline.raw());
                render_pass.set_bind_group(0, &self.uniform_bind_group, &[]);
                render_pass.set_bind_group(1, texture_bind_group, &[]);
                render_pass.set_vertex_buffer(0, vertex_buffer.slice(..));
                render_pass.set_index_buffer(index_buffer.slice(..), wgpu::IndexFormat::Uint16);
                render_pass.draw_indexed(0..indices.len() as u32, 0, 0..1);
                stats.draw_calls = 1;
            }
        }

        queue.submit(std::iter::once(encoder.finish()));
        stats
    }

    /// Draw using pre-allocated `SpriteBuffers`. Call `buffers.prepare()` first.
    /// Zero per-frame GPU allocations after the first frame.
    pub fn draw_with_buffers(
        &self,
        device: &wgpu::Device,
        queue: &wgpu::Queue,
        view: &wgpu::TextureView,
        buffers: &SpriteBuffers,
        texture_bind_group: &wgpu::BindGroup,
        clear_color: Option<Color>,
    ) -> FrameStats {
        let mut stats = FrameStats::default();
        let index_count = buffers.index_count();
        tracing::debug!(
            index_count,
            has_clear = clear_color.is_some(),
            "drawing sprites with buffers"
        );

        if index_count == 0 && clear_color.is_none() {
            return stats;
        }

        stats.sprites = index_count / 6;
        stats.triangles = index_count / 3;

        let mut encoder = device.create_command_encoder(&wgpu::CommandEncoderDescriptor {
            label: Some("sprite_encoder"),
        });

        {
            let mut render_pass = Self::begin_pass(&mut encoder, view, clear_color);

            if index_count > 0 {
                render_pass.set_pipeline(self.pipeline.raw());
                render_pass.set_bind_group(0, &self.uniform_bind_group, &[]);
                render_pass.set_bind_group(1, texture_bind_group, &[]);
                render_pass.set_vertex_buffer(0, buffers.vertex_buffer.slice(..));
                render_pass
                    .set_index_buffer(buffers.index_buffer.slice(..), wgpu::IndexFormat::Uint16);
                render_pass.draw_indexed(0..index_count, 0, 0..1);
                stats.draw_calls = 1;
            }
        }

        queue.submit(std::iter::once(encoder.finish()));
        stats
    }

    /// Draw a sprite batch with multiple textures, issuing one draw call per texture group.
    /// Sprites are drawn in z-order; consecutive sprites sharing a texture_id are batched.
    pub fn draw_batched(
        &self,
        device: &wgpu::Device,
        queue: &wgpu::Queue,
        params: &SpriteBatchDrawParams<'_>,
    ) -> FrameStats {
        let mut stats = FrameStats::default();
        tracing::debug!(
            sprite_count = params.batch.sprites.len(),
            has_clear = params.clear_color.is_some(),
            "drawing sprites batched"
        );

        if params.batch.is_empty() && params.clear_color.is_none() {
            return stats;
        }

        let (vertices, indices) = batch_to_vertices(params.batch);
        stats.sprites = params.batch.sprites.len() as u32;
        stats.triangles = indices.len() as u32 / 3;

        let (vertex_buffer, index_buffer) = Self::upload_buffers(device, &vertices, &indices);
        let mut encoder = device.create_command_encoder(&wgpu::CommandEncoderDescriptor {
            label: Some("sprite_encoder"),
        });

        {
            let mut render_pass = Self::begin_pass(&mut encoder, params.view, params.clear_color);

            if !params.batch.is_empty() {
                render_pass.set_pipeline(self.pipeline.raw());
                render_pass.set_bind_group(0, &self.uniform_bind_group, &[]);
                render_pass.set_vertex_buffer(0, vertex_buffer.slice(..));
                render_pass.set_index_buffer(index_buffer.slice(..), wgpu::IndexFormat::Uint16);

                // Issue draw calls grouped by consecutive texture_id
                let mut run_start: u32 = 0;
                let mut current_tex_id = params.batch.sprites[0].texture_id;

                for (i, sprite) in params.batch.sprites.iter().enumerate() {
                    if sprite.texture_id != current_tex_id {
                        let bind_group = params
                            .texture_cache
                            .get_bind_group(current_tex_id)
                            .unwrap_or(params.fallback_bind_group);
                        render_pass.set_bind_group(1, bind_group, &[]);
                        let idx_start = run_start * 6;
                        let idx_end = (i as u32) * 6;
                        render_pass.draw_indexed(idx_start..idx_end, 0, 0..1);
                        stats.draw_calls += 1;

                        run_start = i as u32;
                        current_tex_id = sprite.texture_id;
                    }
                }

                let bind_group = params
                    .texture_cache
                    .get_bind_group(current_tex_id)
                    .unwrap_or(params.fallback_bind_group);
                render_pass.set_bind_group(1, bind_group, &[]);
                let idx_start = run_start * 6;
                let idx_end = params.batch.sprites.len() as u32 * 6;
                render_pass.draw_indexed(idx_start..idx_end, 0, 0..1);
                stats.draw_calls += 1;
            }
        }

        queue.submit(std::iter::once(encoder.finish()));
        stats
    }

    fn upload_buffers(
        device: &wgpu::Device,
        vertices: &[Vertex2D],
        indices: &[u16],
    ) -> (wgpu::Buffer, wgpu::Buffer) {
        let vertex_buffer = device.create_buffer_init(&wgpu::util::BufferInitDescriptor {
            label: Some("sprite_vertex_buffer"),
            contents: bytemuck::cast_slice(vertices),
            usage: wgpu::BufferUsages::VERTEX,
        });
        let index_buffer = device.create_buffer_init(&wgpu::util::BufferInitDescriptor {
            label: Some("sprite_index_buffer"),
            contents: bytemuck::cast_slice(indices),
            usage: wgpu::BufferUsages::INDEX,
        });
        (vertex_buffer, index_buffer)
    }

    fn begin_pass<'a>(
        encoder: &'a mut wgpu::CommandEncoder,
        view: &'a wgpu::TextureView,
        clear_color: Option<Color>,
    ) -> wgpu::RenderPass<'a> {
        let load_op = match clear_color {
            Some(c) => wgpu::LoadOp::Clear(c.to_wgpu()),
            None => wgpu::LoadOp::Load,
        };

        encoder.begin_render_pass(&wgpu::RenderPassDescriptor {
            label: Some("sprite_pass"),
            color_attachments: &[Some(wgpu::RenderPassColorAttachment {
                view,
                resolve_target: None,
                depth_slice: None,
                ops: wgpu::Operations {
                    load: load_op,
                    store: wgpu::StoreOp::Store,
                },
            })],
            depth_stencil_attachment: None,
            ..Default::default()
        })
    }

    /// Draw a sprite batch into an existing render pass (for egui/editor integration).
    pub fn draw_into_pass<'a>(
        &'a self,
        render_pass: &mut wgpu::RenderPass<'a>,
        batch: &SpriteBatch,
        texture_bind_group: &'a wgpu::BindGroup,
        device: &wgpu::Device,
    ) {
        tracing::debug!(
            sprite_count = batch.sprites.len(),
            "drawing sprites into pass"
        );
        if batch.is_empty() {
            return;
        }
        let (vertices, indices) = batch_to_vertices(batch);
        let (vertex_buffer, index_buffer) = Self::upload_buffers(device, &vertices, &indices);
        render_pass.set_pipeline(self.pipeline.raw());
        render_pass.set_bind_group(0, &self.uniform_bind_group, &[]);
        render_pass.set_bind_group(1, texture_bind_group, &[]);
        render_pass.set_vertex_buffer(0, vertex_buffer.slice(..));
        render_pass.set_index_buffer(index_buffer.slice(..), wgpu::IndexFormat::Uint16);
        render_pass.draw_indexed(0..indices.len() as u32, 0, 0..1);
    }
}

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

    #[test]
    fn orthographic_projection_values() {
        let proj = orthographic_projection(800.0, 600.0);
        assert_eq!(proj.len(), 16);
        // Column-major: proj[0] = 2/w, proj[5] = -2/h, proj[12] = -1, proj[13] = 1
        assert!((proj[0] - 2.0 / 800.0).abs() < f32::EPSILON);
        assert!((proj[5] - (-2.0 / 600.0)).abs() < f32::EPSILON);
        assert!((proj[12] - (-1.0)).abs() < f32::EPSILON);
        assert!((proj[13] - 1.0).abs() < f32::EPSILON);
    }

    #[test]
    fn batch_to_vertices_empty() {
        let batch = SpriteBatch::new();
        let (verts, indices) = batch_to_vertices(&batch);
        assert!(verts.is_empty());
        assert!(indices.is_empty());
    }

    #[test]
    fn batch_to_vertices_single_sprite() {
        let mut batch = SpriteBatch::new();
        batch.push(Sprite::new(10.0, 20.0, 32.0, 32.0));
        let (verts, indices) = batch_to_vertices(&batch);
        assert_eq!(verts.len(), 4);
        assert_eq!(indices.len(), 6);
        assert_eq!(indices, vec![0, 1, 2, 2, 3, 0]);
        // No rotation: corners should match sprite bounds
        assert_eq!(verts[0].position, [10.0, 20.0]);
        assert_eq!(verts[1].position, [42.0, 20.0]);
        assert_eq!(verts[2].position, [42.0, 52.0]);
        assert_eq!(verts[3].position, [10.0, 52.0]);
    }

    #[test]
    fn batch_to_vertices_rotated_sprite() {
        let mut batch = SpriteBatch::new();
        // 90 degrees CCW
        let half_pi = std::f32::consts::FRAC_PI_2;
        batch.push(Sprite::new(0.0, 0.0, 100.0, 100.0).with_rotation(half_pi));
        let (verts, _) = batch_to_vertices(&batch);

        // Center is (50, 50). After 90° CCW rotation:
        // (-50,-50) rotated = (50,-50) + center = (100, 0)... let me check
        // rot(90): x' = x*cos - y*sin, y' = x*sin + y*cos
        // cos(90)=0, sin(90)=1
        // (-50,-50): x'= -50*0 - (-50)*1 = 50, y'= -50*1 + (-50)*0 = -50 => (100, 0)
        // (50,-50):  x'= 50*0 - (-50)*1 = 50,  y'= 50*1 + (-50)*0 = 50 => (100, 100)
        // (50,50):   x'= 50*0 - 50*1 = -50,    y'= 50*1 + 50*0 = 50 => (0, 100)
        // (-50,50):  x'= -50*0 - 50*1 = -50,   y'= -50*1 + 50*0 = -50 => (0, 0)
        let eps = 0.01;
        assert!((verts[0].position[0] - 100.0).abs() < eps);
        assert!((verts[0].position[1] - 0.0).abs() < eps);
        assert!((verts[2].position[0] - 0.0).abs() < eps);
        assert!((verts[2].position[1] - 100.0).abs() < eps);
    }

    #[test]
    fn batch_to_vertices_zero_rotation_matches_unrotated() {
        let mut batch_a = SpriteBatch::new();
        batch_a.push(Sprite::new(10.0, 20.0, 50.0, 30.0));
        let mut batch_b = SpriteBatch::new();
        batch_b.push(Sprite::new(10.0, 20.0, 50.0, 30.0).with_rotation(0.0));
        let (va, _) = batch_to_vertices(&batch_a);
        let (vb, _) = batch_to_vertices(&batch_b);
        for (a, b) in va.iter().zip(vb.iter()) {
            assert_eq!(a.position, b.position);
        }
    }

    #[test]
    fn batch_to_vertices_multiple_sprites() {
        let mut batch = SpriteBatch::new();
        batch.push(Sprite::new(0.0, 0.0, 10.0, 10.0));
        batch.push(Sprite::new(50.0, 50.0, 20.0, 20.0));
        let (verts, indices) = batch_to_vertices(&batch);
        assert_eq!(verts.len(), 8);
        assert_eq!(indices.len(), 12);
        // Second sprite indices should be offset by 4
        assert_eq!(indices[6..], [4, 5, 6, 6, 7, 4]);
    }

    #[test]
    fn batch_to_vertices_preserves_color() {
        let mut batch = SpriteBatch::new();
        batch.push(Sprite::new(0.0, 0.0, 10.0, 10.0).with_color(Color::RED));
        let (verts, _) = batch_to_vertices(&batch);
        for v in &verts {
            assert_eq!(v.color, [1.0, 0.0, 0.0, 1.0]);
        }
    }

    #[test]
    fn batch_to_vertices_tex_coords() {
        let mut batch = SpriteBatch::new();
        batch.push(Sprite::new(0.0, 0.0, 10.0, 10.0));
        let (verts, _) = batch_to_vertices(&batch);
        assert_eq!(verts[0].tex_coords, [0.0, 0.0]);
        assert_eq!(verts[1].tex_coords, [1.0, 0.0]);
        assert_eq!(verts[2].tex_coords, [1.0, 1.0]);
        assert_eq!(verts[3].tex_coords, [0.0, 1.0]);
    }

    #[test]
    fn batch_to_vertices_into_reuses_buffers() {
        let mut verts = Vec::new();
        let mut indices = Vec::new();

        let mut batch = SpriteBatch::new();
        batch.push(Sprite::new(0.0, 0.0, 10.0, 10.0));
        batch_to_vertices_into(&batch, &mut verts, &mut indices);
        assert_eq!(verts.len(), 4);
        assert_eq!(indices.len(), 6);

        // Second call reuses the same Vecs
        batch.push(Sprite::new(20.0, 0.0, 10.0, 10.0));
        batch_to_vertices_into(&batch, &mut verts, &mut indices);
        assert_eq!(verts.len(), 8);
        assert_eq!(indices.len(), 12);
        // Capacity should be >= 8 (no realloc for second call)
        assert!(verts.capacity() >= 8);
    }

    #[test]
    fn frame_stats_default() {
        let stats = FrameStats::default();
        assert_eq!(stats.draw_calls, 0);
        assert_eq!(stats.triangles, 0);
        assert_eq!(stats.sprites, 0);
    }

    #[test]
    fn batch_to_vertices_with_uv() {
        use crate::sprite::UvRect;
        let uv = UvRect::from_pixel_rect(0, 0, 16, 16, 64, 64);
        let mut batch = SpriteBatch::new();
        batch.push(Sprite::new(0.0, 0.0, 32.0, 32.0).with_uv(uv));
        let (verts, _) = batch_to_vertices(&batch);
        assert_eq!(verts[0].tex_coords, [uv.u_min, uv.v_min]);
        assert_eq!(verts[1].tex_coords, [uv.u_max, uv.v_min]);
        assert_eq!(verts[2].tex_coords, [uv.u_max, uv.v_max]);
        assert_eq!(verts[3].tex_coords, [uv.u_min, uv.v_max]);
    }

    #[test]
    fn batch_to_vertices_into_matches_batch_to_vertices() {
        let mut batch = SpriteBatch::new();
        for i in 0..10 {
            batch.push(Sprite::new(i as f32 * 10.0, 0.0, 32.0, 32.0).with_color(Color::RED));
        }

        let (verts_a, indices_a) = batch_to_vertices(&batch);
        let mut verts_b = Vec::new();
        let mut indices_b = Vec::new();
        batch_to_vertices_into(&batch, &mut verts_b, &mut indices_b);

        assert_eq!(verts_a, verts_b);
        assert_eq!(indices_a, indices_b);
    }

    #[test]
    fn max_sprites_constant() {
        assert_eq!(MAX_SPRITES_PER_BATCH, 16383);
    }

    #[test]
    fn batch_u32_overflow_protection() {
        // Verify the u32 checked cast works with a reasonable count
        let mut batch = SpriteBatch::new();
        for i in 0..100 {
            batch.push(Sprite::new(i as f32, 0.0, 1.0, 1.0));
        }
        let (verts, indices) = batch_to_vertices_u32(&batch);
        assert_eq!(verts.len(), 400);
        assert_eq!(indices.len(), 600);
        // All indices must be valid
        for &idx in &indices {
            assert!((idx as usize) < verts.len());
        }
    }

    #[test]
    fn batch_to_vertices_respects_limit() {
        let mut batch = SpriteBatch::new();
        // Push more than the limit
        for i in 0..16400 {
            batch.push(Sprite::new(i as f32, 0.0, 1.0, 1.0));
        }
        let (verts, indices) = batch_to_vertices(&batch);
        // Should be clamped to MAX_SPRITES_PER_BATCH
        assert_eq!(verts.len(), MAX_SPRITES_PER_BATCH * 4);
        assert_eq!(indices.len(), MAX_SPRITES_PER_BATCH * 6);
        // All indices should be valid u16
        for &idx in &indices {
            assert!(idx < u16::MAX);
        }
    }

    #[test]
    fn batch_to_vertices_u32_no_limit() {
        let mut batch = SpriteBatch::new();
        // Push more than u16 limit
        for i in 0..20000 {
            batch.push(Sprite::new(i as f32, 0.0, 1.0, 1.0));
        }
        let (verts, indices) = batch_to_vertices_u32(&batch);
        // Should NOT be clamped
        assert_eq!(verts.len(), 20000 * 4);
        assert_eq!(indices.len(), 20000 * 6);
    }

    #[test]
    fn batch_to_vertices_u32_matches_u16_for_small() {
        let mut batch = SpriteBatch::new();
        for i in 0..10 {
            batch.push(Sprite::new(i as f32, 0.0, 32.0, 32.0));
        }
        let (verts_16, indices_16) = batch_to_vertices(&batch);
        let (verts_32, indices_32) = batch_to_vertices_u32(&batch);
        assert_eq!(verts_16, verts_32);
        // Index values should match (just different types)
        for (a, b) in indices_16.iter().zip(indices_32.iter()) {
            assert_eq!(*a as u32, *b);
        }
    }

    #[test]
    fn batch_to_vertices_at_exact_limit() {
        let mut batch = SpriteBatch::new();
        for i in 0..MAX_SPRITES_PER_BATCH {
            batch.push(Sprite::new(i as f32, 0.0, 1.0, 1.0));
        }
        let (verts, indices) = batch_to_vertices(&batch);
        assert_eq!(verts.len(), MAX_SPRITES_PER_BATCH * 4);
        assert_eq!(indices.len(), MAX_SPRITES_PER_BATCH * 6);
        // Last index should be valid
        let last_idx = *indices.last().unwrap();
        assert!(last_idx < u16::MAX);
    }
}