euv-core 0.55.0

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::*;

/// Predictive focus computation for `SpatialPrefetchVolume`.
impl SpatialPrefetchVolume {
    /// Computes the predicted lookahead center `center + velocity * lookahead_secs`.
    ///
    /// # Returns
    ///
    /// - `[f32; 3]` - Predicted future camera position in world coordinates.
    #[must_use]
    pub fn predicted_center(&self) -> [f32; 3] {
        let center: [f32; 3] = self.get_center();
        let velocity: [f32; 3] = self.get_velocity();
        let horizon: f32 = self.get_lookahead_secs().max(0.0);
        [
            center[0] + velocity[0] * horizon,
            center[1] + velocity[1] * horizon,
            center[2] + velocity[2] * horizon,
        ]
    }
}

/// Default spatial hash prefetcher configured with `16m` uniform grid cells.
impl Default for SpatialPrefetchGrid {
    /// Creates an empty `SpatialPrefetchGrid` using `PREFETCH_DEFAULT_CELL_SIZE`.
    ///
    /// # Returns
    ///
    /// - `Self` - Empty spatial prefetch index.
    fn default() -> Self {
        Self::new(PREFETCH_DEFAULT_CELL_SIZE)
    }
}

/// Spatial anchor registration, lookahead sphere querying, and rear-camera cancellation for `SpatialPrefetchGrid`.
impl SpatialPrefetchGrid {
    /// Creates an empty `SpatialPrefetchGrid` with uniform cell width `cell_size`.
    ///
    /// # Arguments
    ///
    /// - `f32` - Uniform 3D spatial cell width in meters (clamped to `>= 1.0`).
    ///
    /// # Returns
    ///
    /// - `Self` - Empty spatial prefetch grid.
    #[must_use]
    pub fn new(cell_size: f32) -> Self {
        Self {
            cell_size: cell_size.max(1.0),
            anchors: Vec::new(),
            key_to_index: HashMap::new(),
            cells: HashMap::new(),
            active_prefetches: HashSet::new(),
        }
    }

    /// Registers or replaces a spatial asset anchor inside all overlapping 3D hash cells.
    ///
    /// # Arguments
    ///
    /// - `SpatialAssetAnchor` - Asset spatial anchor descriptor.
    pub fn register_anchor(&mut self, anchor: SpatialAssetAnchor) {
        let key_hash: u64 = anchor.get_key_hash();
        let _: bool = self.unregister_anchor(key_hash);
        let Self {
            cell_size,
            anchors,
            key_to_index,
            cells,
            ..
        } = self;
        let idx: usize = anchors.len();
        anchors.push(Some(anchor));
        let _: Option<usize> = key_to_index.insert(key_hash, idx);
        let pos: [f32; 3] = anchor.get_position();
        let rad: f32 = anchor.get_bounding_radius().max(0.0);
        let min_cell: (i32, i32, i32) =
            world_to_prefetch_cell([pos[0] - rad, pos[1] - rad, pos[2] - rad], *cell_size);
        let max_cell: (i32, i32, i32) =
            world_to_prefetch_cell([pos[0] + rad, pos[1] + rad, pos[2] + rad], *cell_size);
        for cx in min_cell.0..=max_cell.0 {
            for cy in min_cell.1..=max_cell.1 {
                for cz in min_cell.2..=max_cell.2 {
                    cells.entry((cx, cy, cz)).or_default().push(idx);
                }
            }
        }
    }

    /// Removes a previously registered spatial anchor by 64-bit asset key hash.
    ///
    /// # Arguments
    ///
    /// - `u64` - Deterministic 64-bit asset key hash.
    ///
    /// # Returns
    ///
    /// - `bool` - `true` when an anchor existed and was removed.
    pub fn unregister_anchor(&mut self, key_hash: u64) -> bool {
        let Self {
            cell_size,
            anchors,
            key_to_index,
            cells,
            active_prefetches,
        } = self;
        let Some(idx) = key_to_index.remove(&key_hash) else {
            return false;
        };
        let _: bool = active_prefetches.remove(&key_hash);
        let Some(anchor) = anchors.get_mut(idx).and_then(Option::take) else {
            return false;
        };
        let pos: [f32; 3] = anchor.get_position();
        let rad: f32 = anchor.get_bounding_radius().max(0.0);
        let min_cell: (i32, i32, i32) =
            world_to_prefetch_cell([pos[0] - rad, pos[1] - rad, pos[2] - rad], *cell_size);
        let max_cell: (i32, i32, i32) =
            world_to_prefetch_cell([pos[0] + rad, pos[1] + rad, pos[2] + rad], *cell_size);
        for cx in min_cell.0..=max_cell.0 {
            for cy in min_cell.1..=max_cell.1 {
                for cz in min_cell.2..=max_cell.2 {
                    if let Some(bucket) = cells.get_mut(&(cx, cy, cz)) {
                        bucket.retain(|&entry_idx: &usize| entry_idx != idx);
                    }
                }
            }
        }
        true
    }

    /// Returns the count of registered spatial asset anchors.
    ///
    /// # Returns
    ///
    /// - `usize` - Active anchor count.
    #[must_use]
    pub fn anchor_count(&self) -> usize {
        let Self { key_to_index, .. } = self;
        key_to_index.len()
    }

