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

/// Persistent worker loop executing epochs with hybrid adaptive spin-then-park synchronization.
///
/// # Arguments
///
/// - `&EnginePoolShared` - Shared dispatch header and per-worker wake slots.
/// - `usize` - Zero-based slot index inside `shared.slots`.
/// - `usize` - Stable one-based worker lane identifier passed into job trampolines.
#[cfg(not(target_arch = "wasm32"))]
pub(crate) fn engine_worker_thread_loop(
    shared: &EnginePoolShared,
    worker_slot_idx: usize,
    worker_lane_id: usize,
) {
    let slot: &EngineWorkerSlot = &shared.slots[worker_slot_idx];
    let mut seen_epoch: usize = 0;
    loop {
        let mut spins: u32 = 0;
        let mut spin_budget: u32 = shared.spin_limit.load(Ordering::Relaxed) as u32;
        let job_ptr: usize = loop {
            let cur_epoch: usize = slot.epoch.load(Ordering::Acquire);
            if cur_epoch != seen_epoch {
                let ptr: usize = shared.active_job.load(Ordering::Acquire);
                if ptr != 0 {
                    seen_epoch = cur_epoch;
                    break ptr;
                }
            }
            if shared.shutdown.load(Ordering::Acquire) != 0 {
                return;
            }
            if spins < spin_budget {
                spins = spins.saturating_add(1);
                if (spins & 63) == 0 {
                    spin_budget = shared.spin_limit.load(Ordering::Relaxed) as u32;
                }
                spin_loop();
                continue;
            }
            let Ok(mut guard) = slot.lock.lock() else {
                return;
            };
            slot.parked.store(1, Ordering::SeqCst);
            let parked_ptr: Option<usize> = loop {
                let locked_epoch: usize = slot.epoch.load(Ordering::SeqCst);
                if locked_epoch != seen_epoch {
                    let ptr: usize = shared.active_job.load(Ordering::Acquire);
                    if ptr != 0 {
                        seen_epoch = locked_epoch;
                        break Some(ptr);
                    }
                }
                if shared.shutdown.load(Ordering::SeqCst) != 0 {
                    break None;
                }
                let Ok(next_guard) = slot.wake.wait(guard) else {
                    break None;
                };
                guard = next_guard;
            };
            slot.parked.store(0, Ordering::SeqCst);
            let Some(ptr) = parked_ptr else {
                return;
            };
            break ptr;
        };
        // SAFETY: Caller pins `EngineDispatchJob` on stack until `workers_done >= active_workers`.
        let job: &EngineDispatchJob = unsafe { &*(job_ptr as *const EngineDispatchJob) };
        // SAFETY: `job.payload_ptr` remains valid until this worker increments `workers_done`.
        unsafe {
            (job.invoke)(job.payload_ptr, worker_lane_id);
        }
        let expected: usize = shared.active_workers.load(Ordering::Acquire);
        let finished: usize = job.workers_done.fetch_add(1, Ordering::SeqCst) + 1;
        if finished >= expected
            && shared.caller_parked.load(Ordering::SeqCst) != 0
            && let Ok(_caller_guard) = shared.caller_lock.lock()
        {
            shared.wake_caller.notify_one();
        }
    }
}

