Skip to main content

sg_abi/
gpu.rs

1//! Wire format of the 0x1 GPU API ("sg-gpu v1").
2//!
3//! The guest (a sandboxed wasm module) never holds a GPU object. It holds `Id`s
4//! that index a per-game table in the host. Requests are postcard-encoded
5//! [`Req`] values passed to the `sg.gpu_call` import; the host validates every
6//! field and replies with a postcard-encoded [`Reply`]. Command encoders are
7//! recorded entirely on the guest side and sent as one [`Req::CreateCommandBuffer`]
8//! when finished, so a frame costs a handful of host calls, not thousands.
9//!
10//! Bulk data (buffer/texture uploads, mapped-range reads/writes) bypasses the
11//! serializer through dedicated imports; see `sg-guest::sys`.
12//!
13//! The descriptor structs embed `wgpu-types` 30 types. Their postcard encoding
14//! is part of this wire format, so the protocol version must be bumped if the
15//! pinned wgpu-types version changes in a layout-affecting way.
16
17use crate::wgt;
18use serde::{Deserialize, Serialize};
19use std::num::NonZeroU32;
20use wgt::{Color, Extent3d, TextureFormat};
21
22/// Bumped on any incompatible change to the types below. v2 added
23/// [`Req::FrameControls`]; hosts still accept v1 guests (which never send it).
24pub const VERSION: u32 = 2;
25/// The oldest guest protocol a host accepts.
26pub const MIN_VERSION: u32 = 1;
27
28/// A host object handle. `0` is never a valid handle and encodes "none".
29pub type Id = u32;
30
31pub type Label = Option<String>;
32
33/// Error kinds, matching `wgpu::ErrorFilter` order.
34pub mod error_kind {
35    pub const OUT_OF_MEMORY: u8 = 0;
36    pub const VALIDATION: u8 = 1;
37    pub const INTERNAL: u8 = 2;
38}
39
40/// Surface acquisition status, matching `wgpu::SurfaceStatus` semantics.
41pub mod surface_status {
42    pub const GOOD: u8 = 0;
43    pub const SUBOPTIMAL: u8 = 1;
44    pub const TIMEOUT: u8 = 2;
45    pub const OUTDATED: u8 = 3;
46    pub const LOST: u8 = 4;
47    pub const OCCLUDED: u8 = 5;
48}
49
50#[derive(Serialize, Deserialize, Debug, Clone)]
51pub struct AdapterDesc {
52    pub info: wgt::AdapterInfo,
53    pub features: [u64; 2],
54    pub limits: wgt::Limits,
55    pub downlevel: wgt::DownlevelCapabilities,
56}
57
58#[derive(Serialize, Deserialize, Debug, Clone)]
59pub struct SurfaceCaps {
60    pub formats: Vec<TextureFormat>,
61    pub present_modes: Vec<wgt::PresentMode>,
62    pub alpha_modes: Vec<wgt::CompositeAlphaMode>,
63    pub usages: u32,
64    /// Every format with the color spaces it can be presented in (a superset of
65    /// `formats`; HDR-only formats appear only here). Appended last so guests
66    /// built before it still decode the reply.
67    pub format_capabilities: Vec<(TextureFormat, u32)>,
68}
69
70#[derive(Serialize, Deserialize, Debug, Clone)]
71pub struct ProgrammableStage {
72    pub module: Id,
73    pub entry_point: Option<String>,
74    pub constants: Vec<(String, f64)>,
75    pub zero_initialize_workgroup_memory: bool,
76}
77
78#[derive(Serialize, Deserialize, Debug, Clone)]
79pub struct VertexBufferLayout {
80    pub array_stride: u64,
81    pub step_mode: wgt::VertexStepMode,
82    pub attributes: Vec<wgt::VertexAttribute>,
83}
84
85#[derive(Serialize, Deserialize, Debug, Clone)]
86pub struct RenderPipelineDesc {
87    pub label: Label,
88    /// 0 = automatic layout
89    pub layout: Id,
90    pub vertex: ProgrammableStage,
91    pub buffers: Vec<Option<VertexBufferLayout>>,
92    pub primitive: wgt::PrimitiveState,
93    pub depth_stencil: Option<wgt::DepthStencilState>,
94    pub multisample: wgt::MultisampleState,
95    pub fragment: Option<(ProgrammableStage, Vec<Option<wgt::ColorTargetState>>)>,
96    pub multiview_mask: Option<NonZeroU32>,
97}
98
99#[derive(Serialize, Deserialize, Debug, Clone)]
100pub struct MeshPipelineDesc {
101    pub label: Label,
102    pub layout: Id,
103    pub task: Option<ProgrammableStage>,
104    pub mesh: ProgrammableStage,
105    pub primitive: wgt::PrimitiveState,
106    pub depth_stencil: Option<wgt::DepthStencilState>,
107    pub multisample: wgt::MultisampleState,
108    pub fragment: Option<(ProgrammableStage, Vec<Option<wgt::ColorTargetState>>)>,
109    pub multiview: Option<NonZeroU32>,
110}
111
112#[derive(Serialize, Deserialize, Debug, Clone)]
113pub struct ComputePipelineDesc {
114    pub label: Label,
115    pub layout: Id,
116    pub stage: ProgrammableStage,
117}
118
119#[derive(Serialize, Deserialize, Debug, Clone)]
120pub struct BufferBinding {
121    pub buffer: Id,
122    pub offset: u64,
123    pub size: Option<u64>,
124}
125
126#[derive(Serialize, Deserialize, Debug, Clone)]
127pub enum Resource {
128    Buffer(BufferBinding),
129    BufferArray(Vec<BufferBinding>),
130    Sampler(Id),
131    SamplerArray(Vec<Id>),
132    TextureView(Id),
133    TextureViewArray(Vec<Id>),
134    Tlas(Id),
135    TlasArray(Vec<Id>),
136}
137
138#[derive(Serialize, Deserialize, Debug, Clone)]
139pub struct BindGroupEntry {
140    pub binding: u32,
141    pub resource: Resource,
142}
143
144#[derive(Serialize, Deserialize, Debug, Clone)]
145pub struct TexelCopyBufferInfo {
146    pub buffer: Id,
147    pub layout: wgt::TexelCopyBufferLayout,
148}
149
150pub type TexelCopyTextureInfo = wgt::TexelCopyTextureInfo<Id>;
151
152#[derive(Serialize, Deserialize, Debug, Clone)]
153pub struct ColorAttachment {
154    pub view: Id,
155    pub depth_slice: Option<u32>,
156    pub resolve_target: Id,
157    pub ops: wgt::Operations<Color>,
158}
159
160#[derive(Serialize, Deserialize, Debug, Clone)]
161pub struct DepthStencilAttachment {
162    pub view: Id,
163    pub depth_ops: Option<wgt::Operations<f32>>,
164    pub stencil_ops: Option<wgt::Operations<u32>>,
165}
166
167#[derive(Serialize, Deserialize, Debug, Clone)]
168pub struct TimestampWrites {
169    pub query_set: Id,
170    pub beginning: Option<u32>,
171    pub end: Option<u32>,
172}
173
174#[derive(Serialize, Deserialize, Debug, Clone)]
175pub struct RenderPassDesc {
176    pub label: Label,
177    pub color_attachments: Vec<Option<ColorAttachment>>,
178    pub depth_stencil: Option<DepthStencilAttachment>,
179    pub timestamp_writes: Option<TimestampWrites>,
180    pub occlusion_query_set: Id,
181    pub multiview_mask: Option<NonZeroU32>,
182}
183
184/// Commands shared by render passes and render bundles.
185#[derive(Serialize, Deserialize, Debug, Clone)]
186pub enum RenderCmd {
187    SetPipeline(Id),
188    SetBindGroup { index: u32, group: Id, offsets: Vec<u32> },
189    SetIndexBuffer { buffer: Id, format: wgt::IndexFormat, offset: u64, size: Option<u64> },
190    SetVertexBuffer { slot: u32, buffer: Id, offset: u64, size: Option<u64> },
191    SetImmediates { offset: u32, data: Vec<u8> },
192    SetBlendConstant(Color),
193    SetScissorRect([u32; 4]),
194    SetViewport([f32; 6]),
195    SetStencilReference(u32),
196    Draw { vertices: (u32, u32), instances: (u32, u32) },
197    DrawIndexed { indices: (u32, u32), base_vertex: i32, instances: (u32, u32) },
198    DrawIndirect { buffer: Id, offset: u64 },
199    DrawIndexedIndirect { buffer: Id, offset: u64 },
200    MultiDrawIndirect { buffer: Id, offset: u64, count: u32 },
201    MultiDrawIndexedIndirect { buffer: Id, offset: u64, count: u32 },
202    MultiDrawIndirectCount { buffer: Id, offset: u64, count_buffer: Id, count_offset: u64, max_count: u32 },
203    MultiDrawIndexedIndirectCount { buffer: Id, offset: u64, count_buffer: Id, count_offset: u64, max_count: u32 },
204    DrawMeshTasks([u32; 3]),
205    DrawMeshTasksIndirect { buffer: Id, offset: u64 },
206    MultiDrawMeshTasksIndirect { buffer: Id, offset: u64, count: u32 },
207    MultiDrawMeshTasksIndirectCount { buffer: Id, offset: u64, count_buffer: Id, count_offset: u64, max_count: u32 },
208    BeginOcclusionQuery(u32),
209    EndOcclusionQuery,
210    WriteTimestamp { query_set: Id, index: u32 },
211    BeginPipelineStatistics { query_set: Id, index: u32 },
212    EndPipelineStatistics,
213    ExecuteBundles(Vec<Id>),
214    PushDebugGroup(String),
215    PopDebugGroup,
216    InsertDebugMarker(String),
217}
218
219#[derive(Serialize, Deserialize, Debug, Clone)]
220pub enum ComputeCmd {
221    SetPipeline(Id),
222    SetBindGroup { index: u32, group: Id, offsets: Vec<u32> },
223    SetImmediates { offset: u32, data: Vec<u8> },
224    Dispatch([u32; 3]),
225    DispatchIndirect { buffer: Id, offset: u64 },
226    WriteTimestamp { query_set: Id, index: u32 },
227    BeginPipelineStatistics { query_set: Id, index: u32 },
228    EndPipelineStatistics,
229    PushDebugGroup(String),
230    PopDebugGroup,
231    InsertDebugMarker(String),
232}
233
234#[derive(Serialize, Deserialize, Debug, Clone)]
235pub struct BlasTriangles {
236    pub size: wgt::BlasTriangleGeometrySizeDescriptor,
237    pub vertex_buffer: Id,
238    pub first_vertex: u32,
239    pub vertex_stride: u64,
240    pub index_buffer: Id,
241    pub first_index: Option<u32>,
242    pub transform_buffer: Id,
243    pub transform_buffer_offset: Option<u64>,
244}
245
246#[derive(Serialize, Deserialize, Debug, Clone)]
247pub struct BlasBuild {
248    pub blas: Id,
249    pub triangles: Vec<BlasTriangles>,
250}
251
252#[derive(Serialize, Deserialize, Debug, Clone)]
253pub struct TlasInstance {
254    pub blas: Id,
255    pub transform: [f32; 12],
256    pub custom_data: u32,
257    pub mask: u8,
258}
259
260#[derive(Serialize, Deserialize, Debug, Clone)]
261pub struct TlasBuild {
262    pub tlas: Id,
263    /// Instance slots, in order; `None` leaves a slot empty.
264    pub instances: Vec<Option<TlasInstance>>,
265}
266
267#[derive(Serialize, Deserialize, Debug, Clone)]
268pub enum Cmd {
269    CopyBufferToBuffer { src: Id, src_offset: u64, dst: Id, dst_offset: u64, size: Option<u64> },
270    CopyBufferToTexture { src: TexelCopyBufferInfo, dst: TexelCopyTextureInfo, size: Extent3d },
271    CopyTextureToBuffer { src: TexelCopyTextureInfo, dst: TexelCopyBufferInfo, size: Extent3d },
272    CopyTextureToTexture { src: TexelCopyTextureInfo, dst: TexelCopyTextureInfo, size: Extent3d },
273    ClearTexture { texture: Id, range: wgt::ImageSubresourceRange },
274    ClearBuffer { buffer: Id, offset: u64, size: Option<u64> },
275    WriteTimestamp { query_set: Id, index: u32 },
276    ResolveQuerySet { query_set: Id, first: u32, count: u32, dst: Id, dst_offset: u64 },
277    RenderPass { desc: RenderPassDesc, cmds: Vec<RenderCmd> },
278    ComputePass { label: Label, timestamp_writes: Option<TimestampWrites>, cmds: Vec<ComputeCmd> },
279    BuildAccelerationStructures { blas: Vec<BlasBuild>, tlas: Vec<TlasBuild> },
280    PushDebugGroup(String),
281    PopDebugGroup,
282    InsertDebugMarker(String),
283}
284
285#[derive(Serialize, Deserialize, Debug, Clone)]
286pub struct RenderBundleEncoderDesc {
287    pub label: Label,
288    pub color_formats: Vec<Option<TextureFormat>>,
289    pub depth_stencil: Option<wgt::RenderBundleDepthStencil>,
290    pub sample_count: u32,
291    pub multiview: Option<NonZeroU32>,
292}
293
294/// Write to a texture from guest memory (the data travels separately).
295#[derive(Serialize, Deserialize, Debug, Clone)]
296pub struct WriteTexture {
297    pub texture: TexelCopyTextureInfo,
298    pub layout: wgt::TexelCopyBufferLayout,
299    pub size: Extent3d,
300}
301
302#[derive(Serialize, Deserialize, Debug, Clone)]
303pub enum Req {
304    Hello { version: u32 },
305    Adapter,
306    RequestDevice { label: Label, features: [u64; 2], limits: wgt::Limits },
307    CreateBuffer { label: Label, size: u64, usage: u32, mapped_at_creation: bool },
308    CreateTexture(wgt::TextureDescriptor<Label, Vec<TextureFormat>>),
309    CreateTextureView { texture: Id, desc: wgt::TextureViewDescriptor<Label> },
310    CreateSampler(wgt::SamplerDescriptor<Label>),
311    CreateShaderModule { label: Label, wgsl: String, runtime_checks: bool },
312    CreateBindGroupLayout { label: Label, entries: Vec<wgt::BindGroupLayoutEntry> },
313    CreateBindGroup { label: Label, layout: Id, entries: Vec<BindGroupEntry> },
314    CreatePipelineLayout { label: Label, bind_group_layouts: Vec<Id>, immediate_size: u32 },
315    CreateRenderPipeline(RenderPipelineDesc),
316    CreateMeshPipeline(MeshPipelineDesc),
317    CreateComputePipeline(ComputePipelineDesc),
318    GetBindGroupLayout { pipeline: Id, index: u32 },
319    CreateQuerySet(wgt::QuerySetDescriptor<Label>),
320    CreateCommandBuffer { label: Label, cmds: Vec<Cmd> },
321    CreateRenderBundle { desc: RenderBundleEncoderDesc, label: Label, cmds: Vec<RenderCmd> },
322    CreateBlas { desc: wgt::CreateBlasDescriptor<Label>, sizes: wgt::BlasGeometrySizeDescriptors },
323    CreateTlas(wgt::CreateTlasDescriptor<Label>),
324    Submit { command_buffers: Vec<Id> },
325    OnSubmittedWorkDone { token: u64 },
326    BufferMapAsync { buffer: Id, write: bool, start: u64, end: u64, token: u64 },
327    BufferUnmap { buffer: Id },
328    BufferDestroy { buffer: Id },
329    TextureDestroy { texture: Id },
330    QuerySetDestroy { query_set: Id },
331    PushErrorScope { filter: u8 },
332    PopErrorScope,
333    /// Poll the device; `wait` blocks until all submitted work is done.
334    Poll { wait: bool },
335    ShaderCompilationInfo { module: Id },
336    TextureFormatFeatures(TextureFormat),
337    SurfaceCaps,
338    SurfaceConfigure(wgt::SurfaceConfiguration<Vec<TextureFormat>>),
339    SurfaceAcquire,
340    SurfacePresent { texture: Id },
341    SurfaceDiscard { texture: Id },
342    Drop { ids: Vec<Id> },
343    /// v2: per-frame inputs for host-side frame passes (DLSS5-NR, `SG_DLSS5=1`), sent before
344    /// `SurfacePresent` and applying to that present only. Replies `U64` with a
345    /// [`frame_controls`] status; refusals are reported, never fatal.
346    FrameControls(FrameControls),
347}
348
349/// Inputs a game gives the host's frame pass for the next presented frame.
350///
351/// `motion`: an `Rg32Float` texture of the surface's size with `COPY_SRC` usage holding,
352/// per output pixel, the offset in pixels **to where that point was in the previous
353/// presented frame** (`prev = cur + mv`, +x right, +y down). Without motion vectors the
354/// pass has no temporal history (every frame is a first frame).
355#[derive(Serialize, Deserialize, Debug, Clone, Default, PartialEq)]
356pub struct FrameControls {
357    pub motion: Option<Id>,
358    /// Drop the temporal history (a camera cut, teleport, respawn, world change).
359    pub reset: bool,
360    /// The pass's style preset, 0..=2 (clamped).
361    pub style: u8,
362}
363
364/// `Req::FrameControls` replies.
365pub mod frame_controls {
366    /// Taken for the next present.
367    pub const ACCEPTED: u64 = 0;
368    /// No frame pass is active (DLSS5 off, disarmed or toggled off): nothing to do.
369    pub const INACTIVE: u64 = 1;
370    /// The motion texture was refused (wrong format, size or usage); the reason is logged
371    /// by the host. The other controls were taken.
372    pub const REFUSED_MOTION: u64 = 2;
373    /// The pass runs outside the GPU process (GPU isolation): motion and controls are not
374    /// forwarded there yet.
375    pub const NOT_FORWARDED: u64 = 3;
376}
377
378#[derive(Serialize, Deserialize, Debug, Clone)]
379pub struct ErrorInfo {
380    pub kind: u8,
381    pub message: String,
382}
383
384#[derive(Serialize, Deserialize, Debug, Clone)]
385pub enum Event {
386    /// A `BufferMapAsync` finished.
387    Mapped { token: u64, ok: bool },
388    /// An `OnSubmittedWorkDone` fired.
389    WorkDone { token: u64 },
390    /// An error not caught by any error scope.
391    Uncaptured(ErrorInfo),
392    DeviceLost(String),
393}
394
395#[derive(Serialize, Deserialize, Debug, Clone)]
396pub struct CompilationMessage {
397    pub message: String,
398    pub is_error: bool,
399    /// (line, column, offset, length)
400    pub location: Option<(u32, u32, u32, u32)>,
401}
402
403#[derive(Serialize, Deserialize, Debug, Clone)]
404pub enum Reply {
405    Unit,
406    Id(Id),
407    U64(u64),
408    Hello { version: u32 },
409    Adapter(AdapterDesc),
410    Device { device: Id, queue: Id, features: [u64; 2], limits: wgt::Limits },
411    Blas { id: Id, handle: Option<u64> },
412    Error(Option<ErrorInfo>),
413    Events(Vec<Event>),
414    Compilation(Vec<CompilationMessage>),
415    FormatFeatures(wgt::TextureFormatFeatures),
416    SurfaceCaps(SurfaceCaps),
417    Surface { texture: Id, status: u8, width: u32, height: u32 },
418}
419
420pub fn encode<T: Serialize>(v: &T) -> Vec<u8> {
421    postcard::to_allocvec(v).expect("sg-gpu-proto: encode")
422}
423
424pub fn decode<'a, T: Deserialize<'a>>(b: &'a [u8]) -> Result<T, postcard::Error> {
425    postcard::from_bytes(b)
426}
427
428#[cfg(test)]
429mod tests {
430    use super::*;
431
432    #[test]
433    fn v2_appends_frame_controls_without_moving_v1_requests() {
434        // postcard tags enum variants by index: v1 requests must keep theirs.
435        assert_eq!(encode(&Req::Hello { version: 1 }), [0, 1]);
436        assert_eq!(encode(&Req::Drop { ids: vec![] })[0], 37);
437        let fc = Req::FrameControls(FrameControls { motion: Some(7), reset: true, style: 2 });
438        let b = encode(&fc);
439        assert_eq!(b[0], 38);
440        match decode::<Req>(&b).unwrap() {
441            Req::FrameControls(f) => assert_eq!(f, FrameControls { motion: Some(7), reset: true, style: 2 }),
442            r => panic!("{r:?}"),
443        }
444    }
445}