euv-core 0.52.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
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
use super::*;

/// Cache-line-isolated atomic counter helpers for `AlignedAtomicUsize`.
impl AlignedAtomicUsize {
    /// Creates a new cache-line-aligned atomic counter initialized to `initial`.
    ///
    /// # Arguments
    ///
    /// - `usize` - Initial atomic value.
    ///
    /// # Returns
    ///
    /// - `Self` - Initialized aligned atomic counter.
    #[cfg_attr(not(target_arch = "wasm32"), inline)]
    #[must_use]
    pub fn new(initial: usize) -> Self {
        Self {
            value: AtomicUsize::new(initial),
        }
    }

    /// Loads the underlying atomic value with `ordering`.
    ///
    /// # Arguments
    ///
    /// - `Ordering` - Memory ordering constraint.
    ///
    /// # Returns
    ///
    /// - `usize` - Loaded value.
    #[cfg_attr(not(target_arch = "wasm32"), inline)]
    #[must_use]
    pub fn load(&self, ordering: Ordering) -> usize {
        let Self { value } = self;
        value.load(ordering)
    }

    /// Stores `next_value` into the underlying atomic counter with `ordering`.
    ///
    /// # Arguments
    ///
    /// - `usize` - Value to store.
    /// - `Ordering` - Memory ordering constraint.
    #[cfg_attr(not(target_arch = "wasm32"), inline)]
    pub fn store(&self, next_value: usize, ordering: Ordering) {
        let Self { value } = self;
        value.store(next_value, ordering);
    }

    /// Atomically adds `delta` and returns the previous value using `ordering`.
    ///
    /// # Arguments
    ///
    /// - `usize` - Increment delta.
    /// - `Ordering` - Memory ordering constraint.
    ///
    /// # Returns
    ///
    /// - `usize` - Previous atomic value before addition.
    #[cfg_attr(not(target_arch = "wasm32"), inline)]
    pub fn fetch_add(&self, delta: usize, ordering: Ordering) -> usize {
        let Self { value } = self;
        value.fetch_add(delta, ordering)
    }
}

/// Unified persistent work-stealing thread pool operations for `EngineWorkerPool`.
impl EngineWorkerPool {
    /// Creates a new persistent worker pool sized to the host hardware concurrency (`1..=ENGINE_WORKER_MAX_THREADS`).
    ///
    /// # Returns
    ///
    /// - `Self` - Initialized worker pool with warm background threads.
    #[must_use]
    pub fn new() -> Self {
        #[cfg(not(target_arch = "wasm32"))]
        {
            let total_threads: usize = available_parallelism()
                .map(usize::from)
                .unwrap_or(4)
                .clamp(1, ENGINE_WORKER_MAX_THREADS);
            Self::with_total_threads(total_threads)
        }
        #[cfg(target_arch = "wasm32")]
        {
            Self { worker_count: 0 }
        }
    }

    /// Creates a persistent worker pool configured for `total_threads` concurrent execution lanes (caller plus background workers).
    ///
    /// # Arguments
    ///
    /// - `usize` - Desired total thread count clamped to `1..=ENGINE_WORKER_MAX_THREADS`.
    ///
    /// # Returns
    ///
    /// - `Self` - Initialized worker pool.
    #[must_use]
    pub fn with_total_threads(total_threads: usize) -> Self {
        #[cfg(not(target_arch = "wasm32"))]
        {
            let clamped_total: usize = total_threads.clamp(1, ENGINE_WORKER_MAX_THREADS);
            let requested_workers: usize = clamped_total.saturating_sub(1);
            let mut slots: Vec<EngineWorkerSlot> = Vec::with_capacity(requested_workers);
            for _ in 0..requested_workers {
                slots.push(EngineWorkerSlot::default());
            }
            let shared: Arc<EnginePoolShared> = Arc::new(EnginePoolShared {
                active_job: AtomicUsize::new(0),
                active_workers: AtomicUsize::new(0),
                spin_limit: AtomicUsize::new(ENGINE_ACTIVE_SPIN_LIMIT.load(Ordering::Relaxed)),
                shutdown: AtomicUsize::new(0),
                caller_parked: AlignedAtomicUsize::default(),
                caller_lock: Mutex::new(()),
                wake_caller: Condvar::new(),
                slots,
            });
            let mut handles: Vec<JoinHandle<()>> = Vec::with_capacity(requested_workers);
            for worker_slot_idx in 0..requested_workers {
                let shared_clone: Arc<EnginePoolShared> = Arc::clone(&shared);
                let thread_name: String =
                    format!("{ENGINE_WORKER_THREAD_PREFIX}-{worker_slot_idx}");
                let worker_lane_id: usize = worker_slot_idx.saturating_add(1);
                if let Ok(handle) = Builder::new().name(thread_name).spawn(move || {
                    engine_worker_thread_loop(&shared_clone, worker_slot_idx, worker_lane_id);
                }) {
                    handles.push(handle);
                } else {
                    break;
                }
            }
            let worker_count: usize = handles.len();
            Self {
                worker_count,
                dispatch_guard: Mutex::new(()),
                shared,
                handles,
            }
        }
        #[cfg(target_arch = "wasm32")]
        {
            let _: usize = total_threads;
            Self { worker_count: 0 }
        }
    }

