Skip to content

The native runtime for three.js: three.js, down to the metal. 45× smaller than Electron, on a Sony PS3, and path-traced at 60 fps on ray-tracing GPUs.

11.7 KB
Raw Blame
//! `copyExternalImageToTexture` from Canvas 2D bitmaps / decoded images / ImageData, and texture
//! readback to RGBA8 (canvas export, headless screenshots).
use wgpu::TextureFormat as F;

/// RGBA8 source pixels, rows top-down.
pub struct Source<'a> {
    pub width: u32,
    pub height: u32,
    pub stride: usize,
    pub data: &'a [u8],
    /// colour channels are premultiplied by alpha (2D canvases and decoded images are)
    pub premultiplied: bool,
}

pub struct CopyParams {
    pub origin: (u32, u32),
    pub flip_y: bool,
    pub size: (u32, u32),
    pub dst_premultiplied: bool,
}

fn bytes_per_texel(f: F) -> Option<usize> {
    Some(match f {
        F::R8Unorm => 1,
        F::Rg8Unorm => 2,
        F::Rgba8Unorm | F::Rgba8UnormSrgb | F::Bgra8Unorm | F::Bgra8UnormSrgb | F::Rgb10a2Unorm => 4,
        F::R16Float => 2,
        F::Rg16Float => 4,
        F::Rgba16Float => 8,
        F::R32Float => 4,
        F::Rg32Float => 8,
        F::Rgba32Float => 16,
        _ => return None,
    })
}

/// IEEE half from f32 (round to nearest even; values here are in [0, 1]).
pub fn f16_bits(x: f32) -> u16 {
    let b = x.to_bits();
    let sign = ((b >> 16) & 0x8000) as u16;
    let exp = ((b >> 23) & 0xff) as i32;
    let mant = b & 0x7f_ffff;
    if exp == 0xff {
        return sign | 0x7c00 | if mant != 0 { 0x200 } else { 0 };
    }
    let e = exp - 127 + 15;
    if e >= 0x1f {
        return sign | 0x7c00;
    }
    if e <= 0 {
        if e < -10 {
            return sign;
        }
        let m = mant | 0x80_0000;
        let shift = (14 - e) as u32;
        let half = m >> shift;
        let rem = m & ((1 << shift) - 1);
        let mid = 1 << (shift - 1);
        let round = if rem > mid || (rem == mid && half & 1 == 1) { 1 } else { 0 };
        return sign | (half + round) as u16;
    }
    let half = ((e as u32) << 10) | (mant >> 13);
    let rem = mant & 0x1fff;
    let round = if rem > 0x1000 || (rem == 0x1000 && half & 1 == 1) { 1 } else { 0 };
    sign | (half + round) as u16
}

pub fn f16_to_f32(h: u16) -> f32 {
    let sign = if h & 0x8000 != 0 { -1.0 } else { 1.0 };
    let exp = ((h >> 10) & 0x1f) as i32;
    let mant = (h & 0x3ff) as f32;
    sign * match exp {
        0 => mant * (2f32).powi(-24),
        31 => {
            if mant == 0.0 {
                f32::INFINITY
            } else {
                f32::NAN
            }
        }
        e => (1.0 + mant / 1024.0) * (2f32).powi(e - 15),
    }
}

