strata-ui-platform 0.1.2

Native Hardware Abstraction Layer for Android, iOS, macOS, Windows, Linux, and Web
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
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
//! Hardware `wgpu` swapchain surface presenter and offscreen GPU bridge for `strata_platform`.
//!
//! Supports uncapped presentation (`PresentMode::Immediate`, `AutoNoVsync`, `Mailbox`),
//! persistent cached 2D HUD overlay compositing (`ui_overlay_texture`), and graceful fallback
//! when running headless without a windowing GPU surface.

use crate::surface::{PresentError, PresentMode, SurfaceConfig, SurfacePresenter};
use std::sync::Arc;
use strata_layout::Rect;
use strata_render::compositor::DisplayList;
use strata_render::gpu_wgpu::Wgpu3DRenderer;
use strata_render::scene3d::Scene3D;
use strata_render::{
    GpuBatchSummary, GpuStencilClipPipeline, Hardware2DFrame, HardwareRenderItem,
    UnifiedGpuCollector, Wgpu2DRenderer,
};

#[inline]
fn surface_perf_logging_enabled() -> bool {
    static ENABLED: std::sync::OnceLock<bool> = std::sync::OnceLock::new();
    *ENABLED.get_or_init(|| std::env::var_os("STRATA_PERF_LOG").is_some())
}

/// Maps platform [`PresentMode`] to the best supported [`wgpu::PresentMode`].
pub fn select_wgpu_present_mode(
    desired: PresentMode,
    caps: &wgpu::SurfaceCapabilities,
) -> wgpu::PresentMode {
    let has = |m: wgpu::PresentMode| caps.present_modes.contains(&m);
    match desired {
        PresentMode::Immediate => {
            if has(wgpu::PresentMode::Immediate) {
                wgpu::PresentMode::Immediate
            } else if has(wgpu::PresentMode::AutoNoVsync) {
                wgpu::PresentMode::AutoNoVsync
            } else if has(wgpu::PresentMode::Mailbox) {
                wgpu::PresentMode::Mailbox
            } else if has(wgpu::PresentMode::FifoRelaxed) {
                wgpu::PresentMode::FifoRelaxed
            } else {
                wgpu::PresentMode::Fifo
            }
        }
        PresentMode::Mailbox => {
            if has(wgpu::PresentMode::Mailbox) {
                wgpu::PresentMode::Mailbox
            } else if has(wgpu::PresentMode::Immediate) {
                wgpu::PresentMode::Immediate
            } else if has(wgpu::PresentMode::AutoNoVsync) {
                wgpu::PresentMode::AutoNoVsync
            } else {
                wgpu::PresentMode::Fifo
            }
        }
        PresentMode::FifoRelaxed => {
            if has(wgpu::PresentMode::FifoRelaxed) {
                wgpu::PresentMode::FifoRelaxed
            } else {
                wgpu::PresentMode::Fifo
            }
        }
        PresentMode::Fifo => wgpu::PresentMode::Fifo,
    }
}

struct CachedOverlayTexture {
    width: u32,
    height: u32,
    texture: wgpu::Texture,
    bind_group: wgpu::BindGroup,
}

struct DisplayOffscreenTarget {
    width: u32,
    height: u32,
    format: wgpu::TextureFormat,
    color: wgpu::Texture,
    view: wgpu::TextureView,
    readback: wgpu::Buffer,
    padded_bytes_per_row: u32,
}

/// Hardware `wgpu` window surface presenter managing 3D rendering, hardware 2D/stencil-clip
/// [`Wgpu2DRenderer`] batches, and cached 2D HUD compositing.
pub struct WgpuWindowPresenter {
    _instance: wgpu::Instance,
    surface: Option<wgpu::Surface<'static>>,
    surface_config: Option<wgpu::SurfaceConfiguration>,
    renderer: Wgpu3DRenderer,
    renderer_2d: Wgpu2DRenderer,
    collector: UnifiedGpuCollector,
    last_batch_summary: GpuBatchSummary,
    present_mode: PresentMode,
    ui_overlay: Option<CachedOverlayTexture>,
    display_offscreen: Option<DisplayOffscreenTarget>,
}

