euv-core 0.51.0

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

/// Safe optional coordinate accessor and builder helpers for `GpuComputeSceneInput`.
impl GpuComputeSceneInput {
    /// Returns the optional pointer hit-test coordinate `[x, y]` without unwrapping.
    ///
    /// # Returns
    ///
    /// - `Option<[f32; 2]>` - Pointer coordinate when hit-testing is requested.
    #[must_use]
    pub fn pick_point_value(&self) -> Option<[f32; 2]> {
        let Self { pick_point, .. } = *self;
        pick_point
    }
}

/// Default initialization probing native hardware compute support with automatic CPU reference parity fallback.
impl Default for GpuComputeLayoutEngine {
    /// Probes the active host for hardware compute pipelines and creates a ready `GpuComputeLayoutEngine`.
    ///
    /// # Returns
    ///
    /// - `Self` - Initialized GPU compute layout engine.
    fn default() -> Self {
        Self::probe()
    }
}

/// Hardware initialization, persistent buffer management, and compute layout dispatch for `GpuComputeLayoutEngine`.
impl GpuComputeLayoutEngine {
    /// Probes physical Apple Metal compute pipelines when available, falling back cleanly to CPU reference parity.
    ///
    /// # Returns
    ///
    /// - `Self` - Ready compute layout engine.
    #[must_use]
    pub fn probe() -> Self {
        #[cfg(any(target_os = "macos", target_os = "ios"))]
        {
            let cache: &MetalComputePipelineCache = init_metal_compute_cache();
            if cache.device != 0
                && cache.queue != 0
                && cache.measure_pso != 0
                && cache.solve_pso != 0
                && cache.cull_emit_pso != 0
                && cache.hit_test_pso != 0
            {
                return Self {
                    backend_kind: GpuComputeBackendKind::MetalHardware,
                    device_handle: mtl_retain_handle(cache.device),
                    queue_handle: mtl_retain_handle(cache.queue),
                    input_buffer_handle: 0,
                    input_contents_ptr: 0,
                    output_buffer_handle: 0,
                    output_contents_ptr: 0,
                    visual_buffer_handle: 0,
                    visual_contents_ptr: 0,
                    primitive_buffer_handle: 0,
                    primitive_contents_ptr: 0,
                    indirect_buffer_handle: 0,
                    indirect_contents_ptr: 0,
                    hit_buffer_handle: 0,
                    hit_contents_ptr: 0,
                    allocated_node_capacity: 0,
                    offscreen_texture_handle: 0,
                    offscreen_width: 0,
                    offscreen_height: 0,
                    total_dispatches: 0,
                    cached_uniform_row_h: 0.0,
                    upload_staging_handles: [0; 2],
                    upload_staging_ptrs: [0; 2],
                    upload_private_handle: 0,
                    upload_capacity_bytes: 0,
                };
            }
        }
        Self::cpu_reference_only()
    }

    /// Creates a deterministic CPU reference compute parity engine that never invokes hardware GPU APIs.
    ///
    /// # Returns
    ///
    /// - `Self` - CPU reference parity compute engine.
    #[must_use]
    pub fn cpu_reference_only() -> Self {
        Self {
            backend_kind: GpuComputeBackendKind::CpuReferenceParity,
            device_handle: 0,
            queue_handle: 0,
            input_buffer_handle: 0,
            input_contents_ptr: 0,
            output_buffer_handle: 0,
            output_contents_ptr: 0,
            visual_buffer_handle: 0,
            visual_contents_ptr: 0,
            primitive_buffer_handle: 0,
            primitive_contents_ptr: 0,
            indirect_buffer_handle: 0,
            indirect_contents_ptr: 0,
            hit_buffer_handle: 0,
            hit_contents_ptr: 0,
            allocated_node_capacity: 0,
            offscreen_texture_handle: 0,
            offscreen_width: 0,
            offscreen_height: 0,
            total_dispatches: 0,
            cached_uniform_row_h: 0.0,
            upload_staging_handles: [0; 2],
            upload_staging_ptrs: [0; 2],
            upload_private_handle: 0,
            upload_capacity_bytes: 0,
        }
    }

