threers 0.0.7

Drop-in three.js replacement for Rust and WebAssembly (wgpu) — THREE.* API, scene graph, PBR, post-fx, mesh BVH, CSG, an OpenSCAD front end with a watertight exact-CSG kernel, headless render, and native media codecs
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
550
551
//! Offscreen colour + depth attachments, and reading them back.

use super::device::{MetalDevice, MetalError};
use super::enums::*;
use super::objc::{msg0, msg9, sel, AutoreleasePool, Id, Owned, NIL};
use super::renderer::PassAttachments;
use super::resources::{new_texture_2d, new_texture_array};

/// Rows of a texture→buffer copy are padded to this many bytes.
///
/// Metal's own requirement is smaller and format-dependent (and queryable per
/// device); 256 is a multiple of every value it can take, costs a few KB on a
/// 4K frame, and removes the question.
const ROW_ALIGNMENT: usize = 256;

/// An offscreen render target: a colour texture, a depth texture, and — when
/// MSAA is on — the multisample texture the pass actually draws into plus the
/// single-sample texture it resolves to.
pub struct MetalRenderTarget {
    /// What the pass draws into: the MSAA texture, or the colour texture itself.
    draw_color: Owned,
    /// The readable single-sample colour. Same object as `draw_color` when
    /// MSAA is off.
    color: Owned,
    depth: Owned,
    /// Under MSAA, the single-sampled depth the main pass resolves into when
    /// it stores depth (`MetalRenderer::set_store_depth`) — what SSAO and
    /// anything else sampling depth as a `depth2d` reads.
    depth_resolved: Option<Owned>,
    width: u32,
    height: u32,
    color_format: NSUInteger,
    sample_count: u32,
    /// Array slices in the attachments — 2 for a stereo (layered) target.
    slices: u32,
}

impl MetalRenderTarget {
    /// Allocate a target of `width` x `height`.
    ///
    /// `sample_count` of 1 disables MSAA; 4 is the usual choice and is
    /// supported everywhere Metal is. `color_format` is normally
    /// [`pixel_format::RGBA8_UNORM_SRGB`] — the same choice the wgpu headless
    /// renderer makes, so the two produce comparable images.
    pub fn new(
        device: &MetalDevice,
        width: u32,
        height: u32,
        color_format: NSUInteger,
        sample_count: u32,
    ) -> Result<Self, MetalError> {
        let (width, height) = (width.max(1), height.max(1));
        let samples = sample_count.max(1);
        if samples > 1 && !device.supports_sample_count(samples) {
            return Err(MetalError::Unsupported(format!(
                "{samples}x MSAA — this device does not support that sample count"
            )));
        }

        // The resolved colour is a blit source for readback and a sampling
        // source for anything downstream, so it needs SHADER_READ as well.
        let color = new_texture_2d(
            device,
            width,
            height,
            color_format,
            texture_usage::RENDER_TARGET | texture_usage::SHADER_READ,
            storage_mode::PRIVATE,
            1,
            1,
        )?;
        let draw_color = if samples > 1 {
            new_texture_2d(
                device,
                width,
                height,
                color_format,
                texture_usage::RENDER_TARGET,
                storage_mode::PRIVATE,
                samples,
                1,
            )?
        } else {
            color.clone()
        };
        let depth = new_texture_2d(
            device,
            width,
            height,
            pixel_format::DEPTH32_FLOAT,
            // SHADER_READ as well as RENDER_TARGET: SSAO reads this depth back
            // as a `depth2d` in a fragment pass. Without the usage bit the
            // texture binds but reads as zero, which is occlusion everywhere.
            texture_usage::RENDER_TARGET | texture_usage::SHADER_READ,
            storage_mode::PRIVATE,
            samples,
            1,
        )?;
        let depth_resolved = if samples > 1 {
            Some(new_texture_2d(
                device,
                width,
                height,
                pixel_format::DEPTH32_FLOAT,
                texture_usage::RENDER_TARGET | texture_usage::SHADER_READ,
                storage_mode::PRIVATE,
                1,
                1,
            )?)
        } else {
            None
        };

        Ok(Self {
            draw_color,
            color,
            depth,
            depth_resolved,
            width,
            height,
            color_format,
            sample_count: samples,
            slices: 1,
        })
    }