impl WgpuWindowPresenter {
    /// Creates an offscreen-capable `WgpuWindowPresenter` with BGRA8 pixel format matching Cairo.
    pub fn new_offscreen(present_mode: PresentMode) -> Result<Self, String> {
        let instance = wgpu::Instance::default();
        let (_adapter, device, queue) = strata_render::gpu_wgpu::request_working_adapter_and_device(
            &instance,
            None,
            "strata_platform_wgpu_device",
        )?;

        let dev_arc = Arc::new(device);
        let queue_arc = Arc::new(queue);
        let format = wgpu::TextureFormat::Bgra8Unorm;
        let renderer = Wgpu3DRenderer::from_device(Arc::clone(&dev_arc), Arc::clone(&queue_arc), format);
        let renderer_2d = Wgpu2DRenderer::from_device(dev_arc, queue_arc, format);
        Ok(Self {
            _instance: instance,
            surface: None,
            surface_config: None,
            renderer,
            renderer_2d,
            collector: UnifiedGpuCollector::new(1280.0, 800.0),
            last_batch_summary: GpuBatchSummary::default(),
            present_mode,
            ui_overlay: None,
            display_offscreen: None,
        })
    }

    /// Creates a `WgpuWindowPresenter` bound directly to a native window/display handle pair.
    ///
    /// # Safety
    /// `window_handle` and `display_handle` must remain valid for the lifetime of this presenter.
    pub unsafe fn from_raw_handles(
        window_handle: raw_window_handle::RawWindowHandle,
        display_handle: raw_window_handle::RawDisplayHandle,
        width: u32,
        height: u32,
        present_mode: PresentMode,
    ) -> Result<Self, String> {
        let instance = wgpu::Instance::default();
        let target = wgpu::SurfaceTargetUnsafe::RawHandle {
            raw_display_handle: display_handle,
            raw_window_handle: window_handle,
        };
        let surface = unsafe { instance.create_surface_unsafe(target) }
            .map_err(|e| format!("create_surface_unsafe failed: {e}"))?;

        let (adapter, device, queue) = strata_render::gpu_wgpu::request_working_adapter_and_device(
            &instance,
            Some(&surface),
            "strata_platform_surface_device",
        )?;

        let caps = surface.get_capabilities(&adapter);
        if surface_perf_logging_enabled() {
            let info = adapter.get_info();
            eprintln!(
                "[perf] wgpu adapter: {} ({:?}/{:?}), caps present_modes={:?}",
                info.name, info.backend, info.device_type, caps.present_modes
            );
        }
        let format = caps
            .formats
            .iter()
            .copied()
            .find(|f| {
                matches!(
                    f,
                    wgpu::TextureFormat::Bgra8Unorm | wgpu::TextureFormat::Rgba8Unorm
                )
            })
            .unwrap_or_else(|| caps.formats[0]);
        let selected_mode = select_wgpu_present_mode(present_mode, &caps);
        let alpha_mode = caps.alpha_modes[0];

        let cfg = wgpu::SurfaceConfiguration {
            usage: wgpu::TextureUsages::RENDER_ATTACHMENT,
            format,
            width: width.max(1),
            height: height.max(1),
            present_mode: selected_mode,
            alpha_mode,
            view_formats: vec![],
            desired_maximum_frame_latency: if selected_mode == wgpu::PresentMode::Mailbox {
                3
            } else {
                2
            },
        };
        surface.configure(&device, &cfg);

        let dev_arc = Arc::new(device);
        let queue_arc = Arc::new(queue);
        let renderer = Wgpu3DRenderer::from_device(Arc::clone(&dev_arc), Arc::clone(&queue_arc), format);
        let renderer_2d = Wgpu2DRenderer::from_device(dev_arc, queue_arc, format);
        Ok(Self {
            _instance: instance,
            surface: Some(surface),
            surface_config: Some(cfg),
            renderer,
            renderer_2d,
            collector: UnifiedGpuCollector::new(width.max(1) as f32, height.max(1) as f32),
            last_batch_summary: GpuBatchSummary::default(),
            present_mode,
            ui_overlay: None,
            display_offscreen: None,
        })
    }

    pub fn renderer_mut(&mut self) -> &mut Wgpu3DRenderer {
        &mut self.renderer
    }

    pub fn renderer_2d(&self) -> &Wgpu2DRenderer {
        &self.renderer_2d
    }

    pub fn renderer_2d_mut(&mut self) -> &mut Wgpu2DRenderer {
        &mut self.renderer_2d
    }

    pub fn batch_collector(&self) -> &UnifiedGpuCollector {
        &self.collector
    }

    pub fn last_batch_summary(&self) -> GpuBatchSummary {
        self.last_batch_summary
    }

    pub fn stencil_clip_pipeline(&self) -> &GpuStencilClipPipeline {
        self.renderer_2d.stencil_clip_pipeline()
    }

    pub fn active_wgpu_present_mode(&self) -> Option<wgpu::PresentMode> {
        self.surface_config.as_ref().map(|c| c.present_mode)
    }

    pub fn surface_size(&self) -> (u32, u32) {
        self.surface_config
            .as_ref()
            .map(|c| (c.width, c.height))
            .unwrap_or((0, 0))
    }

    pub fn has_surface(&self) -> bool {
        self.surface.is_some()
    }

