euv-core 0.46.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
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
use super::*;

/// Validation and footprint helpers for `GpuTextureHandle`.
impl GpuTextureHandle {
    /// Constructs a persistent GPU texture handle bound to `(texture_id, device_id)` with exact `(width, height)` dimensions and `format`.
    ///
    /// # Arguments
    ///
    /// - `u64` - Backend-opaque GPU texture identifier.
    /// - `u64` - Owning GPU logical device identifier.
    /// - `u64` - Surface generation counter.
    /// - `(u32, u32)` - Texture `(width, height)` in physical pixels.
    /// - `GpuTextureFormat` - GPU texture pixel format.
    /// - `u64` - Synchronization fence value.
    /// - `bool` - Whether the texture uses top-left origin orientation.
    ///
    /// # Returns
    ///
    /// - `Self` - Constructed GPU texture handle.
    #[must_use]
    pub const fn new(
        texture_id: u64,
        device_id: u64,
        generation: u64,
        dimensions: (u32, u32),
        format: GpuTextureFormat,
        fence_value: u64,
        origin_top_left: bool,
    ) -> Self {
        Self {
            texture_id,
            device_id,
            generation,
            width: dimensions.0,
            height: dimensions.1,
            format,
            fence_value,
            origin_top_left,
        }
    }

    /// Returns `true` when this handle refers to a non-zero GPU texture with non-zero dimensions.
    ///
    /// # Arguments
    ///
    /// - `&Self` - Texture handle reference.
    ///
    /// # Returns
    ///
    /// - `bool` - Validity flag.
    #[must_use]
    pub const fn is_valid(&self) -> bool {
        let Self {
            texture_id,
            device_id,
            width,
            height,
            ..
        } = *self;
        texture_id != 0 && device_id != 0 && width > 0 && height > 0
    }

    /// Returns `true` when this handle belongs to `device_id` and can be composited without cross-device copies.
    ///
    /// # Arguments
    ///
    /// - `&Self` - Texture handle reference.
    /// - `u64` - Expected logical GPU device identifier.
    ///
    /// # Returns
    ///
    /// - `bool` - `true` when valid and matching `device_id`.
    #[must_use]
    pub const fn matches_device(&self, expected_device: u64) -> bool {
        let Self { device_id, .. } = *self;
        self.is_valid() && device_id == expected_device
    }

    /// Returns bytes per pixel for this handle's `GpuTextureFormat`.
    ///
    /// # Arguments
    ///
    /// - `&Self` - Texture handle reference.
    ///
    /// # Returns
    ///
    /// - `usize` - Byte width per pixel (`4` or `8`).
    #[must_use]
    pub const fn bytes_per_pixel(&self) -> usize {
        let Self { format, .. } = *self;
        match format {
            GpuTextureFormat::Rgba16Float => 8,
            GpuTextureFormat::Rgba8Unorm
            | GpuTextureFormat::Rgba8UnormSrgb
            | GpuTextureFormat::Bgra8Unorm
            | GpuTextureFormat::Rgb10A2Unorm => 4,
        }
    }

    /// Returns estimated GPU texture footprint in bytes.
    ///
    /// # Arguments
    ///
    /// - `&Self` - Texture handle reference.
    ///
    /// # Returns
    ///
    /// - `usize` - Estimated GPU memory footprint in bytes.
    #[must_use]
    pub const fn estimated_bytes(&self) -> usize {
        let Self { width, height, .. } = *self;
        (width as usize)
            .saturating_mul(height as usize)
            .saturating_mul(self.bytes_per_pixel())
    }
}

/// GPU compositing and isolated world/HUD dirty coordination for `GpuCompositeTarget`.
impl GpuCompositeTarget {
    /// Attaches a persistent GPU render target handle and logical viewport rectangle.
    ///
    /// # Arguments
    ///
    /// - `&Self` - Mutable composite target.
    /// - `GpuTextureHandle` - Same-device GPU render target handle.
    /// - `Rect` - Viewport destination rectangle in root logical coordinates.
    pub fn attach_handle(&mut self, handle: GpuTextureHandle, viewport_rect: Rect) {
        self.set_handle(handle);
        self.set_viewport_rect(viewport_rect);
        self.mark_world_dirty();
    }

    /// Marks the 2D/3D game world render target dirty without forcing unrelated HUD invalidations.
    ///
    /// # Arguments
    ///
    /// - `&Self` - Mutable composite target.
    pub fn mark_world_dirty(&mut self) {
        let next: u64 = self.get_world_revision().wrapping_add(1);
        self.set_world_revision(next);
    }

