spottedcat 0.5.0

Rusty SpottedCat simple 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
//! Batch rendering and draw operations.

use std::sync::Mutex;
use std::time::Instant;

use crate::Context;
use crate::DrawCommand;
use crate::ShaderOpts;
use crate::image_raw::InstanceData;
use crate::pt::Pt;

use super::Graphics;
use super::core::{ResolvedDraw};
use super::profile::{PROFILE_RENDER, PROFILE_STATS, RenderProfileStats};

impl Graphics {
    pub(super) fn resolve_drawables(
        &mut self,
        drawables: &[DrawCommand],
        logical_w: u32,
        logical_h: u32,
    ) {
        self.resolved_draws.clear();
        let viewport_rect = [0.0, 0.0, logical_w as f32, logical_h as f32];

        for drawable in drawables {
            match drawable {
                DrawCommand::Image(id, opts, shader_id, shader_opts, _) => {
                    if let Some(Some(entry)) = self.images.get(*id as usize) {
                        if !entry.visible || !entry.is_ready() {
                            continue;
                        }

                        self.resolved_draws.push(ResolvedDraw {
                            img_entry: entry.clone(),
                            opts: *opts,
                            shader_id: *shader_id,
                            shader_opts: *shader_opts,
                        });
                    }
                }
                DrawCommand::Text(text, opts) => {
                    if let Err(e) = self.layout_and_queue_text(text, opts, viewport_rect) {
                        eprintln!("[spot] Text layout error: {:?}", e);
                    }
                }
            }
        }
    }