    pub fn resize(&mut self, width: u32, height: u32) {
        let w = width.max(1);
        let h = height.max(1);
        if let (Some(surface), Some(cfg)) = (&self.surface, &mut self.surface_config) {
            if cfg.width == w && cfg.height == h {
                return;
            }
            cfg.width = w;
            cfg.height = h;
            surface.configure(self.renderer.device(), cfg);
        }
    }

    /// Uploads a new cached 2D UI HUD overlay (BGRA8 pixels matching Cairo `ARgb32`).
    ///
    /// Called only when 2D layout/DOM `paint_dirty` repaints; unchanged camera-only 3D frames
    /// reuse this GPU texture with zero CPU work.
    pub fn upload_ui_overlay_bgra(&mut self, width: u32, height: u32, bgra: &[u8]) {
        let w = width.max(1);
        let h = height.max(1);
        if bgra.len() < (w * h * 4) as usize {
            return;
        }
        let recreate = self
            .ui_overlay
            .as_ref()
            .map(|o| o.width != w || o.height != h)
            .unwrap_or(true);
        if recreate {
            let tex = self
                .renderer
                .device()
                .create_texture(&wgpu::TextureDescriptor {
                    label: Some("strata_2d_ui_overlay_bgra"),
                    size: wgpu::Extent3d {
                        width: w,
                        height: h,
                        depth_or_array_layers: 1,
                    },
                    mip_level_count: 1,
                    sample_count: 1,
                    dimension: wgpu::TextureDimension::D2,
                    format: wgpu::TextureFormat::Bgra8Unorm,
                    usage: wgpu::TextureUsages::TEXTURE_BINDING | wgpu::TextureUsages::COPY_DST,
                    view_formats: &[],
                });
            let view = tex.create_view(&Default::default());
            let bind_group = self.renderer.create_overlay_bind_group(&view);
            self.ui_overlay = Some(CachedOverlayTexture {
                width: w,
                height: h,
                texture: tex,
                bind_group,
            });
        }
        if let Some(ref ov) = self.ui_overlay {
            self.renderer.queue().write_texture(
                wgpu::TexelCopyTextureInfo {
                    texture: &ov.texture,
                    mip_level: 0,
                    origin: wgpu::Origin3d::ZERO,
                    aspect: wgpu::TextureAspect::All,
                },
                &bgra[..(w * h * 4) as usize],
                wgpu::TexelCopyBufferLayout {
                    offset: 0,
                    bytes_per_row: Some(w * 4),
                    rows_per_image: Some(h),
                },
                wgpu::Extent3d {
                    width: w,
                    height: h,
                    depth_or_array_layers: 1,
                },
            );
        }
    }

    /// Uploads only damaged sub-rectangles of the 2D UI HUD overlay texture, avoiding full-frame
    /// 8 MB CPU-to-GPU transfers when only small labels or HUD counters changed.
    #[allow(clippy::too_many_arguments)]
    pub fn upload_ui_overlay_bgra_rects(
        &mut self,
        width: u32,
        height: u32,
        stride: usize,
        bgra: &[u8],
        rects: &[(u32, u32, u32, u32)],
        scratch: &mut Vec<u8>,
    ) {
        let w = width.max(1);
        let h = height.max(1);
        if stride < (w as usize) * 4 || bgra.len() < stride * (h as usize) {
            return;
        }
        let recreate = self
            .ui_overlay
            .as_ref()
            .map(|o| o.width != w || o.height != h)
            .unwrap_or(true);
        if recreate {
            if stride == (w as usize) * 4 {
                self.upload_ui_overlay_bgra(w, h, bgra);
            } else {
                scratch.resize((w * h * 4) as usize, 0);
                let row_bytes = (w as usize) * 4;
                for row in 0..(h as usize) {
                    scratch[row * row_bytes..(row + 1) * row_bytes]
                        .copy_from_slice(&bgra[row * stride..row * stride + row_bytes]);
                }
                self.upload_ui_overlay_bgra(w, h, scratch);
            }
            return;
        }
        let Some(ref ov) = self.ui_overlay else {
            return;
        };
        let queue = self.renderer.queue();
        for &(rx, ry, rw, rh) in rects {
            if rx >= w || ry >= h || rw == 0 || rh == 0 {
                continue;
            }
            let cw = rw.min(w - rx);
            let ch = rh.min(h - ry);
            let row_bytes = (cw as usize) * 4;
            let total_bytes = row_bytes * (ch as usize);
            scratch.resize(total_bytes, 0);
            for r in 0..(ch as usize) {
                let src_off = ((ry as usize) + r) * stride + (rx as usize) * 4;
                let dst_off = r * row_bytes;
                scratch[dst_off..dst_off + row_bytes]
                    .copy_from_slice(&bgra[src_off..src_off + row_bytes]);
            }
            queue.write_texture(
                wgpu::TexelCopyTextureInfo {
                    texture: &ov.texture,
                    mip_level: 0,
                    origin: wgpu::Origin3d { x: rx, y: ry, z: 0 },
                    aspect: wgpu::TextureAspect::All,
                },
                &scratch[..total_bytes],
                wgpu::TexelCopyBufferLayout {
                    offset: 0,
                    bytes_per_row: Some(cw * 4),
                    rows_per_image: Some(ch),
                },
                wgpu::Extent3d {
                    width: cw,
                    height: ch,
                    depth_or_array_layers: 1,
                },
            );
        }
    }