    /// Returns `true` when physical GPU compute pipelines are compiled and ready for dispatch.
    ///
    /// # Returns
    ///
    /// - `bool` - `true` when executing on physical hardware compute pipelines.
    #[must_use]
    pub fn is_hardware_compute_ready(&self) -> bool {
        self.get_backend_kind() == GpuComputeBackendKind::MetalHardware
            && self.get_device_handle() != 0
            && self.get_queue_handle() != 0
    }

    /// Executes the 4-kernel GPU compute layout pipeline and optionally renders compacted primitives via indirect draw into an offscreen target.
    ///
    /// # Arguments
    ///
    /// - `&GpuComputeSceneInput` - Flat BFS layout inputs, styles, and level offsets.
    /// - `bool` - When `true`, also executes hardware `drawPrimitives:indirectBuffer:` into an offscreen `MTLTexture`.
    ///
    /// # Returns
    ///
    /// - `GpuComputeDispatchResult` - Resolved layout outputs, compacted primitives, indirect draw args, hit-test result, and GPU timing telemetry.
    pub fn dispatch(
        &mut self,
        scene: &GpuComputeSceneInput,
        render_offscreen: bool,
    ) -> GpuComputeDispatchResult {
        #[cfg(any(target_os = "macos", target_os = "ios"))]
        if self.is_hardware_compute_ready()
            && let Some(hw_res) =
                metal_execute_compute_layout_with_opts(self, scene, render_offscreen, true, true)
        {
            return hw_res;
        }
        let _: bool = render_offscreen;
        let Self {
            total_dispatches, ..
        } = self;
        *total_dispatches = total_dispatches.wrapping_add(1);
        execute_cpu_reference_compute(scene)
    }

    /// Executes the steady-state zero-readback GPU compute layout and indirect render pipeline without copying outputs, primitives, or offscreen pixels back to CPU memory.
    ///
    /// # Arguments
    ///
    /// - `&GpuComputeSceneInput` - Flat BFS scene descriptors (only root and uniform update when `upload_buffers` is `false`).
    /// - `bool` - When `true`, encodes hardware `drawPrimitives:indirectBuffer:` into the offscreen `MTLTexture`.
    /// - `bool` - When `true`, uploads full node and visual buffers; when `false`, reuses resident GPU buffers and updates only root + uniforms.
    ///
    /// # Returns
    ///
    /// - `GpuComputeDispatchResult` - Hardware GPU timing, draw count, and indirect args with zero CPU readback allocations.
    pub fn dispatch_steady_indirect(
        &mut self,
        scene: &GpuComputeSceneInput,
        render_offscreen: bool,
        upload_buffers: bool,
    ) -> GpuComputeDispatchResult {
        #[cfg(any(target_os = "macos", target_os = "ios"))]
        if self.is_hardware_compute_ready()
            && let Some(hw_res) = metal_execute_compute_layout_with_opts(
                self,
                scene,
                render_offscreen,
                false,
                upload_buffers,
            )
        {
            return hw_res;
        }
        let _: (bool, bool) = (render_offscreen, upload_buffers);
        let Self {
            total_dispatches, ..
        } = self;
        *total_dispatches = total_dispatches.wrapping_add(1);
        execute_cpu_reference_compute(scene)
    }

    /// Commits a zero-readback GPU compute layout and optional indirect render command buffer asynchronously so CPU worker threads can overlap concurrently (`MixedCoExec`).
    ///
    /// # Arguments
    ///
    /// - `&GpuComputeSceneInput` - Flat BFS scene descriptors.
    /// - `bool` - When `true`, also encodes hardware `drawPrimitives:indirectBuffer:` into the offscreen `MTLTexture`.
    /// - `bool` - When `true`, uploads full node and visual buffers; when `false`, reuses resident GPU memory.
    ///
    /// # Returns
    ///
    /// - `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.
    pub fn begin_steady_indirect_async(
        &mut self,
        scene: &GpuComputeSceneInput,
        render_offscreen: bool,
        upload_buffers: bool,
    ) -> Option<(usize, usize, usize)> {
        #[cfg(any(target_os = "macos", target_os = "ios"))]
        if self.is_hardware_compute_ready() {
            return metal_begin_steady_compute_async(self, scene, render_offscreen, upload_buffers);
        }
        let _: (&GpuComputeSceneInput, bool, bool) = (scene, render_offscreen, upload_buffers);
        None
    }