    /// Marks only the overlaid EUV HUD dirty without forcing a full 3D/2D world re-render.
    ///
    /// # Arguments
    ///
    /// - `&Self` - Mutable composite target.
    pub fn mark_hud_dirty(&mut self) {
        let next: u64 = self.get_hud_revision().wrapping_add(1);
        self.set_hud_revision(next);
    }

    /// Returns `true` when the game world target needs a fresh render pass before compositing.
    ///
    /// # Arguments
    ///
    /// - `&Self` - Composite target reference.
    ///
    /// # Returns
    ///
    /// - `bool` - `true` when `world_revision != presented_world_revision`.
    #[must_use]
    pub fn needs_world_render(&self) -> bool {
        self.get_world_revision() != self.get_presented_world_revision()
    }

    /// Returns `true` when only the HUD overlay changed since the last present.
    ///
    /// # Arguments
    ///
    /// - `&Self` - Composite target reference.
    ///
    /// # Returns
    ///
    /// - `bool` - `true` when HUD is dirty while the world target is already up to date.
    #[must_use]
    pub fn is_hud_only_dirty(&self) -> bool {
        !self.needs_world_render() && self.get_hud_revision() != self.get_presented_hud_revision()
    }

    /// Selects `ViewportPresentPath::GpuDirectComposite` when a valid same-device handle is attached, else `CpuPooledFallback`.
    ///
    /// # Arguments
    ///
    /// - `&Self` - Composite target reference.
    /// - `u64` - Active compositor GPU device identifier.
    ///
    /// # Returns
    ///
    /// - `ViewportPresentPath` - Active presentation transport.
    #[must_use]
    pub fn resolve_present_path(&self, compositor_device_id: u64) -> ViewportPresentPath {
        if self.get_handle().matches_device(compositor_device_id) {
            ViewportPresentPath::GpuDirectComposite
        } else {
            ViewportPresentPath::CpuPooledFallback
        }
    }

    /// Records a single-present GPU composite submission advancing fence and revision telemetry.
    ///
    /// # Arguments
    ///
    /// - `&Self` - Mutable composite target.
    /// - `u64` - Submission fence value associated with this present pass.
    ///
    /// # Returns
    ///
    /// - `Option<GpuCompositeDescriptor>` - Descriptor for the compositor when the GPU handle is valid.
    pub fn record_composite_present(&mut self, fence_value: u64) -> Option<GpuCompositeDescriptor> {
        let mut handle: GpuTextureHandle = self.get_handle();
        if !handle.is_valid() {
            return None;
        }
        let hud_only: bool = self.is_hud_only_dirty();
        handle.set_fence_value(fence_value);
        self.set_handle(handle);
        self.set_submitted_fence(fence_value);
        let world_rev: u64 = self.get_world_revision();
        let hud_rev: u64 = self.get_hud_revision();
        self.set_presented_world_revision(world_rev);
        self.set_presented_hud_revision(hud_rev);
        let next_presents: u64 = self.get_zero_readback_presents().saturating_add(1);
        self.set_zero_readback_presents(next_presents);
        if hud_only {
            let next_reuse: u64 = self.get_hud_only_reuses().saturating_add(1);
            self.set_hud_only_reuses(next_reuse);
        }
        Some(GpuCompositeDescriptor::new(
            self.get_viewport_rect(),
            handle,
            0,
            true,
        ))
    }

    /// Retires completed GPU fences up to `fence_value`.
    ///
    /// # Arguments
    ///
    /// - `&Self` - Mutable composite target.
    /// - `u64` - Latest completed GPU queue fence value.
    pub fn retire_fence(&mut self, fence_value: u64) {
        if fence_value > self.get_completed_fence() {
            self.set_completed_fence(fence_value);
        }
    }
}

/// Default triple-buffered `RenderBufferPool`.
impl Default for RenderBufferPool {
    /// Creates a bounded triple-buffered CPU render output pool (`3` slots).
    ///
    /// # Returns
    ///
    /// - `Self` - Default render buffer pool.
    fn default() -> Self {
        Self::with_capacity(RENDER_POOL_DEFAULT_SLOTS)
    }
}

/// Bounded zero-allocation buffer pooling and fence-gated release for `RenderBufferPool`.
impl RenderBufferPool {
    /// Creates a bounded `RenderBufferPool` holding `slot_count` reusable slots (clamped to `1..=8`).
    ///
    /// # Arguments
    ///
    /// - `usize` - Requested bounded slot count.
    ///
    /// # Returns
    ///
    /// - `Self` - Initialized render buffer pool.
    #[must_use]
    pub fn with_capacity(slot_count: usize) -> Self {
        let clamped: usize = slot_count.clamp(RENDER_POOL_MIN_SLOTS, RENDER_POOL_MAX_SLOTS);
        let mut slots: Vec<PooledRenderBufferSlot> = Vec::with_capacity(clamped);
        for _ in 0..clamped {
            slots.push(PooledRenderBufferSlot::default());
        }
        Self {
            state: Rc::new(RefCell::new(RenderBufferPoolState {
                slots,
                completed_fence: 0,
                reuse_hits: 0,
                backing_allocations: 0,
                backpressure_rejections: 0,
            })),
        }
    }