    /// Attachments for [`MetalRenderer::render`](super::MetalRenderer::render).
    pub fn attachments(&self) -> PassAttachments {
        let resolve = if self.sample_count > 1 {
            self.color.id()
        } else {
            NIL
        };
        let pass = unsafe {
            PassAttachments::from_raw(
                self.draw_color.id(),
                resolve,
                self.depth.id(),
                NIL,
                self.width,
                self.height,
                self.color_format,
                pixel_format::DEPTH32_FLOAT,
                self.sample_count,
            )
        };
        match &self.depth_resolved {
            Some(d) => unsafe { pass.with_depth_resolve(d.id()) },
            None => pass,
        }
    }

    /// Size in pixels.
    pub fn size(&self) -> (u32, u32) {
        (self.width, self.height)
    }

    /// MSAA sample count (1 = off).
    pub fn sample_count(&self) -> u32 {
        self.sample_count
    }

    /// The resolved colour texture. Borrowed — do not release.
    pub fn color_texture(&self) -> Id {
        self.color.id()
    }

    /// The depth attachment — multisampled under MSAA. Borrowed — do not
    /// release.
    pub fn depth_texture(&self) -> Id {
        self.depth.id()
    }

    /// Single-sampled depth: under MSAA, what the main pass resolved into
    /// (written only while the renderer stores depth —
    /// `MetalRenderer::set_store_depth`); otherwise the attachment itself.
    /// Borrowed — do not release.
    pub fn resolved_depth_texture(&self) -> Id {
        self.depth_resolved.as_ref().map_or(self.depth.id(), |d| d.id())
    }

    /// A target whose colour and depth attachments are texture *arrays* of
    /// `slices` slices — what stereo rendering draws into, one slice per eye.
    ///
    /// This is the visionOS `layered` layout, reproduced offscreen: the same
    /// attachments the compositor hands over, so the stereo path can be
    /// exercised (and read back) on a Mac.
    pub fn layered(
        device: &MetalDevice,
        width: u32,
        height: u32,
        color_format: NSUInteger,
        slices: u32,
    ) -> Result<Self, MetalError> {
        let (width, height) = (width.max(1), height.max(1));
        let slices = slices.clamp(1, 16);
        let color = new_texture_array(
            device,
            width,
            height,
            color_format,
            texture_usage::RENDER_TARGET | texture_usage::SHADER_READ,
            slices,
        )?;
        let depth = new_texture_array(
            device,
            width,
            height,
            pixel_format::DEPTH32_FLOAT,
            texture_usage::RENDER_TARGET,
            slices,
        )?;
        Ok(Self {
            draw_color: color.clone(),
            color,
            depth,
            depth_resolved: None,
            width,
            height,
            color_format,
            sample_count: 1,
            slices,
        })
    }

    /// Array slices in the attachments. 1 unless this is a
    /// [`layered`](Self::layered) target.
    pub fn slices(&self) -> u32 {
        self.slices
    }

    /// Read the colour attachment back as tightly-packed 8-bit RGBA, top row
    /// first — the same layout [`crate::encode_png`] expects.
    ///
    /// Blocks until the GPU has finished: the copy is committed on the same
    /// queue as the draw, so it cannot observe a half-drawn frame.
    pub fn read_rgba(&self, device: &MetalDevice) -> Result<Vec<u8>, MetalError> {
        let mut out = Vec::new();
        self.read_rgba_into(device, &mut out)?;
        Ok(out)
    }

    /// Unpack the colour attachment into `out`, reusing its capacity when the
    /// size matches. Avoids a fresh allocation every frame in video export.
    pub fn read_rgba_into(
        &self,
        device: &MetalDevice,
        out: &mut Vec<u8>,
    ) -> Result<(), MetalError> {
        self.read_rgba_slice_into(device, 0, out)
    }

    /// Read one array slice back — eye `slice` of a
    /// [`layered`](Self::layered) target.
    pub fn read_rgba_slice(
        &self,
        device: &MetalDevice,
        slice: u32,
    ) -> Result<Vec<u8>, MetalError> {
        let mut out = Vec::new();
        self.read_rgba_slice_into(device, slice, &mut out)?;
        Ok(out)
    }

    /// Like [`read_rgba_slice`](Self::read_rgba_slice) but reuses `out`.
    pub fn read_rgba_slice_into(
        &self,
        device: &MetalDevice,
        slice: u32,
        out: &mut Vec<u8>,
    ) -> Result<(), MetalError> {
        let (width, height, padded, bpp) = self.readback_layout()?;
        let staging = device.new_buffer(&vec![0u8; padded * height])?;
        self.blit_color_to_buffer(device, slice, &staging, padded)?;
        self.unpack_staging(&staging, width, height, padded, bpp, out)
    }

