Skip to main content

euv_core/render/compute/
impl.rs

1use super::*;
2
3/// Safe optional coordinate accessor and builder helpers for `GpuComputeSceneInput`.
4impl GpuComputeSceneInput {
5    /// Returns the optional pointer hit-test coordinate `[x, y]` without unwrapping.
6    ///
7    /// # Returns
8    ///
9    /// - `Option<[f32; 2]>` - Pointer coordinate when hit-testing is requested.
10    #[must_use]
11    pub fn pick_point_value(&self) -> Option<[f32; 2]> {
12        let Self { pick_point, .. } = *self;
13        pick_point
14    }
15}
16
17/// Default initialization probing native hardware compute support with automatic CPU reference parity fallback.
18impl Default for GpuComputeLayoutEngine {
19    /// Probes the active host for hardware compute pipelines and creates a ready `GpuComputeLayoutEngine`.
20    ///
21    /// # Returns
22    ///
23    /// - `Self` - Initialized GPU compute layout engine.
24    fn default() -> Self {
25        Self::probe()
26    }
27}
28
29/// Hardware initialization, persistent buffer management, and compute layout dispatch for `GpuComputeLayoutEngine`.
30impl GpuComputeLayoutEngine {
31    /// Probes physical Apple Metal compute pipelines when available, falling back cleanly to CPU reference parity.
32    ///
33    /// # Returns
34    ///
35    /// - `Self` - Ready compute layout engine.
36    #[must_use]
37    pub fn probe() -> Self {
38        #[cfg(any(target_os = "macos", target_os = "ios"))]
39        {
40            let cache: &MetalComputePipelineCache = init_metal_compute_cache();
41            if cache.device != 0
42                && cache.queue != 0
43                && cache.measure_pso != 0
44                && cache.solve_pso != 0
45                && cache.cull_emit_pso != 0
46                && cache.hit_test_pso != 0
47            {
48                return Self {
49                    backend_kind: GpuComputeBackendKind::MetalHardware,
50                    device_handle: mtl_retain_handle(cache.device),
51                    queue_handle: mtl_retain_handle(cache.queue),
52                    input_buffer_handle: 0,
53                    input_contents_ptr: 0,
54                    output_buffer_handle: 0,
55                    output_contents_ptr: 0,
56                    visual_buffer_handle: 0,
57                    visual_contents_ptr: 0,
58                    primitive_buffer_handle: 0,
59                    primitive_contents_ptr: 0,
60                    indirect_buffer_handle: 0,
61                    indirect_contents_ptr: 0,
62                    hit_buffer_handle: 0,
63                    hit_contents_ptr: 0,
64                    allocated_node_capacity: 0,
65                    offscreen_texture_handle: 0,
66                    offscreen_width: 0,
67                    offscreen_height: 0,
68                    total_dispatches: 0,
69                    cached_uniform_row_h: 0.0,
70                    upload_staging_handles: [0; 2],
71                    upload_staging_ptrs: [0; 2],
72                    upload_private_handle: 0,
73                    upload_capacity_bytes: 0,
74                };
75            }
76        }
77        Self::cpu_reference_only()
78    }
79
80    /// Creates a deterministic CPU reference compute parity engine that never invokes hardware GPU APIs.
81    ///
82    /// # Returns
83    ///
84    /// - `Self` - CPU reference parity compute engine.
85    #[must_use]
86    pub fn cpu_reference_only() -> Self {
87        Self {
88            backend_kind: GpuComputeBackendKind::CpuReferenceParity,
89            device_handle: 0,
90            queue_handle: 0,
91            input_buffer_handle: 0,
92            input_contents_ptr: 0,
93            output_buffer_handle: 0,
94            output_contents_ptr: 0,
95            visual_buffer_handle: 0,
96            visual_contents_ptr: 0,
97            primitive_buffer_handle: 0,
98            primitive_contents_ptr: 0,
99            indirect_buffer_handle: 0,
100            indirect_contents_ptr: 0,
101            hit_buffer_handle: 0,
102            hit_contents_ptr: 0,
103            allocated_node_capacity: 0,
104            offscreen_texture_handle: 0,
105            offscreen_width: 0,
106            offscreen_height: 0,
107            total_dispatches: 0,
108            cached_uniform_row_h: 0.0,
109            upload_staging_handles: [0; 2],
110            upload_staging_ptrs: [0; 2],
111            upload_private_handle: 0,
112            upload_capacity_bytes: 0,
113        }
114    }
115
116    /// Returns `true` when physical GPU compute pipelines are compiled and ready for dispatch.
117    ///
118    /// # Returns
119    ///
120    /// - `bool` - `true` when executing on physical hardware compute pipelines.
121    #[must_use]
122    pub fn is_hardware_compute_ready(&self) -> bool {
123        self.get_backend_kind() == GpuComputeBackendKind::MetalHardware
124            && self.get_device_handle() != 0
125            && self.get_queue_handle() != 0
126    }
127
128    /// Executes the 4-kernel GPU compute layout pipeline and optionally renders compacted primitives via indirect draw into an offscreen target.
129    ///
130    /// # Arguments
131    ///
132    /// - `&GpuComputeSceneInput` - Flat BFS layout inputs, styles, and level offsets.
133    /// - `bool` - When `true`, also executes hardware `drawPrimitives:indirectBuffer:` into an offscreen `MTLTexture`.
134    ///
135    /// # Returns
136    ///
137    /// - `GpuComputeDispatchResult` - Resolved layout outputs, compacted primitives, indirect draw args, hit-test result, and GPU timing telemetry.
138    pub fn dispatch(
139        &mut self,
140        scene: &GpuComputeSceneInput,
141        render_offscreen: bool,
142    ) -> GpuComputeDispatchResult {
143        #[cfg(any(target_os = "macos", target_os = "ios"))]
144        if self.is_hardware_compute_ready()
145            && let Some(hw_res) =
146                metal_execute_compute_layout_with_opts(self, scene, render_offscreen, true, true)
147        {
148            return hw_res;
149        }
150        let _: bool = render_offscreen;
151        let Self {
152            total_dispatches, ..
153        } = self;
154        *total_dispatches = total_dispatches.wrapping_add(1);
155        execute_cpu_reference_compute(scene)
156    }
157
158    /// Executes the steady-state zero-readback GPU compute layout and indirect render pipeline without copying outputs, primitives, or offscreen pixels back to CPU memory.
159    ///
160    /// # Arguments
161    ///
162    /// - `&GpuComputeSceneInput` - Flat BFS scene descriptors (only root and uniform update when `upload_buffers` is `false`).
163    /// - `bool` - When `true`, encodes hardware `drawPrimitives:indirectBuffer:` into the offscreen `MTLTexture`.
164    /// - `bool` - When `true`, uploads full node and visual buffers; when `false`, reuses resident GPU buffers and updates only root + uniforms.
165    ///
166    /// # Returns
167    ///
168    /// - `GpuComputeDispatchResult` - Hardware GPU timing, draw count, and indirect args with zero CPU readback allocations.
169    pub fn dispatch_steady_indirect(
170        &mut self,
171        scene: &GpuComputeSceneInput,
172        render_offscreen: bool,
173        upload_buffers: bool,
174    ) -> GpuComputeDispatchResult {
175        #[cfg(any(target_os = "macos", target_os = "ios"))]
176        if self.is_hardware_compute_ready()
177            && let Some(hw_res) = metal_execute_compute_layout_with_opts(
178                self,
179                scene,
180                render_offscreen,
181                false,
182                upload_buffers,
183            )
184        {
185            return hw_res;
186        }
187        let _: (bool, bool) = (render_offscreen, upload_buffers);
188        let Self {
189            total_dispatches, ..
190        } = self;
191        *total_dispatches = total_dispatches.wrapping_add(1);
192        execute_cpu_reference_compute(scene)
193    }
194
195    /// Commits a zero-readback GPU compute layout and optional indirect render command buffer asynchronously so CPU worker threads can overlap concurrently (`MixedCoExec`).
196    ///
197    /// # Arguments
198    ///
199    /// - `&GpuComputeSceneInput` - Flat BFS scene descriptors.
200    /// - `bool` - When `true`, also encodes hardware `drawPrimitives:indirectBuffer:` into the offscreen `MTLTexture`.
201    /// - `bool` - When `true`, uploads full node and visual buffers; when `false`, reuses resident GPU memory.
202    ///
203    /// # Returns
204    ///
205    /// - `Option<(usize, usize, usize)>` - Retained in-flight command buffer tuple `(cmd_buf_handle, draw_calls, uploaded_bytes)` when submitted on hardware GPU, or `None` on CPU fallback.
206    pub fn begin_steady_indirect_async(
207        &mut self,
208        scene: &GpuComputeSceneInput,
209        render_offscreen: bool,
210        upload_buffers: bool,
211    ) -> Option<(usize, usize, usize)> {
212        #[cfg(any(target_os = "macos", target_os = "ios"))]
213        if self.is_hardware_compute_ready() {
214            return metal_begin_steady_compute_async(self, scene, render_offscreen, upload_buffers);
215        }
216        let _: (&GpuComputeSceneInput, bool, bool) = (scene, render_offscreen, upload_buffers);
217        None
218    }
219
220    /// Awaits completion of a command buffer previously committed by `begin_steady_indirect_async` and returns exact hardware GPU execution telemetry.
221    ///
222    /// # Arguments
223    ///
224    /// - `(usize, usize, usize)` - In-flight tuple `(cmd_buf_handle, draw_calls, uploaded_bytes)` returned by `begin_steady_indirect_async`.
225    ///
226    /// # Returns
227    ///
228    /// - `GpuComputeDispatchResult` - Hardware GPU execution duration, draw calls, and indirect draw arguments.
229    pub fn finish_steady_indirect_async(
230        &mut self,
231        in_flight: (usize, usize, usize),
232    ) -> GpuComputeDispatchResult {
233        #[cfg(any(target_os = "macos", target_os = "ios"))]
234        if self.is_hardware_compute_ready() {
235            return metal_finish_steady_compute_async(self, in_flight);
236        }
237        let _: (usize, usize, usize) = in_flight;
238        GpuComputeDispatchResult::default()
239    }
240
241    /// Ensures persistent Metal compute buffers can hold at least `node_count` BFS nodes without per-frame reallocation.
242    ///
243    /// # Arguments
244    ///
245    /// - `usize` - Required minimum node capacity.
246    #[cfg(any(target_os = "macos", target_os = "ios"))]
247    pub(crate) fn ensure_metal_buffers(&mut self, node_count: usize) {
248        let dev: usize = self.get_device_handle();
249        if dev == 0 {
250            return;
251        }
252        let Self {
253            input_buffer_handle,
254            input_contents_ptr,
255            output_buffer_handle,
256            output_contents_ptr,
257            visual_buffer_handle,
258            visual_contents_ptr,
259            primitive_buffer_handle,
260            primitive_contents_ptr,
261            indirect_buffer_handle,
262            indirect_contents_ptr,
263            hit_buffer_handle,
264            hit_contents_ptr,
265            allocated_node_capacity,
266            ..
267        } = self;
268        if *indirect_buffer_handle == 0 {
269            let (buf, ptr): (usize, usize) =
270                metal_alloc_shared_buffer(dev, size_of::<GpuDrawIndirectArgs>());
271            *indirect_buffer_handle = buf;
272            *indirect_contents_ptr = ptr;
273        }
274        if *hit_buffer_handle == 0 {
275            let (buf, ptr): (usize, usize) = metal_alloc_shared_buffer(dev, size_of::<u32>());
276            *hit_buffer_handle = buf;
277            *hit_contents_ptr = ptr;
278        }
279        if node_count <= *allocated_node_capacity && *input_buffer_handle != 0 {
280            return;
281        }
282        let target_cap: usize = node_count.max(64).next_power_of_two();
283        release_native_gpu_object(*input_buffer_handle);
284        release_native_gpu_object(*output_buffer_handle);
285        release_native_gpu_object(*visual_buffer_handle);
286        release_native_gpu_object(*primitive_buffer_handle);
287        let (in_buf, in_ptr): (usize, usize) = metal_alloc_shared_buffer(
288            dev,
289            target_cap.saturating_mul(size_of::<GpuLayoutNodeInput>()),
290        );
291        let (out_buf, out_ptr): (usize, usize) = metal_alloc_shared_buffer(
292            dev,
293            target_cap.saturating_mul(size_of::<GpuLayoutNodeOutput>()),
294        );
295        let (vis_buf, vis_ptr): (usize, usize) = metal_alloc_shared_buffer(
296            dev,
297            target_cap.saturating_mul(size_of::<GpuVisualStyleInput>()),
298        );
299        let (prim_buf, prim_ptr): (usize, usize) = metal_alloc_shared_buffer(
300            dev,
301            target_cap.saturating_mul(size_of::<GpuPrimitiveInstance>()),
302        );
303        *input_buffer_handle = in_buf;
304        *input_contents_ptr = in_ptr;
305        *output_buffer_handle = out_buf;
306        *output_contents_ptr = out_ptr;
307        *visual_buffer_handle = vis_buf;
308        *visual_contents_ptr = vis_ptr;
309        *primitive_buffer_handle = prim_buf;
310        *primitive_contents_ptr = prim_ptr;
311        *allocated_node_capacity = target_cap;
312    }
313
314    /// Ensures the offscreen `BGRA8Unorm` `MTLTexture` matches `(width, height)`.
315    ///
316    /// # Arguments
317    ///
318    /// - `u32` - Desired offscreen texture width in pixels.
319    /// - `u32` - Desired offscreen texture height in pixels.
320    /// - `bool` - Whether the active Metal device has unified shared memory.
321    #[cfg(any(target_os = "macos", target_os = "ios"))]
322    pub(crate) fn ensure_offscreen_texture(
323        &mut self,
324        width: u32,
325        height: u32,
326        has_unified_memory: bool,
327    ) {
328        let dev: usize = self.get_device_handle();
329        let Self {
330            offscreen_texture_handle,
331            offscreen_width,
332            offscreen_height,
333            ..
334        } = self;
335        if *offscreen_texture_handle != 0
336            && *offscreen_width >= width
337            && *offscreen_height >= height
338        {
339            return;
340        }
341        let alloc_w: u32 = width.max(*offscreen_width);
342        let alloc_h: u32 = height.max(*offscreen_height);
343        release_native_gpu_object(*offscreen_texture_handle);
344        *offscreen_texture_handle =
345            metal_create_offscreen_render_texture(dev, alloc_w, alloc_h, has_unified_memory);
346        *offscreen_width = alloc_w;
347        *offscreen_height = alloc_h;
348    }
349
350    /// Uploads coalesced `DirtyBufferSpan` byte ranges from `primitives` into a GPU-private `MTLBuffer` via a real Metal `MTLBlitCommandEncoder`, supporting both `in_flight = 1` synchronous and `in_flight = 2` ping-pong asynchronous pipelining.
351    ///
352    /// # Arguments
353    ///
354    /// - `&[GpuPrimitiveInstance]` - Source frame primitive array (`64` bytes per entry).
355    /// - `&[DirtyBufferSpan]` - Coalesced dirty byte ranges produced by `DirtySpanCoalescer`.
356    /// - `usize` - Ping-pong staging slot index (`0` or `1`).
357    /// - `bool` - When `true`, blocks on `waitUntilCompleted` (`in_flight = 1`); when `false`, returns the retained command buffer for `finish_upload_metal` (`in_flight = 2`).
358    ///
359    /// # Returns
360    ///
361    /// - `Option<(usize, u64)>` - Tuple `(retained_cmd_buf_or_zero, gpu_exec_ns)` on hardware Metal, or `None` on CPU fallback.
362    pub fn upload_primitive_spans_metal(
363        &mut self,
364        primitives: &[GpuPrimitiveInstance],
365        spans: &[DirtyBufferSpan],
366        slot: usize,
367        wait_sync: bool,
368    ) -> Option<(usize, u64)> {
369        #[cfg(any(target_os = "macos", target_os = "ios"))]
370        if self.is_hardware_compute_ready() {
371            return metal_upload_primitive_spans(self, primitives, spans, slot, wait_sync);
372        }
373        let _: (&[GpuPrimitiveInstance], &[DirtyBufferSpan], usize, bool) =
374            (primitives, spans, slot, wait_sync);
375        None
376    }
377
378    /// Awaits completion of an asynchronous Metal dirty-span blit command buffer returned by `upload_primitive_spans_metal`, returning hardware GPU execution nanoseconds.
379    ///
380    /// # Arguments
381    ///
382    /// - `usize` - Retained `id<MTLCommandBuffer>` handle (`0` is a no-op).
383    ///
384    /// # Returns
385    ///
386    /// - `u64` - Hardware GPU execution duration in nanoseconds.
387    pub fn finish_upload_metal(&self, cmd_handle: usize) -> u64 {
388        #[cfg(any(target_os = "macos", target_os = "ios"))]
389        if cmd_handle != 0 {
390            return metal_finish_upload_async(cmd_handle);
391        }
392        let _: usize = cmd_handle;
393        0
394    }
395}
396
397/// Releases retained native Metal compute buffers and offscreen render textures cleanly on drop.
398impl Drop for GpuComputeLayoutEngine {
399    /// Releases all retained GPU compute buffers, offscreen textures, queue, and device handles.
400    fn drop(&mut self) {
401        let Self {
402            device_handle,
403            queue_handle,
404            input_buffer_handle,
405            output_buffer_handle,
406            visual_buffer_handle,
407            primitive_buffer_handle,
408            indirect_buffer_handle,
409            hit_buffer_handle,
410            offscreen_texture_handle,
411            upload_staging_handles,
412            upload_private_handle,
413            ..
414        } = self;
415        release_native_gpu_object(*upload_private_handle);
416        release_native_gpu_object(upload_staging_handles[1]);
417        release_native_gpu_object(upload_staging_handles[0]);
418        release_native_gpu_object(*offscreen_texture_handle);
419        release_native_gpu_object(*hit_buffer_handle);
420        release_native_gpu_object(*indirect_buffer_handle);
421        release_native_gpu_object(*primitive_buffer_handle);
422        release_native_gpu_object(*visual_buffer_handle);
423        release_native_gpu_object(*output_buffer_handle);
424        release_native_gpu_object(*input_buffer_handle);
425        release_native_gpu_object(*queue_handle);
426        release_native_gpu_object(*device_handle);
427    }
428}