    /// Presents `scene` directly to the swapchain surface and composites cached 2D UI overlay if enabled.
    pub fn present_to_surface(
        &mut self,
        scene: &Scene3D,
        viewport: Option<[f32; 4]>,
        draw_overlay: bool,
    ) -> Result<(), String> {
        let vp = viewport.unwrap_or_else(|| {
            let (w, h) = self
                .surface_config
                .as_ref()
                .map(|c| (c.width as f32, c.height as f32))
                .unwrap_or((1.0, 1.0));
            [0.0, 0.0, w, h]
        });
        self.present_viewports_to_surface(&[(vp, scene)], draw_overlay)
    }

    /// Presents one or more 3D viewports directly into the single swapchain frame and composites
    /// the cached 2D UI overlay once on top before presenting.
    pub fn present_viewports_to_surface(
        &mut self,
        viewports: &[([f32; 4], &Scene3D)],
        draw_overlay: bool,
    ) -> Result<(), String> {
        if viewports.is_empty() {
            return Err("no 3D viewports to present".to_string());
        }
        let Some(ref surface) = self.surface else {
            return Err("no active wgpu swapchain surface".to_string());
        };
        let Some(ref cfg) = self.surface_config else {
            return Err("surface not configured".to_string());
        };
        let perf = surface_perf_logging_enabled();
        let t0 = std::time::Instant::now();
        let output = match surface.get_current_texture() {
            Ok(frame) => frame,
            Err(wgpu::SurfaceError::Outdated | wgpu::SurfaceError::Lost) => {
                surface.configure(self.renderer.device(), cfg);
                surface
                    .get_current_texture()
                    .map_err(|e| format!("acquire surface texture failed: {e}"))?
            }
            Err(e) => return Err(format!("acquire surface texture failed: {e}")),
        };
        let t_acq = std::time::Instant::now();
        let view = output.texture.create_view(&Default::default());
        let ov_bg = if draw_overlay {
            self.ui_overlay.as_ref().map(|ov| &ov.bind_group)
        } else {
            None
        };
        if viewports.len() == 1 {
            let (vp, scene) = viewports[0];
            self.renderer.render_scene_and_overlay_to_view(
                scene,
                &view,
                cfg.width,
                cfg.height,
                Some(vp),
                false,
                ov_bg,
            );
        } else {
            self.renderer.render_viewports_and_overlay_to_view(
                viewports,
                &view,
                cfg.width,
                cfg.height,
                false,
                ov_bg,
            );
        }
        let t_3d = std::time::Instant::now();
        let t_ov = t_3d;
        output.present();
        let t_end = std::time::Instant::now();
        if perf {
            let acq_ms = t_acq.duration_since(t0).as_secs_f64() * 1000.0;
            let r3d_ms = t_3d.duration_since(t_acq).as_secs_f64() * 1000.0;
            let pres_ms = t_end.duration_since(t_ov).as_secs_f64() * 1000.0;
            let total_ms = t_end.duration_since(t0).as_secs_f64() * 1000.0;
            thread_local! {
                static WIN_STATS: std::cell::Cell<(u32, f64, f64, f64, f64, f64, f64)> =
                    const { std::cell::Cell::new((0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0)) };
            }
            WIN_STATS.with(|c| {
                let (n, sum_a, max_a, sum_r, max_r, sum_p, max_p) = c.get();
                let next = (
                    n + 1,
                    sum_a + acq_ms,
                    max_a.max(acq_ms),
                    sum_r + r3d_ms,
                    max_r.max(r3d_ms),
                    sum_p + pres_ms,
                    max_p.max(pres_ms),
                );
                if next.0 >= 65 {
                    let nf = next.0 as f64;
                    eprintln!(
                        "[perf] present65 acq_avg={:.2} max={:.2} | r3d_avg={:.2} max={:.2} | pres_avg={:.2} max={:.2}",
                        next.1 / nf, next.2, next.3 / nf, next.4, next.5 / nf, next.6
                    );
                    c.set((0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0));
                } else {
                    c.set(next);
                }
            });
            if total_ms > 7.5 {
                eprintln!(
                    "[perf] present_to_surface SPIKE total={:.2}ms (acq={:.2} render3d={:.2} present={:.2})",
                    total_ms, acq_ms, r3d_ms, pres_ms
                );
            }
        }
        Ok(())
    }