    /// Queue a texture→buffer copy without blocking. Pair with
    /// [`finish_readback_into`](Self::finish_readback_into) on the next frame.
    pub fn queue_readback(
        &self,
        device: &MetalDevice,
        staging: &Owned,
    ) -> Result<Owned, MetalError> {
        self.queue_readback_slice(device, staging, 0)
    }

    /// Queue readback for one array slice; returns the command buffer to wait on later.
    pub fn queue_readback_slice(
        &self,
        device: &MetalDevice,
        staging: &Owned,
        slice: u32,
    ) -> Result<Owned, MetalError> {
        let (_, height, padded, _) = self.readback_layout()?;
        self.blit_color_to_buffer_async(device, slice, staging, padded, height)
    }

    /// Wait for a prior [`queue_readback`](Self::queue_readback) and unpack into `out`.
    // `Id` is `*mut Object`, so clippy asks for `unsafe fn`. Every `Id` in this
    // module comes from the Metal runtime and is only ever handed back to it;
    // making the encoders unsafe would put the keyword on the whole backend
    // without making any caller check anything it is not already checking.
    #[allow(clippy::not_unsafe_ptr_arg_deref)]
    pub fn finish_readback_into(
        &self,
        cmd: Id,
        staging: &Owned,
        out: &mut Vec<u8>,
    ) -> Result<(), MetalError> {
        let _pool = AutoreleasePool::new();
        unsafe {
            if !cmd.is_null() {
                let _: () = msg0(cmd, sel!("waitUntilCompleted"));
            }
        }
        let (width, height, padded, bpp) = self.readback_layout()?;
        self.unpack_staging(staging, width, height, padded, bpp, out)
    }

    fn readback_layout(&self) -> Result<(usize, usize, usize, usize), MetalError> {
        let bpp = pixel_format::bytes_per_pixel(self.color_format).ok_or_else(|| {
            MetalError::Unsupported(format!(
                "readback of pixel format {} is not implemented",
                self.color_format
            ))
        })?;
        if bpp != 4 {
            return Err(MetalError::Unsupported(format!(
                "readback expects an 8-bit 4-channel format, got {} bytes per pixel",
                bpp
            )));
        }
        let width = self.width as usize;
        let height = self.height as usize;
        let padded = padded_row_bytes(width, bpp);
        Ok((width, height, padded, bpp))
    }

    fn blit_color_to_buffer(
        &self,
        device: &MetalDevice,
        slice: u32,
        staging: &Owned,
        padded: usize,
    ) -> Result<(), MetalError> {
        let cmd =
            self.blit_color_to_buffer_async(device, slice, staging, padded, self.height as usize)?;
        let _pool = AutoreleasePool::new();
        unsafe {
            let _: () = msg0(cmd.id(), sel!("waitUntilCompleted"));
        }
        Ok(())
    }

    fn blit_color_to_buffer_async(
        &self,
        device: &MetalDevice,
        slice: u32,
        staging: &Owned,
        padded: usize,
        height: usize,
    ) -> Result<Owned, MetalError> {
        let _pool = AutoreleasePool::new();
        unsafe {
            let cmd = device.command_buffer();
            if cmd.is_null() {
                return Err(MetalError::NoCommandQueue);
            }
            let blit: Id = msg0(cmd, sel!("blitCommandEncoder"));
            if blit.is_null() {
                return Err(MetalError::NoCommandQueue);
            }
            let _: () = msg9(
                blit,
                sel!(
                    "copyFromTexture:sourceSlice:sourceLevel:sourceOrigin:sourceSize:toBuffer:destinationOffset:destinationBytesPerRow:destinationBytesPerImage:"
                ),
                self.color.id(),
                slice.min(self.slices.saturating_sub(1)) as NSUInteger,
                0usize,
                MTLOrigin::default(),
                MTLSize {
                    width: self.width as NSUInteger,
                    height: self.height as NSUInteger,
                    depth: 1,
                },
                staging.id(),
                0usize,
                padded as NSUInteger,
                (padded * height) as NSUInteger,
            );
            let _: () = msg0(blit, sel!("endEncoding"));
            let _: () = msg0(cmd, sel!("commit"));
            // `[queue commandBuffer]` is autoreleased, and the pool above pops
            // when this returns. Handing the raw pointer back leaves the caller
            // messaging an object whose only remaining owner is the queue —
            // retain it here, inside the pool that owns it, so waiting on it
            // later is defined.
            Owned::retain(cmd).ok_or(MetalError::NoCommandQueue)
        }
    }