/// Convert a source region into texel bytes of `format` (tightly packed rows). `Err` for formats
/// WebGPU does not allow as copyExternalImageToTexture destinations here.
pub fn convert(src: &Source, p: &CopyParams, format: F) -> Result<Vec<u8>, String> {
    let bpt = bytes_per_texel(format).ok_or_else(|| format!("copyExternalImageToTexture: unsupported destination format {format:?}"))?;
    let (w, h) = p.size;
    let (ox, oy) = p.origin;
    if ox as u64 + w as u64 > src.width as u64 || oy as u64 + h as u64 > src.height as u64 {
        return Err(format!("copyExternalImageToTexture: source region {ox},{oy} {w}x{h} exceeds the {}x{} source", src.width, src.height));
    }
    let mut out = vec![0u8; w as usize * h as usize * bpt];
    let mut px = [0f32; 4];
    for y in 0..h {
        // flipY flips the source image; the origin addresses the flipped image
        let sy = if p.flip_y { src.height - 1 - (oy + y) } else { oy + y } as usize;
        let row = &src.data[sy * src.stride..];
        for x in 0..w {
            let s = &row[(ox + x) as usize * 4..(ox + x) as usize * 4 + 4];
            let (mut r, mut g, mut b, a) = (s[0], s[1], s[2], s[3]);
            if src.premultiplied && !p.dst_premultiplied && a != 0 && a != 255 {
                let un = |c: u8| ((c as u32 * 255 + a as u32 / 2) / a as u32).min(255) as u8;
                (r, g, b) = (un(r), un(g), un(b));
            } else if !src.premultiplied && p.dst_premultiplied && a != 255 {
                let pm = |c: u8| ((c as u32 * a as u32 + 127) / 255) as u8;
                (r, g, b) = (pm(r), pm(g), pm(b));
            }
            let o = &mut out[(y as usize * w as usize + x as usize) * bpt..][..bpt];
            match format {
                F::Rgba8Unorm | F::Rgba8UnormSrgb => o.copy_from_slice(&[r, g, b, a]),
                F::Bgra8Unorm | F::Bgra8UnormSrgb => o.copy_from_slice(&[b, g, r, a]),
                F::R8Unorm => o[0] = r,
                F::Rg8Unorm => o.copy_from_slice(&[r, g]),
                F::Rgb10a2Unorm => {
                    let c = |v: u8| (v as u32 * 1023 + 127) / 255;
                    let v = c(r) | (c(g) << 10) | (c(b) << 20) | (((a as u32 * 3 + 127) / 255) << 30);
                    o.copy_from_slice(&v.to_le_bytes());
                }
                _ => {
                    px[0] = r as f32 / 255.0;
                    px[1] = g as f32 / 255.0;
                    px[2] = b as f32 / 255.0;
                    px[3] = a as f32 / 255.0;
                    let n = match format {
                        F::R16Float | F::R32Float => 1,
                        F::Rg16Float | F::Rg32Float => 2,
                        _ => 4,
                    };
                    if matches!(format, F::R16Float | F::Rg16Float | F::Rgba16Float) {
                        for i in 0..n {
                            o[i * 2..i * 2 + 2].copy_from_slice(&f16_bits(px[i]).to_le_bytes());
                        }
                    } else {
                        for i in 0..n {
                            o[i * 4..i * 4 + 4].copy_from_slice(&px[i].to_le_bytes());
                        }
                    }
                }
            }
        }
    }
    Ok(out)
}

pub fn upload(queue: &wgpu::Queue, tex: &wgpu::Texture, mip: u32, origin: wgpu::Origin3d, size: (u32, u32), format: F, bytes: &[u8]) {
    let bpt = bytes_per_texel(format).unwrap_or(4) as u32;
    queue.write_texture(
        wgpu::TexelCopyTextureInfo { texture: tex, mip_level: mip, origin, aspect: wgpu::TextureAspect::All },
        bytes,
        wgpu::TexelCopyBufferLayout { offset: 0, bytes_per_row: Some(size.0 * bpt), rows_per_image: Some(size.1) },
        wgpu::Extent3d { width: size.0, height: size.1, depth_or_array_layers: 1 },
    );
}