    #[allow(clippy::too_many_arguments)]
    fn render_hybrid_frame_to_view(
        &mut self,
        frame: &Hardware2DFrame,
        target_view: &wgpu::TextureView,
        target_w: u32,
        target_h: u32,
        logical_w: f32,
        logical_h: f32,
        dpr: f32,
        clear_color: [f32; 4],
        damage: Option<Rect>,
    ) {
        self.renderer_2d
            .prepare_frame(frame, logical_w, logical_h, dpr);

        let sx = target_w as f32 / logical_w.max(1.0);
        let sy = target_h as f32 / logical_h.max(1.0);
        let mut has_drawn = false;
        let mut idx = 0usize;
        let n = frame.items.len();

        while idx < n {
            match &frame.items[idx] {
                HardwareRenderItem::Batch(_) => {
                    let start = idx;
                    while idx < n && matches!(frame.items[idx], HardwareRenderItem::Batch(_)) {
                        idx += 1;
                    }
                    let clear = if !has_drawn { Some(clear_color) } else { None };
                    self.renderer_2d.render_batch_slice_to_view(
                        frame,
                        start..idx,
                        target_view,
                        target_w,
                        target_h,
                        logical_w,
                        logical_h,
                        clear,
                        damage,
                    );
                    has_drawn = true;
                }
                HardwareRenderItem::Viewport3D { bounds, scene } => {
                    let vp = [
                        bounds.x * sx,
                        bounds.y * sy,
                        bounds.width * sx,
                        bounds.height * sy,
                    ];
                    if !has_drawn {
                        self.renderer.render_scene_and_overlay_to_view(
                            scene,
                            target_view,
                            target_w,
                            target_h,
                            Some(vp),
                            false,
                            None,
                        );
                    } else {
                        self.renderer.render_scene_preserving_color_to_view(
                            scene,
                            target_view,
                            target_w,
                            target_h,
                            Some(vp),
                            false,
                        );
                    }
                    has_drawn = true;
                    idx += 1;
                }
            }
        }

        if !has_drawn {
            self.renderer_2d.render_batch_slice_to_view(
                frame,
                0..0,
                target_view,
                target_w,
                target_h,
                logical_w,
                logical_h,
                Some(clear_color),
                damage,
            );
        }
    }

    /// Presents an entire `DisplayList` (2D quads, vector paths with caps/joins, dashed strokes,
    /// Slug text, polygonal [`GpuStencilClipPipeline`] masks, and any interleaved `DrawViewport3D`)
    /// directly onto the hardware `wgpu::Surface` swapchain via [`UnifiedGpuCollector`] + [`Wgpu2DRenderer`].
    pub fn present_display_list_to_surface(
        &mut self,
        list: &DisplayList,
        logical_width: f32,
        logical_height: f32,
        dpr: f32,
        damage: Option<Rect>,
        clear_color: [f32; 4],
    ) -> Result<GpuBatchSummary, String> {
        let Some(ref surface) = self.surface else {
            return Err("no active wgpu swapchain surface".to_string());
        };
        let Some(ref cfg) = self.surface_config else {
            return Err("surface not configured".to_string());
        };
        let target_w = cfg.width;
        let target_h = cfg.height;

        let lw = logical_width.max(1.0);
        let lh = logical_height.max(1.0);
        self.collector.resize(lw, lh);
        let frame = self.collector.collect_hardware_frame(list, damage);
        self.last_batch_summary = frame.summary;

        let output = match surface.get_current_texture() {
            Ok(frame_tex) => frame_tex,
            Err(wgpu::SurfaceError::Outdated | wgpu::SurfaceError::Lost) => {
                surface.configure(self.renderer.device(), cfg);
                surface
                    .get_current_texture()
                    .map_err(|e| format!("acquire surface texture failed: {e}"))?
            }
            Err(e) => return Err(format!("acquire surface texture failed: {e}")),
        };
        let view = output.texture.create_view(&Default::default());
        self.render_hybrid_frame_to_view(
            &frame,
            &view,
            target_w,
            target_h,
            lw,
            lh,
            dpr,
            clear_color,
            damage,
        );
        output.present();
        Ok(frame.summary)
    }

