euv-core 0.53.1

Core cross-platform runtime for euv featuring arena-based fine-grained reactivity, deterministic layout, flat scene graph, multi-mode rendering, and direct OS platform adapters.
Documentation
use super::*;

/// Display formatting for `PlatformError`.
impl fmt::Display for PlatformError {
    /// Formats `PlatformError` into a human-readable diagnostic message.
    ///
    /// # Arguments
    ///
    /// - `&Self` - Error value.
    /// - `&mut Formatter<'_>` - Output formatter.
    ///
    /// # Returns
    ///
    /// - `fmt::Result` - Formatting status.
    fn fmt(&self, factor_val: &mut Formatter<'_>) -> fmt::Result {
        match self {
            Self::WindowNotFound(id) => write!(factor_val, "{ERR_WINDOW_NOT_FOUND}: {id}"),
            Self::InitializationFailed(msg) => {
                write!(factor_val, "{ERR_NATIVE_INIT_FAILED}: {msg}")
            }
            Self::SurfaceError(msg) => write!(factor_val, "{ERR_SURFACE_UNAVAILABLE}: {msg}"),
            Self::Unsupported(msg) => write!(factor_val, "{msg}"),
        }
    }
}

/// Standard `Error` marker implementation for `PlatformError`.
impl Error for PlatformError {}

/// Helper accessors for `GpuFrameSubmission`.
impl GpuFrameSubmission {
    /// Returns a borrowed reference to the optional R8 glyph atlas upload payload.
    ///
    /// # Returns
    ///
    /// - `Option<&DirectGpuAtlasUpload>` - Borrowed R8 glyph atlas payload when present.
    #[must_use]
    pub fn glyph_atlas_r8_ref(&self) -> Option<&DirectGpuAtlasUpload> {
        let Self { glyph_atlas_r8, .. } = self;
        glyph_atlas_r8.as_ref()
    }

    /// Returns a borrowed reference to the optional packed RGBA8 image atlas upload payload.
    ///
    /// # Returns
    ///
    /// - `Option<&DirectGpuAtlasUpload>` - Borrowed RGBA8 image atlas payload when present.
    #[must_use]
    pub fn image_atlas_rgba8_ref(&self) -> Option<&DirectGpuAtlasUpload> {
        let Self {
            image_atlas_rgba8, ..
        } = self;
        image_atlas_rgba8.as_ref()
    }

    /// Returns a borrowed reference to the optional hardware GPU offscreen scene pass (`OceanFluid` or `World3d`).
    ///
    /// # Returns
    ///
    /// - `Option<&DirectGpuScenePass>` - Borrowed offscreen GPU scene pass when present.
    #[must_use]
    pub fn gpu_scene_pass_ref(&self) -> Option<&DirectGpuScenePass> {
        let Self { gpu_scene_pass, .. } = self;
        gpu_scene_pass.as_ref()
    }

    /// Attaches an optional hardware GPU offscreen scene pass (`OceanFluid` or `World3d`).
    ///
    /// # Arguments
    ///
    /// - `Option<DirectGpuScenePass>` - Offscreen GPU scene pass executed before UI compositing.
    pub fn set_gpu_scene_pass(&mut self, pass: Option<DirectGpuScenePass>) {
        let Self { gpu_scene_pass, .. } = self;
        *gpu_scene_pass = pass;
    }

    /// Attaches an optional R8 glyph atlas upload payload and its dirty sub-rectangles.
    ///
    /// # Arguments
    ///
    /// - `Option<DirectGpuAtlasUpload>` - Backing R8 glyph atlas upload payload.
    /// - `Vec<PixelDirtyRect>` - Dirty sub-rectangles pending GPU upload.
    pub fn set_glyph_atlas_payload(
        &mut self,
        atlas: Option<DirectGpuAtlasUpload>,
        dirty_rects: Vec<PixelDirtyRect>,
    ) {
        let Self {
            glyph_atlas_r8,
            glyph_dirty_rects,
            ..
        } = self;
        *glyph_atlas_r8 = atlas;
        *glyph_dirty_rects = dirty_rects;
    }

    /// Attaches an optional RGBA8 image atlas upload payload and its dirty sub-rectangles.
    ///
    /// # Arguments
    ///
    /// - `Option<DirectGpuAtlasUpload>` - Backing RGBA8 image atlas upload payload.
    /// - `Vec<PixelDirtyRect>` - Dirty sub-rectangles pending GPU upload.
    pub fn set_image_atlas_payload(
        &mut self,
        atlas: Option<DirectGpuAtlasUpload>,
        dirty_rects: Vec<PixelDirtyRect>,
    ) {
        let Self {
            image_atlas_rgba8,
            image_dirty_rects,
            ..
        } = self;
        *image_atlas_rgba8 = atlas;
        *image_dirty_rects = dirty_rects;
    }

