The WebGPU API for MoonBit.
let backend = @memory.Backend::new()
let device = @moonwgpu.Instance::new(backend~).request_adapter().request_device()| Package | What it holds |
|---|---|
| moonbitstack/moonwgpu | The objects: instance, adapter, device, queue, buffers, textures, samplers, shader modules, layouts, pipelines, encoders, passes, bundles, query sets, canvas contexts |
| moonbitstack/moonwgpu/types | The vocabulary: descriptors, enumerations, flag sets, the texture and vertex format tables, limits and features, surface configurations |
| moonbitstack/moonwgpu/core | The rules: descriptor validation, usage tracking, command recording, error scopes |
| moonbitstack/moonwgpu/hal | The contract a host implements: create, write, read, submit, and the Surface a window system fills |
| moonbitstack/moonwgpu/hal/memory | A host that keeps everything in memory and executes every copy and clear for real |
| moonbitstack/moonwgpu/hal/vulkan, hal/metal, hal/dx12, hal/gles, web | One package per graphics API: the name of the backend, the seam it will sit on, and a refusal until its C stub or host bridge exists |
moon add moonbitstack/moonwgputest {
let backend = @memory.Backend::new()
let instance = @moonwgpu.Instance::new(backend~)
let adapter = instance.request_adapter()
let device = adapter.request_device()
assert_eq(instance.backend_name(), "memory")
assert_eq(device.limits().max_bind_groups, 4)
}test {
let backend = @memory.Backend::new()
let device = @moonwgpu.Instance::new(backend~).request_adapter().request_device()
let source = device.create_buffer(
descriptor=@types.BufferDescriptor::new(
size=16,
usage=@types.BufferUsages::copy_src() | @types.BufferUsages::copy_dst(),
),
)
let destination = device.create_buffer(
descriptor=@types.BufferDescriptor::new(
size=16,
usage=@types.BufferUsages::copy_dst() | @types.BufferUsages::map_read(),
),
)
device.queue().write_buffer(buffer=source, offset=0, data=b"\x01\x02\x03\x04")
let encoder = device.create_command_encoder()
encoder.copy_buffer_to_buffer(
source=source,
source_offset=0,
destination=destination,
destination_offset=4,
size=4,
)
device.queue().submit(command_buffers=[encoder.finish()])
destination.map_read()
let bytes = destination.get_mapped_range()
assert_eq(bytes[4], b'\x01')
assert_eq(bytes[7], b'\x04')
}test {
let backend = @memory.Backend::new()
let device = @moonwgpu.Instance::new(backend~).request_adapter().request_device()
let image = @types.ExternalImage::new(
size=@types.Extent3d::new(width=2, height=1),
format=@types.TextureFormat::Rgba8unorm,
data=b"\xff\x00\x00\xff\x00\xff\x00\xff",
)
let frame = device.import_external_texture(
descriptor=@types.ExternalTextureDescriptor::new(image~),
)
let target = device.create_texture(
descriptor=@types.TextureDescriptor::new(
size=@types.Extent3d::new(width=2, height=1),
format=@types.TextureFormat::Rgba8unorm,
usage=@types.TextureUsages::copy_dst(),
),
)
device.queue().copy_external_image_to_texture(
source=@types.CopyExternalImageSourceInfo::new(image~),
destination=@types.CopyExternalImageDestInfo::new(texture=target.id()),
copy_size=@types.Extent3d::new(width=2, height=1),
)
assert_false(frame.is_expired())
frame.expire()
assert_true(frame.is_expired())
}test {
let backend = @memory.Backend::new()
let device = @moonwgpu.Instance::new(backend~).request_adapter().request_device()
let words = b"\x03\x02\x23\x07\x00\x00\x01\x00"
let shader = device.create_shader_module(
descriptor=@types.ShaderModuleDescriptor::spirv(words~),
)
assert_eq(shader.get_compilation_info().messages.length(), 0)
}let canvas = @moonwgpu.CanvasContext::new(surface~=window)
canvas.configure(
device~,
configuration=@types.SurfaceConfiguration::new(
format=instance.get_preferred_canvas_format(),
),
)
let frame = canvas.get_current_texture()
// ... record a pass into `frame` ...
device.queue().submit(command_buffers=[encoder.finish()])
canvas.present(texture=frame)test {
let backend = @memory.Backend::new()
let device = @moonwgpu.Instance::new(backend~).request_adapter().request_device()
try {
device.create_buffer(
descriptor=@types.BufferDescriptor::new(
size=16,
usage=@types.BufferUsages::map_read() | @types.BufferUsages::vertex(),
),
) |> ignore
fail("MAP_READ may only be combined with COPY_DST")
} catch {
@core.Refused::Validation(kind~, at~, ..) => {
assert_eq(kind, @types.InvalidBufferUsage)
assert_eq(at, "descriptor.usage")
}
_ => fail("the refusal should be a validation error")
}
}| Object | What it is for |
|---|---|
| Instance | The entry point, over one backend |
| Adapter | What a host offers: limits, features, and a device |
| Device | Makes resources, encoders, pipelines and query sets; error scopes |
| Queue | Writes bytes, submits command buffers, waits for work |
| Buffer | Bytes the device reads and writes; mapping for read-back |
| Texture, TextureView | Texels, mip levels, array layers, and the views over them |
| Sampler | How a shader reads a texture |
| ShaderModule | WGSL source, kept for the pipelines that name its entry points |
| BindGroupLayout, BindGroup | What a shader sees, and the resources bound to it |
| PipelineLayout, RenderPipeline, ComputePipeline | The whole fixed-function state of a draw or a dispatch |
| CommandEncoder, CommandBuffer | Recording, then submitting |
| RenderPassEncoder, ComputePassEncoder | One pass: pipeline, bindings, draws, dispatches |
| RenderBundleEncoder, RenderBundle | A recorded run of draws any pass can execute |
| QuerySet | Timestamps and occlusion results |
| ExternalTexture | A decoded frame a host handed over, bindable until it expires |
| CanvasContext | A surface a host provides, configured with a device and a format |
| Document | What it is | What it decides here |
|---|---|---|
| WebGPU | the W3C text, on the Recommendation track | the normative one: every validation rule in core follows a step in it, and a rule that exists here and there is implemented as written there |
| WebGPU draft | the editor's copy, the text the TR is built from | the source the rules were read out of, and the place a change appears before it is published; where the two differ, the TR is what is implemented |
| WGSL | the shading language | not here: parsing and executing WGSL belong to moonnaga, and this library keeps only the seam a compiled module arrives through |
git submodule update --init --depth 1 spec # about 4 MB, working tree only| Capability | State |
|---|---|
| Creating every resource, with the specification's validation | done |
| Bind groups, pipeline layouts, render and compute pipelines | done |
| Command recording: passes, bundles, indirect draws and dispatches | done |
| Copies and clears, executed byte exactly on the memory backend | done |
| Mapping a buffer, whole or by range (mapAsync), for reading and for writing | done |
| Query sets, timestamps, occlusion queries | recorded and validated |
| Shader compilation info (getCompilationInfo) | reported by a backend that compiles; empty without one |
| Shader modules from WGSL or from SPIR-V a front end produced | accepted, with the magic number and word alignment checked |
| Immediate constants (setImmediates) | recorded and validated in passes and bundles |
| External frames (importExternalTexture, copyExternalImageToTexture) | copied texel by texel, with row flipping and alpha premultiplication |
| Limits, features and their dependencies | the specification's full tables |
| Texture and vertex format tables | every format the specification defines |
| Canvases (CanvasContext, configure, getCurrentTexture) | a frame is an ordinary texture over the host's Surface |
| The same suite on wasm, wasm-gc, js and native | 187 tests on each, recorded in conformance/targets.json |
| Driving the js backend from JavaScript | src/bindings/js plus a WebGPU-shaped facade in conformance/js |
| Executing a shader | needs a WGSL front end, which is its own library (moonnaga); a module that arrives as SPIR-V runs today |
| Vulkan | real: instance, device, buffers, textures, pipelines, descriptor sets, dynamic render passes, compute, read-back |
| Metal, D3D12 and GLES | packaged and named; each refuses with its reason until its stub exists |
moon run src/examples/05-device --target nativedevice: llvmpipe (LLVM 21.1.8, 256 bits)
clear: 4x4 read back as 51,102,153,255
triangle: 512 of 4096 pixels in the triangle's colour
compute: 1024 of 1024 words read back as 2n+1| Piece | How it is here |
|---|---|
| Instance, device, queue | one VkInstance and one VkDevice per backend, the first device the loader reports |
| Buffers | host-visible and coherent, mapped once at creation |
| Textures, views, samplers | VK_IMAGE_TILING_OPTIMAL, with the usage bits the descriptor asks for |
| Pipelines | built for dynamic rendering (VkPipelineRenderingCreateInfo), so a pass is a vkCmdBeginRendering and the pipeline needs no render pass object |
| Bind groups | one descriptor set per group, at the set index the bind names |
| Subresource layouts | tracked by the backend, one per mip level, and every use is a barrier from what it was to what it now is |
| Read-back | a staging buffer and a copy on the same queue, for read_texture, write_texture and the examples |
| Immediates | Vulkan push constants, in one 128-byte range on every pipeline layout |
| Shaders | SPIR-V, which is what ShaderModuleDescriptor::spirv takes; a WGSL module is created with an error a caller can read, and a pipeline built on it refuses |
python3 scripts/targets.py # run the suite on all four, write the file
python3 scripts/targets.py --check # fail if a backend lost a test| Backend | How the suite runs there | What can call into it |
|---|---|---|
| native | moon test --target native, in the caller's thread over the memory backend | MoonBit |
| wasm | moon test --target wasm, under a wasm runtime | MoonBit |
| wasm-gc | moon test --target wasm-gc, likewise | MoonBit |
| js | moon test --target js, and from JavaScript: src/bindings/js | JavaScript |
moon build --target js
node conformance/js/run.mjs # a dozen cases, in the shape the suite writes themfn AdapterInfo::new(vendor? : String, architecture? : String, device? : String, description? : String, is_fallback_adapter? : Bool, subgroup_min_size? : Int, subgroup_max_size? : Int) -> AdapterInfopub struct BindGroupLayout {
device : Device
id : BindGroupLayoutId
descriptor : BindGroupLayoutDescriptor
}pub struct Buffer {
device : Device
id : BufferId
size : Int
usage : BufferUsages
mapped : Bytes?
mapped_offset : Int
mapped_size : Int
mapped_for_write : Bool
destroyed : Bool
}pub struct CanvasContext {
surface : &Surface
device : Device?
configuration : SurfaceConfiguration?
}fn CanvasContext::configure(self : CanvasContext, device~ : Device, configuration~ : SurfaceConfiguration) -> Unit raise Refusedfn CommandEncoder::begin_compute_pass(self : CommandEncoder, descriptor? : ComputePassDescriptor) -> ComputePassEncoder raise Refusedfn CommandEncoder::begin_render_pass(self : CommandEncoder, descriptor~ : RenderPassDescriptor) -> RenderPassEncoder raise Refusedfn CommandEncoder::clear_buffer(self : CommandEncoder, buffer~ : Buffer, offset? : Int, size? : Int) -> Unit raise Refusedfn CommandEncoder::clear_texture(self : CommandEncoder, texture~ : Texture, mip_level? : Int, origin? : Origin3d, size? : Extent3d, aspect? : TextureAspect) -> Unit raise Refusedfn CommandEncoder::copy_buffer_to_buffer(self : CommandEncoder, source~ : Buffer, source_offset~ : Int, destination~ : Buffer, destination_offset~ : Int, size~ : Int) -> Unit raise Refusedfn CommandEncoder::copy_buffer_to_texture(self : CommandEncoder, source~ : TexelCopyBufferInfo, destination~ : TexelCopyTextureInfo, copy_size~ : Extent3d) -> Unit raise Refusedfn CommandEncoder::copy_texture_to_buffer(self : CommandEncoder, source~ : TexelCopyTextureInfo, destination~ : TexelCopyBufferInfo, copy_size~ : Extent3d) -> Unit raise Refusedfn CommandEncoder::copy_texture_to_texture(self : CommandEncoder, source~ : TexelCopyTextureInfo, destination~ : TexelCopyTextureInfo, copy_size~ : Extent3d) -> Unit raise Refusedfn CommandEncoder::insert_debug_marker(self : CommandEncoder, marker~ : String) -> Unit raise Refusedfn CommandEncoder::push_debug_group(self : CommandEncoder, group_label~ : String) -> Unit raise Refusedfn CommandEncoder::resolve_query_set(self : CommandEncoder, query_set~ : QuerySet, first_query~ : Int, query_count~ : Int, destination~ : Buffer, destination_offset? : Int) -> Unit raise Refusedpub struct ComputePassEncoder {
frame : Frame
descriptor : ComputePassDescriptor
commands : Array[ComputeCommand]
ended : Bool
label : String
}fn ComputePassEncoder::dispatch_workgroups(self : ComputePassEncoder, arguments~ : DispatchArguments) -> Unit raise Refusedfn ComputePassEncoder::dispatch_workgroups_indirect(self : ComputePassEncoder, buffer~ : Buffer, offset? : Int) -> Unit raise Refusedfn ComputePassEncoder::insert_debug_marker(self : ComputePassEncoder, marker~ : String) -> Unit raise Refusedfn ComputePassEncoder::push_debug_group(self : ComputePassEncoder, group_label~ : String) -> Unit raise Refusedfn ComputePassEncoder::set_bind_group(self : ComputePassEncoder, index~ : Int, bind_group~ : BindGroup, dynamic_offsets? : Array[Int]) -> Unit raise Refusedfn ComputePassEncoder::set_immediates(self : ComputePassEncoder, range_offset~ : Int, data~ : Bytes, data_offset? : Int, data_size? : Int) -> Unit raise Refusedfn ComputePassEncoder::set_pipeline(self : ComputePassEncoder, pipeline~ : ComputePipeline) -> Unit raise Refusedfn ComputePassEncoder::write_timestamp(self : ComputePassEncoder, query_set~ : QuerySet, query_index~ : Int) -> Unit raise Refusedfn ComputePipeline::get_bind_group_layout(self : ComputePipeline, index~ : Int) -> BindGroupLayout raise Refusedfn Device::create_bind_group(self : Device, descriptor~ : BindGroupDescriptor) -> BindGroup raise Refusedfn Device::create_bind_group_layout(self : Device, descriptor~ : BindGroupLayoutDescriptor) -> BindGroupLayout raise Refusedfn Device::create_compute_pipeline(self : Device, descriptor~ : ComputePipelineDescriptor) -> ComputePipeline raise Refusedfn Device::create_compute_pipeline_async(self : Device, descriptor~ : ComputePipelineDescriptor) -> ComputePipeline raise Refusedfn Device::create_pipeline_layout(self : Device, descriptor~ : PipelineLayoutDescriptor) -> PipelineLayout raise Refusedfn Device::create_query_set(self : Device, descriptor~ : QuerySetDescriptor) -> QuerySet raise Refusedfn Device::create_render_bundle_encoder(self : Device, descriptor~ : RenderBundleEncoderDescriptor) -> RenderBundleEncoder raise Refusedfn Device::create_render_pipeline(self : Device, descriptor~ : RenderPipelineDescriptor) -> RenderPipeline raise Refusedfn Device::create_render_pipeline_async(self : Device, descriptor~ : RenderPipelineDescriptor) -> RenderPipeline raise Refusedfn Device::create_shader_module(self : Device, descriptor~ : ShaderModuleDescriptor) -> ShaderModule raise Refusedfn Device::import_external_texture(self : Device, descriptor~ : ExternalTextureDescriptor) -> ExternalTexture raise Refusedfn DeviceDescriptor::new(label? : String, required_features? : Features, required_limits? : Limits, default_queue_label? : String) -> DeviceDescriptorpub struct ExternalTexture {
device : Device
id : ExternalTextureId
label : String
descriptor : ExternalTextureDescriptor
expired : Bool
}pub struct PipelineLayout {
device : Device
id : PipelineLayoutId
descriptor : PipelineLayoutDescriptor
}fn Queue::copy_external_image_to_texture(self : Queue, source~ : CopyExternalImageSourceInfo, destination~ : CopyExternalImageDestInfo, copy_size~ : Extent3d) -> Unit raise Refusedfn Queue::write_texture(self : Queue, destination~ : TexelCopyTextureInfo, data~ : Bytes, layout? : TexelCopyBufferLayout) -> Unit raise Refusedpub struct RenderBundleEncoder {
device : Device
descriptor : RenderBundleEncoderDescriptor
commands : Array[RenderCommand]
ended : Bool
}fn RenderBundleEncoder::draw(self : RenderBundleEncoder, arguments~ : DrawArguments) -> Unit raise Refusedfn RenderBundleEncoder::draw_indexed(self : RenderBundleEncoder, arguments~ : DrawIndexedArguments) -> Unit raise Refusedfn RenderBundleEncoder::draw_indexed_indirect(self : RenderBundleEncoder, buffer~ : Buffer, offset? : Int) -> Unit raise Refusedfn RenderBundleEncoder::draw_indirect(self : RenderBundleEncoder, buffer~ : Buffer, offset? : Int) -> Unit raise Refusedfn RenderBundleEncoder::insert_debug_marker(self : RenderBundleEncoder, marker~ : String) -> Unit raise Refusedfn RenderBundleEncoder::push_debug_group(self : RenderBundleEncoder, group_label~ : String) -> Unit raise Refusedfn RenderBundleEncoder::set_bind_group(self : RenderBundleEncoder, index~ : Int, bind_group~ : BindGroup, dynamic_offsets? : Array[Int]) -> Unit raise Refusedfn RenderBundleEncoder::set_immediates(self : RenderBundleEncoder, range_offset~ : Int, data~ : Bytes, data_offset? : Int, data_size? : Int) -> Unit raise Refusedfn RenderBundleEncoder::set_index_buffer(self : RenderBundleEncoder, buffer~ : Buffer, format~ : IndexFormat, offset? : Int, size? : Int) -> Unit raise Refusedfn RenderBundleEncoder::set_pipeline(self : RenderBundleEncoder, pipeline~ : RenderPipeline) -> Unit raise Refusedfn RenderBundleEncoder::set_vertex_buffer(self : RenderBundleEncoder, slot~ : Int, buffer~ : Buffer, offset? : Int, size? : Int) -> Unit raise Refusedpub(all) struct RenderBundleEncoderDescriptor {
label : String
color_formats : Array[TextureFormat]
depth_stencil_format : TextureFormat?
sample_count : Int
depth_read_only : Bool
stencil_read_only : Bool
} derive(Debug)fn RenderBundleEncoderDescriptor::new(color_formats~ : Array[TextureFormat], label? : String, depth_stencil_format? : TextureFormat, sample_count? : Int, depth_read_only? : Bool, stencil_read_only? : Bool) -> RenderBundleEncoderDescriptorpub struct RenderPassEncoder {
frame : Frame
descriptor : RenderPassDescriptor
commands : Array[RenderCommand]
ended : Bool
label : String
}fn RenderPassEncoder::begin_occlusion_query(self : RenderPassEncoder, query_index~ : Int) -> Unit raise Refusedfn RenderPassEncoder::draw(self : RenderPassEncoder, arguments~ : DrawArguments) -> Unit raise Refusedfn RenderPassEncoder::draw_indexed(self : RenderPassEncoder, arguments~ : DrawIndexedArguments) -> Unit raise Refusedfn RenderPassEncoder::draw_indexed_indirect(self : RenderPassEncoder, buffer~ : Buffer, offset? : Int) -> Unit raise Refusedfn RenderPassEncoder::draw_indirect(self : RenderPassEncoder, buffer~ : Buffer, offset? : Int) -> Unit raise Refusedfn RenderPassEncoder::execute_bundles(self : RenderPassEncoder, bundles~ : Array[RenderBundle]) -> Unit raise Refusedfn RenderPassEncoder::insert_debug_marker(self : RenderPassEncoder, marker~ : String) -> Unit raise Refusedfn RenderPassEncoder::push_debug_group(self : RenderPassEncoder, group_label~ : String) -> Unit raise Refusedfn RenderPassEncoder::set_bind_group(self : RenderPassEncoder, index~ : Int, bind_group~ : BindGroup, dynamic_offsets? : Array[Int]) -> Unit raise Refusedfn RenderPassEncoder::set_blend_constant(self : RenderPassEncoder, color~ : Color) -> Unit raise Refusedfn RenderPassEncoder::set_immediates(self : RenderPassEncoder, range_offset~ : Int, data~ : Bytes, data_offset? : Int, data_size? : Int) -> Unit raise Refusedfn RenderPassEncoder::set_index_buffer(self : RenderPassEncoder, buffer~ : Buffer, format~ : IndexFormat, offset? : Int, size? : Int) -> Unit raise Refusedfn RenderPassEncoder::set_pipeline(self : RenderPassEncoder, pipeline~ : RenderPipeline) -> Unit raise Refusedfn RenderPassEncoder::set_scissor_rect(self : RenderPassEncoder, x~ : Int, y~ : Int, width~ : Int, height~ : Int) -> Unit raise Refusedfn RenderPassEncoder::set_stencil_reference(self : RenderPassEncoder, reference~ : Int) -> Unit raise Refusedfn RenderPassEncoder::set_vertex_buffer(self : RenderPassEncoder, slot~ : Int, buffer~ : Buffer, offset? : Int, size? : Int) -> Unit raise Refusedfn RenderPassEncoder::set_viewport(self : RenderPassEncoder, x~ : Double, y~ : Double, width~ : Double, height~ : Double, min_depth? : Double, max_depth? : Double) -> Unit raise Refusedfn RenderPassEncoder::write_timestamp(self : RenderPassEncoder, query_set~ : QuerySet, query_index~ : Int) -> Unit raise Refusedfn RenderPipeline::get_bind_group_layout(self : RenderPipeline, index~ : Int) -> BindGroupLayout raise Refusedpub(all) struct RequestAdapterOptions {
power_preference : PowerPreference
force_fallback_adapter : Bool
} derive(Eq, Debug)fn RequestAdapterOptions::new(power_preference? : PowerPreference, force_fallback_adapter? : Bool) -> RequestAdapterOptionspub struct Texture {
device : Device
id : TextureId
descriptor : TextureDescriptor
destroyed : Bool
}fn Texture::create_view(self : Texture, descriptor? : TextureViewDescriptor) -> TextureView raise Refusedpub struct TextureView {
device : Device
id : TextureViewId
texture : TextureId
format : TextureFormat
dimension : TextureViewDimension
}Install
Download zipThe WebGPU API for MoonBit.