    /// Marks `key_hash` as having an active speculative prefetch job eligible for behind-camera cancellation.
    ///
    /// # Arguments
    ///
    /// - `u64` - Asset key hash currently being prefetched.
    pub fn mark_prefetched(&mut self, key_hash: u64) {
        let Self {
            active_prefetches, ..
        } = self;
        let _: bool = active_prefetches.insert(key_hash);
    }

    /// Clears `key_hash` from the active speculative prefetch set once resident or cancelled.
    ///
    /// # Arguments
    ///
    /// - `u64` - Asset key hash to clear.
    pub fn unmark_prefetched(&mut self, key_hash: u64) {
        let Self {
            active_prefetches, ..
        } = self;
        let _: bool = active_prefetches.remove(&key_hash);
    }

    /// Queries the velocity-predicted lookahead sphere `pos + vel * lookahead_secs` for upcoming assets and identifies trailing behind-camera prefetches to cancel.
    ///
    /// # Arguments
    ///
    /// - `&SpatialPrefetchVolume` - Camera position, velocity, horizon, and spherical prefetch radius.
    /// - `&mut Vec<SpatialAssetAnchor>` - Destination list populated with upcoming lookahead anchors ordered nearest-first.
    /// - `&mut Vec<u64>` - Destination list populated with trailing behind-camera asset key hashes to cancel.
    pub fn query_lookahead(
        &self,
        volume: &SpatialPrefetchVolume,
        out_prefetch: &mut Vec<SpatialAssetAnchor>,
        out_cancel: &mut Vec<u64>,
    ) {
        out_prefetch.clear();
        out_cancel.clear();
        let Self {
            cell_size,
            anchors,
            key_to_index,
            cells,
            active_prefetches,
        } = self;
        let center: [f32; 3] = volume.get_center();
        let velocity: [f32; 3] = volume.get_velocity();
        let predicted: [f32; 3] = volume.predicted_center();
        let radius: f32 = volume.get_radius().max(0.0);
        let speed_sq: f32 = prefetch_dot_3d(velocity, velocity);
        let speed: f32 = speed_sq.sqrt();
        let min_cell: (i32, i32, i32) = world_to_prefetch_cell(
            [
                predicted[0] - radius,
                predicted[1] - radius,
                predicted[2] - radius,
            ],
            *cell_size,
        );
        let max_cell: (i32, i32, i32) = world_to_prefetch_cell(
            [
                predicted[0] + radius,
                predicted[1] + radius,
                predicted[2] + radius,
            ],
            *cell_size,
        );
        let mut visited: HashSet<usize> = HashSet::new();
        let mut ranked: Vec<(f32, SpatialAssetAnchor)> = Vec::new();
        for cx in min_cell.0..=max_cell.0 {
            for cy in min_cell.1..=max_cell.1 {
                for cz in min_cell.2..=max_cell.2 {
                    let Some(bucket) = cells.get(&(cx, cy, cz)) else {
                        continue;
                    };
                    for &anchor_idx in bucket.iter() {
                        if !visited.insert(anchor_idx) {
                            continue;
                        }
                        let Some(Some(anchor)) = anchors.get(anchor_idx) else {
                            continue;
                        };
                        let combined_r: f32 = radius + anchor.get_bounding_radius().max(0.0);
                        let dist_sq: f32 = prefetch_dist_sq_3d(anchor.get_position(), predicted);
                        if dist_sq <= combined_r * combined_r {
                            ranked.push((dist_sq, *anchor));
                        }
                    }
                }
            }
        }
        ranked.sort_by(
            |left: &(f32, SpatialAssetAnchor), right: &(f32, SpatialAssetAnchor)| {
                left.0.total_cmp(&right.0)
            },
        );
        for (_, anchor) in ranked {
            out_prefetch.push(anchor);
        }
        if speed >= PREFETCH_MIN_SPEED_EPSILON {
            let dir: [f32; 3] = [
                velocity[0] / speed,
                velocity[1] / speed,
                velocity[2] / speed,
            ];
            let rear_threshold: f32 = -(radius * PREFETCH_REAR_CANCEL_MARGIN_RATIO);
            for &prefetched_key in active_prefetches.iter() {
                let Some(&anchor_idx) = key_to_index.get(&prefetched_key) else {
                    continue;
                };
                let Some(Some(anchor)) = anchors.get(anchor_idx) else {
                    continue;
                };
                let anchor_pos: [f32; 3] = anchor.get_position();
                let combined_r: f32 = radius + anchor.get_bounding_radius().max(0.0);
                let in_lookahead: bool =
                    prefetch_dist_sq_3d(anchor_pos, predicted) <= combined_r * combined_r;
                if in_lookahead {
                    continue;
                }
                let rel: [f32; 3] = [
                    anchor_pos[0] - center[0],
                    anchor_pos[1] - center[1],
                    anchor_pos[2] - center[2],
                ];
                let forward_proj: f32 = prefetch_dot_3d(rel, dir);
                if forward_proj < rear_threshold {
                    out_cancel.push(prefetched_key);
                }
            }
        }
    }
}