    /// Returns the count of active background worker threads excluding the calling thread.
    ///
    /// # Returns
    ///
    /// - `usize` - Background worker thread count (`0` on single-core or `wasm32`).
    #[cfg_attr(not(target_arch = "wasm32"), inline)]
    #[must_use]
    pub fn worker_count(&self) -> usize {
        let Self { worker_count, .. } = self;
        *worker_count
    }

    /// Returns total concurrent execution threads including the calling thread (`1..=ENGINE_WORKER_MAX_THREADS`).
    ///
    /// # Returns
    ///
    /// - `usize` - Total execution thread count.
    #[cfg_attr(not(target_arch = "wasm32"), inline)]
    #[must_use]
    pub fn total_threads(&self) -> usize {
        self.worker_count().saturating_add(1)
    }

    /// Updates the adaptive hybrid spin limit on this pool (`ENGINE_WORKER_SPIN_LIMIT_ACTIVE` vs `ENGINE_WORKER_SPIN_LIMIT_IDLE`).
    ///
    /// # Arguments
    ///
    /// - `bool` - `true` when high-frequency frames are active; `false` for immediate idle parking.
    pub fn set_spin_active(&self, 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
            };
            let Self { shared, .. } = self;
            shared.spin_limit.store(limit, Ordering::Relaxed);
        }
        #[cfg(target_arch = "wasm32")]
        {
            let _: bool = active;
        }
    }

    /// Returns the active adaptive spin-loop iteration limit configured on this pool.
    ///
    /// # Returns
    ///
    /// - `u32` - Active spin iteration count.
    #[must_use]
    pub fn spin_limit(&self) -> u32 {
        #[cfg(not(target_arch = "wasm32"))]
        {
            let Self { shared, .. } = self;
            shared.spin_limit.load(Ordering::Relaxed) as u32
        }
        #[cfg(target_arch = "wasm32")]
        {
            0
        }
    }

    /// Dispatches a type-erased stack-pinned raw job across up to `max_workers` background threads plus the calling thread.
    ///
    /// # Arguments
    ///
    /// - `usize` - Stack-pinned payload pointer valid until all workers complete.
    /// - `unsafe fn(usize, usize)` - Trampoline receiving `(payload_ptr, worker_lane_index)` (`0` = caller, `1..=max_workers` = workers).
    /// - `usize` - Maximum number of background workers to wake for this epoch.
    #[cfg(not(target_arch = "wasm32"))]
    pub(crate) fn dispatch_raw(
        &self,
        payload_ptr: usize,
        invoke: unsafe fn(usize, usize),
        max_workers: usize,
    ) {
        let Self {
            worker_count,
            dispatch_guard,
            shared,
            ..
        } = self;
        let dispatch_workers: usize = (*worker_count).min(max_workers);
        if dispatch_workers == 0 {
            // SAFETY: Caller guarantees `payload_ptr` is valid for `invoke`.
            unsafe {
                invoke(payload_ptr, 0);
            }
            return;
        }
        let Ok(_guard) = dispatch_guard.try_lock() else {
            // SAFETY: Re-entrant caller falls back serially while `payload_ptr` is live on stack.
            unsafe {
                invoke(payload_ptr, 0);
            }
            return;
        };
        let job: EngineDispatchJob = EngineDispatchJob {
            payload_ptr,
            invoke,
            workers_done: AlignedAtomicUsize::default(),
        };
        shared
            .active_workers
            .store(dispatch_workers, Ordering::Relaxed);
        shared.active_job.store(
            (&job as *const EngineDispatchJob) as usize,
            Ordering::Release,
        );
        let active_slots: &[EngineWorkerSlot] = &shared.slots[..dispatch_workers];
        for slot in active_slots.iter() {
            let next_epoch: usize = slot.epoch.load(Ordering::Relaxed).wrapping_add(1);
            slot.epoch.store(next_epoch, Ordering::SeqCst);
        }
        for slot in active_slots.iter() {
            if slot.parked.load(Ordering::SeqCst) != 0
                && let Ok(_slot_guard) = slot.lock.lock()
            {
                slot.wake.notify_one();
            }
        }
        // SAFETY: Caller executes lane `0` while `job` and `payload_ptr` remain stack-pinned.
        unsafe {
            invoke(payload_ptr, 0);
        }
        let caller_spin_limit: u32 = if shared.spin_limit.load(Ordering::Relaxed) > 0 {
            ENGINE_CALLER_SPIN_LIMIT_ACTIVE
        } else {
            ENGINE_CALLER_SPIN_LIMIT_IDLE
        };
        let mut caller_spins: u32 = 0;
        while job.workers_done.load(Ordering::Acquire) < dispatch_workers {
            if caller_spins < caller_spin_limit {
                caller_spins = caller_spins.saturating_add(1);
                spin_loop();
                continue;
            }
            if let Ok(mut guard) = shared.caller_lock.lock() {
                shared.caller_parked.store(1, Ordering::SeqCst);
                while job.workers_done.load(Ordering::SeqCst) < dispatch_workers {
                    let Ok(next_guard) = shared.wake_caller.wait(guard) else {
                        break;
                    };
                    guard = next_guard;
                }
                shared.caller_parked.store(0, Ordering::SeqCst);
            } else {
                spin_loop();
            }
        }
        shared.active_job.store(0, Ordering::Release);
    }

    /// Partitions `[0..total_items)` into `grain_size` chunks claimed lock-free across workers and executes `work_fn(start, end, worker_lane)`.
    ///
    /// # Arguments
    ///
    /// - `usize` - Total number of logical items to process.
    /// - `usize` - Minimum items per claimed work-stealing chunk (`>= 1`).
    /// - `WorkFn` - Synchronized closure receiving `(chunk_start, chunk_end, worker_lane_index)`.
    pub fn parallel_for_chunks<WorkFn>(
        &self,
        total_items: usize,
        grain_size: usize,
        work_fn: WorkFn,
    ) where
        WorkFn: Fn(usize, usize, usize) + Sync,
    {
        if total_items == 0 {
            return;
        }
        let effective_grain: usize = grain_size.max(1);
        let chunk_count: usize = total_items.div_ceil(effective_grain);
        if chunk_count <= 1 || self.worker_count() == 0 {
            work_fn(0, total_items, 0);
            return;
        }
        #[cfg(not(target_arch = "wasm32"))]
        {
            let state: ParallelChunksState<'_, WorkFn> = ParallelChunksState {
                total_items,
                grain_size: effective_grain,
                chunk_count,
                next_chunk: AlignedAtomicUsize::default(),
                work_fn: &work_fn,
            };
            let max_workers: usize = chunk_count.saturating_sub(1);
            let payload_ptr: usize = (&state as *const ParallelChunksState<'_, WorkFn>) as usize;
            self.dispatch_raw(
                payload_ptr,
                parallel_chunks_trampoline::<WorkFn>,
                max_workers,
            );
        }
        #[cfg(target_arch = "wasm32")]
        {
            work_fn(0, total_items, 0);
        }
    }

    /// Executes `work_fn(index, item, worker_lane)` for every element in `items` using lock-free atomic work-stealing.
    ///
    /// # Arguments
    ///
    /// - `&[ItemType]` - Contiguous slice of work items to distribute across workers.
    /// - `WorkFn` - Synchronized closure receiving `(item_index, item_ref, worker_lane_index)`.
    pub fn parallel_work_steal<ItemType, WorkFn>(&self, items: &[ItemType], work_fn: WorkFn)
    where
        ItemType: Sync,
        WorkFn: Fn(usize, &ItemType, usize) + Sync,
    {
        if items.is_empty() {
            return;
        }
        if items.len() == 1 || self.worker_count() == 0 {
            for (item_index, item_ref) in items.iter().enumerate() {
                work_fn(item_index, item_ref, 0);
            }
            return;
        }
        #[cfg(not(target_arch = "wasm32"))]
        {
            let state: ParallelStealState<'_, ItemType, WorkFn> = ParallelStealState {
                items,
                next_index: AlignedAtomicUsize::default(),
                work_fn: &work_fn,
            };
            let max_workers: usize = items.len().saturating_sub(1);
            let payload_ptr: usize =
                (&state as *const ParallelStealState<'_, ItemType, WorkFn>) as usize;
            self.dispatch_raw(
                payload_ptr,
                parallel_steal_trampoline::<ItemType, WorkFn>,
                max_workers,
            );
        }
        #[cfg(target_arch = "wasm32")]
        {
            for (item_index, item_ref) in items.iter().enumerate() {
                work_fn(item_index, item_ref, 0);
            }
        }
    }
}

/// Default construction creating a host-sized `EngineWorkerPool`.
impl Default for EngineWorkerPool {
    /// Creates a default host-sized `EngineWorkerPool`.
    ///
    /// # Returns
    ///
    /// - `Self` - Host-sized persistent worker pool.
    fn default() -> Self {
        Self::new()
    }
}

/// Clean background thread shutdown and handle join when an `EngineWorkerPool` drops.
#[cfg(not(target_arch = "wasm32"))]
impl Drop for EngineWorkerPool {
    /// Signals all persistent background worker threads to exit and joins every handle.
    fn drop(&mut self) {
        let Self {
            shared, handles, ..
        } = self;
        shared.shutdown.store(1, Ordering::SeqCst);
        for slot in shared.slots.iter() {
            if let Ok(_guard) = slot.lock.lock() {
                slot.wake.notify_one();
            }
        }
        for handle in handles.drain(..) {
            let _: Result<(), Box<dyn Any + Send>> = handle.join();
        }
    }
}