    /// Pre-allocates backing storage for all slots for a `(width, height)` RGBA8 framebuffer so steady-state renders allocate zero bytes.
    ///
    /// # Arguments
    ///
    /// - `&Self` - Pool reference.
    /// - `u32` - Framebuffer width in pixels.
    /// - `u32` - Framebuffer height in pixels.
    pub fn preallocate(&self, width: u32, height: u32) {
        let needed: usize = (width as usize)
            .saturating_mul(height as usize)
            .saturating_mul(4);
        if needed == 0 {
            return;
        }
        if let Ok(mut guard) = self.get_state().try_borrow_mut() {
            let mut grew: u64 = 0;
            for slot in guard.get_mut_slots().iter_mut() {
                if !slot.get_in_flight() && slot.get_pixels().capacity() < needed {
                    slot.get_mut_pixels().reserve_exact(needed);
                    grew += 1;
                }
            }
            let next_allocs: u64 = guard.get_backing_allocations().saturating_add(grew);
            guard.set_backing_allocations(next_allocs);
        }
    }

    /// Acquires a free buffer slot sized for `(width, height)` RGBA8 output tagged with `fence_id`.
    ///
    /// Returns `None` when all bounded slots are still in flight (enforcing strict memory backpressure).
    ///
    /// # Arguments
    ///
    /// - `&Self` - Pool reference.
    /// - `u32` - Target framebuffer width in pixels.
    /// - `u32` - Target framebuffer height in pixels.
    /// - `u64` - Fence value guarding reclamation of this frame.
    ///
    /// # Returns
    ///
    /// - `Option<PooledFrameLease>` - Exclusive RAII buffer lease, or `None` under backpressure.
    #[must_use]
    pub fn acquire(&self, width: u32, height: u32, fence_id: u64) -> Option<PooledFrameLease> {
        let needed: usize = (width as usize)
            .saturating_mul(height as usize)
            .saturating_mul(4);
        let mut guard: RefMut<'_, RenderBufferPoolState> =
            self.get_state().try_borrow_mut().ok()?;
        let free_idx_opt: Option<usize> = guard
            .get_slots()
            .iter()
            .position(|slot: &PooledRenderBufferSlot| !slot.get_in_flight());
        let Some(slot_index) = free_idx_opt else {
            let rej: u64 = guard.get_backpressure_rejections().saturating_add(1);
            guard.set_backpressure_rejections(rej);
            return None;
        };
        let mut pixels: Vec<u8> = {
            let slot: &mut PooledRenderBufferSlot = &mut guard.get_mut_slots()[slot_index];
            slot.set_in_flight(true);
            slot.set_checked_out(true);
            slot.set_width(width);
            slot.set_height(height);
            slot.set_fence_id(fence_id);
            let next_gen: u64 = slot.get_generation().wrapping_add(1);
            slot.set_generation(next_gen);
            take(slot.get_mut_pixels())
        };
        let generation: u64 = guard.get_slots()[slot_index].get_generation();
        if pixels.capacity() < needed {
            pixels.reserve_exact(needed - pixels.len());
            let allocs: u64 = guard.get_backing_allocations().saturating_add(1);
            guard.set_backing_allocations(allocs);
        } else {
            let hits: u64 = guard.get_reuse_hits().saturating_add(1);
            guard.set_reuse_hits(hits);
        }
        pixels.clear();
        drop(guard);
        Some(PooledFrameLease {
            state: Rc::clone(self.get_state()),
            slot_index,
            width,
            height,
            fence_id,
            generation,
            pixels,
            released: false,
        })
    }

    /// Retires all in-flight slots whose `fence_id <= completed_fence`, making them available for zero-allocation reuse.
    ///
    /// # Arguments
    ///
    /// - `&Self` - Pool reference.
    /// - `u64` - Highest fence confirmed complete by the compositor or uploader.
    ///
    /// # Returns
    ///
    /// - `usize` - Number of slots retired back to the free set.
    pub fn retire_fence(&self, completed_fence: u64) -> usize {
        let Ok(mut guard) = self.get_state().try_borrow_mut() else {
            return 0;
        };
        if completed_fence > guard.get_completed_fence() {
            guard.set_completed_fence(completed_fence);
        }
        let mut freed: usize = 0;
        for slot in guard.get_mut_slots().iter_mut() {
            if slot.get_in_flight()
                && !slot.get_checked_out()
                && slot.get_fence_id() <= completed_fence
            {
                slot.set_in_flight(false);
                freed += 1;
            }
        }
        freed
    }

