euv_core/game/surface/impl.rs
1use super::*;
2
3/// Validation and footprint helpers for `GpuTextureHandle`.
4impl GpuTextureHandle {
5 /// Constructs a persistent GPU texture handle bound to `(texture_id, device_id)` with exact `(width, height)` dimensions and `format`.
6 ///
7 /// # Arguments
8 ///
9 /// - `u64` - Backend-opaque GPU texture identifier.
10 /// - `u64` - Owning GPU logical device identifier.
11 /// - `u64` - Surface generation counter.
12 /// - `(u32, u32)` - Texture `(width, height)` in physical pixels.
13 /// - `GpuTextureFormat` - GPU texture pixel format.
14 /// - `u64` - Synchronization fence value.
15 /// - `bool` - Whether the texture uses top-left origin orientation.
16 ///
17 /// # Returns
18 ///
19 /// - `Self` - Constructed GPU texture handle.
20 #[must_use]
21 pub const fn new(
22 texture_id: u64,
23 device_id: u64,
24 generation: u64,
25 dimensions: (u32, u32),
26 format: GpuTextureFormat,
27 fence_value: u64,
28 origin_top_left: bool,
29 ) -> Self {
30 Self {
31 texture_id,
32 device_id,
33 generation,
34 width: dimensions.0,
35 height: dimensions.1,
36 format,
37 fence_value,
38 origin_top_left,
39 }
40 }
41
42 /// Returns `true` when this handle refers to a non-zero GPU texture with non-zero dimensions.
43 ///
44 /// # Arguments
45 ///
46 /// - `&Self` - Texture handle reference.
47 ///
48 /// # Returns
49 ///
50 /// - `bool` - Validity flag.
51 #[must_use]
52 pub const fn is_valid(&self) -> bool {
53 let Self {
54 texture_id,
55 device_id,
56 width,
57 height,
58 ..
59 } = *self;
60 texture_id != 0 && device_id != 0 && width > 0 && height > 0
61 }
62
63 /// Returns `true` when this handle belongs to `device_id` and can be composited without cross-device copies.
64 ///
65 /// # Arguments
66 ///
67 /// - `&Self` - Texture handle reference.
68 /// - `u64` - Expected logical GPU device identifier.
69 ///
70 /// # Returns
71 ///
72 /// - `bool` - `true` when valid and matching `device_id`.
73 #[must_use]
74 pub const fn matches_device(&self, expected_device: u64) -> bool {
75 let Self { device_id, .. } = *self;
76 self.is_valid() && device_id == expected_device
77 }
78
79 /// Returns bytes per pixel for this handle's `GpuTextureFormat`.
80 ///
81 /// # Arguments
82 ///
83 /// - `&Self` - Texture handle reference.
84 ///
85 /// # Returns
86 ///
87 /// - `usize` - Byte width per pixel (`4` or `8`).
88 #[must_use]
89 pub const fn bytes_per_pixel(&self) -> usize {
90 let Self { format, .. } = *self;
91 match format {
92 GpuTextureFormat::Rgba16Float => 8,
93 GpuTextureFormat::Rgba8Unorm
94 | GpuTextureFormat::Rgba8UnormSrgb
95 | GpuTextureFormat::Bgra8Unorm
96 | GpuTextureFormat::Rgb10A2Unorm => 4,
97 }
98 }
99
100 /// Returns estimated GPU texture footprint in bytes.
101 ///
102 /// # Arguments
103 ///
104 /// - `&Self` - Texture handle reference.
105 ///
106 /// # Returns
107 ///
108 /// - `usize` - Estimated GPU memory footprint in bytes.
109 #[must_use]
110 pub const fn estimated_bytes(&self) -> usize {
111 let Self { width, height, .. } = *self;
112 (width as usize)
113 .saturating_mul(height as usize)
114 .saturating_mul(self.bytes_per_pixel())
115 }
116}
117
118/// GPU compositing and isolated world/HUD dirty coordination for `GpuCompositeTarget`.
119impl GpuCompositeTarget {
120 /// Attaches a persistent GPU render target handle and logical viewport rectangle.
121 ///
122 /// # Arguments
123 ///
124 /// - `&Self` - Mutable composite target.
125 /// - `GpuTextureHandle` - Same-device GPU render target handle.
126 /// - `Rect` - Viewport destination rectangle in root logical coordinates.
127 pub fn attach_handle(&mut self, handle: GpuTextureHandle, viewport_rect: Rect) {
128 self.set_handle(handle);
129 self.set_viewport_rect(viewport_rect);
130 self.mark_world_dirty();
131 }
132
133 /// Marks the 2D/3D game world render target dirty without forcing unrelated HUD invalidations.
134 ///
135 /// # Arguments
136 ///
137 /// - `&Self` - Mutable composite target.
138 pub fn mark_world_dirty(&mut self) {
139 let next: u64 = self.get_world_revision().wrapping_add(1);
140 self.set_world_revision(next);
141 }
142
143 /// Marks only the overlaid EUV HUD dirty without forcing a full 3D/2D world re-render.
144 ///
145 /// # Arguments
146 ///
147 /// - `&Self` - Mutable composite target.
148 pub fn mark_hud_dirty(&mut self) {
149 let next: u64 = self.get_hud_revision().wrapping_add(1);
150 self.set_hud_revision(next);
151 }
152
153 /// Returns `true` when the game world target needs a fresh render pass before compositing.
154 ///
155 /// # Arguments
156 ///
157 /// - `&Self` - Composite target reference.
158 ///
159 /// # Returns
160 ///
161 /// - `bool` - `true` when `world_revision != presented_world_revision`.
162 #[must_use]
163 pub fn needs_world_render(&self) -> bool {
164 self.get_world_revision() != self.get_presented_world_revision()
165 }
166
167 /// Returns `true` when only the HUD overlay changed since the last present.
168 ///
169 /// # Arguments
170 ///
171 /// - `&Self` - Composite target reference.
172 ///
173 /// # Returns
174 ///
175 /// - `bool` - `true` when HUD is dirty while the world target is already up to date.
176 #[must_use]
177 pub fn is_hud_only_dirty(&self) -> bool {
178 !self.needs_world_render() && self.get_hud_revision() != self.get_presented_hud_revision()
179 }
180
181 /// Selects `ViewportPresentPath::GpuDirectComposite` when a valid same-device handle is attached, else `CpuPooledFallback`.
182 ///
183 /// # Arguments
184 ///
185 /// - `&Self` - Composite target reference.
186 /// - `u64` - Active compositor GPU device identifier.
187 ///
188 /// # Returns
189 ///
190 /// - `ViewportPresentPath` - Active presentation transport.
191 #[must_use]
192 pub fn resolve_present_path(&self, compositor_device_id: u64) -> ViewportPresentPath {
193 if self.get_handle().matches_device(compositor_device_id) {
194 ViewportPresentPath::GpuDirectComposite
195 } else {
196 ViewportPresentPath::CpuPooledFallback
197 }
198 }
199
200 /// Records a single-present GPU composite submission advancing fence and revision telemetry.
201 ///
202 /// # Arguments
203 ///
204 /// - `&Self` - Mutable composite target.
205 /// - `u64` - Submission fence value associated with this present pass.
206 ///
207 /// # Returns
208 ///
209 /// - `Option<GpuCompositeDescriptor>` - Descriptor for the compositor when the GPU handle is valid.
210 pub fn record_composite_present(&mut self, fence_value: u64) -> Option<GpuCompositeDescriptor> {
211 let mut handle: GpuTextureHandle = self.get_handle();
212 if !handle.is_valid() {
213 return None;
214 }
215 let hud_only: bool = self.is_hud_only_dirty();
216 handle.set_fence_value(fence_value);
217 self.set_handle(handle);
218 self.set_submitted_fence(fence_value);
219 let world_rev: u64 = self.get_world_revision();
220 let hud_rev: u64 = self.get_hud_revision();
221 self.set_presented_world_revision(world_rev);
222 self.set_presented_hud_revision(hud_rev);
223 let next_presents: u64 = self.get_zero_readback_presents().saturating_add(1);
224 self.set_zero_readback_presents(next_presents);
225 if hud_only {
226 let next_reuse: u64 = self.get_hud_only_reuses().saturating_add(1);
227 self.set_hud_only_reuses(next_reuse);
228 }
229 Some(GpuCompositeDescriptor::new(
230 self.get_viewport_rect(),
231 handle,
232 0,
233 true,
234 ))
235 }
236
237 /// Retires completed GPU fences up to `fence_value`.
238 ///
239 /// # Arguments
240 ///
241 /// - `&Self` - Mutable composite target.
242 /// - `u64` - Latest completed GPU queue fence value.
243 pub fn retire_fence(&mut self, fence_value: u64) {
244 if fence_value > self.get_completed_fence() {
245 self.set_completed_fence(fence_value);
246 }
247 }
248}
249
250/// Default triple-buffered `RenderBufferPool`.
251impl Default for RenderBufferPool {
252 /// Creates a bounded triple-buffered CPU render output pool (`3` slots).
253 ///
254 /// # Returns
255 ///
256 /// - `Self` - Default render buffer pool.
257 fn default() -> Self {
258 Self::with_capacity(RENDER_POOL_DEFAULT_SLOTS)
259 }
260}
261
262/// Bounded zero-allocation buffer pooling and fence-gated release for `RenderBufferPool`.
263impl RenderBufferPool {
264 /// Creates a bounded `RenderBufferPool` holding `slot_count` reusable slots (clamped to `1..=8`).
265 ///
266 /// # Arguments
267 ///
268 /// - `usize` - Requested bounded slot count.
269 ///
270 /// # Returns
271 ///
272 /// - `Self` - Initialized render buffer pool.
273 #[must_use]
274 pub fn with_capacity(slot_count: usize) -> Self {
275 let clamped: usize = slot_count.clamp(RENDER_POOL_MIN_SLOTS, RENDER_POOL_MAX_SLOTS);
276 let mut slots: Vec<PooledRenderBufferSlot> = Vec::with_capacity(clamped);
277 for _ in 0..clamped {
278 slots.push(PooledRenderBufferSlot::default());
279 }
280 Self {
281 state: Rc::new(RefCell::new(RenderBufferPoolState {
282 slots,
283 completed_fence: 0,
284 reuse_hits: 0,
285 backing_allocations: 0,
286 backpressure_rejections: 0,
287 })),
288 }
289 }
290
291 /// Pre-allocates backing storage for all slots for a `(width, height)` RGBA8 framebuffer so steady-state renders allocate zero bytes.
292 ///
293 /// # Arguments
294 ///
295 /// - `&Self` - Pool reference.
296 /// - `u32` - Framebuffer width in pixels.
297 /// - `u32` - Framebuffer height in pixels.
298 pub fn preallocate(&self, width: u32, height: u32) {
299 let needed: usize = (width as usize)
300 .saturating_mul(height as usize)
301 .saturating_mul(4);
302 if needed == 0 {
303 return;
304 }
305 if let Ok(mut guard) = self.get_state().try_borrow_mut() {
306 let mut grew: u64 = 0;
307 for slot in guard.get_mut_slots().iter_mut() {
308 if !slot.get_in_flight() && slot.get_pixels().capacity() < needed {
309 slot.get_mut_pixels().reserve_exact(needed);
310 grew += 1;
311 }
312 }
313 let next_allocs: u64 = guard.get_backing_allocations().saturating_add(grew);
314 guard.set_backing_allocations(next_allocs);
315 }
316 }
317
318 /// Acquires a free buffer slot sized for `(width, height)` RGBA8 output tagged with `fence_id`.
319 ///
320 /// Returns `None` when all bounded slots are still in flight (enforcing strict memory backpressure).
321 ///
322 /// # Arguments
323 ///
324 /// - `&Self` - Pool reference.
325 /// - `u32` - Target framebuffer width in pixels.
326 /// - `u32` - Target framebuffer height in pixels.
327 /// - `u64` - Fence value guarding reclamation of this frame.
328 ///
329 /// # Returns
330 ///
331 /// - `Option<PooledFrameLease>` - Exclusive RAII buffer lease, or `None` under backpressure.
332 #[must_use]
333 pub fn acquire(&self, width: u32, height: u32, fence_id: u64) -> Option<PooledFrameLease> {
334 let needed: usize = (width as usize)
335 .saturating_mul(height as usize)
336 .saturating_mul(4);
337 let mut guard: RefMut<'_, RenderBufferPoolState> =
338 self.get_state().try_borrow_mut().ok()?;
339 let free_idx_opt: Option<usize> = guard
340 .get_slots()
341 .iter()
342 .position(|slot: &PooledRenderBufferSlot| {
343 !slot.get_in_flight()
344 && slot
345 .pixels
346 .as_ref()
347 .is_none_or(|arc: &Arc<Vec<u8>>| Arc::strong_count(arc) == 1)
348 })
349 .or_else(|| {
350 guard
351 .get_slots()
352 .iter()
353 .position(|slot: &PooledRenderBufferSlot| !slot.get_in_flight())
354 });
355 let Some(slot_index) = free_idx_opt else {
356 let rej: u64 = guard.get_backpressure_rejections().saturating_add(1);
357 guard.set_backpressure_rejections(rej);
358 return None;
359 };
360 let mut pixels_arc: Arc<Vec<u8>> = {
361 let slot: &mut PooledRenderBufferSlot = &mut guard.get_mut_slots()[slot_index];
362 slot.set_in_flight(true);
363 slot.set_checked_out(true);
364 slot.set_width(width);
365 slot.set_height(height);
366 slot.set_fence_id(fence_id);
367 let next_gen: u64 = slot.get_generation().wrapping_add(1);
368 slot.set_generation(next_gen);
369 slot.pixels.take().unwrap_or_else(|| Arc::new(Vec::new()))
370 };
371 let generation: u64 = guard.get_slots()[slot_index].get_generation();
372 let exclusive: bool = Arc::get_mut(&mut pixels_arc).is_some();
373 let pixels: &mut Vec<u8> = if exclusive {
374 Arc::make_mut(&mut pixels_arc)
375 } else {
376 pixels_arc = Arc::new(Vec::new());
377 Arc::make_mut(&mut pixels_arc)
378 };
379 if pixels.capacity() < needed {
380 pixels.reserve_exact(needed - pixels.len());
381 let allocs: u64 = guard.get_backing_allocations().saturating_add(1);
382 guard.set_backing_allocations(allocs);
383 } else {
384 let hits: u64 = guard.get_reuse_hits().saturating_add(1);
385 guard.set_reuse_hits(hits);
386 }
387 pixels.clear();
388 drop(guard);
389 Some(PooledFrameLease {
390 state: Rc::clone(self.get_state()),
391 slot_index,
392 width,
393 height,
394 fence_id,
395 generation,
396 pixels: Some(pixels_arc),
397 released: false,
398 })
399 }
400
401 /// Retires all in-flight slots whose `fence_id <= completed_fence`, making them available for zero-allocation reuse.
402 ///
403 /// # Arguments
404 ///
405 /// - `&Self` - Pool reference.
406 /// - `u64` - Highest fence confirmed complete by the compositor or uploader.
407 ///
408 /// # Returns
409 ///
410 /// - `usize` - Number of slots retired back to the free set.
411 pub fn retire_fence(&self, completed_fence: u64) -> usize {
412 let Ok(mut guard) = self.get_state().try_borrow_mut() else {
413 return 0;
414 };
415 if completed_fence > guard.get_completed_fence() {
416 guard.set_completed_fence(completed_fence);
417 }
418 let mut freed: usize = 0;
419 for slot in guard.get_mut_slots().iter_mut() {
420 if slot.get_in_flight()
421 && !slot.get_checked_out()
422 && slot.get_fence_id() <= completed_fence
423 {
424 slot.set_in_flight(false);
425 freed += 1;
426 }
427 }
428 freed
429 }
430
431 /// Returns a snapshot of current pool capacity, in-flight slots, reuse hits, and backpressure rejections.
432 ///
433 /// # Arguments
434 ///
435 /// - `&Self` - Pool reference.
436 ///
437 /// # Returns
438 ///
439 /// - `RenderBufferPoolStats` - Current pool telemetry snapshot.
440 #[must_use]
441 pub fn stats(&self) -> RenderBufferPoolStats {
442 let Ok(guard) = self.get_state().try_borrow() else {
443 return RenderBufferPoolStats::default();
444 };
445 let capacity: usize = guard.get_slots().len();
446 let in_flight: usize = guard
447 .get_slots()
448 .iter()
449 .filter(|s: &&PooledRenderBufferSlot| s.get_in_flight())
450 .count();
451 RenderBufferPoolStats::new(
452 capacity,
453 in_flight,
454 capacity.saturating_sub(in_flight),
455 guard.get_reuse_hits(),
456 guard.get_backing_allocations(),
457 guard.get_backpressure_rejections(),
458 )
459 }
460}
461
462/// Shared pixel-buffer accessors for `PooledRenderBufferSlot`.
463impl PooledRenderBufferSlot {
464 /// Returns a read-only reference to this slot's pixel storage vector.
465 ///
466 /// # Arguments
467 ///
468 /// - `&Self` - Pool slot reference.
469 ///
470 /// # Returns
471 ///
472 /// - `&Vec<u8>` - Pixel storage vector.
473 #[must_use]
474 pub fn get_pixels(&self) -> &Vec<u8> {
475 let Self { pixels, .. } = self;
476 pixels.as_deref().unwrap_or(&EMPTY_POOLED_PIXELS)
477 }
478
479 /// Returns an exclusive mutable reference to this slot's pixel storage vector.
480 ///
481 /// # Arguments
482 ///
483 /// - `&Self` - Mutable pool slot reference.
484 ///
485 /// # Returns
486 ///
487 /// - `&mut Vec<u8>` - Mutable pixel storage vector.
488 pub fn get_mut_pixels(&mut self) -> &mut Vec<u8> {
489 let Self { pixels, .. } = self;
490 let arc: &mut Arc<Vec<u8>> = pixels.get_or_insert_with(|| Arc::new(Vec::new()));
491 Arc::make_mut(arc)
492 }
493
494 /// Replaces this slot's pixel storage vector with `next`.
495 ///
496 /// # Arguments
497 ///
498 /// - `&Self` - Mutable pool slot reference.
499 /// - `Vec<u8>` - Replacement pixel storage vector.
500 pub fn set_pixels(&mut self, next: Vec<u8>) {
501 let Self { pixels, .. } = self;
502 *pixels = Some(Arc::new(next));
503 }
504}
505
506/// Zero-copy pixel accessors for `PooledFrameRef`.
507impl PooledFrameRef {
508 /// Returns a read-only slice of the shared RGBA8 pixel buffer.
509 ///
510 /// # Arguments
511 ///
512 /// - `&Self` - Shared frame reference.
513 ///
514 /// # Returns
515 ///
516 /// - `&[u8]` - Shared RGBA8 byte slice.
517 #[must_use]
518 pub fn as_slice(&self) -> &[u8] {
519 let Self { pixels, .. } = self;
520 pixels.as_slice()
521 }
522
523 /// Clones an O(1) reference-counted handle to the underlying RGBA8 pixel vector.
524 ///
525 /// # Arguments
526 ///
527 /// - `&Self` - Shared frame reference.
528 ///
529 /// # Returns
530 ///
531 /// - `Arc<Vec<u8>>` - Reference-counted RGBA8 pixel buffer.
532 #[must_use]
533 pub fn shared_pixels(&self) -> Arc<Vec<u8>> {
534 let Self { pixels, .. } = self;
535 Arc::clone(pixels)
536 }
537
538 /// Checks whether two `PooledFrameRef` handles share the exact same heap pixel allocation.
539 ///
540 /// # Arguments
541 ///
542 /// - `&Self` - Left frame reference.
543 /// - `&Self` - Right frame reference.
544 ///
545 /// # Returns
546 ///
547 /// - `bool` - `true` when both references point to the same underlying allocation.
548 #[must_use]
549 pub fn ptr_eq(&self, other: &Self) -> bool {
550 let Self { pixels: a, .. } = self;
551 let Self { pixels: b, .. } = other;
552 Arc::ptr_eq(a, b)
553 }
554}
555
556/// Buffer access, fence-gated submission, and explicit release for `PooledFrameLease`.
557impl PooledFrameLease {
558 /// Creates an O(1) zero-copy `PooledFrameRef` sharing this lease's RGBA8 pixel allocation without memcpy.
559 ///
560 /// # Arguments
561 ///
562 /// - `&Self` - Frame lease reference.
563 ///
564 /// # Returns
565 ///
566 /// - `PooledFrameRef` - Zero-copy shared frame reference.
567 #[must_use]
568 pub fn to_frame_ref(&self) -> PooledFrameRef {
569 PooledFrameRef {
570 width: self.get_width(),
571 height: self.get_height(),
572 fence_id: self.get_fence_id(),
573 generation: self.get_generation(),
574 pixels: self.shared_pixels(),
575 }
576 }
577 /// Returns a read-only reference to the leased RGBA8 pixel vector.
578 ///
579 /// # Arguments
580 ///
581 /// - `&Self` - Frame lease reference.
582 ///
583 /// # Returns
584 ///
585 /// - `&Vec<u8>` - Leased RGBA8 byte vector.
586 #[must_use]
587 pub fn get_pixels(&self) -> &Vec<u8> {
588 let Self { pixels, .. } = self;
589 pixels.as_deref().unwrap_or(&EMPTY_POOLED_PIXELS)
590 }
591
592 /// Returns an exclusive mutable reference to the leased RGBA8 pixel vector (zero-alloc when uniquely owned).
593 ///
594 /// # Arguments
595 ///
596 /// - `&Self` - Mutable frame lease.
597 ///
598 /// # Returns
599 ///
600 /// - `&mut Vec<u8>` - Mutable RGBA8 byte vector.
601 pub fn get_mut_pixels(&mut self) -> &mut Vec<u8> {
602 let Self { pixels, .. } = self;
603 let arc: &mut Arc<Vec<u8>> = pixels.get_or_insert_with(|| Arc::new(Vec::new()));
604 Arc::make_mut(arc)
605 }
606
607 /// Clones an O(1) shared handle to the rendered pixel bytes for zero-copy display-list submission.
608 ///
609 /// # Arguments
610 ///
611 /// - `&Self` - Frame lease reference.
612 ///
613 /// # Returns
614 ///
615 /// - `Arc<Vec<u8>>` - Shared reference-counted RGBA8 pixel buffer.
616 #[must_use]
617 pub fn shared_pixels(&self) -> Arc<Vec<u8>> {
618 let Self { pixels, .. } = self;
619 pixels
620 .as_ref()
621 .map_or_else(|| Arc::new(Vec::new()), Arc::clone)
622 }
623
624 /// Returns a read-only slice of the rendered RGBA8 pixels.
625 ///
626 /// # Arguments
627 ///
628 /// - `&Self` - Frame lease reference.
629 ///
630 /// # Returns
631 ///
632 /// - `&[u8]` - Rendered RGBA8 byte slice.
633 #[must_use]
634 pub fn as_slice(&self) -> &[u8] {
635 let Self { pixels, .. } = self;
636 pixels.as_deref().map_or(&[], Vec::as_slice)
637 }
638
639 /// Updates recorded pixel dimensions after a renderer writes into `get_mut_pixels()`.
640 ///
641 /// # Arguments
642 ///
643 /// - `&Self` - Mutable frame lease.
644 /// - `u32` - Actual rendered width in pixels.
645 /// - `u32` - Actual rendered height in pixels.
646 pub fn set_dimensions(&mut self, width: u32, height: u32) {
647 self.set_width(width);
648 self.set_height(height);
649 }
650
651 /// Copies the rendered pixels into a standalone `ImageBuffer` for legacy upload callers.
652 ///
653 /// # Arguments
654 ///
655 /// - `&Self` - Frame lease reference.
656 ///
657 /// # Returns
658 ///
659 /// - `ImageBuffer` - Copied RGBA8 image buffer.
660 #[must_use]
661 pub fn to_image_buffer_copy(&self) -> ImageBuffer {
662 ImageBuffer::new(
663 self.get_width(),
664 self.get_height(),
665 self.as_slice().to_vec(),
666 )
667 }
668
669 /// Returns the pixel buffer to its pool slot while keeping the slot marked `in_flight` until `RenderBufferPool::retire_fence(fence_id)` completes.
670 ///
671 /// # Arguments
672 ///
673 /// - `Self` - Consumed frame lease.
674 pub fn submit_in_flight(mut self) {
675 self.return_to_pool(true);
676 }
677
678 /// Returns the pixel buffer to its pool slot and immediately marks the slot free for reuse.
679 ///
680 /// # Arguments
681 ///
682 /// - `Self` - Consumed frame lease.
683 pub fn release_now(mut self) {
684 self.return_to_pool(false);
685 }
686
687 /// Internal helper returning backing memory to the pool slot with either fence-gated or immediate release.
688 ///
689 /// # Arguments
690 ///
691 /// - `&Self` - Mutable frame lease.
692 /// - `bool` - When `true`, keeps the slot in flight until its fence retires.
693 fn return_to_pool(&mut self, keep_in_flight: bool) {
694 if self.get_released() {
695 return;
696 }
697 self.set_released(true);
698 let slot_index: usize = self.get_slot_index();
699 let width: u32 = self.get_width();
700 let height: u32 = self.get_height();
701 let fence_id: u64 = self.get_fence_id();
702 let pixels: Option<Arc<Vec<u8>>> = {
703 let Self { pixels, .. } = self;
704 pixels.take()
705 };
706 let Self { state, .. } = self;
707 if let Ok(mut guard) = state.try_borrow_mut() {
708 let completed: u64 = guard.get_completed_fence();
709 if let Some(slot) = guard.get_mut_slots().get_mut(slot_index) {
710 if let Some(returned) = pixels {
711 slot.pixels = Some(returned);
712 }
713 slot.set_width(width);
714 slot.set_height(height);
715 slot.set_fence_id(fence_id);
716 slot.set_checked_out(false);
717 let still_pending: bool = keep_in_flight && fence_id > completed;
718 slot.set_in_flight(still_pending);
719 }
720 }
721 }
722}
723
724/// Guaranteed buffer reclamation back into `RenderBufferPool` when a lease drops.
725impl Drop for PooledFrameLease {
726 /// Returns the leased buffer to its owning slot on drop without leaking pool capacity.
727 ///
728 /// # Arguments
729 ///
730 /// - `&Self` - Mutable frame lease being dropped.
731 fn drop(&mut self) {
732 self.return_to_pool(false);
733 }
734}
735
736/// Zero-readback shared GPU 3D+HUD presentation chain coordination for `GpuSharedSurface`.
737impl GpuSharedSurface {
738 /// Creates a `GpuSharedSurface` binding `handle` to `viewport_rect` and `hud_overlay_rect` with `zero_cpu_readback = true` when valid.
739 ///
740 /// # Arguments
741 ///
742 /// - `GpuTextureHandle` - Same-device 3D GPU render target texture handle.
743 /// - `Rect` - 3D viewport destination bounds in logical coordinates.
744 /// - `Rect` - HUD overlay destination bounds in logical coordinates.
745 ///
746 /// # Returns
747 ///
748 /// - `Self` - Configured shared GPU presentation surface.
749 #[must_use]
750 pub fn new_shared(
751 handle: GpuTextureHandle,
752 viewport_rect: Rect,
753 hud_overlay_rect: Rect,
754 ) -> Self {
755 let valid: bool = handle.is_valid();
756 Self {
757 handle,
758 viewport_rect,
759 hud_overlay_rect,
760 zero_cpu_readback: valid,
761 duplicate_upload_avoided: valid,
762 world_revision: if valid { 1 } else { 0 },
763 hud_revision: if valid { 1 } else { 0 },
764 presented_world_revision: 0,
765 presented_hud_revision: 0,
766 fence_value: handle.get_fence_value(),
767 cpu_readback_bytes: 0,
768 full_frame_uploads: 0,
769 shared_gpu_composites: 0,
770 hud_only_reuses: 0,
771 }
772 }
773
774 /// Returns `true` when the shared surface holds a valid GPU texture matching `compositor_device_id` with zero CPU readback.
775 ///
776 /// # Arguments
777 ///
778 /// - `&Self` - Shared surface reference.
779 /// - `u64` - Active compositor logical GPU device identifier.
780 ///
781 /// # Returns
782 ///
783 /// - `bool` - `true` when direct same-device GPU compositing is ready.
784 #[must_use]
785 pub fn is_shared_gpu_ready(&self, compositor_device_id: u64) -> bool {
786 self.get_zero_cpu_readback() && self.get_handle().matches_device(compositor_device_id)
787 }
788
789 /// Marks the 3D scene world texture updated for the next shared GPU composite.
790 ///
791 /// # Arguments
792 ///
793 /// - `&Self` - Mutable shared surface.
794 pub fn mark_world_updated(&mut self) {
795 self.set_world_revision(self.get_world_revision().wrapping_add(1));
796 }
797
798 /// Marks only the HUD overlay updated so the compositor can reuse the existing 3D texture without re-rendering 3D.
799 ///
800 /// # Arguments
801 ///
802 /// - `&Self` - Mutable shared surface.
803 pub fn mark_hud_updated(&mut self) {
804 self.set_hud_revision(self.get_hud_revision().wrapping_add(1));
805 }
806
807 /// Composes the 3D viewport texture and HUD overlay on the shared GPU present chain with zero CPU readback and zero duplicate full-frame upload.
808 ///
809 /// # Arguments
810 ///
811 /// - `&Self` - Mutable shared surface.
812 /// - `u64` - Active compositor logical GPU device identifier.
813 /// - `&mut GameRenderContext<'_>` - Active viewport render context receiving the direct GPU texture composite descriptor.
814 ///
815 /// # Returns
816 ///
817 /// - `SharedGpuCompositeReceipt` - Honest receipt detailing zero-readback status, world reuse, and fence progression.
818 pub fn compose_frame(
819 &mut self,
820 compositor_device_id: u64,
821 render_ctx: &mut GameRenderContext<'_>,
822 ) -> SharedGpuCompositeReceipt {
823 let mut handle: GpuTextureHandle = self.get_handle();
824 let same_device: bool = handle.matches_device(compositor_device_id);
825 let world_dirty: bool = self.get_world_revision() != self.get_presented_world_revision();
826 let hud_dirty: bool = self.get_hud_revision() != self.get_presented_hud_revision();
827 if !same_device {
828 self.set_zero_cpu_readback(false);
829 self.set_duplicate_upload_avoided(false);
830 return SharedGpuCompositeReceipt::new(
831 handle,
832 false,
833 world_dirty,
834 hud_dirty,
835 0,
836 handle.estimated_bytes() as u64,
837 self.get_fence_value(),
838 );
839 }
840 let next_fence: u64 = self.get_fence_value().saturating_add(1);
841 handle.set_fence_value(next_fence);
842 self.set_handle(handle);
843 let bound: bool = render_ctx.composite_gpu_texture(self.get_viewport_rect(), handle);
844 self.set_zero_cpu_readback(bound);
845 self.set_duplicate_upload_avoided(bound);
846 self.set_fence_value(next_fence);
847 if bound {
848 self.set_shared_gpu_composites(self.get_shared_gpu_composites().saturating_add(1));
849 if !world_dirty && hud_dirty {
850 self.set_hud_only_reuses(self.get_hud_only_reuses().saturating_add(1));
851 }
852 }
853 self.set_presented_world_revision(self.get_world_revision());
854 self.set_presented_hud_revision(self.get_hud_revision());
855 SharedGpuCompositeReceipt::new(
856 handle,
857 bound,
858 world_dirty,
859 hud_dirty || bound,
860 0,
861 0,
862 next_fence,
863 )
864 }
865}