    /// Presents the cached `ui_overlay` texture directly onto the swapchain surface.
    pub fn present_overlay_to_surface(&mut self, clear_color: [f32; 4]) -> Result<(), String> {
        let Some(ref surface) = self.surface else {
            return Err("no active wgpu swapchain surface".to_string());
        };
        let Some(ref cfg) = self.surface_config else {
            return Err("surface not configured".to_string());
        };
        let output = match surface.get_current_texture() {
            Ok(frame_tex) => frame_tex,
            Err(wgpu::SurfaceError::Outdated | wgpu::SurfaceError::Lost) => {
                surface.configure(self.renderer.device(), cfg);
                surface
                    .get_current_texture()
                    .map_err(|e| format!("acquire surface texture failed: {e}"))?
            }
            Err(e) => return Err(format!("acquire surface texture failed: {e}")),
        };
        let view = output.texture.create_view(&Default::default());
        let empty = Hardware2DFrame::default();
        self.renderer_2d.render_batch_slice_to_view(
            &empty,
            0..0,
            &view,
            cfg.width,
            cfg.height,
            cfg.width.max(1) as f32,
            cfg.height.max(1) as f32,
            Some(clear_color),
            None,
        );
        if let Some(ref ov) = self.ui_overlay {
            self.renderer
                .composite_overlay_to_view(&view, &ov.bind_group);
        }
        output.present();
        Ok(())
    }

    /// Renders a `DisplayList` (pure 2D or hybrid 3D+2D) via [`UnifiedGpuCollector`],
    /// [`GpuStencilClipPipeline`], and [`Wgpu2DRenderer`] into an offscreen BGRA8 target,
    /// returning raw BGRA8 pixels when `readback` is `true`.
    #[allow(clippy::too_many_arguments)]
    pub fn render_display_list_offscreen_bgra(
        &mut self,
        list: &DisplayList,
        width: u32,
        height: u32,
        dpr: f32,
        damage: Option<Rect>,
        clear_color: [f32; 4],
        readback: bool,
    ) -> Result<(GpuBatchSummary, Vec<u8>), String> {
        let w = width.max(1);
        let h = height.max(1);
        let lw = w as f32 / dpr.max(0.1);
        let lh = h as f32 / dpr.max(0.1);
        self.collector.resize(lw, lh);
        let frame = self.collector.collect_hardware_frame(list, damage);
        self.last_batch_summary = frame.summary;

        let has_3d = frame
            .items
            .iter()
            .any(|it| matches!(it, HardwareRenderItem::Viewport3D { .. }));
        if !has_3d {
            return self.renderer_2d.render_display_list_offscreen(
                &mut self.collector,
                list,
                w,
                h,
                dpr,
                clear_color,
                damage,
                readback,
            );
        }

        let align = wgpu::COPY_BYTES_PER_ROW_ALIGNMENT;
        let unpadded = w * 4;
        let padded = unpadded.div_ceil(align) * align;
        let format = self.renderer_2d.color_format();
        let recreate = self
            .display_offscreen
            .as_ref()
            .is_none_or(|o| o.width != w || o.height != h || o.format != format);
        if recreate {
            let dev = self.renderer_2d.device();
            let color = dev.create_texture(&wgpu::TextureDescriptor {
                label: Some("strata_hybrid_offscreen_color"),
                size: wgpu::Extent3d {
                    width: w,
                    height: h,
                    depth_or_array_layers: 1,
                },
                mip_level_count: 1,
                sample_count: 1,
                dimension: wgpu::TextureDimension::D2,
                format,
                usage: wgpu::TextureUsages::RENDER_ATTACHMENT | wgpu::TextureUsages::COPY_SRC,
                view_formats: &[],
            });
            let view = color.create_view(&Default::default());
            let rb = dev.create_buffer(&wgpu::BufferDescriptor {
                label: Some("strata_hybrid_offscreen_readback"),
                size: (padded * h) as u64,
                usage: wgpu::BufferUsages::COPY_DST | wgpu::BufferUsages::MAP_READ,
                mapped_at_creation: false,
            });
            self.display_offscreen = Some(DisplayOffscreenTarget {
                width: w,
                height: h,
                format,
                color,
                view,
                readback: rb,
                padded_bytes_per_row: padded,
            });
        }

        let target_view = self.display_offscreen.as_ref().unwrap().view.clone();
        self.render_hybrid_frame_to_view(
            &frame,
            &target_view,
            w,
            h,
            lw,
            lh,
            dpr,
            clear_color,
            damage,
        );

        let dev = self.renderer_2d.device();
        if !readback {
            dev.poll(wgpu::Maintain::Wait);
            return Ok((frame.summary, Vec::new()));
        }

        let off = self.display_offscreen.as_ref().unwrap();
        let mut enc = dev.create_command_encoder(&wgpu::CommandEncoderDescriptor {
            label: Some("strata_hybrid_readback_encoder"),
        });
        enc.copy_texture_to_buffer(
            wgpu::TexelCopyTextureInfo {
                texture: &off.color,
                mip_level: 0,
                origin: wgpu::Origin3d::ZERO,
                aspect: wgpu::TextureAspect::All,
            },
            wgpu::TexelCopyBufferInfo {
                buffer: &off.readback,
                layout: wgpu::TexelCopyBufferLayout {
                    offset: 0,
                    bytes_per_row: Some(off.padded_bytes_per_row),
                    rows_per_image: Some(h),
                },
            },
            wgpu::Extent3d {
                width: w,
                height: h,
                depth_or_array_layers: 1,
            },
        );
        self.renderer_2d.queue().submit(Some(enc.finish()));

        let slice = off.readback.slice(..);
        let (tx, rx) = std::sync::mpsc::channel();
        slice.map_async(wgpu::MapMode::Read, move |res| {
            let _ = tx.send(res);
        });
        dev.poll(wgpu::Maintain::Wait);
        rx.recv()
            .map_err(|e| format!("hybrid readback recv error: {e}"))?
            .map_err(|e| format!("hybrid readback map error: {e:?}"))?;

        let data = slice.get_mapped_range();
        let mut out = vec![0u8; (w * h * 4) as usize];
        let row_len = w as usize * 4;
        for row in 0..h as usize {
            let src_start = row * off.padded_bytes_per_row as usize;
            let dst_start = row * row_len;
            out[dst_start..dst_start + row_len]
                .copy_from_slice(&data[src_start..src_start + row_len]);
        }
        drop(data);
        off.readback.unmap();
        Ok((frame.summary, out))
    }