    /// Awaits completion of a command buffer previously committed by `begin_steady_indirect_async` and returns exact hardware GPU execution telemetry.
    ///
    /// # Arguments
    ///
    /// - `(usize, usize, usize)` - In-flight tuple `(cmd_buf_handle, draw_calls, uploaded_bytes)` returned by `begin_steady_indirect_async`.
    ///
    /// # Returns
    ///
    /// - `GpuComputeDispatchResult` - Hardware GPU execution duration, draw calls, and indirect draw arguments.
    pub fn finish_steady_indirect_async(
        &mut self,
        in_flight: (usize, usize, usize),
    ) -> GpuComputeDispatchResult {
        #[cfg(any(target_os = "macos", target_os = "ios"))]
        if self.is_hardware_compute_ready() {
            return metal_finish_steady_compute_async(self, in_flight);
        }
        let _: (usize, usize, usize) = in_flight;
        GpuComputeDispatchResult::default()
    }

    /// Ensures persistent Metal compute buffers can hold at least `node_count` BFS nodes without per-frame reallocation.
    ///
    /// # Arguments
    ///
    /// - `usize` - Required minimum node capacity.
    #[cfg(any(target_os = "macos", target_os = "ios"))]
    pub(crate) fn ensure_metal_buffers(&mut self, node_count: usize) {
        let dev: usize = self.get_device_handle();
        if dev == 0 {
            return;
        }
        let Self {
            input_buffer_handle,
            input_contents_ptr,
            output_buffer_handle,
            output_contents_ptr,
            visual_buffer_handle,
            visual_contents_ptr,
            primitive_buffer_handle,
            primitive_contents_ptr,
            indirect_buffer_handle,
            indirect_contents_ptr,
            hit_buffer_handle,
            hit_contents_ptr,
            allocated_node_capacity,
            ..
        } = self;
        if *indirect_buffer_handle == 0 {
            let (buf, ptr): (usize, usize) =
                metal_alloc_shared_buffer(dev, size_of::<GpuDrawIndirectArgs>());
            *indirect_buffer_handle = buf;
            *indirect_contents_ptr = ptr;
        }
        if *hit_buffer_handle == 0 {
            let (buf, ptr): (usize, usize) = metal_alloc_shared_buffer(dev, size_of::<u32>());
            *hit_buffer_handle = buf;
            *hit_contents_ptr = ptr;
        }
        if node_count <= *allocated_node_capacity && *input_buffer_handle != 0 {
            return;
        }
        let target_cap: usize = node_count.max(64).next_power_of_two();
        release_native_gpu_object(*input_buffer_handle);
        release_native_gpu_object(*output_buffer_handle);
        release_native_gpu_object(*visual_buffer_handle);
        release_native_gpu_object(*primitive_buffer_handle);
        let (in_buf, in_ptr): (usize, usize) = metal_alloc_shared_buffer(
            dev,
            target_cap.saturating_mul(size_of::<GpuLayoutNodeInput>()),
        );
        let (out_buf, out_ptr): (usize, usize) = metal_alloc_shared_buffer(
            dev,
            target_cap.saturating_mul(size_of::<GpuLayoutNodeOutput>()),
        );
        let (vis_buf, vis_ptr): (usize, usize) = metal_alloc_shared_buffer(
            dev,
            target_cap.saturating_mul(size_of::<GpuVisualStyleInput>()),
        );
        let (prim_buf, prim_ptr): (usize, usize) = metal_alloc_shared_buffer(
            dev,
            target_cap.saturating_mul(size_of::<GpuPrimitiveInstance>()),
        );
        *input_buffer_handle = in_buf;
        *input_contents_ptr = in_ptr;
        *output_buffer_handle = out_buf;
        *output_contents_ptr = out_ptr;
        *visual_buffer_handle = vis_buf;
        *visual_contents_ptr = vis_ptr;
        *primitive_buffer_handle = prim_buf;
        *primitive_contents_ptr = prim_ptr;
        *allocated_node_capacity = target_cap;
    }