/// Read a 2D texture (mip 0, layer 0) back as RGBA8, rows top-down. Blocks until the GPU is done.
/// `opaque` forces alpha to 255 (an opaque canvas as composited); otherwise colours are
/// un-premultiplied when `premultiplied`.
pub fn read_rgba(dev: &wgpu::Device, queue: &wgpu::Queue, tex: &wgpu::Texture, opaque: bool, premultiplied: bool) -> Result<(u32, u32, Vec<u8>), String> {
    let format = tex.format();
    let bpt = match format {
        F::Rgba8Unorm | F::Rgba8UnormSrgb | F::Bgra8Unorm | F::Bgra8UnormSrgb => 4,
        F::Rgba16Float => 8,
        F::Rgba32Float => 16,
        f => return Err(format!("readback of {f:?} is not supported")),
    };
    if !tex.usage().contains(wgpu::TextureUsages::COPY_SRC) {
        return Err("texture lacks COPY_SRC".into());
    }
    let (w, h) = (tex.width(), tex.height());
    let row = w as u64 * bpt;
    let padded = row.div_ceil(256) * 256;
    let buf = dev.create_buffer(&wgpu::BufferDescriptor { label: Some("readback"), size: (padded * h as u64).max(4), usage: wgpu::BufferUsages::MAP_READ | wgpu::BufferUsages::COPY_DST, mapped_at_creation: false });
    let mut enc = dev.create_command_encoder(&Default::default());
    enc.copy_texture_to_buffer(
        wgpu::TexelCopyTextureInfo { texture: tex, mip_level: 0, origin: wgpu::Origin3d::ZERO, aspect: wgpu::TextureAspect::All },
        wgpu::TexelCopyBufferInfo { buffer: &buf, layout: wgpu::TexelCopyBufferLayout { offset: 0, bytes_per_row: Some(padded as u32), rows_per_image: Some(h) } },
        wgpu::Extent3d { width: w, height: h, depth_or_array_layers: 1 },
    );
    queue.submit([enc.finish()]);
    let (tx, rx) = std::sync::mpsc::channel();
    let slice = buf.slice(..);
    slice.map_async(wgpu::MapMode::Read, move |r| {
        let _ = tx.send(r.is_ok());
    });
    let _ = dev.poll(wgpu::PollType::Wait);
    if !rx.recv().unwrap_or(false) {
        return Err("readback map failed".into());
    }
    let data = slice.get_mapped_range();
    let mut out = vec![0u8; w as usize * h as usize * 4];
    for y in 0..h as usize {
        let src = &data[y * padded as usize..][..row as usize];
        let dst = &mut out[y * w as usize * 4..][..w as usize * 4];
        for x in 0..w as usize {
            let mut p = match format {
                F::Bgra8Unorm | F::Bgra8UnormSrgb => [src[x * 4 + 2], src[x * 4 + 1], src[x * 4], src[x * 4 + 3]],
                F::Rgba8Unorm | F::Rgba8UnormSrgb => [src[x * 4], src[x * 4 + 1], src[x * 4 + 2], src[x * 4 + 3]],
                _ => {
                    let mut c = [0u8; 4];
                    for (i, v) in c.iter_mut().enumerate() {
                        let f = if bpt == 8 {
                            f16_to_f32(u16::from_le_bytes([src[x * 8 + i * 2], src[x * 8 + i * 2 + 1]]))
                        } else {
                            f32::from_le_bytes(src[x * 16 + i * 4..x * 16 + i * 4 + 4].try_into().unwrap())
                        };
                        *v = (f.clamp(0.0, 1.0) * 255.0 + 0.5) as u8;
                    }
                    c
                }
            };
            if opaque {
                p[3] = 255;
            } else if premultiplied && p[3] != 0 && p[3] != 255 {
                let a = p[3] as u32;
                for c in &mut p[..3] {
                    *c = ((*c as u32 * 255 + a / 2) / a).min(255) as u8;
                }
            }
            dst[x * 4..x * 4 + 4].copy_from_slice(&p);
        }
    }
    drop(data);
    buf.unmap();
    Ok((w, h, out))
}

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

    #[test]
    fn half_floats() {
        for v in [0.0f32, 1.0, 0.5, 0.25, 1.0 / 255.0, 0.999, 65504.0, 6.1e-5, 3.0e-7] {
            let back = f16_to_f32(f16_bits(v));
            assert!((back - v).abs() <= v.abs() * 1e-3 + 6e-8, "{v} → {back}");
        }
        assert_eq!(f16_bits(1.0), 0x3c00);
        assert_eq!(f16_bits(-2.0), 0xc000);
        assert_eq!(f16_bits(1e9), 0x7c00);
    }

    #[test]
    fn convert_flip_unpremultiply_swizzle() {
        // 2x2 premultiplied: top row red (opaque) + half-transparent white, bottom row blue + black
        let data = [255, 0, 0, 255, 128, 128, 128, 128, 0, 0, 255, 255, 0, 0, 0, 255];
        let src = Source { width: 2, height: 2, stride: 8, data: &data, premultiplied: true };
        let p = CopyParams { origin: (0, 0), flip_y: false, size: (2, 2), dst_premultiplied: false };
        let out = convert(&src, &p, F::Rgba8Unorm).unwrap();
        assert_eq!(&out[..8], &[255, 0, 0, 255, 255, 255, 255, 128]);
        let flipped = convert(&src, &CopyParams { flip_y: true, ..p }, F::Rgba8Unorm).unwrap();
        assert_eq!(&flipped[..4], &[0, 0, 255, 255], "bottom row first");
        let bgra = convert(&src, &CopyParams { dst_premultiplied: true, ..p }, F::Bgra8Unorm).unwrap();
        assert_eq!(&bgra[..8], &[0, 0, 255, 255, 128, 128, 128, 128]);
        let half = convert(&src, &p, F::Rgba16Float).unwrap();
        assert_eq!(u16::from_le_bytes([half[0], half[1]]), 0x3c00);
        let region = convert(&src, &CopyParams { origin: (1, 1), size: (1, 1), ..p }, F::Rgba8Unorm).unwrap();
        assert_eq!(region, vec![0, 0, 0, 255]);
        assert!(convert(&src, &CopyParams { origin: (1, 1), size: (2, 1), ..p }, F::Rgba8Unorm).is_err());
        assert!(convert(&src, &p, F::Depth24Plus).is_err());
        // ImageData (unpremultiplied) into a premultiplied destination
        let id = [200, 100, 50, 0, 255, 255, 255, 51];
        let src = Source { width: 2, height: 1, stride: 8, data: &id, premultiplied: false };
        let out = convert(&src, &CopyParams { origin: (0, 0), flip_y: false, size: (2, 1), dst_premultiplied: true }, F::Rgba8Unorm).unwrap();
        assert_eq!(out, vec![0, 0, 0, 0, 51, 51, 51, 51]);
    }
}