    /// Returns total 64-byte primitive instance count across all queued `GpuBatch` records.
    ///
    /// # Returns
    ///
    /// - `usize` - Total primitive instance count.
    #[must_use]
    pub fn total_primitive_count(&self) -> usize {
        self.get_batches()
            .iter()
            .map(|batch: &GpuBatch| {
                batch
                    .get_primitives()
                    .len()
                    .max(batch.get_instances().len())
            })
            .sum()
    }

    /// Converts this `GpuFrameSubmission` into a flattened `DirectGpuFrameBatch` for DXGI/D3D11 and EGL/GLES3 direct presentation.
    ///
    /// # Returns
    ///
    /// - `DirectGpuFrameBatch` - Flattened 64-byte primitive and atlas batch ready for native GPU submission.
    #[must_use]
    pub fn to_direct_gpu_frame_batch(&self) -> DirectGpuFrameBatch {
        let viewport_width: u32 = self.get_width().max(1);
        let viewport_height: u32 = self.get_height().max(1);
        let clear: Color = self.get_clear_color();
        let clear_rgba: [f32; 4] = [
            f32::from(clear.get_red()) / 255.0,
            f32::from(clear.get_green()) / 255.0,
            f32::from(clear.get_blue()) / 255.0,
            f32::from(clear.get_alpha()) / 255.0,
        ];
        let total_prims: usize = self.total_primitive_count();
        let mut primitives: Vec<GpuPrimitiveInstance> = Vec::with_capacity(total_prims);
        let mut draw_ranges: Vec<DirectGpuBatchRange> =
            Vec::with_capacity(self.get_batches().len());
        for batch in self.get_batches() {
            let batch_prims: &[GpuPrimitiveInstance] = batch.get_primitives().as_slice();
            if batch_prims.is_empty() {
                continue;
            }
            let base_instance: u32 = primitives.len() as u32;
            let instance_count: u32 = batch_prims.len() as u32;
            primitives.extend_from_slice(batch_prims);
            let scissor: Rect = batch.get_scissor();
            let (scissor_x, scissor_y, scissor_w, scissor_h): (u32, u32, u32, u32) =
                if scissor.get_width() > 0.0 && scissor.get_height() > 0.0 {
                    let sx: u32 = scissor.get_x().max(0.0).floor() as u32;
                    let sy: u32 = scissor.get_y().max(0.0).floor() as u32;
                    let sw: u32 = scissor
                        .get_width()
                        .max(1.0)
                        .ceil()
                        .min((viewport_width.saturating_sub(sx)) as f32)
                        as u32;
                    let sh: u32 = scissor
                        .get_height()
                        .max(1.0)
                        .ceil()
                        .min((viewport_height.saturating_sub(sy)) as f32)
                        as u32;
                    (sx, sy, sw.max(1), sh.max(1))
                } else {
                    (0, 0, viewport_width, viewport_height)
                };
            let scroll: [f32; 2] = batch.get_scroll_offset();
            draw_ranges.push(DirectGpuBatchRange {
                base_instance,
                instance_count,
                scissor_x,
                scissor_y,
                scissor_w,
                scissor_h,
                scroll_x: scroll[0],
                scroll_y: scroll[1],
                texture_slot: batch.get_texture_slot(),
                layer_id: batch.get_layer_id(),
                pad: [0, 0],
            });
        }
        let glyph_r8_atlas: Option<DirectGpuAtlasUpload> = self.glyph_atlas_r8_ref().cloned();
        let image_rgba8_atlas: Option<DirectGpuAtlasUpload> = self.image_atlas_rgba8_ref().cloned();
        let glyph_bytes: usize = glyph_r8_atlas
            .as_ref()
            .map_or(0, |atlas: &DirectGpuAtlasUpload| atlas.get_pixels().len());
        let image_bytes: usize = image_rgba8_atlas
            .as_ref()
            .map_or(0, |atlas: &DirectGpuAtlasUpload| atlas.get_pixels().len());
        let instance_upload_bytes: usize = primitives
            .len()
            .saturating_mul(size_of::<GpuPrimitiveInstance>())
            .saturating_add(glyph_bytes)
            .saturating_add(image_bytes);
        DirectGpuFrameBatch {
            viewport_width,
            viewport_height,
            clear_rgba,
            primitives,
            draw_ranges,
            backdrop_blurs: self.get_blur_passes().clone(),
            glyph_r8_atlas,
            image_rgba8_atlas,
            instance_upload_bytes,
            cpu_mirror_active: false,
            upload_strategy: MobileUploadStrategy::DirectGpu,
        }
    }
}

/// Constructors for `GpuPresentReceipt`.
impl GpuPresentReceipt {
    /// Returns an unsupported no-op receipt indicating the platform falls back to framebuffer presentation.
    ///
    /// # Returns
    ///
    /// - `Self` - Receipt with `presented = false` and `device_lost = false`.
    #[must_use]
    pub fn unsupported() -> Self {
        Self::default()
    }
}