    /// Offscreen render returning BGRA8 pixels (or empty vec if `readback == false`).
    pub fn render_offscreen_bgra(
        &mut self,
        scene: &Scene3D,
        width: u32,
        height: u32,
        readback: bool,
    ) -> Result<Vec<u8>, String> {
        self.renderer
            .render_offscreen(scene, width, height, readback, true)
    }

    pub fn present_mode(&self) -> PresentMode {
        self.present_mode
    }
}

/// Hardware `wgpu` Swapchain Presenter wiring [`UnifiedGpuCollector`],
/// [`GpuStencilClipPipeline`], and [`Wgpu2DRenderer`] into `strata_platform`'s swapchain layer.
pub struct WgpuSwapchainPresenter {
    config: SurfaceConfig,
    presenter: WgpuWindowPresenter,
    pub presented_frames: u64,
    pub damage_clipped_frames: u64,
    upload_scratch: Vec<u8>,
}

impl WgpuSwapchainPresenter {
    /// Creates a headless/offscreen hardware GPU swapchain presenter.
    pub fn new_offscreen(config: SurfaceConfig) -> Result<Self, String> {
        let presenter = WgpuWindowPresenter::new_offscreen(config.present_mode)?;
        Ok(Self {
            config,
            presenter,
            presented_frames: 0,
            damage_clipped_frames: 0,
            upload_scratch: Vec::new(),
        })
    }

    /// Creates a hardware GPU swapchain presenter bound directly to a native window handle pair.
    ///
    /// # Safety
    /// `window_handle` and `display_handle` must remain valid for the lifetime of this presenter.
    pub unsafe fn from_raw_handles(
        window_handle: raw_window_handle::RawWindowHandle,
        display_handle: raw_window_handle::RawDisplayHandle,
        config: SurfaceConfig,
    ) -> Result<Self, String> {
        let (pw, ph) = config.physical_size();
        let presenter = unsafe {
            WgpuWindowPresenter::from_raw_handles(
                window_handle,
                display_handle,
                pw.max(1),
                ph.max(1),
                config.present_mode,
            )?
        };
        Ok(Self {
            config,
            presenter,
            presented_frames: 0,
            damage_clipped_frames: 0,
            upload_scratch: Vec::new(),
        })
    }

    #[inline]
    pub fn config(&self) -> &SurfaceConfig {
        &self.config
    }

    #[inline]
    pub fn presenter(&self) -> &WgpuWindowPresenter {
        &self.presenter
    }

    #[inline]
    pub fn presenter_mut(&mut self) -> &mut WgpuWindowPresenter {
        &mut self.presenter
    }

    #[inline]
    pub fn batch_collector(&self) -> &UnifiedGpuCollector {
        self.presenter.batch_collector()
    }

    #[inline]
    pub fn last_batch_summary(&self) -> GpuBatchSummary {
        self.presenter.last_batch_summary()
    }

    #[inline]
    pub fn stencil_clip_pipeline(&self) -> &GpuStencilClipPipeline {
        self.presenter.stencil_clip_pipeline()
    }