    pub(super) fn render_batches<'a>(
        &'a mut self,
        rpass: &mut wgpu::RenderPass<'a>,
        screen_size_data: [f32; 4],
        sf: f64,
    ) {
        let mut current_opacity = 1.0f32;

        // Upload initial engine globals
        let engine_globals = crate::image_raw::EngineGlobals {
            screen: screen_size_data,
            opacity: current_opacity,
            shader_opacity: 1.0, // Default for first batch
            _padding: [0.0; 2],
        };
        let mut current_engine_globals_offset = self
            .image_renderer
            .upload_engine_globals(&self.queue, &engine_globals)
            .unwrap_or(0);

        let default_user_globals = ShaderOpts::default();
        let mut current_user_globals_offset = self
            .image_renderer
            .upload_user_globals_bytes(&self.queue, default_user_globals.as_bytes())
            .unwrap_or(0);

        self.batch.clear();
        let mut current_atlas_index: Option<u32> = None;
        let mut current_shader_id: u32 = 0;
        let mut current_user_globals = ShaderOpts::default();
        let mut current_clip: Option<[Pt; 4]> = None;

        let config_width = self.config.width;
        let config_height = self.config.height;

        rpass.set_scissor_rect(0, 0, config_width.max(1), config_height.max(1));
        let mut last_set_scissor: Option<(u32, u32, u32, u32)> = None;

        for resolved in &self.resolved_draws {
            let img_entry = &resolved.img_entry;
            let opts = resolved.opts;
            let shader_id = resolved.shader_id;
            let shader_opts = resolved.shader_opts;
            let draw_opacity = opts.opacity();

            let uv_rect = match img_entry.uv_rect {
                Some(uv) => uv,
                None => continue,
            };

            let effective_user_globals = shader_opts;

            let state_changed = current_atlas_index != img_entry.atlas_index
                || current_shader_id != shader_id
                || current_user_globals != effective_user_globals
                || current_clip != opts.get_clip()
                || current_opacity != draw_opacity;

            if state_changed && !self.batch.is_empty() {
                let ai = current_atlas_index
                    .expect("current_atlas_index should be Some if batch is not empty");
                let atlas_bg = &self.atlases.get(ai as usize).expect("atlas").bind_group;

                if let Ok(range) = self
                    .image_renderer
                    .upload_instances(&self.queue, self.batch.as_slice())
                {
                    let pipeline = if current_shader_id == 0 {
                        &self.default_pipeline
                    } else {
                        self.image_pipelines.get(&current_shader_id).unwrap()
                    };
                    self.image_renderer.draw_batch(
                        rpass,
                        pipeline,
                        atlas_bg,
                        range,
                        current_user_globals_offset,
                        current_engine_globals_offset,
                    );
                }
                self.batch.clear();
            }

            if current_opacity != draw_opacity
                || current_user_globals.opacity != resolved.shader_opts.opacity
            {
                current_opacity = draw_opacity;
                let eg = crate::image_raw::EngineGlobals {
                    screen: screen_size_data,
                    opacity: current_opacity,
                    shader_opacity: resolved.shader_opts.opacity,
                    _padding: [0.0; 2],
                };
                current_engine_globals_offset = self
                    .image_renderer
                    .upload_engine_globals(&self.queue, &eg)
                    .unwrap_or(0);
            }

            if current_user_globals != effective_user_globals
                || (current_atlas_index.is_none() && self.batch.is_empty())
            {
                current_user_globals = effective_user_globals;
                current_user_globals_offset = self
                    .image_renderer
                    .upload_user_globals_bytes(&self.queue, current_user_globals.as_bytes())
                    .unwrap_or(current_user_globals_offset);
            }

            if current_clip != opts.get_clip() {
                current_clip = opts.get_clip();
                let (sx, sy, sw, sh) = if let Some(clip) = current_clip {
                    let x0 = (clip[0].as_f32() * sf as f32).clamp(0.0, config_width as f32);
                    let y0 = (clip[1].as_f32() * sf as f32).clamp(0.0, config_height as f32);
                    let x1 = ((clip[0].as_f32() + clip[2].as_f32()) * sf as f32)
                        .clamp(0.0, config_width as f32);
                    let y1 = ((clip[1].as_f32() + clip[3].as_f32()) * sf as f32)
                        .clamp(0.0, config_height as f32);
                    let fw = (x1 - x0).max(0.0) as u32;
                    let fh = (y1 - y0).max(0.0) as u32;
                    if fw > 0 && fh > 0 {
                        (x0 as u32, y0 as u32, fw, fh)
                    } else {
                        (0, 0, 1, 1)
                    }
                } else {
                    (0, 0, config_width, config_height)
                };

                if last_set_scissor != Some((sx, sy, sw, sh)) {
                    rpass.set_scissor_rect(sx, sy, sw, sh);
                    last_set_scissor = Some((sx, sy, sw, sh));
                }
            }

            current_atlas_index = img_entry.atlas_index;
            current_shader_id = shader_id;

            self.batch.push(InstanceData {
                pos: [opts.position()[0].as_f32(), opts.position()[1].as_f32()],
                rotation: opts.rotation(),
                size: [
                    img_entry.bounds.width.as_f32() * opts.scale()[0],
                    img_entry.bounds.height.as_f32() * opts.scale()[1],
                ],
                uv_rect,
            });
        }

        if !self.batch.is_empty() {
            let ai = current_atlas_index
                .expect("current_atlas_index should be Some if batch is not empty");
            let atlas_bg = &self.atlases.get(ai as usize).expect("atlas").bind_group;
            if let Ok(range) = self
                .image_renderer
                .upload_instances(&self.queue, self.batch.as_slice())
            {
                let pipeline = if current_shader_id == 0 {
                    &self.default_pipeline
                } else {
                    self.image_pipelines.get(&current_shader_id).unwrap()
                };
                self.image_renderer.draw_batch(
                    rpass,
                    pipeline,
                    atlas_bg,
                    range,
                    current_user_globals_offset,
                    current_engine_globals_offset,
                );
            }
            self.batch.clear();
        }
    }


    pub(super) fn render_3d_internal<'a>(
        &'a mut self,
        rpass: &mut wgpu::RenderPass<'a>,
        context: &Context,
        is_shadow_pass: bool,
    ) {
        let config_width = self.config.width as f32;
        let config_height = self.config.height as f32;
        let aspect = config_width / config_height;
        let proj = crate::graphics::model_raw::create_perspective(aspect, std::f32::consts::PI / 4.0, 0.1, 1000.0);
        
        // Update Scene Globals (Group 4)
        // Set a default light view-proj for the first directional light
        // Simple orthographic view-proj for the light
        self.scene_globals.light_view_proj = [
            [0.1, 0.0, 0.0, 0.0],
            [0.0, 0.1, 0.0, 0.0],
            [0.0, 0.0, 0.05, 0.0],
            [0.0, 0.0, 0.5, 1.0], // Simplified ortho
        ];

        if !is_shadow_pass {
            self.model_renderer.upload_scene_globals(&self.queue, &self.scene_globals);
        }

        let view = crate::graphics::model_raw::create_translation([0.0, 0.0, -5.0]);

        for command in context.draw_list_3d() {
            match command {
                crate::drawable::DrawCommand3D::Model(model, opts, shader_id, shader_opts, skin_id_cmd) => {
                    let model_mat = crate::graphics::model_raw::create_translation(opts.position);
                    let rot_mat = crate::graphics::model_raw::create_rotation(opts.rotation);
                    let scale_mat = crate::graphics::model_raw::create_scale(opts.scale);
                    let model_mat_all = crate::graphics::model_raw::multiply(model_mat, crate::graphics::model_raw::multiply(rot_mat, scale_mat));
                    
                    let mvp = if is_shadow_pass {
                        crate::graphics::model_raw::multiply(self.scene_globals.light_view_proj, model_mat_all)
                    } else {
                        crate::graphics::model_raw::multiply(proj, crate::graphics::model_raw::multiply(view, model_mat_all))
                    };

                    let base_globals = crate::graphics::model_raw::ModelGlobals {
                        mvp,
                        model: model_mat_all,
                        extra: [opts.opacity, 0.0, 0.0, 0.0],
                        ..Default::default()
                    };

                    for part in &model.parts {
                        if let Some(Some(mesh)) = self.models.get(part.id as usize) {
                            let mut globals = base_globals;
                            if !is_shadow_pass {
                                let get_tex_info = |img_id: Option<u32>, fallback_id: u32| -> [f32; 4] {
                                    let id = img_id.filter(|&id| self.images.get(id as usize).map(|v| v.is_some()).unwrap_or(false)).unwrap_or(fallback_id);
                                    let entry = self.images[id as usize].as_ref().unwrap();
                                    entry.uv_rect.unwrap_or([0.0, 0.0, 1.0, 1.0])
                                };
                                globals.albedo_uv = get_tex_info(part.material.albedo, self.white_image_id);
                                globals.pbr_uv = get_tex_info(part.material.pbr, self.black_image_id);
                                globals.normal_uv = get_tex_info(part.material.normal, self.normal_image_id);
                                globals.ao_uv = get_tex_info(part.material.occlusion, self.white_image_id);
                                globals.emissive_uv = get_tex_info(part.material.emissive, self.black_image_id);
                            }

                            if let Ok(offset) = self.model_renderer.upload_globals(&self.queue, &globals) {
                                let pipeline = if is_shadow_pass {
                                    &self.shadow_pipeline
                                } else if *shader_id == 0 {
                                    &self.model_pipeline
                                } else {
                                    self.model_pipelines.get(shader_id).unwrap_or(&self.model_pipeline)
                                };

                                rpass.set_pipeline(pipeline);
                                rpass.set_vertex_buffer(0, mesh.vertex_buffer.slice(..));
                                rpass.set_index_buffer(mesh.index_buffer.slice(..), wgpu::IndexFormat::Uint32);

                                let mut bone_offset = 0;
                                if let Some(skin_id) = skin_id_cmd {
                                    if let Some(Some(skin)) = self.skins.get(*skin_id as usize) {
                                        if let Ok(off) = self.model_renderer.upload_bone_matrices(&self.queue, &skin.bone_matrices) {
                                            bone_offset = off;
                                        }
                                    }
                                }

                                if is_shadow_pass {
                                    // Shadow pass only needs Group 0 (ModelGlobals) and Group 1 (Bones)
                                    rpass.set_bind_group(0, &self.model_renderer.globals_bind_group, &[offset, 0]); // 0 for unused opts
                                    rpass.set_bind_group(1, &self.model_renderer.bone_matrices_bind_group, &[bone_offset]);
                                } else {
                                    if let Ok(opts_offset) = self.model_renderer.upload_shader_opts_bytes(&self.queue, shader_opts.as_bytes()) {
                                        // Group 0: [Model, Scene, UserOpts]
                                        // dynamic offsets: [model, user_opts]
                                        rpass.set_bind_group(0, &self.model_renderer.globals_bind_group, &[offset, opts_offset]);
                                    }

                                    let get_view = |img_id: Option<u32>, fallback_id: u32| -> &wgpu::TextureView {
                                        let id = img_id.filter(|&id| self.images.get(id as usize).map(|v| v.is_some()).unwrap_or(false)).unwrap_or(fallback_id);
                                        let entry = self.images[id as usize].as_ref().unwrap();
                                        let ai = entry.atlas_index.unwrap_or(0);
                                        &self.atlases[ai as usize].texture.0.view
                                    };

                                    // Group 1: Textures
                                    let tex_bg = self.model_renderer.create_texture_bind_group(
                                        &self.device, 
                                        get_view(part.material.albedo, self.white_image_id),
                                        get_view(part.material.pbr, self.black_image_id),
                                        get_view(part.material.normal, self.normal_image_id),
                                        get_view(part.material.occlusion, self.white_image_id),
                                        get_view(part.material.emissive, self.black_image_id)
                                    );
                                    rpass.set_bind_group(1, &tex_bg, &[]);

                                    // Group 2: Bones
                                    rpass.set_bind_group(2, &self.model_renderer.bone_matrices_bind_group, &[bone_offset]);

                                    // Group 3: Environment
                                    let env_bg = self.model_renderer.create_environment_bind_group(
                                        &self.device,
                                        &self.shadow_view,
                                        &self.irradiance_view,
                                        &self.prefiltered_view,
                                        &self.brdf_lut_view,
                                    );
                                    rpass.set_bind_group(3, &env_bg, &[]);
                                }

                                rpass.draw_indexed(0..mesh.index_count, 0, 0..1);
                            }
                        }
                    }
                }
                crate::drawable::DrawCommand3D::ModelInstanced(model, opts, _shader_id, shader_opts, skin_id_cmd, instances) => {
                    if instances.is_empty() { continue; }
                    
                    let model_mat = crate::graphics::model_raw::create_translation(opts.position);
                    let rot_mat = crate::graphics::model_raw::create_rotation(opts.rotation);
                    let model_mat_all = crate::graphics::model_raw::multiply(model_mat, rot_mat);

                    let mvp = if is_shadow_pass {
                        crate::graphics::model_raw::multiply(self.scene_globals.light_view_proj, model_mat_all)
                    } else {
                        crate::graphics::model_raw::multiply(proj, crate::graphics::model_raw::multiply(view, model_mat_all))
                    };

                    let base_globals = crate::graphics::model_raw::ModelGlobals {
                        mvp,
                        model: model_mat_all,
                        extra: [opts.opacity, 0.0, 0.0, 0.0],
                        ..Default::default()
                    };

                    let instance_bytes = bytemuck::cast_slice(&instances);
                    let instance_buffer = self.device.create_buffer(&wgpu::BufferDescriptor {
                        label: Some("instancing_buffer"),
                        size: instance_bytes.len() as u64,
                        usage: wgpu::BufferUsages::VERTEX | wgpu::BufferUsages::COPY_DST,
                        mapped_at_creation: false,
                    });
                    self.queue.write_buffer(&instance_buffer, 0, instance_bytes);

                    let pipeline = if is_shadow_pass {
                        &self.instanced_shadow_pipeline
                    } else {
                        &self.instanced_model_pipeline
                    };

                    for part in &model.parts {
                        if let Some(Some(mesh)) = self.models.get(part.id as usize) {
                            let mut globals = base_globals;
                            if !is_shadow_pass {
                                let get_tex_info = |img_id: Option<u32>, fallback_id: u32| -> [f32; 4] {
                                    let id = img_id.filter(|&id| self.images.get(id as usize).map(|v| v.is_some()).unwrap_or(false)).unwrap_or(fallback_id);
                                    let entry = self.images[id as usize].as_ref().unwrap();
                                    entry.uv_rect.unwrap_or([0.0, 0.0, 1.0, 1.0])
                                };
                                globals.albedo_uv = get_tex_info(part.material.albedo, self.white_image_id);
                                globals.pbr_uv = get_tex_info(part.material.pbr, self.black_image_id);
                                globals.normal_uv = get_tex_info(part.material.normal, self.normal_image_id);
                                globals.ao_uv = get_tex_info(part.material.occlusion, self.white_image_id);
                                globals.emissive_uv = get_tex_info(part.material.emissive, self.black_image_id);
                            }

                            if let Ok(offset) = self.model_renderer.upload_globals(&self.queue, &globals) {
                                rpass.set_pipeline(pipeline);
                                rpass.set_vertex_buffer(0, mesh.vertex_buffer.slice(..));
                                rpass.set_vertex_buffer(1, instance_buffer.slice(..));
                                rpass.set_index_buffer(mesh.index_buffer.slice(..), wgpu::IndexFormat::Uint32);

                                let mut bone_offset = 0;
                                if let Some(skin_id) = skin_id_cmd {
                                    if let Some(Some(skin)) = self.skins.get(*skin_id as usize) {
                                        if let Ok(off) = self.model_renderer.upload_bone_matrices(&self.queue, &skin.bone_matrices) {
                                            bone_offset = off;
                                        }
                                    }
                                }

                                if is_shadow_pass {
                                    rpass.set_bind_group(0, &self.model_renderer.globals_bind_group, &[offset, 0]);
                                    rpass.set_bind_group(1, &self.model_renderer.bone_matrices_bind_group, &[bone_offset]);
                                } else {
                                    if let Ok(opts_offset) = self.model_renderer.upload_shader_opts_bytes(&self.queue, shader_opts.as_bytes()) {
                                        rpass.set_bind_group(0, &self.model_renderer.globals_bind_group, &[offset, opts_offset]);
                                    }

                                    let get_view = |img_id: Option<u32>, fallback_id: u32| -> &wgpu::TextureView {
                                        let id = img_id.filter(|&id| self.images.get(id as usize).map(|v| v.is_some()).unwrap_or(false)).unwrap_or(fallback_id);
                                        let entry = self.images[id as usize].as_ref().unwrap();
                                        let ai = entry.atlas_index.unwrap_or(0);
                                        &self.atlases[ai as usize].texture.0.view
                                    };

                                    let tex_bg = self.model_renderer.create_texture_bind_group(&self.device, get_view(part.material.albedo, self.white_image_id), get_view(part.material.pbr, self.black_image_id), get_view(part.material.normal, self.normal_image_id), get_view(part.material.occlusion, self.white_image_id), get_view(part.material.emissive, self.black_image_id));
                                    rpass.set_bind_group(1, &tex_bg, &[]);

                                    rpass.set_bind_group(2, &self.model_renderer.bone_matrices_bind_group, &[bone_offset]);
                                    
                                    let env_bg = self.model_renderer.create_environment_bind_group(&self.device, &self.shadow_view, &self.irradiance_view, &self.prefiltered_view, &self.brdf_lut_view);
                                    rpass.set_bind_group(3, &env_bg, &[]);
                                }
                                
                                rpass.draw_indexed(0..mesh.index_count, 0, 0..instances.len() as u32);
                            }
                        }
                    }
                }
            }
        }
    }

    pub fn draw_context(
        &mut self,
        surface: &wgpu::Surface<'_>,
        context: &Context,
    ) -> Result<(), wgpu::SurfaceError> {
        let _ = self.process_registrations();
        self.draw_drawables_with_context(
            surface,
            context.draw_list(),
            context.scale_factor(),
            context,
        )
    }

    fn draw_drawables_with_context(
        &mut self,
        surface: &wgpu::Surface<'_>,
        drawables: &[DrawCommand],
        scale_factor: f64,
        context: &Context,
    ) -> Result<(), wgpu::SurfaceError> {
        let (_lw, _lh) = context.window_logical_size();
        let sf = if scale_factor.is_finite() && scale_factor > 0.0 {
            scale_factor
        } else {
            1.0
        };
        // No need to resize here anymore, we'll do it in draw_drawables_internal after getting the texture
        self.draw_drawables_internal(surface, drawables, sf, Some(context))
    }

    fn draw_drawables_internal(
        &mut self,
        surface: &wgpu::Surface<'_>,
        drawables: &[DrawCommand],
        scale_factor: f64,
        _context: Option<&Context>,
    ) -> Result<(), wgpu::SurfaceError> {
        let profile_enabled = *PROFILE_RENDER.get_or_init(|| {
            std::env::var("SPOT_PROFILE_RENDER")
                .ok()
                .map(|v| {
                    let v = v.trim().to_ascii_lowercase();
                    !v.is_empty() && v != "0" && v != "false" && v != "off"
                })
                .unwrap_or(false)
        });

        let mut t_prev = if profile_enabled {
            Some(Instant::now())
        } else {
            None
        };
        let frame = surface.get_current_texture()?;
        
        // Robust resize: Ensure resources match the ACTUAL texture size
        let (actual_w, actual_h) = (frame.texture.width(), frame.texture.height());
        if actual_w != self.config.width || actual_h != self.config.height {
            eprintln!("[spot][graphics] dynamic resize to match texture: {}x{}", actual_w, actual_h);
            drop(frame); // Drop the texture before reconfiguring the surface
            self.resize(surface, actual_w, actual_h);
            // Re-acquire texture with new configuration
            return self.draw_drawables_internal(surface, drawables, scale_factor, _context);
        }

        let dt_acquire_ms = if let Some(t0) = t_prev {
            t0.elapsed().as_secs_f64() * 1000.0
        } else {
            0.0
        };
        t_prev = if profile_enabled {
            Some(Instant::now())
        } else {
            None
        };

        let view = frame
            .texture
            .create_view(&wgpu::TextureViewDescriptor::default());
        let mut encoder = self
            .device
            .create_command_encoder(&wgpu::CommandEncoderDescriptor {
                label: Some("graphics_encoder"),
            });
        let dt_encoder_ms = if let Some(t0) = t_prev {
            t0.elapsed().as_secs_f64() * 1000.0
        } else {
            0.0
        };
        t_prev = if profile_enabled {
            Some(Instant::now())
        } else {
            None
        };

        self.image_renderer.begin_frame();
        let sf = if scale_factor.is_finite() && scale_factor > 0.0 {
            scale_factor
        } else {
            1.0
        };
        let logical_w = ((self.config.width as f64) / sf).round().max(1.0) as u32;
        let logical_h = ((self.config.height as f64) / sf).round().max(1.0) as u32;

        let (sw, sh) = (logical_w as f32, logical_h as f32);
        let sw_inv = 1.0 / sw;
        let sh_inv = 1.0 / sh;
        let screen_size_data = [sw_inv * 2.0, sh_inv * 2.0, sw_inv, sh_inv];

        self.resolve_drawables(drawables, logical_w, logical_h);

        let dt_setup_ms = if let Some(t0) = t_prev {
            t0.elapsed().as_secs_f64() * 1000.0
        } else {
            0.0
        };
        t_prev = if profile_enabled {
            Some(Instant::now())
        } else {
            None
        };

        // Shadow pass in a SEPARATE command buffer to avoid Metal read-write conflict.
        // Metal requires the shadow texture write to complete before it can be sampled.
        {
            let mut shadow_encoder = self.device.create_command_encoder(&wgpu::CommandEncoderDescriptor {
                label: Some("shadow_encoder"),
            });
            {
                let mut rpass = shadow_encoder.begin_render_pass(&wgpu::RenderPassDescriptor {
                    label: Some("graphics_shadow_pass"),
                    color_attachments: &[],
                    depth_stencil_attachment: Some(wgpu::RenderPassDepthStencilAttachment {
                        view: &self.shadow_view,
                        depth_ops: Some(wgpu::Operations {
                            load: wgpu::LoadOp::Clear(1.0),
                            store: wgpu::StoreOp::Store,
                        }),
                        stencil_ops: None,
                    }),
                    ..Default::default()
                });

                self.model_renderer.begin_frame();
                if let Some(ctx) = _context {
                    self.render_3d_internal(&mut rpass, ctx, true);
                }
            }
            self.queue.submit(Some(shadow_encoder.finish()));
        }

        {
            let mut rpass = encoder.begin_render_pass(&wgpu::RenderPassDescriptor {
                label: Some("graphics_render_pass_3d"),
                color_attachments: &[Some(wgpu::RenderPassColorAttachment {
                    view: &view,
                    resolve_target: None,
                    depth_slice: None,
                    ops: wgpu::Operations {
                        load: wgpu::LoadOp::Clear(wgpu::Color::BLACK),
                        store: wgpu::StoreOp::Store,
                    },
                })],
                depth_stencil_attachment: Some(wgpu::RenderPassDepthStencilAttachment {
                    view: &self.depth_view,
                    depth_ops: Some(wgpu::Operations {
                        load: wgpu::LoadOp::Clear(1.0),
                        store: wgpu::StoreOp::Store,
                    }),
                    stencil_ops: None,
                }),
                ..Default::default()
            });

            self.model_renderer.begin_frame();
            if let Some(ctx) = _context {
                self.render_3d_internal(&mut rpass, ctx, false);
            }
        }
        {
            let mut rpass = encoder.begin_render_pass(&wgpu::RenderPassDescriptor {
                label: Some("graphics_render_pass_2d"),
                color_attachments: &[Some(wgpu::RenderPassColorAttachment {
                    view: &view,
                    resolve_target: None,
                    depth_slice: None,
                    ops: wgpu::Operations {
                        load: wgpu::LoadOp::Load,
                        store: wgpu::StoreOp::Store,
                    },
                })],
                depth_stencil_attachment: None,
                timestamp_writes: None,
                occlusion_query_set: None,
                multiview_mask: None,
            });

            self.render_batches(&mut rpass, screen_size_data, sf);
        }

        let dt_renderpass_ms = if let Some(t0) = t_prev {
            t0.elapsed().as_secs_f64() * 1000.0
        } else {
            0.0
        };
        t_prev = if profile_enabled {
            Some(Instant::now())
        } else {
            None
        };
        self.queue.submit(Some(encoder.finish()));
        let dt_submit_ms = if let Some(t0) = t_prev {
            t0.elapsed().as_secs_f64() * 1000.0
        } else {
            0.0
        };
        frame.present();

        if profile_enabled {
            let total_ms =
                dt_acquire_ms + dt_encoder_ms + dt_setup_ms + dt_renderpass_ms + dt_submit_ms;
            let wait_ms = dt_acquire_ms;
            let work_ms = total_ms - wait_ms;

            let stats_lock =
                PROFILE_STATS.get_or_init(|| Mutex::new(RenderProfileStats::default()));
            if let Ok(mut s) = stats_lock.lock() {
                s.frame = s.frame.saturating_add(1);
                s.sum_total_ms += total_ms;
                s.sum_wait_ms += wait_ms;
                s.sum_work_ms += work_ms;
                s.min_total_ms = s.min_total_ms.min(total_ms);
                s.max_total_ms = s.max_total_ms.max(total_ms);

                if s.frame % 30 == 0 {
                    let n = s.frame as f64;
                    eprintln!(
                        "[spot][render][avg@{}] total={:.3}ms work={:.3} wait={:.3} min={:.3} max={:.3}",
                        s.frame,
                        s.sum_total_ms / n,
                        s.sum_work_ms / n,
                        s.sum_wait_ms / n,
                        s.min_total_ms,
                        s.max_total_ms
                    );
                }
            }
        }
        Ok(())
    }
}