    /// Ensures the offscreen `BGRA8Unorm` `MTLTexture` matches `(width, height)`.
    ///
    /// # Arguments
    ///
    /// - `u32` - Desired offscreen texture width in pixels.
    /// - `u32` - Desired offscreen texture height in pixels.
    /// - `bool` - Whether the active Metal device has unified shared memory.
    #[cfg(any(target_os = "macos", target_os = "ios"))]
    pub(crate) fn ensure_offscreen_texture(
        &mut self,
        width: u32,
        height: u32,
        has_unified_memory: bool,
    ) {
        let dev: usize = self.get_device_handle();
        let Self {
            offscreen_texture_handle,
            offscreen_width,
            offscreen_height,
            ..
        } = self;
        if *offscreen_texture_handle != 0
            && *offscreen_width >= width
            && *offscreen_height >= height
        {
            return;
        }
        let alloc_w: u32 = width.max(*offscreen_width);
        let alloc_h: u32 = height.max(*offscreen_height);
        release_native_gpu_object(*offscreen_texture_handle);
        *offscreen_texture_handle =
            metal_create_offscreen_render_texture(dev, alloc_w, alloc_h, has_unified_memory);
        *offscreen_width = alloc_w;
        *offscreen_height = alloc_h;
    }

    /// 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.
    ///
    /// # Arguments
    ///
    /// - `&[GpuPrimitiveInstance]` - Source frame primitive array (`64` bytes per entry).
    /// - `&[DirtyBufferSpan]` - Coalesced dirty byte ranges produced by `DirtySpanCoalescer`.
    /// - `usize` - Ping-pong staging slot index (`0` or `1`).
    /// - `bool` - When `true`, blocks on `waitUntilCompleted` (`in_flight = 1`); when `false`, returns the retained command buffer for `finish_upload_metal` (`in_flight = 2`).
    ///
    /// # Returns
    ///
    /// - `Option<(usize, u64)>` - Tuple `(retained_cmd_buf_or_zero, gpu_exec_ns)` on hardware Metal, or `None` on CPU fallback.
    pub fn upload_primitive_spans_metal(
        &mut self,
        primitives: &[GpuPrimitiveInstance],
        spans: &[DirtyBufferSpan],
        slot: usize,
        wait_sync: bool,
    ) -> Option<(usize, u64)> {
        #[cfg(any(target_os = "macos", target_os = "ios"))]
        if self.is_hardware_compute_ready() {
            return metal_upload_primitive_spans(self, primitives, spans, slot, wait_sync);
        }
        let _: (&[GpuPrimitiveInstance], &[DirtyBufferSpan], usize, bool) =
            (primitives, spans, slot, wait_sync);
        None
    }

    /// Awaits completion of an asynchronous Metal dirty-span blit command buffer returned by `upload_primitive_spans_metal`, returning hardware GPU execution nanoseconds.
    ///
    /// # Arguments
    ///
    /// - `usize` - Retained `id<MTLCommandBuffer>` handle (`0` is a no-op).
    ///
    /// # Returns
    ///
    /// - `u64` - Hardware GPU execution duration in nanoseconds.
    pub fn finish_upload_metal(&self, cmd_handle: usize) -> u64 {
        #[cfg(any(target_os = "macos", target_os = "ios"))]
        if cmd_handle != 0 {
            return metal_finish_upload_async(cmd_handle);
        }
        let _: usize = cmd_handle;
        0
    }
}

/// Releases retained native Metal compute buffers and offscreen render textures cleanly on drop.
impl Drop for GpuComputeLayoutEngine {
    /// Releases all retained GPU compute buffers, offscreen textures, queue, and device handles.
    fn drop(&mut self) {
        let Self {
            device_handle,
            queue_handle,
            input_buffer_handle,
            output_buffer_handle,
            visual_buffer_handle,
            primitive_buffer_handle,
            indirect_buffer_handle,
            hit_buffer_handle,
            offscreen_texture_handle,
            upload_staging_handles,
            upload_private_handle,
            ..
        } = self;
        release_native_gpu_object(*upload_private_handle);
        release_native_gpu_object(upload_staging_handles[1]);
        release_native_gpu_object(upload_staging_handles[0]);
        release_native_gpu_object(*offscreen_texture_handle);
        release_native_gpu_object(*hit_buffer_handle);
        release_native_gpu_object(*indirect_buffer_handle);
        release_native_gpu_object(*primitive_buffer_handle);
        release_native_gpu_object(*visual_buffer_handle);
        release_native_gpu_object(*output_buffer_handle);
        release_native_gpu_object(*input_buffer_handle);
        release_native_gpu_object(*queue_handle);
        release_native_gpu_object(*device_handle);
    }
}