    /// Compiles and presents a `DisplayList` directly via `Wgpu2DRenderer` + `GpuStencilClipPipeline`
    /// onto the configured swapchain (or offscreen target when headless).
    pub fn present_display_list(
        &mut self,
        list: &DisplayList,
        damage: Option<Rect>,
        clear_color: [f32; 4],
    ) -> Result<GpuBatchSummary, PresentError> {
        let (pw, ph) = self.config.physical_size();
        let summary = if self.presenter.has_surface() {
            self.presenter
                .present_display_list_to_surface(
                    list,
                    self.config.width.max(1) as f32,
                    self.config.height.max(1) as f32,
                    self.config.scale_factor,
                    damage,
                    clear_color,
                )
                .map_err(PresentError::Custom)?
        } else {
            let (s, _) = self
                .presenter
                .render_display_list_offscreen_bgra(
                    list,
                    pw.max(1),
                    ph.max(1),
                    self.config.scale_factor,
                    damage,
                    clear_color,
                    false,
                )
                .map_err(PresentError::Custom)?;
            s
        };
        self.presented_frames += 1;
        if damage.is_some() {
            self.damage_clipped_frames += 1;
        }
        Ok(summary)
    }

    /// Renders a `DisplayList` into BGRA8 pixels via the GPU 2D + stencil clip + 3D pipelines.
    pub fn render_display_list_to_bgra(
        &mut self,
        list: &DisplayList,
        damage: Option<Rect>,
        clear_color: [f32; 4],
    ) -> Result<(GpuBatchSummary, Vec<u8>), PresentError> {
        let (pw, ph) = self.config.physical_size();
        let res = self
            .presenter
            .render_display_list_offscreen_bgra(
                list,
                pw.max(1),
                ph.max(1),
                self.config.scale_factor,
                damage,
                clear_color,
                true,
            )
            .map_err(PresentError::Custom)?;
        self.presented_frames += 1;
        if damage.is_some() {
            self.damage_clipped_frames += 1;
        }
        Ok(res)
    }
}

impl SurfacePresenter for WgpuSwapchainPresenter {
    fn present(
        &mut self,
        buffer: &strata_render::FrameBuffer,
        damage: Option<Rect>,
    ) -> Result<(), PresentError> {
        let w = buffer.width as u32;
        let h = buffer.height as u32;
        let expected = buffer.width * buffer.height * 4;
        if buffer.pixels.len() < expected || w == 0 || h == 0 {
            return Err(PresentError::BufferTooSmall);
        }

        // Convert RGBA8 FrameBuffer pixels into BGRA8 matching WgpuWindowPresenter overlay format.
        self.upload_scratch.resize(expected, 0);
        for (dst, src) in self
            .upload_scratch
            .chunks_exact_mut(4)
            .zip(buffer.pixels[..expected].chunks_exact(4))
        {
            dst[0] = src[2];
            dst[1] = src[1];
            dst[2] = src[0];
            dst[3] = src[3];
        }
        self.presenter
            .upload_ui_overlay_bgra(w, h, &self.upload_scratch);
        if self.presenter.has_surface() {
            self.presenter
                .present_overlay_to_surface([0.0, 0.0, 0.0, 1.0])
                .map_err(PresentError::Custom)?;
        }
        self.presented_frames += 1;
        if damage.is_some() {
            self.damage_clipped_frames += 1;
        }
        Ok(())
    }

    fn resize(&mut self, width: u32, height: u32) -> Result<(), PresentError> {
        self.config.width = width.max(1);
        self.config.height = height.max(1);
        let (pw, ph) = self.config.physical_size();
        self.presenter.resize(pw.max(1), ph.max(1));
        Ok(())
    }

    fn surface_size(&self) -> (u32, u32) {
        let (pw, ph) = self.config.physical_size();
        (pw.max(1), ph.max(1))
    }
}

thread_local! {
    static THREAD_WGPU_RENDERER: std::cell::RefCell<Option<Result<WgpuWindowPresenter, String>>> =
        const { std::cell::RefCell::new(None) };
}

/// Renders `scene` into BGRA8 pixels on a cached thread-local `Wgpu3DRenderer`.
///
/// Returns `None` if no wgpu adapter is available in the current environment so callers can
/// transparently fall back to the software `rasterizer3d` path.
pub fn render_scene_3d_wgpu_bgra(scene: &Scene3D, width: u32, height: u32) -> Option<Vec<u8>> {
    THREAD_WGPU_RENDERER.with(|slot| {
        let mut cell = slot.borrow_mut();
        if cell.is_none() {
            *cell = Some(WgpuWindowPresenter::new_offscreen(PresentMode::Fifo));
        }
        let Ok(ref mut presenter) = cell.as_mut().unwrap() else {
            return None;
        };
        presenter
            .render_offscreen_bgra(scene, width.max(1), height.max(1), true)
            .ok()
    })
}