Skip to main content

euv_core/platform/backend/
impl.rs

1use super::*;
2
3/// Display formatting for `PlatformError`.
4impl fmt::Display for PlatformError {
5    /// Formats `PlatformError` into a human-readable diagnostic message.
6    ///
7    /// # Arguments
8    ///
9    /// - `&Self` - Error value.
10    /// - `&mut Formatter<'_>` - Output formatter.
11    ///
12    /// # Returns
13    ///
14    /// - `fmt::Result` - Formatting status.
15    fn fmt(&self, factor_val: &mut Formatter<'_>) -> fmt::Result {
16        match self {
17            Self::WindowNotFound(id) => write!(factor_val, "{ERR_WINDOW_NOT_FOUND}: {id}"),
18            Self::InitializationFailed(msg) => {
19                write!(factor_val, "{ERR_NATIVE_INIT_FAILED}: {msg}")
20            }
21            Self::SurfaceError(msg) => write!(factor_val, "{ERR_SURFACE_UNAVAILABLE}: {msg}"),
22            Self::Unsupported(msg) => write!(factor_val, "{msg}"),
23        }
24    }
25}
26
27/// Standard `Error` marker implementation for `PlatformError`.
28impl Error for PlatformError {}
29
30/// Helper accessors for `GpuFrameSubmission`.
31impl GpuFrameSubmission {
32    /// Returns a borrowed reference to the optional R8 glyph atlas upload payload.
33    ///
34    /// # Returns
35    ///
36    /// - `Option<&DirectGpuAtlasUpload>` - Borrowed R8 glyph atlas payload when present.
37    #[must_use]
38    pub fn glyph_atlas_r8_ref(&self) -> Option<&DirectGpuAtlasUpload> {
39        let Self { glyph_atlas_r8, .. } = self;
40        glyph_atlas_r8.as_ref()
41    }
42
43    /// Returns a borrowed reference to the optional packed RGBA8 image atlas upload payload.
44    ///
45    /// # Returns
46    ///
47    /// - `Option<&DirectGpuAtlasUpload>` - Borrowed RGBA8 image atlas payload when present.
48    #[must_use]
49    pub fn image_atlas_rgba8_ref(&self) -> Option<&DirectGpuAtlasUpload> {
50        let Self {
51            image_atlas_rgba8, ..
52        } = self;
53        image_atlas_rgba8.as_ref()
54    }
55
56    /// Returns a borrowed reference to the optional hardware GPU offscreen scene pass (`OceanFluid` or `World3d`).
57    ///
58    /// # Returns
59    ///
60    /// - `Option<&DirectGpuScenePass>` - Borrowed offscreen GPU scene pass when present.
61    #[must_use]
62    pub fn gpu_scene_pass_ref(&self) -> Option<&DirectGpuScenePass> {
63        let Self { gpu_scene_pass, .. } = self;
64        gpu_scene_pass.as_ref()
65    }
66
67    /// Attaches an optional hardware GPU offscreen scene pass (`OceanFluid` or `World3d`).
68    ///
69    /// # Arguments
70    ///
71    /// - `Option<DirectGpuScenePass>` - Offscreen GPU scene pass executed before UI compositing.
72    pub fn set_gpu_scene_pass(&mut self, pass: Option<DirectGpuScenePass>) {
73        let Self { gpu_scene_pass, .. } = self;
74        *gpu_scene_pass = pass;
75    }
76
77    /// Attaches an optional R8 glyph atlas upload payload and its dirty sub-rectangles.
78    ///
79    /// # Arguments
80    ///
81    /// - `Option<DirectGpuAtlasUpload>` - Backing R8 glyph atlas upload payload.
82    /// - `Vec<PixelDirtyRect>` - Dirty sub-rectangles pending GPU upload.
83    pub fn set_glyph_atlas_payload(
84        &mut self,
85        atlas: Option<DirectGpuAtlasUpload>,
86        dirty_rects: Vec<PixelDirtyRect>,
87    ) {
88        let Self {
89            glyph_atlas_r8,
90            glyph_dirty_rects,
91            ..
92        } = self;
93        *glyph_atlas_r8 = atlas;
94        *glyph_dirty_rects = dirty_rects;
95    }
96
97    /// Attaches an optional RGBA8 image atlas upload payload and its dirty sub-rectangles.
98    ///
99    /// # Arguments
100    ///
101    /// - `Option<DirectGpuAtlasUpload>` - Backing RGBA8 image atlas upload payload.
102    /// - `Vec<PixelDirtyRect>` - Dirty sub-rectangles pending GPU upload.
103    pub fn set_image_atlas_payload(
104        &mut self,
105        atlas: Option<DirectGpuAtlasUpload>,
106        dirty_rects: Vec<PixelDirtyRect>,
107    ) {
108        let Self {
109            image_atlas_rgba8,
110            image_dirty_rects,
111            ..
112        } = self;
113        *image_atlas_rgba8 = atlas;
114        *image_dirty_rects = dirty_rects;
115    }
116
117    /// Returns total 64-byte primitive instance count across all queued `GpuBatch` records.
118    ///
119    /// # Returns
120    ///
121    /// - `usize` - Total primitive instance count.
122    #[must_use]
123    pub fn total_primitive_count(&self) -> usize {
124        self.get_batches()
125            .iter()
126            .map(|batch: &GpuBatch| {
127                batch
128                    .get_primitives()
129                    .len()
130                    .max(batch.get_instances().len())
131            })
132            .sum()
133    }
134
135    /// Converts this `GpuFrameSubmission` into a flattened `DirectGpuFrameBatch` for DXGI/D3D11 and EGL/GLES3 direct presentation.
136    ///
137    /// # Returns
138    ///
139    /// - `DirectGpuFrameBatch` - Flattened 64-byte primitive and atlas batch ready for native GPU submission.
140    #[must_use]
141    pub fn to_direct_gpu_frame_batch(&self) -> DirectGpuFrameBatch {
142        let viewport_width: u32 = self.get_width().max(1);
143        let viewport_height: u32 = self.get_height().max(1);
144        let clear: Color = self.get_clear_color();
145        let clear_rgba: [f32; 4] = [
146            f32::from(clear.get_red()) / 255.0,
147            f32::from(clear.get_green()) / 255.0,
148            f32::from(clear.get_blue()) / 255.0,
149            f32::from(clear.get_alpha()) / 255.0,
150        ];
151        let total_prims: usize = self.total_primitive_count();
152        let mut primitives: Vec<GpuPrimitiveInstance> = Vec::with_capacity(total_prims);
153        let mut draw_ranges: Vec<DirectGpuBatchRange> =
154            Vec::with_capacity(self.get_batches().len());
155        for batch in self.get_batches() {
156            let batch_prims: &[GpuPrimitiveInstance] = batch.get_primitives().as_slice();
157            if batch_prims.is_empty() {
158                continue;
159            }
160            let base_instance: u32 = primitives.len() as u32;
161            let instance_count: u32 = batch_prims.len() as u32;
162            primitives.extend_from_slice(batch_prims);
163            let scissor: Rect = batch.get_scissor();
164            let (scissor_x, scissor_y, scissor_w, scissor_h): (u32, u32, u32, u32) =
165                if scissor.get_width() > 0.0 && scissor.get_height() > 0.0 {
166                    let sx: u32 = scissor.get_x().max(0.0).floor() as u32;
167                    let sy: u32 = scissor.get_y().max(0.0).floor() as u32;
168                    let sw: u32 = scissor
169                        .get_width()
170                        .max(1.0)
171                        .ceil()
172                        .min((viewport_width.saturating_sub(sx)) as f32)
173                        as u32;
174                    let sh: u32 = scissor
175                        .get_height()
176                        .max(1.0)
177                        .ceil()
178                        .min((viewport_height.saturating_sub(sy)) as f32)
179                        as u32;
180                    (sx, sy, sw.max(1), sh.max(1))
181                } else {
182                    (0, 0, viewport_width, viewport_height)
183                };
184            let scroll: [f32; 2] = batch.get_scroll_offset();
185            draw_ranges.push(DirectGpuBatchRange {
186                base_instance,
187                instance_count,
188                scissor_x,
189                scissor_y,
190                scissor_w,
191                scissor_h,
192                scroll_x: scroll[0],
193                scroll_y: scroll[1],
194                texture_slot: batch.get_texture_slot(),
195                layer_id: batch.get_layer_id(),
196                pad: [0, 0],
197            });
198        }
199        let glyph_r8_atlas: Option<DirectGpuAtlasUpload> = self.glyph_atlas_r8_ref().cloned();
200        let image_rgba8_atlas: Option<DirectGpuAtlasUpload> = self.image_atlas_rgba8_ref().cloned();
201        let glyph_bytes: usize = glyph_r8_atlas
202            .as_ref()
203            .map_or(0, |atlas: &DirectGpuAtlasUpload| atlas.get_pixels().len());
204        let image_bytes: usize = image_rgba8_atlas
205            .as_ref()
206            .map_or(0, |atlas: &DirectGpuAtlasUpload| atlas.get_pixels().len());
207        let instance_upload_bytes: usize = primitives
208            .len()
209            .saturating_mul(size_of::<GpuPrimitiveInstance>())
210            .saturating_add(glyph_bytes)
211            .saturating_add(image_bytes);
212        DirectGpuFrameBatch {
213            viewport_width,
214            viewport_height,
215            clear_rgba,
216            primitives,
217            draw_ranges,
218            backdrop_blurs: self.get_blur_passes().clone(),
219            glyph_r8_atlas,
220            image_rgba8_atlas,
221            instance_upload_bytes,
222            cpu_mirror_active: false,
223            upload_strategy: MobileUploadStrategy::DirectGpu,
224        }
225    }
226}
227
228/// Constructors for `GpuPresentReceipt`.
229impl GpuPresentReceipt {
230    /// Returns an unsupported no-op receipt indicating the platform falls back to framebuffer presentation.
231    ///
232    /// # Returns
233    ///
234    /// - `Self` - Receipt with `presented = false` and `device_lost = false`.
235    #[must_use]
236    pub fn unsupported() -> Self {
237        Self::default()
238    }
239}