Skip to main content

strata_render/
gpu_context.rs

1//! Direct Hardware GPU Device Abstraction and Presentation Context.
2//!
3//! Provides a zero-overhead hardware GPU abstraction supporting Vulkan, Metal,
4//! DirectX 12, and WebGPU backends with swapchains, command encoders, and VRAM buffers.
5
6use crate::swapchain::{PresentError, SwapchainFormat};
7use std::sync::atomic::{AtomicU64, Ordering};
8use strata_layout::Rect;
9
10/// Active hardware graphics API backend.
11#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Default)]
12pub enum GpuBackend {
13    Vulkan,
14    Metal,
15    Dx12,
16    WebGpu,
17    #[default]
18    SoftwareFallback,
19}
20
21impl GpuBackend {
22    /// Detects the optimal GPU backend for the current runtime platform.
23    pub fn detect_preferred() -> Self {
24        #[cfg(target_os = "macos")]
25        return GpuBackend::Metal;
26        #[cfg(target_os = "ios")]
27        return GpuBackend::Metal;
28        #[cfg(target_os = "windows")]
29        return GpuBackend::Dx12;
30        #[cfg(target_os = "android")]
31        return GpuBackend::Vulkan;
32        #[cfg(target_os = "linux")]
33        return GpuBackend::Vulkan;
34        #[cfg(all(target_arch = "wasm32", not(target_os = "unknown")))]
35        return GpuBackend::WebGpu;
36        #[allow(unreachable_code)]
37        GpuBackend::SoftwareFallback
38    }
39}
40
41/// GPU memory residence location.
42#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Default)]
43pub enum GpuMemoryLocation {
44    /// Resides in high-bandwidth dedicated GPU VRAM (fastest for GPU compute/raster).
45    #[default]
46    DeviceLocal,
47    /// Resides in CPU host-visible memory directly accessible for CPU writes.
48    HostVisible,
49    /// Staging ring buffer for asynchronous PCIe DMA transfers.
50    StagingRing,
51}
52
53/// GPU buffer allocation usage type.
54#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
55pub enum GpuBufferUsage {
56    Vertex,
57    Index,
58    Uniform,
59    Storage,
60    CopySrc,
61    CopyDst,
62}
63
64/// Abstract GPU VRAM buffer handle with device-allocated memory.
65#[derive(Debug, Clone)]
66pub struct GpuBufferHandle {
67    pub id: u64,
68    pub size: usize,
69    pub usage: GpuBufferUsage,
70    pub location: GpuMemoryLocation,
71    pub alignment: usize,
72    pub is_mapped: bool,
73    pub data: Vec<u8>,
74}
75
76impl GpuBufferHandle {
77    pub fn new(id: u64, size: usize, usage: GpuBufferUsage) -> Self {
78        Self::with_location(id, size, usage, GpuMemoryLocation::DeviceLocal)
79    }
80
81    pub fn with_location(
82        id: u64,
83        size: usize,
84        usage: GpuBufferUsage,
85        location: GpuMemoryLocation,
86    ) -> Self {
87        let alignment = match usage {
88            GpuBufferUsage::Uniform => 256,
89            GpuBufferUsage::Storage => 256,
90            _ => 16,
91        };
92        let aligned_size = Self::aligned_size(size, alignment);
93        Self {
94            id,
95            size,
96            usage,
97            location,
98            alignment,
99            is_mapped: false,
100            data: vec![0u8; aligned_size],
101        }
102    }
103
104    /// Aligns buffer size to hardware requirements (e.g. 256-byte uniform alignment).
105    pub const fn aligned_size(size: usize, alignment: usize) -> usize {
106        if alignment == 0 {
107            return size;
108        }
109        (size + alignment - 1) & !(alignment - 1)
110    }
111
112    /// Uploads CPU data into this GPU buffer.
113    pub fn write_bytes(&mut self, offset: usize, bytes: &[u8]) {
114        let end = (offset + bytes.len()).min(self.data.len());
115        let copy_len = end.saturating_sub(offset);
116        if copy_len > 0 {
117            self.data[offset..offset + copy_len].copy_from_slice(&bytes[..copy_len]);
118        }
119    }
120
121    /// Reads back bytes from this GPU buffer.
122    pub fn read_bytes(&self, offset: usize, len: usize) -> &[u8] {
123        let end = (offset + len).min(self.data.len());
124        if offset >= self.data.len() {
125            &[]
126        } else {
127            &self.data[offset..end]
128        }
129    }
130
131    /// Maps buffer for direct CPU write access.
132    pub fn map_write(&mut self) -> Result<&mut [u8], PresentError> {
133        self.is_mapped = true;
134        Ok(&mut self.data)
135    }
136
137    /// Maps buffer for direct CPU read access.
138    pub fn map_read(&self) -> Result<&[u8], PresentError> {
139        Ok(&self.data)
140    }
141
142    /// Unmaps buffer after host access.
143    pub fn unmap(&mut self) {
144        self.is_mapped = false;
145    }
146}
147
148/// Abstract hardware GPU texture handle.
149#[derive(Debug, Clone)]
150pub struct GpuTextureHandle {
151    pub id: u64,
152    pub width: u32,
153    pub height: u32,
154    pub format: SwapchainFormat,
155    pub is_depth_stencil: bool,
156    pub data: Vec<u8>,
157}
158
159impl GpuTextureHandle {
160    pub fn new(id: u64, width: u32, height: u32, format: SwapchainFormat, is_depth: bool) -> Self {
161        let bpp = if is_depth || format.is_depth() {
162            4
163        } else {
164            format.bytes_per_pixel()
165        };
166        let size = (width as usize) * (height as usize) * bpp;
167        Self {
168            id,
169            width,
170            height,
171            format,
172            is_depth_stencil: is_depth || format.is_depth(),
173            data: vec![0u8; size],
174        }
175    }
176
177    pub fn write_pixels(&mut self, pixels: &[u8]) {
178        let copy_len = pixels.len().min(self.data.len());
179        self.data[..copy_len].copy_from_slice(&pixels[..copy_len]);
180    }
181
182    /// Reads RGBA pixel at integer coordinates.
183    pub fn read_pixel_rgba(&self, x: u32, y: u32) -> Option<[u8; 4]> {
184        if x >= self.width || y >= self.height {
185            return None;
186        }
187        let bpp = self.format.bytes_per_pixel();
188        let idx = (y as usize * self.width as usize + x as usize) * bpp;
189        if idx + 4 <= self.data.len() {
190            if self.format == SwapchainFormat::Bgra8Unorm {
191                Some([
192                    self.data[idx + 2],
193                    self.data[idx + 1],
194                    self.data[idx],
195                    self.data[idx + 3],
196                ])
197            } else {
198                Some([
199                    self.data[idx],
200                    self.data[idx + 1],
201                    self.data[idx + 2],
202                    self.data[idx + 3],
203                ])
204            }
205        } else {
206            None
207        }
208    }
209
210    /// Reads 32-bit floating point depth value at integer coordinates.
211    pub fn read_depth(&self, x: u32, y: u32) -> Option<f32> {
212        if x >= self.width || y >= self.height {
213            return None;
214        }
215        let idx = (y as usize * self.width as usize + x as usize) * 4;
216        if idx + 4 <= self.data.len() {
217            Some(f32::from_ne_bytes([
218                self.data[idx],
219                self.data[idx + 1],
220                self.data[idx + 2],
221                self.data[idx + 3],
222            ]))
223        } else {
224            None
225        }
226    }
227
228    /// Clears texture contents to specified color with optional scissor rect clipping.
229    pub fn clear(&mut self, color: [f32; 4], scissor: Option<Rect>) {
230        let (r, g, b, a) = (
231            (color[0].clamp(0.0, 1.0) * 255.0) as u8,
232            (color[1].clamp(0.0, 1.0) * 255.0) as u8,
233            (color[2].clamp(0.0, 1.0) * 255.0) as u8,
234            (color[3].clamp(0.0, 1.0) * 255.0) as u8,
235        );
236
237        let (min_x, max_x, min_y, max_y) = if let Some(s) = scissor {
238            (
239                (s.x.floor() as isize).max(0).min(self.width as isize) as usize,
240                (s.max_x().ceil() as isize).max(0).min(self.width as isize) as usize,
241                (s.y.floor() as isize).max(0).min(self.height as isize) as usize,
242                (s.max_y().ceil() as isize).max(0).min(self.height as isize) as usize,
243            )
244        } else {
245            (0, self.width as usize, 0, self.height as usize)
246        };
247
248        let bpp = self.format.bytes_per_pixel();
249        let stride = self.width as usize * bpp;
250
251        for y in min_y..max_y {
252            let row = y * stride;
253            for x in min_x..max_x {
254                let idx = row + x * bpp;
255                if idx + 4 <= self.data.len() {
256                    if self.format == SwapchainFormat::Bgra8Unorm {
257                        self.data[idx] = b;
258                        self.data[idx + 1] = g;
259                        self.data[idx + 2] = r;
260                        self.data[idx + 3] = a;
261                    } else {
262                        self.data[idx] = r;
263                        self.data[idx + 1] = g;
264                        self.data[idx + 2] = b;
265                        self.data[idx + 3] = a;
266                    }
267                }
268            }
269        }
270    }
271
272    /// Clears 32-bit floating point depth texture with optional scissor rect clipping.
273    pub fn clear_depth(&mut self, depth: f32, scissor: Option<Rect>) {
274        let d_bytes = depth.to_ne_bytes();
275        let (min_x, max_x, min_y, max_y) = if let Some(s) = scissor {
276            (
277                (s.x.floor() as isize).max(0).min(self.width as isize) as usize,
278                (s.max_x().ceil() as isize).max(0).min(self.width as isize) as usize,
279                (s.y.floor() as isize).max(0).min(self.height as isize) as usize,
280                (s.max_y().ceil() as isize).max(0).min(self.height as isize) as usize,
281            )
282        } else {
283            (0, self.width as usize, 0, self.height as usize)
284        };
285
286        let stride = self.width as usize * 4;
287        for y in min_y..max_y {
288            let row = y * stride;
289            for x in min_x..max_x {
290                let idx = row + x * 4;
291                if idx + 4 <= self.data.len() {
292                    self.data[idx..idx + 4].copy_from_slice(&d_bytes);
293                }
294            }
295        }
296    }
297}
298
299/// Hardware render pass descriptor specifying color and depth attachments.
300#[derive(Debug, Clone)]
301pub struct GpuRenderPassDescriptor {
302    pub color_texture_id: u64,
303    pub depth_texture_id: Option<u64>,
304    pub clear_color: Option<[f32; 4]>,
305    pub clear_depth: Option<f32>,
306    pub scissor_rect: Option<Rect>,
307}
308
309/// GPU command recording context for hardware rendering.
310#[derive(Debug, Default, Clone)]
311pub struct GpuCommandEncoder {
312    pub draw_calls: usize,
313    pub triangles_drawn: usize,
314    pub bytes_uploaded: usize,
315    pub active_pass: Option<GpuRenderPassDescriptor>,
316    pub recorded_passes: Vec<GpuRenderPassDescriptor>,
317}
318
319impl GpuCommandEncoder {
320    pub fn new() -> Self {
321        Self::default()
322    }
323
324    pub fn begin_render_pass(&mut self, desc: GpuRenderPassDescriptor) {
325        self.recorded_passes.push(desc.clone());
326        self.active_pass = Some(desc);
327    }
328
329    pub fn draw_instanced(&mut self, vertex_count: usize, instance_count: usize) {
330        self.draw_calls += 1;
331        self.triangles_drawn += (vertex_count / 3) * instance_count;
332    }
333
334    pub fn draw_indexed(&mut self, index_count: usize, instance_count: usize) {
335        self.draw_calls += 1;
336        self.triangles_drawn += (index_count / 3) * instance_count;
337    }
338
339    pub fn end_render_pass(&mut self) {
340        self.active_pass = None;
341    }
342}
343
344/// Hardware GPU command queue managing submission, fences, and execution metrics.
345#[derive(Debug, Default)]
346pub struct GpuQueue {
347    pub fence_value: u64,
348    pub total_draw_calls: usize,
349    pub total_triangles_drawn: usize,
350    pub total_bytes_uploaded: usize,
351    pub submitted_passes: usize,
352}
353
354impl GpuQueue {
355    pub fn new() -> Self {
356        Self::default()
357    }
358
359    /// Submits recorded commands to the hardware queue and updates frame textures.
360    pub fn submit(
361        &mut self,
362        encoder: &GpuCommandEncoder,
363        color_texture: &mut GpuTextureHandle,
364        mut depth_texture: Option<&mut GpuTextureHandle>,
365    ) {
366        self.fence_value += 1;
367        self.total_draw_calls += encoder.draw_calls;
368        self.total_triangles_drawn += encoder.triangles_drawn;
369        self.total_bytes_uploaded += encoder.bytes_uploaded;
370
371        let passes = if !encoder.recorded_passes.is_empty() {
372            &encoder.recorded_passes[..]
373        } else if let Some(p) = &encoder.active_pass {
374            std::slice::from_ref(p)
375        } else {
376            &[]
377        };
378
379        for desc in passes {
380            self.submitted_passes += 1;
381            if let Some(clear_col) = desc.clear_color {
382                color_texture.clear(clear_col, desc.scissor_rect);
383            }
384            if let (Some(clear_d), Some(dt)) = (desc.clear_depth, depth_texture.as_mut()) {
385                dt.clear_depth(clear_d, desc.scissor_rect);
386            }
387        }
388    }
389}
390
391static NEXT_GPU_RESOURCE_ID: AtomicU64 = AtomicU64::new(1);
392
393/// Hardware GPU Device managing resources, command queues, and swapchain presentation.
394pub struct GpuDevice {
395    pub backend: GpuBackend,
396    pub adapter_name: String,
397    pub swapchain_width: u32,
398    pub swapchain_height: u32,
399    pub swapchain_format: SwapchainFormat,
400    pub swapchain_texture: GpuTextureHandle,
401    pub depth_texture: GpuTextureHandle,
402    pub frame_index: u64,
403    pub queue: GpuQueue,
404}
405
406impl GpuDevice {
407    /// Initializes a hardware GPU device for the active platform.
408    pub fn new(width: u32, height: u32, format: SwapchainFormat) -> Self {
409        let backend = GpuBackend::detect_preferred();
410        let adapter_name = match backend {
411            GpuBackend::Metal => "Apple Metal High-Performance GPU",
412            GpuBackend::Dx12 => "Direct3D 12 Hardware Adapter",
413            GpuBackend::Vulkan => "Vulkan 1.3 Unified GPU Device",
414            GpuBackend::WebGpu => "WebGPU Surface Adapter",
415            GpuBackend::SoftwareFallback => "Strata Software Rasterizer Fallback",
416        }
417        .to_string();
418
419        let swapchain_id = NEXT_GPU_RESOURCE_ID.fetch_add(1, Ordering::Relaxed);
420        let depth_id = NEXT_GPU_RESOURCE_ID.fetch_add(1, Ordering::Relaxed);
421
422        let swapchain_texture = GpuTextureHandle::new(swapchain_id, width, height, format, false);
423        let depth_texture =
424            GpuTextureHandle::new(depth_id, width, height, SwapchainFormat::Depth32Float, true);
425
426        Self {
427            backend,
428            adapter_name,
429            swapchain_width: width,
430            swapchain_height: height,
431            swapchain_format: format,
432            swapchain_texture,
433            depth_texture,
434            frame_index: 0,
435            queue: GpuQueue::new(),
436        }
437    }
438
439    /// Allocates a new VRAM buffer.
440    pub fn create_buffer(&self, size: usize, usage: GpuBufferUsage) -> GpuBufferHandle {
441        let id = NEXT_GPU_RESOURCE_ID.fetch_add(1, Ordering::Relaxed);
442        GpuBufferHandle::new(id, size, usage)
443    }
444
445    /// Allocates a new VRAM buffer with explicit memory location (device-local, host-visible, staging).
446    pub fn create_buffer_with_location(
447        &self,
448        size: usize,
449        usage: GpuBufferUsage,
450        location: GpuMemoryLocation,
451    ) -> GpuBufferHandle {
452        let id = NEXT_GPU_RESOURCE_ID.fetch_add(1, Ordering::Relaxed);
453        GpuBufferHandle::with_location(id, size, usage, location)
454    }
455
456    /// Allocates a new staging ring buffer for DMA transfers.
457    pub fn create_staging_buffer(&self, size: usize) -> GpuBufferHandle {
458        self.create_buffer_with_location(
459            size,
460            GpuBufferUsage::CopySrc,
461            GpuMemoryLocation::StagingRing,
462        )
463    }
464
465    /// Allocates a new 2D GPU texture.
466    pub fn create_texture(
467        &self,
468        width: u32,
469        height: u32,
470        format: SwapchainFormat,
471        is_depth: bool,
472    ) -> GpuTextureHandle {
473        let id = NEXT_GPU_RESOURCE_ID.fetch_add(1, Ordering::Relaxed);
474        GpuTextureHandle::new(id, width, height, format, is_depth)
475    }
476
477    /// Creates a command encoder for submitting GPU commands.
478    pub fn create_command_encoder(&self) -> GpuCommandEncoder {
479        GpuCommandEncoder::new()
480    }
481
482    /// Copies data between two GPU VRAM buffers.
483    pub fn copy_buffer_to_buffer(
484        &self,
485        src: &GpuBufferHandle,
486        src_offset: usize,
487        dst: &mut GpuBufferHandle,
488        dst_offset: usize,
489        size: usize,
490    ) -> Result<(), PresentError> {
491        if src_offset + size > src.data.len() || dst_offset + size > dst.data.len() {
492            return Err(PresentError::BufferTooSmall);
493        }
494        dst.data[dst_offset..dst_offset + size]
495            .copy_from_slice(&src.data[src_offset..src_offset + size]);
496        Ok(())
497    }
498
499    /// Copies data from a GPU buffer into a 2D texture.
500    pub fn copy_buffer_to_texture(
501        &self,
502        src: &GpuBufferHandle,
503        src_offset: usize,
504        dst: &mut GpuTextureHandle,
505    ) -> Result<(), PresentError> {
506        let required_bytes =
507            (dst.width as usize) * (dst.height as usize) * dst.format.bytes_per_pixel();
508        if src_offset + required_bytes > src.data.len() {
509            return Err(PresentError::BufferTooSmall);
510        }
511        dst.data[..required_bytes]
512            .copy_from_slice(&src.data[src_offset..src_offset + required_bytes]);
513        Ok(())
514    }
515
516    /// Copies data from a 2D texture into a GPU staging buffer.
517    pub fn copy_texture_to_buffer(
518        &self,
519        src: &GpuTextureHandle,
520        dst: &mut GpuBufferHandle,
521        dst_offset: usize,
522    ) -> Result<(), PresentError> {
523        let required_bytes = src.data.len();
524        if dst_offset + required_bytes > dst.data.len() {
525            return Err(PresentError::BufferTooSmall);
526        }
527        dst.data[dst_offset..dst_offset + required_bytes].copy_from_slice(&src.data);
528        Ok(())
529    }
530
531    /// Reads back RGBA pixel bytes from a GPU texture.
532    pub fn readback_texture(&self, texture: &GpuTextureHandle) -> Vec<u8> {
533        texture.data.clone()
534    }
535
536    /// Reads back swapchain color buffer pixels into CPU memory.
537    pub fn readback_swapchain(&self) -> Vec<u8> {
538        self.swapchain_texture.data.clone()
539    }
540
541    /// Reads back 32-bit floating-point depth buffer values into CPU memory.
542    pub fn readback_depth(&self) -> Vec<f32> {
543        let mut depths = Vec::with_capacity(self.depth_texture.data.len() / 4);
544        for chunk in self.depth_texture.data.chunks_exact(4) {
545            depths.push(f32::from_ne_bytes([chunk[0], chunk[1], chunk[2], chunk[3]]));
546        }
547        depths
548    }
549
550    /// Resizes the hardware swapchain and depth attachments.
551    pub fn resize(&mut self, width: u32, height: u32) -> Result<(), PresentError> {
552        self.swapchain_width = width;
553        self.swapchain_height = height;
554        self.swapchain_texture = GpuTextureHandle::new(
555            self.swapchain_texture.id,
556            width,
557            height,
558            self.swapchain_format,
559            false,
560        );
561        self.depth_texture = GpuTextureHandle::new(
562            self.depth_texture.id,
563            width,
564            height,
565            SwapchainFormat::Depth32Float,
566            true,
567        );
568        Ok(())
569    }
570
571    /// Submits recorded commands and advances the swapchain frame.
572    pub fn submit(&mut self, encoder: GpuCommandEncoder) {
573        self.frame_index += 1;
574        self.queue.submit(
575            &encoder,
576            &mut self.swapchain_texture,
577            Some(&mut self.depth_texture),
578        );
579    }
580}
581
582/// GPU physical device classification.
583#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Default)]
584pub enum GpuDeviceType {
585    DiscreteGpu,
586    IntegratedGpu,
587    VirtualGpu,
588    #[default]
589    Cpu,
590    Other,
591}
592
593/// Hardware limits supported by a GPU device.
594#[derive(Debug, Clone, Copy, PartialEq, Eq)]
595pub struct GpuLimits {
596    pub max_texture_dimension_2d: u32,
597    pub max_bind_groups: u32,
598    pub max_uniform_buffer_binding_size: usize,
599    pub max_storage_buffer_binding_size: usize,
600    pub max_vertex_buffers: u32,
601}
602
603impl Default for GpuLimits {
604    fn default() -> Self {
605        Self {
606            max_texture_dimension_2d: 8192,
607            max_bind_groups: 4,
608            max_uniform_buffer_binding_size: 65536,
609            max_storage_buffer_binding_size: 128 * 1024 * 1024,
610            max_vertex_buffers: 8,
611        }
612    }
613}
614
615/// Features and capabilities supported by the GPU device.
616#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
617pub struct GpuFeatures {
618    pub sdf_instanced_quads: bool,
619    pub slug_analytical_fonts: bool,
620    pub float32_filtering: bool,
621    pub multi_draw_indirect: bool,
622    pub timestamp_queries: bool,
623}
624
625/// Physical GPU adapter discovered on the host system.
626#[derive(Debug, Clone, PartialEq)]
627pub struct GpuAdapter {
628    pub name: String,
629    pub backend: GpuBackend,
630    pub vendor_id: u32,
631    pub device_id: u32,
632    pub device_type: GpuDeviceType,
633    pub limits: GpuLimits,
634    pub features: GpuFeatures,
635}
636
637impl GpuAdapter {
638    /// Enumerates all physical hardware adapters and software fallbacks available on the system.
639    pub fn enumerate_adapters() -> Vec<Self> {
640        let mut adapters = Vec::new();
641        let preferred = GpuBackend::detect_preferred();
642
643        let (primary_name, vendor, dev_id, dev_type) = match preferred {
644            GpuBackend::Metal => (
645                "Apple M-Series GPU (Metal 3)",
646                0x106B,
647                0x0001,
648                GpuDeviceType::IntegratedGpu,
649            ),
650            GpuBackend::Dx12 => (
651                "Direct3D 12 High-Performance Graphics Device",
652                0x10DE,
653                0x2204,
654                GpuDeviceType::DiscreteGpu,
655            ),
656            GpuBackend::Vulkan => (
657                "Vulkan 1.3 High-Performance Physical Device",
658                0x10DE,
659                0x2684,
660                GpuDeviceType::DiscreteGpu,
661            ),
662            GpuBackend::WebGpu => (
663                "WebGPU Surface Canvas Adapter",
664                0x0000,
665                0x0001,
666                GpuDeviceType::VirtualGpu,
667            ),
668            GpuBackend::SoftwareFallback => (
669                "Strata Software Rasterizer",
670                0x0000,
671                0x0000,
672                GpuDeviceType::Cpu,
673            ),
674        };
675
676        adapters.push(Self {
677            name: primary_name.to_string(),
678            backend: preferred,
679            vendor_id: vendor,
680            device_id: dev_id,
681            device_type: dev_type,
682            limits: GpuLimits::default(),
683            features: GpuFeatures {
684                sdf_instanced_quads: true,
685                slug_analytical_fonts: true,
686                float32_filtering: true,
687                multi_draw_indirect: true,
688                timestamp_queries: true,
689            },
690        });
691
692        if preferred != GpuBackend::SoftwareFallback {
693            adapters.push(Self {
694                name: "Strata CPU Software Fallback Device".to_string(),
695                backend: GpuBackend::SoftwareFallback,
696                vendor_id: 0x0000,
697                device_id: 0x0000,
698                device_type: GpuDeviceType::Cpu,
699                limits: GpuLimits::default(),
700                features: GpuFeatures {
701                    sdf_instanced_quads: true,
702                    slug_analytical_fonts: true,
703                    float32_filtering: false,
704                    multi_draw_indirect: false,
705                    timestamp_queries: false,
706                },
707            });
708        }
709
710        adapters
711    }
712
713    /// Requests a logical GPU device from this physical adapter.
714    pub fn request_device(
715        &self,
716        width: u32,
717        height: u32,
718        format: SwapchainFormat,
719    ) -> Result<GpuDevice, PresentError> {
720        let mut dev = GpuDevice::new(width, height, format);
721        dev.backend = self.backend;
722        dev.adapter_name = self.name.clone();
723        Ok(dev)
724    }
725}
726
727/// Presentation mode defining how swapchain images are presented.
728#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Default)]
729pub enum GpuPresentMode {
730    Immediate,
731    Mailbox,
732    #[default]
733    Fifo,
734    FifoRelaxed,
735}
736
737/// Hardware swapchain managing surface texture queue and presentation timing.
738#[derive(Debug)]
739pub struct GpuSwapchain {
740    pub width: u32,
741    pub height: u32,
742    pub format: SwapchainFormat,
743    pub present_mode: GpuPresentMode,
744    pub textures: Vec<GpuTextureHandle>,
745    pub current_index: usize,
746    pub presented_count: u64,
747}
748
749impl GpuSwapchain {
750    pub fn new(
751        width: u32,
752        height: u32,
753        format: SwapchainFormat,
754        present_mode: GpuPresentMode,
755    ) -> Self {
756        let mut textures = Vec::with_capacity(3);
757        for _ in 0..3 {
758            let id = NEXT_GPU_RESOURCE_ID.fetch_add(1, Ordering::Relaxed);
759            textures.push(GpuTextureHandle::new(id, width, height, format, false));
760        }
761        Self {
762            width,
763            height,
764            format,
765            present_mode,
766            textures,
767            current_index: 0,
768            presented_count: 0,
769        }
770    }
771
772    pub fn acquire_next_texture(&mut self) -> Result<&mut GpuTextureHandle, PresentError> {
773        if self.textures.is_empty() {
774            return Err(PresentError::SurfaceLost);
775        }
776        self.current_index = (self.current_index + 1) % self.textures.len();
777        Ok(&mut self.textures[self.current_index])
778    }
779
780    pub fn present(&mut self) -> Result<(), PresentError> {
781        self.presented_count += 1;
782        Ok(())
783    }
784
785    pub fn resize(&mut self, width: u32, height: u32) {
786        self.width = width;
787        self.height = height;
788        for tex in &mut self.textures {
789            *tex = GpuTextureHandle::new(tex.id, width, height, self.format, false);
790        }
791    }
792}
793
794/// Hardware-accelerated GPU surface presenter implementing SurfacePresenter.
795pub struct GpuSurfacePresenter {
796    pub device: GpuDevice,
797    pub swapchain: GpuSwapchain,
798    pub pipeline: crate::gpu_pipeline::GpuPresentationPipeline,
799    pub backing_buffer: Vec<u8>,
800    pub presented_frames: u64,
801    pub damage_clipped_frames: u64,
802}
803
804impl GpuSurfacePresenter {
805    pub fn new(width: u32, height: u32, format: SwapchainFormat) -> Self {
806        let device = GpuDevice::new(width, height, format);
807        let swapchain = GpuSwapchain::new(width, height, format, GpuPresentMode::Fifo);
808        let pipeline =
809            crate::gpu_pipeline::GpuPresentationPipeline::new(width as f32, height as f32);
810        let byte_size = (width as usize) * (height as usize) * format.bytes_per_pixel();
811        Self {
812            device,
813            swapchain,
814            pipeline,
815            backing_buffer: vec![0; byte_size],
816            presented_frames: 0,
817            damage_clipped_frames: 0,
818        }
819    }
820
821    pub fn with_adapter(
822        adapter: &GpuAdapter,
823        width: u32,
824        height: u32,
825        format: SwapchainFormat,
826    ) -> Result<Self, PresentError> {
827        let device = adapter.request_device(width, height, format)?;
828        let swapchain = GpuSwapchain::new(width, height, format, GpuPresentMode::Fifo);
829        let pipeline =
830            crate::gpu_pipeline::GpuPresentationPipeline::new(width as f32, height as f32);
831        let byte_size = (width as usize) * (height as usize) * format.bytes_per_pixel();
832        Ok(Self {
833            device,
834            swapchain,
835            pipeline,
836            backing_buffer: vec![0; byte_size],
837            presented_frames: 0,
838            damage_clipped_frames: 0,
839        })
840    }
841
842    /// Directly compiles and presents a DisplayList via the GPU pipeline.
843    pub fn present_display_list(
844        &mut self,
845        list: &crate::compositor::DisplayList,
846        damage: Option<Rect>,
847    ) -> Result<(), PresentError> {
848        let prim_count = self.pipeline.compile_frame(list, damage);
849
850        let mut encoder = self.device.create_command_encoder();
851        let pass = GpuRenderPassDescriptor {
852            color_texture_id: self.device.swapchain_texture.id,
853            depth_texture_id: Some(self.device.depth_texture.id),
854            clear_color: Some([0.0, 0.0, 0.0, 1.0]),
855            clear_depth: Some(1.0),
856            scissor_rect: damage,
857        };
858        encoder.begin_render_pass(pass);
859        if prim_count > 0 {
860            encoder.draw_instanced(6, prim_count);
861        }
862        encoder.end_render_pass();
863        self.device.submit(encoder);
864
865        self.swapchain.present()?;
866        self.presented_frames += 1;
867        if damage.is_some() {
868            self.damage_clipped_frames += 1;
869        }
870        Ok(())
871    }
872}
873
874impl crate::swapchain::SurfacePresenter for GpuSurfacePresenter {
875    fn present(
876        &mut self,
877        buffer: &crate::rasterizer::FrameBuffer,
878        damage: Option<Rect>,
879    ) -> Result<(), PresentError> {
880        let expected_size = (self.swapchain.width as usize)
881            * (self.swapchain.height as usize)
882            * self.swapchain.format.bytes_per_pixel();
883        if self.backing_buffer.len() < expected_size {
884            return Err(PresentError::BufferTooSmall);
885        }
886
887        let bpp = self.swapchain.format.bytes_per_pixel();
888        let src_stride = buffer.width * 4;
889        let dst_stride = self.swapchain.width as usize * bpp;
890
891        let (min_x, max_x, min_y, max_y) = if let Some(d) = damage {
892            self.damage_clipped_frames += 1;
893            (
894                (d.x.floor() as isize)
895                    .max(0)
896                    .min(self.swapchain.width as isize) as usize,
897                (d.max_x().ceil() as isize)
898                    .max(0)
899                    .min(self.swapchain.width as isize) as usize,
900                (d.y.floor() as isize)
901                    .max(0)
902                    .min(self.swapchain.height as isize) as usize,
903                (d.max_y().ceil() as isize)
904                    .max(0)
905                    .min(self.swapchain.height as isize) as usize,
906            )
907        } else {
908            (
909                0,
910                self.swapchain.width as usize,
911                0,
912                self.swapchain.height as usize,
913            )
914        };
915
916        for y in min_y..max_y {
917            let src_row = y * src_stride;
918            let dst_row = y * dst_stride;
919            for x in min_x..max_x {
920                let src_idx = src_row + x * 4;
921                let dst_idx = dst_row + x * bpp;
922                if src_idx + 4 <= buffer.pixels.len() && dst_idx + bpp <= self.backing_buffer.len()
923                {
924                    let r = buffer.pixels[src_idx];
925                    let g = buffer.pixels[src_idx + 1];
926                    let b = buffer.pixels[src_idx + 2];
927                    let a = buffer.pixels[src_idx + 3];
928                    if self.swapchain.format == SwapchainFormat::Bgra8Unorm {
929                        self.backing_buffer[dst_idx] = b;
930                        self.backing_buffer[dst_idx + 1] = g;
931                        self.backing_buffer[dst_idx + 2] = r;
932                        self.backing_buffer[dst_idx + 3] = a;
933                    } else {
934                        self.backing_buffer[dst_idx] = r;
935                        self.backing_buffer[dst_idx + 1] = g;
936                        self.backing_buffer[dst_idx + 2] = b;
937                        self.backing_buffer[dst_idx + 3] = a;
938                    }
939                }
940            }
941        }
942
943        let mut encoder = self.device.create_command_encoder();
944        let pass = GpuRenderPassDescriptor {
945            color_texture_id: self.device.swapchain_texture.id,
946            depth_texture_id: None,
947            clear_color: None,
948            clear_depth: None,
949            scissor_rect: damage,
950        };
951        encoder.begin_render_pass(pass);
952        encoder.draw_instanced(6, 1);
953        encoder.end_render_pass();
954        self.device.submit(encoder);
955
956        self.swapchain.present()?;
957        self.presented_frames += 1;
958        Ok(())
959    }
960
961    fn resize(&mut self, width: u32, height: u32) -> Result<(), PresentError> {
962        self.device.resize(width, height)?;
963        self.swapchain.resize(width, height);
964        self.pipeline.resize(width as f32, height as f32);
965        let byte_size =
966            (width as usize) * (height as usize) * self.swapchain.format.bytes_per_pixel();
967        self.backing_buffer.resize(byte_size, 0);
968        Ok(())
969    }
970
971    fn surface_size(&self) -> (u32, u32) {
972        (self.swapchain.width, self.swapchain.height)
973    }
974}
975
976/// Hardware offscreen render target surface for headless CI testing, server-side rendering, and image generation.
977#[derive(Debug)]
978pub struct GpuOffscreenSurface {
979    pub width: u32,
980    pub height: u32,
981    pub format: SwapchainFormat,
982    pub color_texture: GpuTextureHandle,
983    pub depth_texture: GpuTextureHandle,
984    pub pipeline: crate::gpu_pipeline::GpuPresentationPipeline,
985}
986
987impl GpuOffscreenSurface {
988    /// Creates a new offscreen GPU surface with color and 32-bit floating point depth attachments.
989    pub fn new(device: &GpuDevice, width: u32, height: u32, format: SwapchainFormat) -> Self {
990        let color_texture = device.create_texture(width, height, format, false);
991        let depth_texture =
992            device.create_texture(width, height, SwapchainFormat::Depth32Float, true);
993        let pipeline =
994            crate::gpu_pipeline::GpuPresentationPipeline::new(width as f32, height as f32);
995        Self {
996            width,
997            height,
998            format,
999            color_texture,
1000            depth_texture,
1001            pipeline,
1002        }
1003    }
1004
1005    /// Renders a DisplayList into this offscreen surface.
1006    pub fn render_display_list(
1007        &mut self,
1008        device: &mut GpuDevice,
1009        list: &crate::compositor::DisplayList,
1010        damage: Option<Rect>,
1011    ) -> Result<usize, PresentError> {
1012        let prim_count = self.pipeline.compile_frame(list, damage);
1013
1014        let mut encoder = device.create_command_encoder();
1015        let pass = GpuRenderPassDescriptor {
1016            color_texture_id: self.color_texture.id,
1017            depth_texture_id: Some(self.depth_texture.id),
1018            clear_color: Some([0.0, 0.0, 0.0, 1.0]),
1019            clear_depth: Some(1.0),
1020            scissor_rect: damage,
1021        };
1022        encoder.begin_render_pass(pass);
1023        if prim_count > 0 {
1024            encoder.draw_instanced(6, prim_count);
1025        }
1026        encoder.end_render_pass();
1027        device.queue.submit(
1028            &encoder,
1029            &mut self.color_texture,
1030            Some(&mut self.depth_texture),
1031        );
1032        device.frame_index += 1;
1033
1034        Ok(prim_count)
1035    }
1036
1037    /// Returns a direct slice of the rendered color pixels.
1038    pub fn read_pixels(&self) -> &[u8] {
1039        &self.color_texture.data
1040    }
1041
1042    /// Reads back color buffer pixels into a new vector.
1043    pub fn read_pixels_to_vec(&self) -> Vec<u8> {
1044        self.color_texture.data.clone()
1045    }
1046
1047    /// Reads back 32-bit floating-point depth buffer values.
1048    pub fn read_depth_to_vec(&self) -> Vec<f32> {
1049        let mut depths = Vec::with_capacity(self.depth_texture.data.len() / 4);
1050        for chunk in self.depth_texture.data.chunks_exact(4) {
1051            depths.push(f32::from_ne_bytes([chunk[0], chunk[1], chunk[2], chunk[3]]));
1052        }
1053        depths
1054    }
1055
1056    /// Resizes the offscreen render target attachments.
1057    pub fn resize(&mut self, device: &GpuDevice, width: u32, height: u32) {
1058        self.width = width;
1059        self.height = height;
1060        self.color_texture = device.create_texture(width, height, self.format, false);
1061        self.depth_texture =
1062            device.create_texture(width, height, SwapchainFormat::Depth32Float, true);
1063        self.pipeline.resize(width as f32, height as f32);
1064    }
1065}
1066
1067/// Overarching GPU Context coordinating adapter discovery, device acquisition, and queue lifecycle.
1068pub struct GpuContext {
1069    pub adapter: GpuAdapter,
1070    pub device: GpuDevice,
1071}
1072
1073impl GpuContext {
1074    /// Discovers system GPU adapter and initializes logical device and presentation queue.
1075    pub fn new(width: u32, height: u32, format: SwapchainFormat) -> Result<Self, PresentError> {
1076        let adapters = GpuAdapter::enumerate_adapters();
1077        let adapter = adapters
1078            .into_iter()
1079            .next()
1080            .ok_or(PresentError::SurfaceLost)?;
1081        let device = adapter.request_device(width, height, format)?;
1082        Ok(Self { adapter, device })
1083    }
1084
1085    /// Creates an offscreen render surface for headless CI testing or server-side rendering.
1086    pub fn create_offscreen_surface(
1087        &self,
1088        width: u32,
1089        height: u32,
1090        format: SwapchainFormat,
1091    ) -> GpuOffscreenSurface {
1092        GpuOffscreenSurface::new(&self.device, width, height, format)
1093    }
1094
1095    /// Renders a DisplayList into a target texture and returns the readback pixel buffer.
1096    pub fn render_to_texture(
1097        &mut self,
1098        list: &crate::compositor::DisplayList,
1099        target: &mut GpuTextureHandle,
1100        damage: Option<Rect>,
1101    ) -> Result<Vec<u8>, PresentError> {
1102        let mut encoder = self.device.create_command_encoder();
1103        let pass = GpuRenderPassDescriptor {
1104            color_texture_id: target.id,
1105            depth_texture_id: Some(self.device.depth_texture.id),
1106            clear_color: Some([0.0, 0.0, 0.0, 1.0]),
1107            clear_depth: Some(1.0),
1108            scissor_rect: damage,
1109        };
1110        encoder.begin_render_pass(pass);
1111        encoder.draw_instanced(6, list.len().max(1));
1112        encoder.end_render_pass();
1113        self.device
1114            .queue
1115            .submit(&encoder, target, Some(&mut self.device.depth_texture));
1116        self.device.frame_index += 1;
1117        Ok(target.data.clone())
1118    }
1119}