    fn unpack_staging(
        &self,
        staging: &Owned,
        width: usize,
        height: usize,
        padded: usize,
        bpp: usize,
        out: &mut Vec<u8>,
    ) -> Result<(), MetalError> {
        unpack_staging_buffer(staging, width, height, padded, bpp, self.color_format, out)
    }
}

fn unpack_staging_buffer(
    staging: &Owned,
    width: usize,
    height: usize,
    padded: usize,
    bpp: usize,
    color_format: NSUInteger,
    out: &mut Vec<u8>,
) -> Result<(), MetalError> {
    let need = width * height * bpp;
    out.clear();
    out.resize(need, 0);
    let _pool = AutoreleasePool::new();
    unsafe {
        use std::ffi::c_void;
        let contents: *const u8 =
            msg0::<*mut c_void>(staging.id(), sel!("contents")).cast();
        if contents.is_null() {
            return Err(MetalError::Allocation("readback buffer contents".into()));
        }
        for y in 0..height {
            let src = std::slice::from_raw_parts(contents.add(y * padded), width * bpp);
            out[y * width * bpp..(y + 1) * width * bpp].copy_from_slice(src);
        }
    }
    if pixel_format::is_bgra(color_format) {
        for px in out.chunks_exact_mut(4) {
            px.swap(0, 2);
        }
    }
    Ok(())
}

/// Append a texture→staging blit onto an existing (uncommitted) command buffer.
pub fn blit_texture_to_buffer_on_cmd(
    cmd: Id,
    texture: Id,
    width: u32,
    height: u32,
    staging: &Owned,
    padded: usize,
) -> Result<(), MetalError> {
    unsafe {
        let blit: Id = msg0(cmd, sel!("blitCommandEncoder"));
        if blit.is_null() {
            return Err(MetalError::NoCommandQueue);
        }
        let _: () = msg9(
            blit,
            sel!(
                "copyFromTexture:sourceSlice:sourceLevel:sourceOrigin:sourceSize:toBuffer:destinationOffset:destinationBytesPerRow:destinationBytesPerImage:"
            ),
            texture,
            0usize,
            0usize,
            MTLOrigin::default(),
            MTLSize {
                width: width as NSUInteger,
                height: height as NSUInteger,
                depth: 1,
            },
            staging.id(),
            0usize,
            padded as NSUInteger,
            (padded * height as usize) as NSUInteger,
        );
        let _: () = msg0(blit, sel!("endEncoding"));
    }
    Ok(())
}


/// Unpack a prior async texture readback (after `waitUntilCompleted` on its cmd).
pub fn finish_texture_readback_into(
    cmd: Id,
    staging: &Owned,
    width: u32,
    height: u32,
    color_format: NSUInteger,
    out: &mut Vec<u8>,
) -> Result<(), MetalError> {
    let _pool = AutoreleasePool::new();
    unsafe {
        if !cmd.is_null() {
            let _: () = msg0(cmd, sel!("waitUntilCompleted"));
        }
    }
    let bpp = pixel_format::bytes_per_pixel(color_format).ok_or_else(|| {
        MetalError::Unsupported(format!(
            "readback of pixel format {color_format} is not implemented"
        ))
    })?;
    if bpp != 4 {
        return Err(MetalError::Unsupported(
            "readback expects an 8-bit 4-channel format".into(),
        ));
    }
    let width = width as usize;
    let height = height as usize;
    let padded = padded_row_bytes(width, bpp);
    unpack_staging_buffer(staging, width, height, padded, bpp, color_format, out)
}

impl std::fmt::Debug for MetalRenderTarget {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        f.debug_struct("MetalRenderTarget")
            .field("width", &self.width)
            .field("height", &self.height)
            .field("color_format", &self.color_format)
            .field("sample_count", &self.sample_count)
            .finish()
    }
}

/// Padded row stride for a texture→buffer copy.
fn padded_row_bytes(width: usize, bytes_per_pixel: usize) -> usize {
    (width * bytes_per_pixel).div_ceil(ROW_ALIGNMENT) * ROW_ALIGNMENT
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn rows_pad_up_to_the_alignment() {
        assert_eq!(padded_row_bytes(64, 4), 256);
        assert_eq!(padded_row_bytes(65, 4), 512);
        assert_eq!(padded_row_bytes(256, 4), 1024);
        // Never smaller than the unpadded row.
        for w in [1usize, 3, 17, 100, 1920] {
            assert!(padded_row_bytes(w, 4) >= w * 4);
            assert_eq!(padded_row_bytes(w, 4) % ROW_ALIGNMENT, 0);
        }
    }
}