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
//! `__native.gpu`: the functions `runtime/webgpu.ts` calls. Ids are slab ids; `Err` results
//! become JS exceptions that the JS layer maps to the WebGPU exception types (TypeError for
//! descriptor parse errors, OperationError for mapping misuse). GPU validation errors are
//! reported through the error sink instead and return an id anyway (an "invalid" object).
use std::time::Instant;
use jsc::{Ctx, NativeResult, TypedArrayType, Value};
use serde_json::Value as J;
use crate::args;
use crate::canvas::{Canvas, Config};
use crate::cmd;
use crate::desc;
use crate::fmt;
use crate::gpu::{self, ErrKind, Gpu};
use crate::image;
use crate::res::{BufferRes, MapState, QuerySetRes, Res, ShaderRes, TextureRes, ViewRes};
use crate::{STATE, State, WINDOW, encode_writes, flush_writes_now, frame_encoder, push_event, token};
type F = fn(Ctx, &[Value]) -> NativeResult;
fn arg(a: &[Value], i: usize) -> Value {
a.get(i).copied().unwrap_or(Value(std::ptr::null()))
}
fn is_missing(c: Ctx, a: &[Value], i: usize) -> bool {
a.get(i).is_none_or(|v| args::is_nullish(c, *v))
}
fn num(c: Ctx, a: &[Value], i: usize) -> f64 {
a.get(i).map(|v| args::num(c, *v)).unwrap_or(f64::NAN)
}
/// Non-negative integer argument (ids, offsets, sizes); NaN/negative → 0.
fn u(c: Ctx, a: &[Value], i: usize) -> u32 {
let d = num(c, a, i);
if d.is_finite() && d > 0.0 { d.min(u32::MAX as f64) as u32 } else { 0 }
}
fn u64a(c: Ctx, a: &[Value], i: usize) -> u64 {
let d = num(c, a, i);
if d.is_finite() && d > 0.0 { d as u64 } else { 0 }
}
/// Optional size: negative / missing → None.
fn opt_u64(c: Ctx, a: &[Value], i: usize) -> Option<u64> {
let d = num(c, a, i);
if d.is_finite() && d >= 0.0 { Some(d as u64) } else { None }
}
fn string(c: Ctx, a: &[Value], i: usize) -> String {
a.get(i).map(|v| v.to_string(c)).unwrap_or_default()
}
fn json(c: Ctx, a: &[Value], i: usize) -> Result<J, String> {
if is_missing(c, a, i) {
return Ok(J::Null);
}
serde_json::from_str(&string(c, a, i)).map_err(|e| format!("bad descriptor JSON: {e}"))
}
fn id_val(c: Ctx, id: u32) -> Value {
args::num_val(c, id as f64)
}
fn gpu() -> Result<&'static Gpu, String> {
gpu::get().ok_or_else(|| "no GPU device".to_string())
}
fn with<R>(f: impl FnOnce(&mut State) -> R) -> R {
STATE.with(|s| {
let mut st = s.borrow_mut();
st.stats.calls += 1;
f(&mut st)
})
}
/// An object for the page whose wgpu creation failed before reaching wgpu (bad id): report a
/// validation error; the page gets id 0, which fails validation wherever it is used.
fn invalid(c: Ctx, msg: String) -> NativeResult {
gpu::validation(msg);
Ok(id_val(c, 0))
}
pub fn install(c: Ctx, native: Value) {
let o = c.object();
native.set(c, "gpu", o);
let fns: &[(&str, F)] = &[
("info", info),
("preferredFormat", preferred_format),
("createBuffer", create_buffer),
("bufferDestroy", buffer_destroy),
("mapAsync", map_async),
("getMappedRange", get_mapped_range),
("unmap", unmap),
("poll", poll),
("workDone", work_done),
("createTexture", create_texture),
("textureDestroy", texture_destroy),
("createView", create_view),
("createSampler", create_sampler),
("createShaderModule", create_shader_module),
("shaderInfo", shader_info),
("createBindGroupLayout", create_bind_group_layout),
("createPipelineLayout", create_pipeline_layout),
("createBindGroup", create_bind_group),
("createRenderPipeline", create_render_pipeline),
("createRenderPipelineAsync", create_render_pipeline_async),
("createComputePipeline", create_compute_pipeline),
("createComputePipelineAsync", create_compute_pipeline_async),
("getBindGroupLayout", get_bind_group_layout),
("createQuerySet", create_query_set),
("querySetDestroy", query_set_destroy),
("finish", finish),
("submit", submit),
("writeBuffer", write_buffer),
("writeTexture", write_texture),
("copyExternal", copy_external),
("pushErrorScope", push_error_scope),
("popErrorScope", pop_error_scope),
("takeErrors", take_errors),
("reportError", report_error),
("release", release),
("canvasCreate", canvas_create),
("windowCanvas", window_canvas),
("windowInfo", window_info),
("canvasResize", canvas_resize),
("canvasConfigure", canvas_configure),
("canvasUnconfigure", canvas_unconfigure),
("canvasTexture", canvas_texture),
("canvasRead", canvas_read),
("canvasRelease", canvas_release),
("stats", stats),
];
for (name, f) in fns {
let f = *f;
o.set(c, name, c.function(move |c, _this, a| f(c, a)));
}
}
// ------------------------------------------------------------------------------------- adapter
fn info(c: Ctx, _a: &[Value]) -> NativeResult {
let Some(g) = gpu::get() else { return Ok(c.null()) };
let l = g.device.limits();
let ai = g.adapter.get_info();
let limits = serde_json::json!({
"maxTextureDimension1D": l.max_texture_dimension_1d,
"maxTextureDimension2D": l.max_texture_dimension_2d,
"maxTextureDimension3D": l.max_texture_dimension_3d,
"maxTextureArrayLayers": l.max_texture_array_layers,
"maxBindGroups": l.max_bind_groups,
"maxBindGroupsPlusVertexBuffers": l.max_bind_groups + l.max_vertex_buffers,
"maxBindingsPerBindGroup": l.max_bindings_per_bind_group,
"maxDynamicUniformBuffersPerPipelineLayout": l.max_dynamic_uniform_buffers_per_pipeline_layout,
"maxDynamicStorageBuffersPerPipelineLayout": l.max_dynamic_storage_buffers_per_pipeline_layout,
"maxSampledTexturesPerShaderStage": l.max_sampled_textures_per_shader_stage,
"maxSamplersPerShaderStage": l.max_samplers_per_shader_stage,
"maxStorageBuffersPerShaderStage": l.max_storage_buffers_per_shader_stage,
"maxStorageTexturesPerShaderStage": l.max_storage_textures_per_shader_stage,
"maxUniformBuffersPerShaderStage": l.max_uniform_buffers_per_shader_stage,
"maxUniformBufferBindingSize": l.max_uniform_buffer_binding_size,
"maxStorageBufferBindingSize": l.max_storage_buffer_binding_size,
"minUniformBufferOffsetAlignment": l.min_uniform_buffer_offset_alignment,
"minStorageBufferOffsetAlignment": l.min_storage_buffer_offset_alignment,
"maxVertexBuffers": l.max_vertex_buffers,
"maxBufferSize": l.max_buffer_size,
"maxVertexAttributes": l.max_vertex_attributes,
"maxVertexBufferArrayStride": l.max_vertex_buffer_array_stride,
"maxInterStageShaderVariables": l.max_inter_stage_shader_components / 4,
"maxColorAttachments": l.max_color_attachments,
"maxColorAttachmentBytesPerSample": l.max_color_attachment_bytes_per_sample,
"maxComputeWorkgroupStorageSize": l.max_compute_workgroup_storage_size,
"maxComputeInvocationsPerWorkgroup": l.max_compute_invocations_per_workgroup,
"maxComputeWorkgroupSizeX": l.max_compute_workgroup_size_x,
"maxComputeWorkgroupSizeY": l.max_compute_workgroup_size_y,
"maxComputeWorkgroupSizeZ": l.max_compute_workgroup_size_z,
"maxComputeWorkgroupsPerDimension": l.max_compute_workgroups_per_dimension,
});
let out = serde_json::json!({
"features": g.js_features,
"limits": limits,
"info": { "vendor": "apple", "architecture": "metal", "device": ai.name, "description": ai.name },
});
Ok(c.str(&out.to_string()))
}
/// The host target's format when it is a valid canvas format, else bgra8unorm.
fn preferred_format(c: Ctx, _a: &[Value]) -> NativeResult {
let f = WINDOW.with(|w| w.borrow().target.as_ref().map(|t| t.texture.format()));
let name = match f {
Some(wgpu::TextureFormat::Rgba8Unorm) => "rgba8unorm",
Some(wgpu::TextureFormat::Rgba16Float) => "rgba16float",
_ => "bgra8unorm",
};
Ok(c.str(name))
}
// ------------------------------------------------------------------------------------- buffers
/// createBuffer(size, usage, mappedAtCreation, label) → id. Throws RangeError text for an
/// unaligned mappedAtCreation size (the JS layer rethrows it as RangeError).
fn create_buffer(c: Ctx, a: &[Value]) -> NativeResult {
let g = gpu()?;
let size = u64a(c, a, 0);
let usage = wgpu::BufferUsages::from_bits_retain(u(c, a, 1));
let mapped = args::truthy(c, arg(a, 2));
if mapped && size % 4 != 0 {
return Err("RangeError: mappedAtCreation buffers need a size that is a multiple of 4".into());
}
let label = if is_missing(c, a, 3) { None } else { Some(string(c, a, 3)) };
// A creation error must not leave wgpu believing an invalid buffer is mapped (reading its
// mapped range would panic): capture, then re-report to the page.
let (buf, err) = gpu::capture(|| g.device.create_buffer(&wgpu::BufferDescriptor { label: label.as_deref(), size, usage, mapped_at_creation: mapped }));
let ok = err.is_none();
if let Some(e) = err {
gpu::validation(e);
}
let map = if mapped && ok { MapState::Mapped } else { MapState::Unmapped };
let id = with(|st| st.slab.insert(Res::Buffer(BufferRes { buf, size, usage, map, map_range: 0..size, map_write: mapped, map_token: 0.0, destroyed: !ok })));
Ok(id_val(c, id))
}
fn buffer_destroy(c: Ctx, a: &[Value]) -> NativeResult {
let g = gpu()?;
let id = u(c, a, 0);
with(|st| {
flush_writes_now(st, g);
if let Ok(b) = st.slab.buffer_mut(id) {
if b.map != MapState::Unmapped && !b.destroyed {
gpu::quietly(|| b.buf.unmap());
}
b.map = MapState::Unmapped;
b.destroyed = true;
b.buf.destroy();
}
});
Ok(args::undef(c))
}
/// mapAsync(id, mode, offset, size|-1) → token (> 0), or 0 after a validation error.
fn map_async(c: Ctx, a: &[Value]) -> NativeResult {
let g = gpu()?;
let (id, mode, off) = (u(c, a, 0), u(c, a, 1), u64a(c, a, 2));
let size = opt_u64(c, a, 3);
let tok = token();
let r = with(|st| -> Result<(), String> {
flush_writes_now(st, g);
let b = st.slab.buffer_mut(id)?;
if b.map != MapState::Unmapped {
return Err("mapAsync: the buffer is already mapped or has a pending map".into());
}
if b.destroyed {
return Err("mapAsync: the buffer is destroyed".into());
}
let end = match size {
Some(s) => off.checked_add(s).ok_or("mapAsync: range overflows")?,
None => b.size.max(off),
};
let (m, need) = match mode {
1 => (wgpu::MapMode::Read, wgpu::BufferUsages::MAP_READ),
2 => (wgpu::MapMode::Write, wgpu::BufferUsages::MAP_WRITE),
_ => return Err(format!("mapAsync: mode must be READ or WRITE, got {mode}")),
};
if !b.usage.contains(need) {
return Err("mapAsync: the buffer's usage does not allow this map mode".into());
}
if off % 8 != 0 || (end - off) % 4 != 0 || end > b.size {
return Err(format!("mapAsync: invalid range [{off}, {end}) for a buffer of size {}", b.size));
}
b.map = MapState::Pending;
b.map_range = off..end;
b.map_write = mode == 2;
b.map_token = tok;
if end == off {
push_event(tok, 0, id);
} else {
b.buf.slice(off..end).map_async(m, move |r| push_event(tok, if r.is_ok() { 0 } else { 1 }, id));
}
Ok(())
});
match r {
Ok(()) => Ok(args::num_val(c, tok)),
Err(e) => {
gpu::validation(e);
Ok(args::num_val(c, 0.0))
}
}
}
/// poll() → [token, status, token, status, …] (status 0 ok, 1 failed) or null. Settles the
/// map state of buffers whose mapAsync completed.
fn poll(c: Ctx, _a: &[Value]) -> NativeResult {
let g = gpu()?;
let _ = g.device.poll(wgpu::PollType::Poll);
let events: Vec<(f64, u32, u32)> = std::mem::take(&mut *crate::EVENTS.lock().unwrap_or_else(|e| e.into_inner()));
if events.is_empty() {
return Ok(args::null(c));
}
with(|st| {
for &(tok, status, id) in &events {
if id == 0 {
continue;
}
if let Ok(b) = st.slab.buffer_mut(id) {
if b.map == MapState::Pending && b.map_token == tok {
if status == 0 {
b.map = MapState::Mapped;
} else {
b.map = MapState::Unmapped;
gpu::quietly(|| b.buf.unmap());
}
}
}
}
});
let mut out = Vec::with_capacity(events.len() * 2);
for (t, s, _) in events {
out.push(args::num_val(c, t));
out.push(args::int_val(c, s as i32));
}
Ok(c.array(&out))
}
fn work_done(c: Ctx, _a: &[Value]) -> NativeResult {
let g = gpu()?;
let tok = token();
with(|st| flush_writes_now(st, g));
g.queue.on_submitted_work_done(move || push_event(tok, 0, 0));
Ok(args::num_val(c, tok))
}
/// getMappedRange(id, offset, size|-1) → Uint8Array with a copy of the mapped bytes.
fn get_mapped_range(c: Ctx, a: &[Value]) -> NativeResult {
let (id, off) = (u(c, a, 0), u64a(c, a, 1));
let size = opt_u64(c, a, 2);
let bytes = with(|st| -> Result<Vec<u8>, String> {
let b = st.slab.buffer(id)?;
if b.map != MapState::Mapped {
return Err("OperationError: the buffer is not mapped".into());
}
let end = match size {
Some(s) => off.checked_add(s).ok_or("OperationError: range overflows")?,
None => b.map_range.end.max(off),
};
if off % 8 != 0 || (end - off) % 4 != 0 || off < b.map_range.start || end > b.map_range.end {
return Err(format!("OperationError: getMappedRange [{off}, {end}) is outside the mapped range or unaligned"));
}
if end == off || b.destroyed {
return Ok(vec![0; (end - off) as usize]);
}
Ok(b.buf.slice(off..end).get_mapped_range().to_vec())
})?;
Ok(c.typed_array(TypedArrayType::Uint8, bytes.len(), &bytes))
}
/// unmap(id, [offset, Uint8Array, …] | null): writes back the page's views of a write mapping.
fn unmap(c: Ctx, a: &[Value]) -> NativeResult {
let id = u(c, a, 0);
// gather (offset, bytes) before touching the slab (reading arrays calls into JSC)
let mut writes: Vec<(u64, Vec<u8>)> = Vec::new();
if !is_missing(c, a, 1) {
let list = arg(a, 1);
let n = list.len(c);
for i in 0..n / 2 {
let off = list.at(c, i * 2).to_num(c).max(0.0) as u64;
let v = list.at(c, i * 2 + 1);
if let Some(b) = v.bytes(c) {
writes.push((off, b.to_vec()));
}
}
}
with(|st| {
let Ok(b) = st.slab.buffer_mut(id) else { return };
match b.map {
MapState::Unmapped => {}
MapState::Pending => {
b.map = MapState::Unmapped;
gpu::quietly(|| b.buf.unmap());
}
MapState::Mapped => {
if b.map_write && !b.destroyed {
for (off, data) in &writes {
let end = off + data.len() as u64;
if data.is_empty() || *off < b.map_range.start || end > b.map_range.end {
continue;
}
b.buf.slice(*off..end).get_mapped_range_mut().copy_from_slice(data);
}
}
b.map = MapState::Unmapped;
if !b.destroyed {
b.buf.unmap();
}
}
}
});
Ok(args::undef(c))
}
/// writeBuffer(id, bufferOffset, data, dataByteOffset, byteSize|-1)
fn write_buffer(c: Ctx, a: &[Value]) -> NativeResult {
let t0 = Instant::now();
let (id, dst) = (u(c, a, 0), u64a(c, a, 1));
let data = arg(a, 2);
let bytes: &[u8] = match args::view(c, data) {
Some(b) => b,
None => match data.bytes(c) {
Some(b) => b,
None => return Err("TypeError: writeBuffer data must be an ArrayBuffer or ArrayBufferView".into()),
},
};
let src_off = u64a(c, a, 3) as usize;
let size = opt_u64(c, a, 4).map(|s| s as usize).unwrap_or(bytes.len().saturating_sub(src_off));
if src_off > bytes.len() || size > bytes.len() - src_off {
return Err("OperationError: writeBuffer data range is out of bounds".into());
}
let src = &bytes[src_off..src_off + size];
with(|st| {
let err = match st.slab.buffer(id) {
Err(e) => Some(e),
Ok(b) if b.destroyed => Some("writeBuffer: the buffer is destroyed".into()),
Ok(b) if b.map != MapState::Unmapped => Some("writeBuffer: the buffer is mapped".into()),
Ok(b) if !b.usage.contains(wgpu::BufferUsages::COPY_DST) => Some("writeBuffer: the buffer lacks COPY_DST usage".into()),
Ok(b) if dst % 4 != 0 || size % 4 != 0 || dst + size as u64 > b.size => Some(format!("writeBuffer: invalid range [{dst}, {}) for a buffer of size {}", dst + size as u64, b.size)),
Ok(_) => None,
};
if let Some(e) = err {
gpu::validation(e);
return;
}
if size == 0 {
return;
}
let w = &mut st.writes;
let at = w.staging.len();
w.staging.extend_from_slice(src);
w.staging.resize((at + size + 3) & !3, 0);
w.ops.push((id, dst, at as u32, size as u32));
st.stats.writes += 1;
st.stats.write_bytes += size as u64;
st.stats.write_ns += t0.elapsed().as_nanos() as u64;
});
Ok(args::undef(c))
}
// ------------------------------------------------------------------------------------- textures
fn create_texture(c: Ctx, a: &[Value]) -> NativeResult {
let g = gpu()?;
let spec = desc::texture(&json(c, a, 0)?)?;
let tex = g.device.create_texture(&spec.desc());
let id = with(|st| {
st.slab.insert(Res::Texture(TextureRes { tex, format: spec.format, size: spec.size, mips: spec.mips, samples: spec.samples, dimension: spec.dimension, usage: spec.usage, canvas: false }))
});
Ok(id_val(c, id))
}
fn texture_destroy(c: Ctx, a: &[Value]) -> NativeResult {
let id = u(c, a, 0);
with(|st| {
if let Some(g) = gpu::get() {
flush_writes_now(st, g);
}
if let Ok(t) = st.slab.texture(id) {
// canvas textures belong to the canvas (the host's target must stay usable)
if !t.canvas {
t.tex.destroy();
}
}
});
Ok(args::undef(c))
}
fn create_view(c: Ctx, a: &[Value]) -> NativeResult {
let tex = u(c, a, 0);
let spec = desc::view(&json(c, a, 1)?)?;
let r = with(|st| -> Result<u32, String> {
let t = st.slab.texture(tex)?;
let view = t.tex.create_view(&spec.desc());
Ok(st.slab.insert(Res::View(ViewRes { view, texture: tex })))
});
match r {
Ok(id) => Ok(id_val(c, id)),
Err(e) => invalid(c, format!("createView: {e}")),
}
}
fn create_sampler(c: Ctx, a: &[Value]) -> NativeResult {
let g = gpu()?;
let d = desc::sampler(&json(c, a, 0)?)?;
let s = g.device.create_sampler(&d);
Ok(id_val(c, with(|st| st.slab.insert(Res::Sampler(s)))))
}
// ------------------------------------------------------------------------------------- shaders
fn create_shader_module(c: Ctx, a: &[Value]) -> NativeResult {
let g = gpu()?;
let code = string(c, a, 0);
let label = if is_missing(c, a, 1) { None } else { Some(string(c, a, 1)) };
g.device.push_error_scope(wgpu::ErrorFilter::Validation);
let mut module = g.device.create_shader_module(wgpu::ShaderModuleDescriptor { label: label.as_deref(), source: wgpu::ShaderSource::Wgsl(code.as_str().into()) });
if let Some(e) = pollster::block_on(g.device.pop_error_scope()) {
// naga 25 rejects abstract-typed expressions outside constant expressions, which Tint
// concretises (three.js folds e.g. `smoothstep(0.1, 0.9, 1.0)` into such a call): retry with
// every float literal made f32; any other error goes to the page as it would in a browser.
let msg = e.to_string();
if msg.contains("Abstract types may only appear in constant expressions") {
module = g.device.create_shader_module(wgpu::ShaderModuleDescriptor { label: label.as_deref(), source: wgpu::ShaderSource::Wgsl(concrete_float_literals(&code).into()) });
} else {
crate::gpu::sink_wgpu(e);
}
}
Ok(id_val(c, with(|st| st.slab.insert(Res::Shader(ShaderRes { module })))))
}
/// `code` with an `f` suffix on every abstract float literal (`0.5`, `1.`, `.25`, `2e3`), leaving
/// integers, suffixed literals and digits inside identifiers alone.
pub(crate) fn concrete_float_literals(code: &str) -> String {
let b = code.as_bytes();
let mut out = String::with_capacity(code.len() + code.len() / 16);
let ident = |c: u8| c.is_ascii_alphanumeric() || c == b'_';
let mut i = 0;
while i < b.len() {
let c = b[i];
let starts = c.is_ascii_digit() || (c == b'.' && i + 1 < b.len() && b[i + 1].is_ascii_digit());
if starts && (i == 0 || !(ident(b[i - 1]) || b[i - 1] == b'.')) {
let start = i;
let hex = c == b'0' && i + 1 < b.len() && (b[i + 1] == b'x' || b[i + 1] == b'X');
if hex {
i += 2;
while i < b.len() && (b[i].is_ascii_hexdigit() || b[i] == b'.' || b[i] == b'p' || b[i] == b'P') {
i += 1;
}
out.push_str(&code[start..i]);
continue;
}
let mut float = false;
while i < b.len() && b[i].is_ascii_digit() {
i += 1;
}
if i < b.len() && b[i] == b'.' {
float = true;
i += 1;
while i < b.len() && b[i].is_ascii_digit() {
i += 1;
}
}
if i < b.len() && (b[i] == b'e' || b[i] == b'E') {
let mut j = i + 1;
if j < b.len() && (b[j] == b'+' || b[j] == b'-') {
j += 1;
}
if j < b.len() && b[j].is_ascii_digit() {
float = true;
i = j;
while i < b.len() && b[i].is_ascii_digit() {
i += 1;
}
}
}
out.push_str(&code[start..i]);
if float && !(i < b.len() && ident(b[i])) {
out.push('f');
}
continue;
}
let ch = code[i..].chars().next().unwrap();
out.push(ch);
i += ch.len_utf8();
}
out
}
#[cfg(test)]
mod literal_tests {
use super::concrete_float_literals as f;
#[test]
fn floats_become_f32_and_the_rest_stays() {
assert_eq!(f("smoothstep( 0.1, 0.9, 1.0 )"), "smoothstep( 0.1f, 0.9f, 1.0f )");
assert_eq!(f("let a = 1. + .5 + 2e3 + 3E-2;"), "let a = 1.f + .5f + 2e3f + 3E-2f;");
assert_eq!(f("nodeVar3 = vec3<f32>( 0.5h, 1u, 2i, 7 ); x.y1 = tex2D;"), "nodeVar3 = vec3<f32>( 0.5h, 1u, 2i, 7 ); x.y1 = tex2D;");
assert_eq!(f("0x1p4 + 0xFF + 1.0f + 中文 1.5"), "0x1p4 + 0xFF + 1.0f + 中文 1.5f");
}
}
/// shaderInfo(id) → JSON [{message, type, lineNum, linePos, offset, length}]
fn shader_info(c: Ctx, a: &[Value]) -> NativeResult {
let id = u(c, a, 0);
let info = with(|st| st.slab.shader(id).map(|s| pollster::block_on(s.module.get_compilation_info())));
let mut out = Vec::new();
if let Ok(info) = info {
for m in info.messages {
let ty = match m.message_type {
wgpu::CompilationMessageType::Error => "error",
wgpu::CompilationMessageType::Warning => "warning",
wgpu::CompilationMessageType::Info => "info",
};
let (line, pos, off, len) = m.location.map(|l| (l.line_number, l.line_position, l.offset, l.length)).unwrap_or((0, 0, 0, 0));
out.push(serde_json::json!({"message": m.message, "type": ty, "lineNum": line, "linePos": pos, "offset": off, "length": len}));
}
}
Ok(c.str(&J::Array(out).to_string()))
}
// ------------------------------------------------------------------------------------- layouts, groups, pipelines
fn create_bind_group_layout(c: Ctx, a: &[Value]) -> NativeResult {
let g = gpu()?;
let j = json(c, a, 0)?;
let entries = desc::bind_group_layout(&j)?;
let label = j.get("label").and_then(|l| l.as_str()).map(str::to_owned);
let l = g.device.create_bind_group_layout(&wgpu::BindGroupLayoutDescriptor { label: label.as_deref(), entries: &entries });
Ok(id_val(c, with(|st| st.slab.insert(Res::BindGroupLayout(l)))))
}
fn create_pipeline_layout(c: Ctx, a: &[Value]) -> NativeResult {
let g = gpu()?;
let ids = desc::pipeline_layout(&json(c, a, 0)?)?;
let r = with(|st| -> Result<u32, String> {
let empty = if ids.iter().any(|i| i.is_none()) { Some(g.device.create_bind_group_layout(&wgpu::BindGroupLayoutDescriptor { label: None, entries: &[] })) } else { None };
let mut layouts = Vec::with_capacity(ids.len());
for id in &ids {
layouts.push(match id {
Some(id) => st.slab.bind_group_layout(*id)?,
None => empty.as_ref().unwrap(),
});
}
let l = g.device.create_pipeline_layout(&wgpu::PipelineLayoutDescriptor { label: None, bind_group_layouts: &layouts, push_constant_ranges: &[] });
Ok(st.slab.insert(Res::PipelineLayout(l)))
});
match r {
Ok(id) => Ok(id_val(c, id)),
Err(e) => invalid(c, format!("createPipelineLayout: {e}")),
}
}
fn create_bind_group(c: Ctx, a: &[Value]) -> NativeResult {
let g = gpu()?;
let spec = desc::bind_group(&json(c, a, 0)?)?;
let r = with(|st| -> Result<u32, String> {
let bg = spec.create(&g.device, &st.slab)?;
Ok(st.slab.insert(Res::BindGroup(bg)))
});
match r {
Ok(id) => Ok(id_val(c, id)),
Err(e) => invalid(c, format!("createBindGroup: {e}")),
}
}
fn render_pipeline(c: Ctx, a: &[Value]) -> Result<Result<u32, String>, String> {
let g = gpu()?;
let spec = desc::render_pipeline(&json(c, a, 0)?)?;
Ok(with(|st| -> Result<u32, String> {
let p = spec.create(&g.device, &st.slab)?;
Ok(st.slab.insert(Res::RenderPipeline(p)))
}))
}
fn compute_pipeline(c: Ctx, a: &[Value]) -> Result<Result<u32, String>, String> {
let g = gpu()?;
let spec = desc::compute_pipeline(&json(c, a, 0)?)?;
Ok(with(|st| -> Result<u32, String> {
let p = spec.create(&g.device, &st.slab)?;
Ok(st.slab.insert(Res::ComputePipeline(p)))
}))
}
fn create_render_pipeline(c: Ctx, a: &[Value]) -> NativeResult {
match render_pipeline(c, a)? {
Ok(id) => Ok(id_val(c, id)),
Err(e) => invalid(c, format!("createRenderPipeline: {e}")),
}
}
fn create_compute_pipeline(c: Ctx, a: &[Value]) -> NativeResult {
match compute_pipeline(c, a)? {
Ok(id) => Ok(id_val(c, id)),
Err(e) => invalid(c, format!("createComputePipeline: {e}")),
}
}
/// → [id, errorMessage | null]: async creation rejects instead of reporting to error scopes.
fn async_result(c: Ctx, r: (Result<Result<u32, String>, String>, Option<String>)) -> NativeResult {
let (r, err) = r;
let r = r?;
let (id, err) = match r {
Ok(id) => (id, err),
Err(e) => (0, Some(e)),
};
Ok(c.array(&[id_val(c, id), err.map(|e| c.str(&e)).unwrap_or_else(|| c.null())]))
}
fn create_render_pipeline_async(c: Ctx, a: &[Value]) -> NativeResult {
async_result(c, gpu::capture(|| render_pipeline(c, a)))
}
fn create_compute_pipeline_async(c: Ctx, a: &[Value]) -> NativeResult {
async_result(c, gpu::capture(|| compute_pipeline(c, a)))
}
fn get_bind_group_layout(c: Ctx, a: &[Value]) -> NativeResult {
let (id, index) = (u(c, a, 0), u(c, a, 1));
let r = with(|st| -> Result<u32, String> {
let l = match st.slab.get(id) {
Some(Res::RenderPipeline(p)) => p.get_bind_group_layout(index),
Some(Res::ComputePipeline(p)) => p.get_bind_group_layout(index),
_ => return Err(format!("invalid pipeline id {id}")),
};
Ok(st.slab.insert(Res::BindGroupLayout(l)))
});
match r {
Ok(id) => Ok(id_val(c, id)),
Err(e) => invalid(c, format!("getBindGroupLayout: {e}")),
}
}
fn create_query_set(c: Ctx, a: &[Value]) -> NativeResult {
let g = gpu()?;
let ty = match string(c, a, 0).as_str() {
"occlusion" => wgpu::QueryType::Occlusion,
"timestamp" => wgpu::QueryType::Timestamp,
t => return Err(format!("TypeError: '{t}' is not a valid GPUQueryType")),
};
let count = u(c, a, 1);
let set = g.device.create_query_set(&wgpu::QuerySetDescriptor { label: None, ty, count });
Ok(id_val(c, with(|st| st.slab.insert(Res::QuerySet(QuerySetRes { set, ty, count })))))
}
fn query_set_destroy(c: Ctx, a: &[Value]) -> NativeResult {
let id = u(c, a, 0);
// wgpu has no QuerySet::destroy; dropping our handle frees it once the GPU is done
with(|st| {
if st.slab.query_set(id).is_ok() {
st.slab.remove(id);
}
});
Ok(args::undef(c))
}
// ------------------------------------------------------------------------------------- encoding, submission
struct CanvasHooks<'a> {
canvases: &'a mut Vec<Option<Canvas>>,
}
impl cmd::Hooks for CanvasHooks<'_> {
fn canvas_use(&mut self, texture: u32, load: bool) -> bool {
for c in self.canvases.iter_mut().flatten() {
if c.current == texture && c.pending_clear {
c.pending_clear = false;
return load;
}
}
false
}
}
/// finish(words: Uint32Array, length) → command buffer id. The stream is kept and replayed at
/// submit, into the frame's encoder.
fn finish(c: Ctx, a: &[Value]) -> NativeResult {
let t0 = Instant::now();
let n = u(c, a, 1) as usize;
let Some(bytes) = args::view(c, arg(a, 0)) else { return Err("finish: expected a Uint32Array".into()) };
if n * 4 > bytes.len() || bytes.as_ptr() as usize % 4 != 0 {
return Err("finish: bad command stream length".into());
}
// SAFETY: the view is a Uint32Array (4-byte aligned, checked above) of at least n words, and
// nothing calls into JavaScriptCore while the slice is alive.
let words = unsafe { std::slice::from_raw_parts(bytes.as_ptr() as *const u32, n) }.to_vec();
let id = with(|st| {
st.stats.finish_ns += t0.elapsed().as_nanos() as u64;
st.slab.insert(Res::CommandBuffer(Some(words)))
});
Ok(id_val(c, id))
}
/// Ids from a Uint32Array (or a plain array) argument.
fn ids(c: Ctx, v: Value, n: usize) -> Vec<u32> {
if let Some(b) = args::view(c, v) {
if b.as_ptr() as usize % 4 == 0 && b.len() >= n * 4 {
// SAFETY: aligned and long enough; read before any further JSC call.
return unsafe { std::slice::from_raw_parts(b.as_ptr() as *const u32, n) }.to_vec();
}
}
if v.is_array(c) {
let len = (v.len(c) as usize).min(n);
return (0..len).map(|i| v.at(c, i as u32).to_u32(c)).collect();
}
Vec::new()
}
/// submit(ids, n): replay the command buffers into an encoder of their own, after the writes
/// queued before them; the frame's command buffers reach the queue together at the next flush.
fn submit(c: Ctx, a: &[Value]) -> NativeResult {
let g = gpu()?;
let t0 = Instant::now();
let list = ids(c, arg(a, 0), u(c, a, 1) as usize);
with(|st| {
let mut streams = Vec::with_capacity(list.len());
let mut bad = None;
for id in &list {
match st.slab.get_mut(*id) {
Some(Res::CommandBuffer(cb)) => match cb.take() {
Some(words) => streams.push(words),
None => bad = Some(format!("submit: command buffer {id} is invalid or was already submitted")),
},
_ => bad = Some(format!("submit: {id} is not a command buffer")),
}
st.slab.remove(*id);
}
if let Some(e) = bad {
// WebGPU: one invalid command buffer fails the whole submit
gpu::validation(e);
return;
}
// the writes queued before this submit land whether or not its command buffers are valid
let mut writes = st.frame.take();
if !st.writes.ops.is_empty() {
encode_writes(st, g, frame_encoder(&mut writes, g));
}
if let Some(enc) = writes {
st.finished.push(enc.finish());
}
// its command buffers in an encoder of their own: an invalid one is dropped (and its error
// reported), so it cannot fail the frame's other command buffers in the batched submit
let mut enc = g.device.create_command_encoder(&wgpu::CommandEncoderDescriptor { label: None });
g.device.push_error_scope(wgpu::ErrorFilter::Validation);
let State { slab, canvases, stats, finished, .. } = st;
let mut counts = cmd::Counts::default();
let mut hooks = CanvasHooks { canvases };
let mut decoded = Ok(());
for words in &streams {
if let Err(e) = cmd::encode_into(&mut enc, slab, words, &mut hooks, &mut counts) {
decoded = Err(e);
break;
}
}
let cb = enc.finish();
let invalid = pollster::block_on(g.device.pop_error_scope());
match (decoded, invalid) {
(Ok(()), None) => finished.push(cb),
(Err(e), _) => gpu::validation(format!("GPUQueue.submit: {e}")),
(Ok(()), Some(e)) => crate::gpu::sink_wgpu(e),
}
stats.passes += counts.passes as u64;
stats.draws += counts.draws as u64;
stats.submit_ns += t0.elapsed().as_nanos() as u64;
if crate::submit_mode() == crate::SubmitMode::Each {
flush_writes_now(st, g);
}
});
Ok(args::undef(c))
}
/// writeTexture(tex, mip, x, y, z, aspect, data, byteOffset, bytesPerRow|-1, rowsPerImage|-1, w, h, d)
fn write_texture(c: Ctx, a: &[Value]) -> NativeResult {
let g = gpu()?;
let tex = u(c, a, 0);
let mip = u(c, a, 1);
let origin = wgpu::Origin3d { x: u(c, a, 2), y: u(c, a, 3), z: u(c, a, 4) };
let aspect = fmt::aspect_code(u(c, a, 5));
let data = arg(a, 6);
let bytes: &[u8] = match args::view(c, data).map(|b| &*b).or_else(|| data.bytes(c).map(|b| &*b)) {
Some(b) => b,
None => return Err("TypeError: writeTexture data must be an ArrayBuffer or ArrayBufferView".into()),
};
let off = u64a(c, a, 7) as usize;
let bpr = opt_u64(c, a, 8).map(|v| v as u32);
let rpi = opt_u64(c, a, 9).map(|v| v as u32);
let size = wgpu::Extent3d { width: u(c, a, 10), height: u(c, a, 11), depth_or_array_layers: u(c, a, 12) };
if off > bytes.len() {
gpu::validation("writeTexture: data offset is past the end of the data");
return Ok(args::undef(c));
}
let src = &bytes[off..];
with(|st| flush_writes_now(st, g));
with(|st| match st.slab.texture(tex) {
Ok(t) => g.queue.write_texture(
wgpu::TexelCopyTextureInfo { texture: &t.tex, mip_level: mip, origin, aspect },
src,
wgpu::TexelCopyBufferLayout { offset: 0, bytes_per_row: bpr, rows_per_image: rpi },
size,
),
Err(e) => gpu::validation(format!("writeTexture: {e}")),
});
Ok(args::undef(c))
}
/// copyExternal(kind, source, srcWidth, srcHeight, srcX, srcY, flipY, tex, mip, x, y, z, premultiplied, w, h)
/// kind 1: canvas2d bitmap id (2D canvas, image, ImageBitmap); 2: unpremultiplied RGBA bytes
/// (ImageData); 3: a WebGPU canvas context id.
fn copy_external(c: Ctx, a: &[Value]) -> NativeResult {
let g = gpu()?;
// the upload goes straight to the queue: put deferred work ahead of it
with(|st| flush_writes_now(st, g));
let kind = u(c, a, 0);
let (sw, sh) = (u(c, a, 2), u(c, a, 3));
let (sx, sy) = (u(c, a, 4), u(c, a, 5));
let flip_y = args::truthy(c, arg(a, 6));
let tex = u(c, a, 7);
let mip = u(c, a, 8);
let origin = wgpu::Origin3d { x: u(c, a, 9), y: u(c, a, 10), z: u(c, a, 11) };
let dst_premultiplied = args::truthy(c, arg(a, 12));
let size = (u(c, a, 13), u(c, a, 14));
if size.0 == 0 || size.1 == 0 {
return Ok(args::undef(c));
}
let params = image::CopyParams { origin: (sx, sy), flip_y, size, dst_premultiplied };
let Some((format, dst)) = with(|st| st.slab.texture(tex).ok().map(|t| (t.format, t.tex.clone()))) else {
gpu::validation(format!("copyExternalImageToTexture: invalid destination texture {tex}"));
return Ok(args::undef(c));
};
let converted: Option<Result<Vec<u8>, String>> = match kind {
1 => canvas2d::with_bitmap(u(c, a, 1), |bm| {
image::convert(&image::Source { width: bm.width, height: bm.height, stride: bm.stride, data: bm.data, premultiplied: true }, ¶ms, format)
}),
2 => {
let Some(bytes) = args::view(c, arg(a, 1)) else { return Err("TypeError: bad ImageData".into()) };
if (sw as usize) * (sh as usize) * 4 > bytes.len() {
return Err("TypeError: ImageData is smaller than its size".into());
}
Some(image::convert(&image::Source { width: sw, height: sh, stride: sw as usize * 4, data: bytes, premultiplied: false }, ¶ms, format))
}
3 => {
let ctx = u(c, a, 1);
let src = with(|st| st.canvases.get(ctx as usize).and_then(|x| x.as_ref()).and_then(|cv| cv.content(&st.slab).map(|t| (t, cv.config.as_ref().is_some_and(|k| k.premultiplied)))));
match src {
Some((t, premul)) => match image::read_rgba(&g.device, &g.queue, &t, !premul, false) {
Ok((w, h, px)) => Some(image::convert(&image::Source { width: w, height: h, stride: w as usize * 4, data: &px, premultiplied: premul }, ¶ms, format)),
Err(e) => Some(Err(e)),
},
None => None,
}
}
_ => return Err(format!("TypeError: unknown image source kind {kind}")),
};
match converted {
None => {} // blank source (e.g. a canvas without content): nothing to copy
Some(Err(e)) => gpu::validation(e),
Some(Ok(bytes)) => image::upload(&g.queue, &dst, mip, origin, size, format, &bytes),
}
let _ = sw;
Ok(args::undef(c))
}
// ------------------------------------------------------------------------------------- errors
fn push_error_scope(c: Ctx, a: &[Value]) -> NativeResult {
let f = string(c, a, 0);
let kind = ErrKind::from_filter(&f).ok_or_else(|| format!("TypeError: '{f}' is not a valid GPUErrorFilter"))?;
gpu::push_scope(kind);
Ok(args::undef(c))
}
/// → null | [kind, message]; throws when the stack is empty.
fn pop_error_scope(c: Ctx, _a: &[Value]) -> NativeResult {
match gpu::pop_scope() {
Err(()) => Err("OperationError: the error scope stack is empty".into()),
Ok(None) => Ok(args::null(c)),
Ok(Some((k, m))) => Ok(c.array(&[args::int_val(c, k as i32), c.str(&m)])),
}
}
/// reportError(kind, message): errors the JS layer detects (encoder state misuse).
fn report_error(c: Ctx, a: &[Value]) -> NativeResult {
let kind = match u(c, a, 0) {
1 => ErrKind::OutOfMemory,
2 => ErrKind::Internal,
_ => ErrKind::Validation,
};
gpu::report(kind, string(c, a, 1));
Ok(args::undef(c))
}
fn take_errors(c: Ctx, _a: &[Value]) -> NativeResult {
if !gpu::has_uncaptured() {
return Ok(args::null(c));
}
let mut out = Vec::new();
for (k, m) in gpu::take_uncaptured() {
out.push(args::int_val(c, k as i32));
out.push(c.str(&m));
}
Ok(c.array(&out))
}
/// release(ids, n): the page dropped these objects.
fn release(c: Ctx, a: &[Value]) -> NativeResult {
let list = ids(c, arg(a, 0), u(c, a, 1) as usize);
with(|st| {
for id in list {
// canvas textures are owned by their canvas
if matches!(st.slab.get(id), Some(Res::Texture(t)) if t.canvas) {
continue;
}
st.slab.remove(id);
}
});
Ok(args::undef(c))
}
// ------------------------------------------------------------------------------------- canvases
fn new_canvas(st: &mut State, cv: Canvas) -> u32 {
if let Some(i) = st.canvases.iter().skip(1).position(|c| c.is_none()) {
st.canvases[i + 1] = Some(cv);
return (i + 1) as u32;
}
st.canvases.push(Some(cv));
(st.canvases.len() - 1) as u32
}
fn canvas_create(c: Ctx, a: &[Value]) -> NativeResult {
let (w, h) = (u(c, a, 0), u(c, a, 1));
Ok(id_val(c, with(|st| new_canvas(st, Canvas::new(false, w, h)))))
}
/// The page's window canvas context (created on first use, sized like the target).
fn window_canvas(c: Ctx, _a: &[Value]) -> NativeResult {
let size = WINDOW.with(|w| w.borrow().target.as_ref().map(|t| (t.texture.width(), t.texture.height())));
let id = with(|st| {
if st.window_canvas == 0 {
let (w, h) = size.unwrap_or((300, 150));
st.window_canvas = new_canvas(st, Canvas::new(true, w, h));
}
st.window_canvas
});
Ok(id_val(c, id))
}
/// → [targetWidth, targetHeight, logicalWidth, logicalHeight] (0s without a target)
fn window_info(c: Ctx, _a: &[Value]) -> NativeResult {
let (w, h, lw, lh) = WINDOW.with(|w| w.borrow().target.as_ref().map(|t| (t.texture.width(), t.texture.height(), t.logical.0, t.logical.1)).unwrap_or((0, 0, 0.0, 0.0)));
Ok(c.array(&[id_val(c, w), id_val(c, h), args::num_val(c, lw), args::num_val(c, lh)]))
}
fn canvas_resize(c: Ctx, a: &[Value]) -> NativeResult {
let (id, w, h) = (u(c, a, 0), u(c, a, 1), u(c, a, 2));
with(|st| {
let State { canvases, slab, .. } = st;
if let Some(Some(cv)) = canvases.get_mut(id as usize) {
if cv.width != w || cv.height != h {
cv.width = w;
cv.height = h;
// the current texture keeps its size until the next frame; a new one is made then
cv.release_current(slab);
}
}
});
Ok(args::undef(c))
}
/// canvasConfigure(id, format, usage, premultiplied, viewFormats[])
fn canvas_configure(c: Ctx, a: &[Value]) -> NativeResult {
let id = u(c, a, 0);
let f = string(c, a, 1);
let format = match f.as_str() {
"bgra8unorm" => wgpu::TextureFormat::Bgra8Unorm,
"rgba8unorm" => wgpu::TextureFormat::Rgba8Unorm,
"rgba16float" => wgpu::TextureFormat::Rgba16Float,
_ => return Err(format!("TypeError: '{f}' is not a supported canvas format")),
};
let usage = desc::texture_usage(u(c, a, 2));
let premultiplied = args::truthy(c, arg(a, 3));
let mut view_formats = Vec::new();
if let J::Array(v) = json(c, a, 4)? {
for s in v.iter().filter_map(|x| x.as_str()) {
view_formats.push(fmt::texture_format(s).ok_or_else(|| format!("TypeError: '{s}' is not a valid GPUTextureFormat"))?);
}
}
with(|st| {
let State { canvases, slab, .. } = st;
if let Some(Some(cv)) = canvases.get_mut(id as usize) {
let cfg = Config { format, usage, premultiplied, view_formats };
if cv.config.as_ref() != Some(&cfg) {
cv.drop_textures(slab);
cv.config = Some(cfg);
}
}
});
Ok(args::undef(c))
}
fn canvas_unconfigure(c: Ctx, a: &[Value]) -> NativeResult {
let id = u(c, a, 0);
with(|st| {
let State { canvases, slab, .. } = st;
if let Some(Some(cv)) = canvases.get_mut(id as usize) {
cv.drop_textures(slab);
cv.config = None;
}
});
Ok(args::undef(c))
}
/// getCurrentTexture → texture id (throws "InvalidStateError: …" when unconfigured).
fn canvas_texture(c: Ctx, a: &[Value]) -> NativeResult {
let g = gpu()?;
let id = u(c, a, 0);
let r = WINDOW.with(|w| {
let w = w.borrow();
with(|st| {
let State { canvases, slab, .. } = st;
match canvases.get_mut(id as usize) {
Some(Some(cv)) => cv.current_texture(&g.device, slab, w.target.as_ref()),
_ => Err("unknown canvas context".into()),
}
})
});
match r {
Ok(t) => Ok(id_val(c, t)),
Err(e) => Err(format!("InvalidStateError: {e}")),
}
}
/// canvasRead(id) → [width, height, Uint8Array RGBA (unpremultiplied, top-down)] or null
fn canvas_read(c: Ctx, a: &[Value]) -> NativeResult {
let g = gpu()?;
let id = u(c, a, 0);
let src = with(|st| {
flush_writes_now(st, g);
let cv = st.canvases.get(id as usize)?.as_ref()?;
let premul = cv.config.as_ref().is_some_and(|k| k.premultiplied);
cv.content(&st.slab).map(|t| (t, premul))
});
let Some((tex, premul)) = src else { return Ok(args::null(c)) };
match image::read_rgba(&g.device, &g.queue, &tex, !premul, premul) {
Ok((w, h, px)) => Ok(c.array(&[id_val(c, w), id_val(c, h), c.typed_array(TypedArrayType::Uint8, px.len(), &px)])),
Err(e) => {
eprintln!("[webgpu] canvas readback: {e}");
Ok(args::null(c))
}
}
}
fn canvas_release(c: Ctx, a: &[Value]) -> NativeResult {
let id = u(c, a, 0);
with(|st| {
if id as usize >= st.canvases.len() || id == st.window_canvas {
return;
}
if let Some(mut cv) = st.canvases[id as usize].take() {
cv.drop_textures(&mut st.slab);
}
});
Ok(args::undef(c))
}
fn stats(c: Ctx, _a: &[Value]) -> NativeResult {
let s = with(|st| {
let mut s = st.stats;
s.calls -= 1;
(s, st.slab.live)
});
let (s, live) = s;
let j = serde_json::json!({
"calls": s.calls, "finishMs": s.finish_ns as f64 / 1e6, "submitMs": s.submit_ns as f64 / 1e6, "writeMs": s.write_ns as f64 / 1e6,
"writes": s.writes, "writeBytes": s.write_bytes, "passes": s.passes, "draws": s.draws, "submits": s.submits, "liveObjects": live,
});
Ok(c.str(&j.to_string()))
}