/// Monomorphized work-stealing chunk trampoline invoked by `EngineWorkerPool::parallel_for_chunks`.
///
/// # Arguments
///
/// - `usize` - Raw pointer to stack-pinned `ParallelChunksState`.
/// - `usize` - Executing thread lane index (`0` = caller, `1..=worker_count` = worker).
#[cfg(not(target_arch = "wasm32"))]
pub(crate) unsafe fn parallel_chunks_trampoline<WorkFn>(payload_ptr: usize, worker_lane: usize)
where
    WorkFn: Fn(usize, usize, usize) + Sync,
{
    // SAFETY: Caller pins `ParallelChunksState` on stack for the duration of `dispatch_raw`.
    let state: &ParallelChunksState<'_, WorkFn> =
        unsafe { &*(payload_ptr as *const ParallelChunksState<'_, WorkFn>) };
    loop {
        let chunk_index: usize = state.next_chunk.fetch_add(1, Ordering::AcqRel);
        if chunk_index >= state.chunk_count {
            break;
        }
        let start_index: usize = chunk_index.saturating_mul(state.grain_size);
        let end_index: usize = start_index
            .saturating_add(state.grain_size)
            .min(state.total_items);
        if start_index < end_index {
            (state.work_fn)(start_index, end_index, worker_lane);
        }
    }
}

/// Monomorphized single-item work-stealing trampoline invoked by `EngineWorkerPool::parallel_work_steal`.
///
/// # Arguments
///
/// - `usize` - Raw pointer to stack-pinned `ParallelStealState`.
/// - `usize` - Executing thread lane index (`0` = caller, `1..=worker_count` = worker).
#[cfg(not(target_arch = "wasm32"))]
pub(crate) unsafe fn parallel_steal_trampoline<ItemType, WorkFn>(
    payload_ptr: usize,
    worker_lane: usize,
) where
    ItemType: Sync,
    WorkFn: Fn(usize, &ItemType, usize) + Sync,
{
    // SAFETY: Caller pins `ParallelStealState` on stack for the duration of `dispatch_raw`.
    let state: &ParallelStealState<'_, ItemType, WorkFn> =
        unsafe { &*(payload_ptr as *const ParallelStealState<'_, ItemType, WorkFn>) };
    let total_items: usize = state.items.len();
    loop {
        let item_index: usize = state.next_index.fetch_add(1, Ordering::AcqRel);
        if item_index >= total_items {
            break;
        }
        (state.work_fn)(item_index, &state.items[item_index], worker_lane);
    }
}

/// Returns the process-wide `EngineWorkerPool`, initializing it synchronously if not yet warm.
///
/// # Returns
///
/// - `&'static EngineWorkerPool` - Shared process-wide work-stealing worker pool.
#[cfg(not(target_arch = "wasm32"))]
#[must_use]
pub fn global_engine_worker_pool() -> &'static EngineWorkerPool {
    let pool: &EngineWorkerPool = ENGINE_WORKER_POOL.get_or_init(EngineWorkerPool::new);
    let current_spin: usize = ENGINE_ACTIVE_SPIN_LIMIT.load(Ordering::Relaxed);
    pool.shared
        .spin_limit
        .store(current_spin, Ordering::Relaxed);
    ENGINE_POOL_STATE.store(ENGINE_POOL_READY, Ordering::Release);
    pool
}

/// Returns the process-wide `EngineWorkerPool` only when already warm and ready, without ever blocking Frame 1.
///
/// # Returns
///
/// - `Option<&'static EngineWorkerPool>` - Warm worker pool reference if initialization has finished.
#[cfg(not(target_arch = "wasm32"))]
#[cfg_attr(not(target_arch = "wasm32"), inline)]
#[must_use]
pub fn try_get_ready_engine_worker_pool() -> Option<&'static EngineWorkerPool> {
    if ENGINE_POOL_STATE.load(Ordering::Acquire) == ENGINE_POOL_READY {
        ENGINE_WORKER_POOL.get()
    } else {
        None
    }
}

/// Returns the current lifecycle state of the process-wide `EngineWorkerPool`.
///
/// # Returns
///
/// - `EnginePoolState` - Current initialization state (`Uninitialized`, `Spawning`, or `Ready`).
#[must_use]
pub fn engine_worker_pool_state() -> EnginePoolState {
    #[cfg(not(target_arch = "wasm32"))]
    {
        match ENGINE_POOL_STATE.load(Ordering::Acquire) {
            ENGINE_POOL_SPAWNING => EnginePoolState::Spawning,
            ENGINE_POOL_READY => EnginePoolState::Ready,
            _ => EnginePoolState::Uninitialized,
        }
    }
    #[cfg(target_arch = "wasm32")]
    {
        EnginePoolState::Uninitialized
    }
}

/// Returns `true` when the process-wide `EngineWorkerPool` is warm and ready for lock-free dispatch.
///
/// # Returns
///
/// - `bool` - `true` when background worker threads are ready.
#[must_use]
pub fn is_engine_worker_pool_ready() -> bool {
    engine_worker_pool_state() == EnginePoolState::Ready
}

/// Returns the active adaptive worker spin iteration limit (`ENGINE_WORKER_SPIN_LIMIT_ACTIVE` or `0`).
///
/// # Returns
///
/// - `u32` - Active adaptive spin iteration count.
#[must_use]
pub fn engine_worker_active_spin_limit() -> u32 {
    #[cfg(not(target_arch = "wasm32"))]
    {
        ENGINE_ACTIVE_SPIN_LIMIT.load(Ordering::Relaxed) as u32
    }
    #[cfg(target_arch = "wasm32")]
    {
        0
    }
}

/// Updates the process-wide adaptive worker spin budget (`active = true` during motion/bulk layout, `false` when idle).
///
/// # Arguments
///
/// - `bool` - `true` to enable short hybrid spinning; `false` for immediate idle park.
pub fn set_engine_worker_spin_active(active: bool) {
    #[cfg(not(target_arch = "wasm32"))]
    {
        let limit: usize = if active {
            ENGINE_WORKER_SPIN_LIMIT_ACTIVE as usize
        } else {
            ENGINE_WORKER_SPIN_LIMIT_IDLE as usize
        };
        ENGINE_ACTIVE_SPIN_LIMIT.store(limit, Ordering::Relaxed);
        if let Some(pool) = try_get_ready_engine_worker_pool() {
            pool.shared.spin_limit.store(limit, Ordering::Relaxed);
        }
    }
    #[cfg(target_arch = "wasm32")]
    {
        let _: bool = active;
    }
}

/// Triggers non-blocking asynchronous background initialization of the process-wide `EngineWorkerPool`.
pub fn warm_engine_worker_pool_async() {
    #[cfg(not(target_arch = "wasm32"))]
    {
        if ENGINE_POOL_STATE
            .compare_exchange(
                ENGINE_POOL_UNINITIALIZED,
                ENGINE_POOL_SPAWNING,
                Ordering::AcqRel,
                Ordering::Acquire,
            )
            .is_err()
        {
            return;
        }
        let spawned: io::Result<JoinHandle<()>> = Builder::new()
            .name(ENGINE_POOL_INIT_THREAD_NAME.to_string())
            .spawn(|| {
                let pool: &EngineWorkerPool = ENGINE_WORKER_POOL.get_or_init(EngineWorkerPool::new);
                let current_spin: usize = ENGINE_ACTIVE_SPIN_LIMIT.load(Ordering::Relaxed);
                pool.shared
                    .spin_limit
                    .store(current_spin, Ordering::Relaxed);
                ENGINE_POOL_STATE.store(ENGINE_POOL_READY, Ordering::Release);
            });
        if spawned.is_err() {
            ENGINE_POOL_STATE.store(ENGINE_POOL_UNINITIALIZED, Ordering::Release);
        }
    }
}