    /// Returns a snapshot of current pool capacity, in-flight slots, reuse hits, and backpressure rejections.
    ///
    /// # Arguments
    ///
    /// - `&Self` - Pool reference.
    ///
    /// # Returns
    ///
    /// - `RenderBufferPoolStats` - Current pool telemetry snapshot.
    #[must_use]
    pub fn stats(&self) -> RenderBufferPoolStats {
        let Ok(guard) = self.get_state().try_borrow() else {
            return RenderBufferPoolStats::default();
        };
        let capacity: usize = guard.get_slots().len();
        let in_flight: usize = guard
            .get_slots()
            .iter()
            .filter(|s: &&PooledRenderBufferSlot| s.get_in_flight())
            .count();
        RenderBufferPoolStats::new(
            capacity,
            in_flight,
            capacity.saturating_sub(in_flight),
            guard.get_reuse_hits(),
            guard.get_backing_allocations(),
            guard.get_backpressure_rejections(),
        )
    }
}

/// Buffer access, fence-gated submission, and explicit release for `PooledFrameLease`.
impl PooledFrameLease {
    /// Returns a read-only slice of the rendered RGBA8 pixels.
    ///
    /// # Arguments
    ///
    /// - `&Self` - Frame lease reference.
    ///
    /// # Returns
    ///
    /// - `&[u8]` - Rendered RGBA8 byte slice.
    #[must_use]
    pub fn as_slice(&self) -> &[u8] {
        self.get_pixels().as_slice()
    }

    /// Updates recorded pixel dimensions after a renderer writes into `get_mut_pixels()`.
    ///
    /// # Arguments
    ///
    /// - `&Self` - Mutable frame lease.
    /// - `u32` - Actual rendered width in pixels.
    /// - `u32` - Actual rendered height in pixels.
    pub fn set_dimensions(&mut self, width: u32, height: u32) {
        self.set_width(width);
        self.set_height(height);
    }

    /// Copies the rendered pixels into a standalone `ImageBuffer` for legacy upload callers.
    ///
    /// # Arguments
    ///
    /// - `&Self` - Frame lease reference.
    ///
    /// # Returns
    ///
    /// - `ImageBuffer` - Copied RGBA8 image buffer.
    #[must_use]
    pub fn to_image_buffer_copy(&self) -> ImageBuffer {
        ImageBuffer::new(
            self.get_width(),
            self.get_height(),
            self.get_pixels().clone(),
        )
    }

    /// Returns the pixel buffer to its pool slot while keeping the slot marked `in_flight` until `RenderBufferPool::retire_fence(fence_id)` completes.
    ///
    /// # Arguments
    ///
    /// - `Self` - Consumed frame lease.
    pub fn submit_in_flight(mut self) {
        self.return_to_pool(true);
    }

    /// Returns the pixel buffer to its pool slot and immediately marks the slot free for reuse.
    ///
    /// # Arguments
    ///
    /// - `Self` - Consumed frame lease.
    pub fn release_now(mut self) {
        self.return_to_pool(false);
    }

    /// Internal helper returning backing memory to the pool slot with either fence-gated or immediate release.
    ///
    /// # Arguments
    ///
    /// - `&Self` - Mutable frame lease.
    /// - `bool` - When `true`, keeps the slot in flight until its fence retires.
    fn return_to_pool(&mut self, keep_in_flight: bool) {
        if self.get_released() {
            return;
        }
        self.set_released(true);
        let slot_index: usize = self.get_slot_index();
        let width: u32 = self.get_width();
        let height: u32 = self.get_height();
        let fence_id: u64 = self.get_fence_id();
        let pixels: Vec<u8> = take(self.get_mut_pixels());
        let Self { state, .. } = self;
        if let Ok(mut guard) = state.try_borrow_mut() {
            let completed: u64 = guard.get_completed_fence();
            if let Some(slot) = guard.get_mut_slots().get_mut(slot_index) {
                slot.set_pixels(pixels);
                slot.set_width(width);
                slot.set_height(height);
                slot.set_fence_id(fence_id);
                slot.set_checked_out(false);
                let still_pending: bool = keep_in_flight && fence_id > completed;
                slot.set_in_flight(still_pending);
            }
        }
    }
}

/// Guaranteed buffer reclamation back into `RenderBufferPool` when a lease drops.
impl Drop for PooledFrameLease {
    /// Returns the leased buffer to its owning slot on drop without leaking pool capacity.
    ///
    /// # Arguments
    ///
    /// - `&Self` - Mutable frame lease being dropped.
    fn drop(&mut self) {
        self.return_to_pool(false);
    }
}