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.
Rust electron-alternativegame-engineglobal-illuminationgraphicsjavascript-runtimemetalpath-tracingray-tracingreal-time-renderingrenderingrustthreejstypescriptvoxelvulkanwebgpuwgpu
//! The command stream: what a `GPUCommandEncoder` recorded in JS, replayed into wgpu at
//! `finish()`.
//!
//! JS appends 32-bit words to a growable `Uint32Array` (floats are written through a
//! `Float32Array` over the same buffer); `finish()` hands the whole stream over in one call, which
//! reads it in place. Objects are slab ids (`0` = none); [`NONE`] marks an omitted optional value.
//! The opcode table is mirrored in `runtime/webgpu.ts` (`OP`).
//!
//! Encoder level:
//! ```text
//! BEGIN_RENDER_PASS nColor { view resolve load store r g b a }×nColor hasDS [view dLoad dStore dClear(f32) dRO sLoad sStore sClear sRO]
//! occlusionSet tsSet tsBegin tsEnd load: 0 load/1 clear, store: 0 store/1 discard
//! dLoad/sLoad: 0 none/1 load/2 clear, dStore/sStore: 0 none/1 store/2 discard
//! BEGIN_COMPUTE_PASS tsSet tsBegin tsEnd
//! COPY_B2B src srcOff dst dstOff size
//! COPY_B2T buf off bpr rpi | tex mip x y z aspect | w h d
//! COPY_T2B tex mip x y z aspect | buf off bpr rpi | w h d
//! COPY_T2T tex mip x y z aspect | tex mip x y z aspect | w h d
//! CLEAR_BUFFER buf off size
//! RESOLVE_QUERY_SET set first count buf off
//! ```
//! Pass level (until END_PASS):
//! ```text
//! SET_PIPELINE id · SET_BIND_GROUP index id n off×n · SET_VERTEX_BUFFER slot id off size ·
//! SET_INDEX_BUFFER id fmt(0 u16/1 u32) off size · DRAW vc ic fv fi · DRAW_INDEXED ic inst fi base(i32) finst ·
//! DRAW_INDIRECT id off · DRAW_INDEXED_INDIRECT id off · SET_VIEWPORT x y w h min max (f32) ·
//! SET_SCISSOR x y w h · SET_BLEND_CONSTANT r g b a (f32) · SET_STENCIL_REF ref ·
//! BEGIN_OCCLUSION index · END_OCCLUSION · DISPATCH x y z · DISPATCH_INDIRECT id off · END_PASS
//! ```
use crate::fmt;
use crate::res::Slab;
pub const NONE: u32 = u32::MAX;
pub mod op {
pub const BEGIN_RENDER_PASS: u32 = 1;
pub const BEGIN_COMPUTE_PASS: u32 = 2;
pub const END_PASS: u32 = 3;
pub const COPY_B2B: u32 = 4;
pub const COPY_B2T: u32 = 5;
pub const COPY_T2B: u32 = 6;
pub const COPY_T2T: u32 = 7;
pub const CLEAR_BUFFER: u32 = 8;
pub const RESOLVE_QUERY_SET: u32 = 9;
pub const SET_PIPELINE: u32 = 16;
pub const SET_BIND_GROUP: u32 = 17;
pub const SET_VERTEX_BUFFER: u32 = 18;
pub const SET_INDEX_BUFFER: u32 = 19;
pub const DRAW: u32 = 20;
pub const DRAW_INDEXED: u32 = 21;
pub const DRAW_INDIRECT: u32 = 22;
pub const DRAW_INDEXED_INDIRECT: u32 = 23;
pub const SET_VIEWPORT: u32 = 24;
pub const SET_SCISSOR: u32 = 25;
pub const SET_BLEND_CONSTANT: u32 = 26;
pub const SET_STENCIL_REF: u32 = 27;
pub const BEGIN_OCCLUSION: u32 = 28;
pub const END_OCCLUSION: u32 = 29;
pub const DISPATCH: u32 = 30;
pub const DISPATCH_INDIRECT: u32 = 31;
}
/// Bounds-checked reader over the words.
pub struct Reader<'a> {
w: &'a [u32],
pos: usize,
}
impl<'a> Reader<'a> {
pub fn new(w: &'a [u32]) -> Self {
Reader { w, pos: 0 }
}
pub fn done(&self) -> bool {
self.pos >= self.w.len()
}
#[inline]
pub fn u(&mut self) -> Result<u32, String> {
let v = *self.w.get(self.pos).ok_or("truncated command stream")?;
self.pos += 1;
Ok(v)
}
#[inline]
pub fn f(&mut self) -> Result<f32, String> {
self.u().map(f32::from_bits)
}
#[inline]
pub fn i(&mut self) -> Result<i32, String> {
self.u().map(|v| v as i32)
}
pub fn opt(&mut self) -> Result<Option<u32>, String> {
self.u().map(|v| if v == NONE { None } else { Some(v) })
}
pub fn take(&mut self, n: usize) -> Result<&'a [u32], String> {
let end = self.pos.checked_add(n).filter(|e| *e <= self.w.len()).ok_or("truncated command stream")?;
let s = &self.w[self.pos..end];
self.pos = end;
Ok(s)
}
}
/// Builds streams in Rust (tests and internal passes); mirrors the JS encoder.
#[derive(Default)]
pub struct Writer {
pub w: Vec<u32>,
}
impl Writer {
pub fn u(&mut self, v: u32) -> &mut Self {
self.w.push(v);
self
}
pub fn f(&mut self, v: f32) -> &mut Self {
self.w.push(v.to_bits());
self
}
}
/// Per-replay hooks into the canvas module.
pub trait Hooks {
/// `texture` is used as a color attachment (`load`: with loadOp "load") or resolve target.
/// Returns whether the load must become a clear: a canvas texture's first use in a frame
/// sees transparent black, like a freshly presented canvas.
fn canvas_use(&mut self, texture: u32, load: bool) -> bool;
}
#[derive(Default, Clone, Copy, Debug)]
pub struct Counts {
pub passes: u32,
pub draws: u32,
pub commands: u32,
}
fn buffer_slice<'s>(slab: &'s Slab, id: u32, off: u32, size: u32) -> Result<wgpu::BufferSlice<'s>, String> {
let b = slab.buffer(id)?;
let off = off as u64;
let end = if size == NONE { b.size } else { off + size as u64 };
if off >= b.size || end > b.size || end <= off {
return Err(format!("buffer range [{off}, {end}) is empty or outside buffer {id} of size {}", b.size));
}
Ok(b.buf.slice(off..end))
}
fn tex_info<'s>(slab: &'s Slab, r: &mut Reader) -> Result<wgpu::TexelCopyTextureInfo<'s>, String> {
let t = slab.texture(r.u()?)?;
let mip_level = r.u()?;
let origin = wgpu::Origin3d { x: r.u()?, y: r.u()?, z: r.u()? };
let aspect = fmt::aspect_code(r.u()?);
Ok(wgpu::TexelCopyTextureInfo { texture: &t.tex, mip_level, origin, aspect })
}
fn buf_info<'s>(slab: &'s Slab, r: &mut Reader) -> Result<wgpu::TexelCopyBufferInfo<'s>, String> {
let b = slab.buffer(r.u()?)?;
let offset = r.u()? as u64;
let bytes_per_row = r.opt()?;
let rows_per_image = r.opt()?;
Ok(wgpu::TexelCopyBufferInfo { buffer: &b.buf, layout: wgpu::TexelCopyBufferLayout { offset, bytes_per_row, rows_per_image } })
}
fn extent(r: &mut Reader) -> Result<wgpu::Extent3d, String> {
Ok(wgpu::Extent3d { width: r.u()?, height: r.u()?, depth_or_array_layers: r.u()? })
}
fn timestamp_set<'s>(slab: &'s Slab, r: &mut Reader) -> Result<Option<(&'s wgpu::QuerySet, Option<u32>, Option<u32>)>, String> {
let set = r.u()?;
let begin = r.opt()?;
let end = r.opt()?;
if set == 0 {
return Ok(None);
}
Ok(Some((&slab.query_set(set)?.set, begin, end)))
}
/// Replay a recorded command encoder. Errors are encoding errors (bad ids, malformed stream);
/// wgpu's own validation errors go to the error sink as usual.
pub fn encode(dev: &wgpu::Device, slab: &Slab, words: &[u32], hooks: &mut dyn Hooks, counts: &mut Counts) -> Result<wgpu::CommandBuffer, String> {
let mut enc = dev.create_command_encoder(&wgpu::CommandEncoderDescriptor { label: None });
encode_into(&mut enc, slab, words, hooks, counts)?;
Ok(enc.finish())
}
/// Replay a recorded stream into `enc`.
pub fn encode_into(enc: &mut wgpu::CommandEncoder, slab: &Slab, words: &[u32], hooks: &mut dyn Hooks, counts: &mut Counts) -> Result<(), String> {
let mut enc = enc;
let mut r = Reader::new(words);
while !r.done() {
counts.commands += 1;
match r.u()? {
op::BEGIN_RENDER_PASS => render_pass(&mut enc, slab, &mut r, hooks, counts)?,
op::BEGIN_COMPUTE_PASS => compute_pass(&mut enc, slab, &mut r, counts)?,
op::COPY_B2B => {
let src = slab.buffer(r.u()?)?;
let so = r.u()? as u64;
let dst = slab.buffer(r.u()?)?;
let d_o = r.u()? as u64;
let size = r.u()? as u64;
enc.copy_buffer_to_buffer(&src.buf, so, &dst.buf, d_o, size);
}
op::COPY_B2T => {
let b = buf_info(slab, &mut r)?;
let t = tex_info(slab, &mut r)?;
enc.copy_buffer_to_texture(b, t, extent(&mut r)?);
}
op::COPY_T2B => {
let t = tex_info(slab, &mut r)?;
let b = buf_info(slab, &mut r)?;
enc.copy_texture_to_buffer(t, b, extent(&mut r)?);
}
op::COPY_T2T => {
let s = tex_info(slab, &mut r)?;
let d = tex_info(slab, &mut r)?;
enc.copy_texture_to_texture(s, d, extent(&mut r)?);
}
op::CLEAR_BUFFER => {
let b = slab.buffer(r.u()?)?;
let off = r.u()? as u64;
let size = r.opt()?.map(|s| s as u64);
enc.clear_buffer(&b.buf, off, size);
}
op::RESOLVE_QUERY_SET => {
let q = slab.query_set(r.u()?)?;
let first = r.u()?;
let count = r.u()?;
let b = slab.buffer(r.u()?)?;
let off = r.u()? as u64;
let end = first.checked_add(count).ok_or("query range overflows")?;
enc.resolve_query_set(&q.set, first..end, &b.buf, off);
}
o => return Err(format!("unknown encoder command {o}")),
}
}
Ok(())
}
fn depth_ops<V>(load: u32, store: u32, clear: V) -> Option<wgpu::Operations<V>> {
if load == 0 && store == 0 {
return None;
}
Some(wgpu::Operations {
load: if load == 2 { wgpu::LoadOp::Clear(clear) } else { wgpu::LoadOp::Load },
store: if store == 2 { wgpu::StoreOp::Discard } else { wgpu::StoreOp::Store },
})
}
fn render_pass(enc: &mut wgpu::CommandEncoder, slab: &Slab, r: &mut Reader, hooks: &mut dyn Hooks, counts: &mut Counts) -> Result<(), String> {
counts.passes += 1;
let n = r.u()? as usize;
if n > 8 {
return Err(format!("{n} color attachments"));
}
let mut colors: Vec<Option<wgpu::RenderPassColorAttachment>> = Vec::with_capacity(n);
for _ in 0..n {
let view = r.u()?;
let resolve = r.u()?;
let load = r.u()?;
let store = r.u()?;
let c = [r.f()?, r.f()?, r.f()?, r.f()?];
if view == 0 {
colors.push(None);
continue;
}
let v = slab.view(view)?;
let resolve_target = if resolve == 0 {
None
} else {
let rv = slab.view(resolve)?;
hooks.canvas_use(rv.texture, false);
Some(&rv.view)
};
let clear = wgpu::Color { r: c[0] as f64, g: c[1] as f64, b: c[2] as f64, a: c[3] as f64 };
let mut load = if load == 1 { wgpu::LoadOp::Clear(clear) } else { wgpu::LoadOp::Load };
if hooks.canvas_use(v.texture, matches!(load, wgpu::LoadOp::Load)) {
load = wgpu::LoadOp::Clear(wgpu::Color::TRANSPARENT);
}
let store = if store == 1 { wgpu::StoreOp::Discard } else { wgpu::StoreOp::Store };
colors.push(Some(wgpu::RenderPassColorAttachment { view: &v.view, resolve_target, ops: wgpu::Operations { load, store } }));
}
let depth_stencil_attachment = if r.u()? != 0 {
let view = &slab.view(r.u()?)?.view;
let (dl, ds, dc, _dro) = (r.u()?, r.u()?, r.f()?, r.u()?);
let (sl, ss, sc, _sro) = (r.u()?, r.u()?, r.u()?, r.u()?);
Some(wgpu::RenderPassDepthStencilAttachment { view, depth_ops: depth_ops(dl, ds, dc), stencil_ops: depth_ops(sl, ss, sc) })
} else {
None
};
let occ = r.u()?;
let occlusion_query_set = if occ == 0 { None } else { Some(&slab.query_set(occ)?.set) };
let timestamp_writes = timestamp_set(slab, r)?.map(|(query_set, b, e)| wgpu::RenderPassTimestampWrites {
query_set,
beginning_of_pass_write_index: b,
end_of_pass_write_index: e,
});
let mut pass = enc.begin_render_pass(&wgpu::RenderPassDescriptor { label: None, color_attachments: &colors, depth_stencil_attachment, timestamp_writes, occlusion_query_set });
loop {
counts.commands += 1;
match r.u()? {
op::END_PASS => return Ok(()),
op::SET_PIPELINE => pass.set_pipeline(slab.render_pipeline(r.u()?)?),
op::SET_BIND_GROUP => {
let index = r.u()?;
let id = r.u()?;
let n = r.u()? as usize;
let offsets = r.take(n)?;
let bg = if id == 0 { None } else { Some(slab.bind_group(id)?) };
pass.set_bind_group(index, bg, offsets);
}
op::SET_VERTEX_BUFFER => {
let slot = r.u()?;
let (id, off, size) = (r.u()?, r.u()?, r.u()?);
if id != 0 && size != 0 {
pass.set_vertex_buffer(slot, buffer_slice(slab, id, off, size)?);
}
}
op::SET_INDEX_BUFFER => {
let id = r.u()?;
let f = if r.u()? == 1 { wgpu::IndexFormat::Uint32 } else { wgpu::IndexFormat::Uint16 };
let (off, size) = (r.u()?, r.u()?);
if size != 0 {
pass.set_index_buffer(buffer_slice(slab, id, off, size)?, f);
}
}
op::DRAW => {
let (vc, ic, fv, fi) = (r.u()?, r.u()?, r.u()?, r.u()?);
counts.draws += 1;
pass.draw(fv..fv.saturating_add(vc), fi..fi.saturating_add(ic));
}
op::DRAW_INDEXED => {
let (ic, inst, fi, base, finst) = (r.u()?, r.u()?, r.u()?, r.i()?, r.u()?);
counts.draws += 1;
pass.draw_indexed(fi..fi.saturating_add(ic), base, finst..finst.saturating_add(inst));
}
op::DRAW_INDIRECT => {
let b = slab.buffer(r.u()?)?;
counts.draws += 1;
pass.draw_indirect(&b.buf, r.u()? as u64);
}
op::DRAW_INDEXED_INDIRECT => {
let b = slab.buffer(r.u()?)?;
counts.draws += 1;
pass.draw_indexed_indirect(&b.buf, r.u()? as u64);
}
op::SET_VIEWPORT => {
let v = [r.f()?, r.f()?, r.f()?, r.f()?, r.f()?, r.f()?];
pass.set_viewport(v[0], v[1], v[2], v[3], v[4], v[5]);
}
op::SET_SCISSOR => {
let (x, y, w, h) = (r.u()?, r.u()?, r.u()?, r.u()?);
pass.set_scissor_rect(x, y, w, h);
}
op::SET_BLEND_CONSTANT => {
let c = [r.f()?, r.f()?, r.f()?, r.f()?];
pass.set_blend_constant(wgpu::Color { r: c[0] as f64, g: c[1] as f64, b: c[2] as f64, a: c[3] as f64 });
}
op::SET_STENCIL_REF => pass.set_stencil_reference(r.u()?),
op::BEGIN_OCCLUSION => pass.begin_occlusion_query(r.u()?),
op::END_OCCLUSION => pass.end_occlusion_query(),
o => return Err(format!("command {o} is not valid in a render pass")),
}
}
}
fn compute_pass(enc: &mut wgpu::CommandEncoder, slab: &Slab, r: &mut Reader, counts: &mut Counts) -> Result<(), String> {
counts.passes += 1;
let timestamp_writes = timestamp_set(slab, r)?.map(|(query_set, b, e)| wgpu::ComputePassTimestampWrites {
query_set,
beginning_of_pass_write_index: b,
end_of_pass_write_index: e,
});
let mut pass = enc.begin_compute_pass(&wgpu::ComputePassDescriptor { label: None, timestamp_writes });
loop {
counts.commands += 1;
match r.u()? {
op::END_PASS => return Ok(()),
op::SET_PIPELINE => pass.set_pipeline(slab.compute_pipeline(r.u()?)?),
op::SET_BIND_GROUP => {
let index = r.u()?;
let id = r.u()?;
let n = r.u()? as usize;
let offsets = r.take(n)?;
let bg = if id == 0 { None } else { Some(slab.bind_group(id)?) };
pass.set_bind_group(index, bg, offsets);
}
op::DISPATCH => {
let (x, y, z) = (r.u()?, r.u()?, r.u()?);
pass.dispatch_workgroups(x, y, z);
}
op::DISPATCH_INDIRECT => {
let b = slab.buffer(r.u()?)?;
pass.dispatch_workgroups_indirect(&b.buf, r.u()? as u64);
}
o => return Err(format!("command {o} is not valid in a compute pass")),
}
}
}
/// Walk a stream without executing it: the number of passes and draws, or the first structural
/// error. Used by tests and by debug builds to check the JS encoder.
pub fn validate(words: &[u32]) -> Result<Counts, String> {
let mut c = Counts::default();
let mut r = Reader::new(words);
let mut in_pass: Option<bool> = None; // Some(true) render, Some(false) compute
while !r.done() {
let o = r.u()?;
c.commands += 1;
let n = match (in_pass, o) {
(None, op::BEGIN_RENDER_PASS) => {
let k = r.u()? as usize;
r.take(k * 8)?;
if r.u()? != 0 {
r.take(9)?;
}
r.take(4)?;
c.passes += 1;
in_pass = Some(true);
0
}
(None, op::BEGIN_COMPUTE_PASS) => {
c.passes += 1;
in_pass = Some(false);
3
}
(None, op::COPY_B2B) => 5,
(None, op::COPY_B2T | op::COPY_T2B) => 4 + 6 + 3,
(None, op::COPY_T2T) => 6 + 6 + 3,
(None, op::CLEAR_BUFFER) => 3,
(None, op::RESOLVE_QUERY_SET) => 5,
(Some(_), op::END_PASS) => {
in_pass = None;
0
}
(Some(_), op::SET_PIPELINE) => 1,
(Some(_), op::SET_BIND_GROUP) => {
r.take(2)?;
r.u()? as usize
}
(Some(true), op::SET_VERTEX_BUFFER) => 4,
(Some(true), op::SET_INDEX_BUFFER) => 4,
(Some(true), op::DRAW) => {
c.draws += 1;
4
}
(Some(true), op::DRAW_INDEXED) => {
c.draws += 1;
5
}
(Some(true), op::DRAW_INDIRECT | op::DRAW_INDEXED_INDIRECT) => {
c.draws += 1;
2
}
(Some(true), op::SET_VIEWPORT) => 6,
(Some(true), op::SET_SCISSOR | op::SET_BLEND_CONSTANT) => 4,
(Some(true), op::SET_STENCIL_REF | op::BEGIN_OCCLUSION) => 1,
(Some(true), op::END_OCCLUSION) => 0,
(Some(false), op::DISPATCH) => 3,
(Some(false), op::DISPATCH_INDIRECT) => 2,
(p, o) => return Err(format!("command {o} is not valid {}", if p.is_some() { "in a pass" } else { "outside a pass" })),
};
r.take(n)?;
}
if in_pass.is_some() {
return Err("pass not ended".into());
}
Ok(c)
}
#[cfg(test)]
mod tests {
use super::*;
/// A frame the way the JS encoder writes it: a cleared MSAA pass with depth, two draws, a copy.
fn sample() -> Vec<u32> {
let mut w = Writer::default();
w.u(op::BEGIN_RENDER_PASS).u(1);
w.u(7).u(8).u(1).u(1).f(0.25).f(0.5).f(0.75).f(1.0); // view, resolve, clear, discard
w.u(1).u(9).u(2).u(1).f(1.0).u(0).u(0).u(0).u(0).u(0); // depth: clear 1.0 / store, no stencil
w.u(0).u(0).u(NONE).u(NONE); // no occlusion / timestamps
w.u(op::SET_VIEWPORT).f(0.0).f(0.0).f(800.0).f(600.0).f(0.0).f(1.0);
w.u(op::SET_PIPELINE).u(3);
w.u(op::SET_BIND_GROUP).u(0).u(4).u(2).u(256).u(512);
w.u(op::SET_VERTEX_BUFFER).u(0).u(5).u(0).u(NONE);
w.u(op::SET_INDEX_BUFFER).u(6).u(1).u(0).u(NONE);
w.u(op::DRAW_INDEXED).u(36).u(1).u(0).u((-4i32) as u32).u(0);
w.u(op::SET_STENCIL_REF).u(1);
w.u(op::DRAW).u(3).u(1).u(0).u(0);
w.u(op::END_PASS);
w.u(op::COPY_B2B).u(5).u(0).u(10).u(0).u(64);
w.u(op::BEGIN_COMPUTE_PASS).u(0).u(NONE).u(NONE);
w.u(op::SET_PIPELINE).u(11).u(op::DISPATCH).u(8).u(8).u(1).u(op::END_PASS);
w.w
}
#[test]
fn stream_structure() {
let c = validate(&sample()).unwrap();
assert_eq!((c.passes, c.draws), (2, 2));
}
#[test]
fn reader_decodes_values() {
let s = sample();
let mut r = Reader::new(&s);
assert_eq!(r.u().unwrap(), op::BEGIN_RENDER_PASS);
assert_eq!(r.u().unwrap(), 1);
assert_eq!(r.take(4).unwrap(), &[7, 8, 1, 1]);
assert_eq!([r.f().unwrap(), r.f().unwrap(), r.f().unwrap(), r.f().unwrap()], [0.25, 0.5, 0.75, 1.0]);
let mut r = Reader::new(&[5, NONE, (-4i32) as u32]);
assert_eq!(r.opt().unwrap(), Some(5));
assert_eq!(r.opt().unwrap(), None);
assert_eq!(r.i().unwrap(), -4);
assert!(r.u().is_err(), "reads past the end fail instead of panicking");
assert!(Reader::new(&[1, 2]).take(3).is_err());
}
#[test]
fn malformed_streams_are_rejected() {
let s = sample();
for cut in 1..s.len() {
// every truncation either is a valid prefix (ends between commands) or errors
let r = validate(&s[..cut]);
if let Ok(c) = r {
assert!(c.passes <= 2);
}
}
assert!(validate(&[op::DRAW, 3, 1, 0, 0]).unwrap_err().contains("outside a pass"));
assert!(validate(&[op::BEGIN_COMPUTE_PASS, 0, NONE, NONE, op::DRAW, 3, 1, 0, 0]).is_err());
assert!(validate(&[op::BEGIN_COMPUTE_PASS, 0, NONE, NONE]).unwrap_err().contains("not ended"));
assert!(validate(&[99]).is_err());
assert!(validate(&[op::BEGIN_RENDER_PASS, u32::MAX]).is_err(), "absurd attachment counts fail cleanly");
}
}