gpu

tape
import gpu from "gpu";
import io from "io";
import ui from "ui";
import bytes from "bytes";

pub struct Dot { pos: gpu.Vec2; vel: gpu.Vec2; }
pub struct Step { dt: f32; count: u32; }
pub struct View { size: f32; tint: gpu.Vec4; }

@tape { gpu.gen_uniforms(Step); }
@tape { gpu.gen_uniforms(View); }
@tape { bytes.gen_of(Dot); }

fn run(dev: *gpu.Device) -> void or gpu.GpuError {
    let step = dev.compute_pipeline(&advance) or return;
    let draw = dev.render_pipeline(&dot_vs, &dot_ps, gpu.RenderOptions {
        primitive: gpu.Primitive.TriangleStrip;
    }) or return;
    let s_dots = step.slot("dots");
    let s_corner = draw.slot("corner");
    let s_dot = draw.slot("d");

    var start: [1024]Dot;
    for (i in 0..1024) {
        let a = i as f32 * 2.399;
        start[i] = Dot { pos: gpu.splat2(0.0); vel: gpu.vec2(gpu.cos(a), gpu.sin(a)) * 0.3; };
    }
    let dots = dev.buffer(1024 * 16, gpu.STORAGE | gpu.VERTEX) or return;
    dots.write(dev, 0, of_Dot(start[0..]));
    let corners = [0.0 as f32, 0.0, 1.0, 0.0, 0.0, 1.0, 1.0, 1.0];
    let quad = dev.buffer(32, gpu.VERTEX) or return;
    quad.write(dev, 0, bytes.of_f32(corners[0..]));

    var su = Step { dt: 0.016; count: 1024; };
    var vu = View { size: 0.02; tint: gpu.vec4(1.0, 0.8, 0.2, 1.0); };
    while (!dev.closed()) {
        while (true) {
            let ev = dev.poll() or { break; };
            match (ev) {
                gpu.Event.Key { e } => { if (e.key == ui.Key.Escape) { return; } }
                _ => {}
            }
        }
        var cp = dev.compute();                 // move the dots
        cp.pipeline(&step);
        uniforms_Step(&cp, &su);
        cp.storage(s_dots, &dots, 0);
        cp.dispatch_for(1024);
        cp.end();

        var rp = dev.render(null, gpu.vec4(0.05, 0.05, 0.08, 1.0));   // draw them
        rp.pipeline(&draw);
        uniforms_View(&rp, &vu);
        rp.vertices(s_corner, &quad, 0);
        rp.vertices(s_dot, &dots, 0);           // what the compute pass wrote, as instances
        rp.draw(4, 1024);
        rp.end();
        dev.present() or return;
    }
}

fn main() -> i32 {
    var dev = gpu.open(800, 600, "dots", gpu.Options {}) or {
        io.println(err.desc());
        return 1;
    };
    run(&dev) or { io.println(err.desc()); };
    dev.close();
    return 0;
}

#shader
import gpu from "gpu";

compute(64) fn advance(dots: []Dot, u: uniform Step) {
    let i = gpu.global_id().x;
    if (i >= u.count) { return; }
    var d = dots[i];
    d.pos = d.pos + d.vel * u.dt;
    if (d.pos.x < -1.0 || d.pos.x > 1.0) { d.vel.x = -d.vel.x; }
    if (d.pos.y < -1.0 || d.pos.y > 1.0) { d.vel.y = -d.vel.y; }
    dots[i] = d;
}

pub struct DotOut { position: gpu.Vec4; uv: gpu.Vec2; }

vertex fn dot_vs(corner: gpu.Vec2, d: instance Dot, u: uniform View) -> DotOut {
    let p = d.pos + (corner - gpu.splat2(0.5)) * u.size;
    return DotOut { position: gpu.vec4(p.x, p.y, 0.0, 1.0); uv: corner; };
}

pixel fn dot_ps(v: DotOut, u: uniform View) -> gpu.Vec4 {
    return u.tint;
}

gpu is one GPU API that a renderer is written against once: Metal underneath on macOS, Vulkan on Windows and Linux (OpenGL 4.3 where the machine has no Vulkan 1.3 device), through the gpu100 runtime library that tape build puts beside the program. Shaders are tape, in a #shader region; each stage’s name is a gpu.Shader that pipelines are made from. Work happens in the order the program asks for it, and gpu places the barriers between passes. It works the same under tape run and in a built program.

The vectors and matrices (gpu.Vec2 to gpu.Vec4, the integer ones, gpu.Mat4) are math3d’s under gpu’s names: a math3d.Mat4 made with math3d.mat4_perspective and mat4_look_at is a gpu.Mat4 a uniform takes, with nothing converted.

Windows and Linux need a driver with Vulkan 1.3 (and VK_KHR_push_descriptor, which every desktop driver has) or, failing that, OpenGL 4.3 (compute shaders); on Linux that is Mesa or the GPU vendor’s driver. Nothing has to be installed to build: the Vulkan loader (vulkan-1.dll, libvulkan.so.1) comes with the driver and is found when the program runs. macOS uses Metal. It is a capability module: it opens windows and talks to the GPU.

The device

CallGives
gpu.open(width, height, title, opts) -> Device or GpuErrorA window and the GPU drawing into it
gpu.offscreen(opts) -> Device or GpuErrorThe GPU with no window
tape
pub struct Options {
    vsync: bool = true;
    visible: bool = true;          // false: a hidden window, shown later with dev.show()
    debug: bool = false;           // Vulkan: the validation layer, when installed;
                                   // OpenGL: a debug context; Metal: the API validation layer
    backend: ?gpu.Backend = null;  // null: the platform's best; or Vulkan, Gl, Metal
    icon: []const gfx.Surface = [];  // the window's icon, set before it shows (dev.set_icon)
}

offscreen is for tests and tools that render into textures: on Vulkan and Metal it needs no window server at all; OpenGL has no context without a window, so there it is a hidden window’s.

Backends

gpu.Backend is Metal, Gl (OpenGL) or Vulkan. With backend left null, gpu takes the platform’s best: on Windows and Linux a Vulkan GPU, else OpenGL, else a Vulkan device that runs on the CPU (Mesa’s lavapipe: a software Vulkan isn’t taken over the machine’s OpenGL). Asking for one backend gives that one or GpuError.Unsupported saying the platform lacks it (Metal on Windows, Vulkan on macOS), so a program can try one and fall back itself. The program is the same on each: shaders, pipelines, passes and readbacks behave alike, and dev.info() says which it got.

The same shader’s integer results, conversions, comparisons and atomics are exact on every backend. Its float results are the GPU’s: another backend, driver or GPU may round differently, within the precision the shader languages allow. Drivers fuse multiplies and adds, reorder arithmetic and compute sqrt and normalize their own way. A simulation that turns an ulp into a different outcome, such as a crowd whose members push each other, can come out differently on Vulkan than on OpenGL even on one machine. When every machine must get the same answer, compute it in integers, or round the floats to a grid each step.

MethodDoes
dev.poll() -> ?EventOne waiting event, null when none: drain it at the top of each frame
dev.wait() -> EventBlock until an event comes
dev.present()Show the frame in the window (void or GpuError)
dev.finish()Wait for all the work asked for so far (void or GpuError)
dev.read_frame(out)The window’s frame as drawn so far, Bgra8, rows top down (void or GpuError)
dev.gpu_ms() -> ?f64The last finished frame’s GPU time, null until one has finished
dev.set_vsync(on)Vsync on or off from the next present on, so a game’s setting applies live. A request: a driver that can’t honour it isn’t an error. Nothing offscreen
dev.vsync() -> boolWhether presents wait for the display now: what is in effect, not what was asked for. When false, pace the frame loop yourself. False offscreen
dev.size() -> SizeThe window’s drawable area, in pixels (0 by 0 offscreen)
dev.info() -> Infobackend (gpu.Backend.Vulkan, Gl or Metal, .desc() names it), the device’s name, and what not every backend has (below)
dev.set_title(text), dev.show()The title bar; show a window opened with visible: false
dev.focused() -> bool, dev.closed() -> boolThe window is in front; the user closed it, or close() ran
dev.key_down(k) -> boolKey k (a ui.Key) is held down, as the events polled so far say: let go when the window leaves the front, the same keys on every platform, F10 and Alt among them (gl’s key_down)
dev.key_pressed(k), dev.mouse_down(b), dev.set_relative_mouse(on), dev.set_cursor(c), …The mouse and the cursor
dev.close()Release everything and the window; twice is fine
tape
pub struct Info {
    backend: Backend;
    name: string;
    exact_depth: bool;   // z 0..1 reaches the depth buffer as it is: reversed Z keeps its precision
                         // (false only on OpenGL older than 4.5 without clip control)
    max_anisotropy: i64; // the most Sampler.anisotropy does: 16 on Metal, Vulkan GPUs and current GL drivers; 1 none
    image_atomics: bool; // atomics on R32u storage images
    image_formats: bool; // every storage image format read and written in one stage (else R32f, R32u)
    subgroup_size: i64;  // a compute stage's usual subgroup size; 0: the device has no subgroups
    subgroups: bool;     // every gpu.subgroup_* operation (Metal on Metal 3, Apple7 and Mac2 GPUs, Vulkan; OpenGL with GL_KHR_shader_subgroup)
    texture_tables: bool;          // TextureTable (Vulkan: descriptor indexing; Metal: argument buffers tier 2; OpenGL: GL_ARB_bindless_texture)
    bc_textures: bool;             // the block-compressed Formats (Vulkan: textureCompressionBC; Metal: supportsBCTextureCompression; OpenGL: S3TC)
    primitive_id: bool;            // gpu.primitive_id in a pixel stage (Vulkan: geometryShader; Metal: an Apple7 or Mac2 GPU; OpenGL always)
    max_samples: i64;              // the largest of 2, 4, 8 every renderable colour format and Depth32f have; 1 none (see Multisampling)
    indirect_count: bool;          // pass.draw_indirect_count (Vulkan: drawIndirectCount; OpenGL: 4.6 or GL_ARB_indirect_parameters)
    indirect_first_instance: bool; // an indirect draw's first_instance counts in gpu.instance_index()
    timers: bool;        // dev.timer() works (every Metal device, Vulkan queues with timestamps, GL drivers with them)
    mesh_shaders: bool;        // dev.mesh_pipeline: Vulkan with VK_EXT_mesh_shader, Metal 3 GPUs; never OpenGL
    max_mesh_vertices: i64;    // the most a mesh stage's `vertices *[N]V` may hold (0 without mesh shaders)
    max_mesh_primitives: i64;  // and its `primitives *[M]gpu.UVec3`
    max_task_payload: i64;     // the most bytes a task stage's payload may have
    atomics_u64: bool;         // gpu.atomic_min_u64/max_u64 on storage buffers (Vulkan; Metal on Apple9, M3 and later)
    image_atomics_u64: bool;   // and on ImageRg32u storage images
    ray_queries: bool;         // dev.blas, dev.tlas, gpu.ray_query in compute stages (Vulkan VK_KHR_ray_query; Metal)
    ray_queries_render: bool;  // and in the stages that draw
}

A frame is passes, then present(). A resize needs nothing from the program: the next pass into the window has the new size, and Resize says it happened. read_frame needs width * height * 4 bytes; rows come top down on every backend, so a screenshot needs no flip.

The screen and fullscreen

A window counts the screen’s real pixels, so the GPU renders at the screen’s own resolution on a scaled screen too (150 %, Retina), and fullscreen is the screen’s full resolution.

CallGives
gpu.primary_display() -> DisplayThe primary screen, before any window is open
dev.display() -> DisplayThe screen most of the window is on
dev.set_mode(m)gpu.Mode.Windowed, Borderless (no frame, covering the screen) or Fullscreen
dev.mode() -> ModeThe window’s mode now
tape
pub struct Display {
    x: i64; y: i64; width: i64; height: i64;              // the whole screen
    work_x: i64; work_y: i64; work_width: i64; work_height: i64;   // less the taskbar, dock, panels
    scale: f64;                                            // the desktop's scaling: 1.0, 1.5, 2.0
    refresh_hz: f64;                                       // its refresh rate: 60.0, 59.94, 144.0; 0 when unknown
}

Open at a share of the screen, and toggle fullscreen with a key:

tape
let d = gpu.primary_display();
var dev = gpu.open(d.work_width * 8 / 10, d.work_height * 8 / 10, "game", gpu.Options {}) or return;
// ... on F11:
if (dev.mode() == gpu.Mode.Windowed) { dev.set_mode(gpu.Mode.Fullscreen); }
else { dev.set_mode(gpu.Mode.Windowed); }

A mode change arrives as a Resize, as a resize by the user does. Windowed again is where the window was and the size it had. No display mode is ever changed: fullscreen is the screen’s current resolution (on macOS, its own Space). scale is for sizing your own interface: draw text and buttons scale times larger on a 150 % screen. refresh_hz is for a game that paces itself with vsync off: time.pacer. It is read at each call (a screen set to another rate says so), a fraction where the platform has one (59.94, not 60), and 0 when the screen doesn’t say: fall back to your own rate then. time never reads it on its own: you pass time.from_hz(d.refresh_hz). Ask dev.display() again after the window moves to know the screen it is on now.

The icon

dev.set_icon(images) -> bool sets the window’s icon from one picture in several sizes, each a gfx.Surface (what image.decode gives); the platform shows the one that fits. gpu.Options.icon sets it before the window shows:

tape
let png = fs.read_file("icon.png") or { return 1; };
var img = image.decode(png) or { return 1; };
var dev = gpu.open(1280, 720, "game", gpu.Options { icon: [img] }) or { return 1; };
img.free();                       // copied

Up to 16 images of 1 to 1024 pixels a side; empty gives the platform’s default back. On macOS it is the Dock’s icon, the application’s, as macOS has none per window. Where each platform shows it: ui’s window icon. False offscreen.

Events

tape
import ui from "ui";

pub tagged Event {
    Key { e: ui.KeyEvent; }
    Pointer { e: ui.PointerEvent; }
    Resize { width: i64; height: i64; }
    Focus { focused: bool; }
    Close;
}

They are gl’s events, filled the same way: keys and the pointer as ui’s own events (e.key == ui.Key.Escape, the wheel in e.wheel_x and e.wheel_y), Focus when the window comes to the front or leaves it, Close once when the user closes it. poll also runs what your threads sent back, so a worker’s callback runs on the GPU thread.

The mouse and the cursor

dev.set_relative_mouse(on), dev.mouse_delta(), dev.mouse_pos(), dev.mouse_down(b), dev.mouse_pressed(b), dev.mouse_released(b), dev.mouse_wheel(), dev.key_pressed(k), dev.key_released(k), dev.set_cursor(c), dev.set_custom_cursor(c), dev.show_cursor(on), dev.make_cursor(argb, w, h, hot_x, hot_y), dev.free_cursor(&c), dev.confine_cursor(on), dev.warp_cursor(x, y) and dev.overlay_cursor(c): as gl’s, in the screen’s native pixels. An offscreen device does nothing, reads zero and says false.

tape
dev.set_relative_mouse(true);
while (!dev.closed()) {
    while (true) {
        let ev = dev.poll() or { break; };
    }
    let d = dev.mouse_delta();
    camera.turn(d.x, d.y);
    if (dev.mouse_pressed(ui.MouseButton.Left)) { shoot(); }
    dev.overlay_cursor(hud.cursor());     // a ui.Screen drawn over the scene
    // draw, present
}

Buffers

tape
pub const VERTEX: u32 = 1;         // usages, combined with |
pub const STORAGE: u32 = 2;
pub const READ: u32 = 4;           // the CPU reads it back
pub const INDEX: u32 = 8;          // indices for indexed draws
pub const INDIRECT: u32 = 16;      // arguments of indirect draws and dispatches, a draw count
CallDoes
dev.buffer(size, usage) -> Buffer or GpuErrorA buffer of size bytes, zeroed
buf.write(dev, offset, data)Bytes into it; data may be reused at once
buf.clear(dev, offset, size)Bytes to zero
buf.read(dev, offset, out) -> void or GpuErrorBytes back into out
buf.ready(dev) -> boolA read now would not wait
buf.size() -> i64Its size in bytes
buf.release(dev)Free it; the GPU keeps it until it is done with it
  • Writes, clears and reads take effect at their place in the program: a pass after write sees the bytes, a pass before it doesn’t. They go between passes, never inside one.
  • read waits only for the work that used this buffer, never for the whole queue. A program that reads last frame’s results (two buffers, ping-ponged) never waits; ready() asks without waiting.
  • A buffer can be STORAGE | VERTEX: written by a compute shader and drawn as instances with no copy.
  • A range outside the buffer traps (gpu: buffer write of 64 bytes at 4096: the buffer holds 4096).
  • Bytes come from bytes: bytes.of_f32(xs[0..n]), of_u32, …, and @tape { bytes.gen_of(Dot); } makes of_Dot for a struct of your own. Its layout is the GPU’s as it is.

Textures

tape
pub enum Format : u32 {
    Bgra8 = 1; Rgba8 = 2; Rgba32f = 3; R32f = 4; R32u = 5; Depth32f = 6;
    Rgba16f = 7; Rg16f = 8; Rg32f = 9; R16f = 10; Rg32u = 11; R8 = 12;
}
pub enum Filter : u8 { Nearest = 0; Linear = 1; }
pub enum Wrap : u8 { Clamp = 0; Repeat = 1; }
pub enum MipFilter : u8 { None = 0; Nearest = 1; Linear = 2; }
pub struct Sampler {
    filter: Filter = Filter.Nearest;
    wrap: Wrap = Wrap.Clamp;
    mip: MipFilter = MipFilter.None;   // between mip levels; None reads level 0 only
    anisotropy: i64 = 1;               // 1..16 (dev.info().max_anisotropy is the device's most)
}
CallDoes
dev.texture(width, height, format, target) -> Texture or GpuErrorA 2D texture; target: true lets a render pass draw into it (and read it back)
tex.write(dev, x, y, w, h, data, row_bytes)A w by h rectangle at (x, y), rows row_bytes apart in data
tex.read(dev, out) -> void or GpuErrorThe whole texture, rows top down
dev.texture_with(gpu.TextureOptions {...}) -> Texture or GpuErrorA texture with mip levels, a 2D array or a 3D texture
tex.write_level(dev, level, layer, x, y, w, h, data, row_bytes)A rectangle of one level of one layer (or 3D slice)
tex.read_level(dev, level, layer, out) -> void or GpuErrorOne level of one layer, whole
tex.generate_levels(dev)Levels 1 and on, filtered down from level 0
tex.width(), tex.height()Its size
tex.levels(), tex.layers(), tex.depth()Its mip levels, array layers, 3D slices
tex.samples()Its samples a pixel (see Multisampling)
tex.release(dev)Free it, as a buffer
  • Row 0 is the top, on every backend.
  • Rgba8Srgb and Bgra8Srgb hold sRGB-encoded colour. A stage samples them as linear light, and what it draws into one is encoded, blended in linear light; generate_levels filters in linear light; alpha isn’t encoded. write and read take the bytes as they are. They aren’t storage images. The window stays Bgra8, unconverted: to render linearly, draw into a texture and write the window from it, encoding in that last pass (gpu.pow(c, 1.0 / 2.2) or the exact curve).
  • The block-compressed formats, Bc1 to Bc7 with their Srgb forms (the names of texture’s Format), go up as the file holds them: 2D or 2D arrays, never 3D, a target or a storage image. write and write_level take blocks, row_bytes a row of blocks apart, the rectangle in texels a multiple of 4 or reaching the level’s edge, and read gives blocks. A device without them refuses them with GpuError.Unsupported; dev.info().bc_textures says so first.
  • A new texture reads as zero, every level and layer, on every backend, however it is first used. A new depth texture is 0.0, so clear it before testing with Compare.Less.
  • Bgra8 is a gfx surface’s pixels as they are (0xAARRGGBB, colours unmultiplied): write one with row_bytes its stride * 4 and draw it with Blend.Alpha, or write what s.premultiplied_into gives (a ui.Screen’s premultiplied) and draw it with Blend.Premultiplied. Rgba32f is four f32 a texel, R32f one, R32u one u32 (a gpu.UTexture2D in a shader).
  • Rgba16f, Rg16f, R16f are half floats (their bits, 2 bytes a channel), Rg32f two f32, Rg32u two u32 (a gpu.UTexture2D, as R32u), R8 one byte read as 0 to 1. Every format can be drawn into.
  • Depth32f is a depth target (made with target: true): one f32 a texel, read back as they are, and a gpu.DepthTexture2D in a shader (gpu.sample_depth, gpu.load_depth).
  • Textures and buffers can be made, written and released at any time between passes, mid-game included.

Indirect work

A draw or dispatch can take its arguments from a buffer, so a compute pass decides what is drawn (culling) with no read back to the CPU:

tape
pub struct DrawArgs { vertices: u32; instances: u32; first_vertex: u32; first_instance: u32; }   // 16 bytes
pub struct DrawIndexedArgs { indices: u32; instances: u32; first_index: u32; base_vertex: i32;
                             first_instance: u32; }                                              // 20 bytes
pub struct DispatchArgs { x: u32; y: u32; z: u32; }                                              // 12 bytes
MethodDoes
pass.draw_indirect(&buf, offset, count)count draws, their DrawArgs one after another from offset
pass.draw_indexed_indirect(&buf, offset, count)the same with DrawIndexedArgs, from the indices set (at offset 0)
pass.draw_indirect_count(&buf, offset, &counts, count_offset, max_count)at most max_count, as many as the u32 at count_offset of counts says (and draw_indexed_indirect_count)
pass.dispatch_indirect(&buf, offset)a dispatch of the DispatchArgs’ workgroups
tape
import gpu from "gpu";

fn draw_visible(dev: *gpu.Device, cull: *const gpu.Pipeline, draw: *const gpu.Pipeline,
                objects: *const gpu.Buffer, mesh: *const gpu.Buffer, idx: *const gpu.Buffer,
                draws: *const gpu.Buffer, count: *const gpu.Buffer, n: i64) {
    count.clear(dev, 0, 4);
    var cp = dev.compute();
    cp.pipeline(cull);
    cp.storage(cull.slot("objects"), objects, 0);
    cp.storage(cull.slot("draws"), draws, 0);
    cp.storage(cull.slot("count"), count, 0);
    cp.dispatch_for(n);
    cp.end();                                   // the draws see what it wrote
    var rp = dev.render(null, gpu.splat4(0.0));
    rp.pipeline(draw);
    rp.vertices(draw.slot("v"), mesh, 0);
    rp.indices(idx, 0, gpu.IndexFormat.U32);
    rp.draw_indexed_indirect_count(draws, 0, count, 0, n);
    rp.end();
}

fn main() -> i32 { return 0; }

#shader
import gpu from "gpu";

pub struct Object { centre: gpu.Vec4; first_index: u32; indices: u32; pad0: u32; pad1: u32; }
pub struct Counter { n: u32; }

compute(64) fn cull(objects: []const Object, draws: []gpu.DrawIndexedArgs, count: *Counter) {
    let i = gpu.global_id().x;
    let o = objects[i];
    if (o.centre.z < 0.0) { return; }           // behind: not drawn
    let at = gpu.atomic_add(&count.n, 1);
    draws[at] = gpu.DrawIndexedArgs { indices: o.indices; instances: 1; first_index: o.first_index;
                                      base_vertex: 0; first_instance: i; };
}

pub struct Vtx { pos: gpu.Vec4; }
pub struct Out { position: gpu.Vec4; }

vertex fn draw_vs(v: Vtx) -> Out { return Out { position: v.pos; }; }
pixel fn draw_ps(o: Out) -> gpu.Vec4 { return gpu.vec4(1.0, 1.0, 1.0, 1.0); }
  • The buffers are made with gpu.INDIRECT (and gpu.STORAGE for a compute pass to write them); offsets are multiples of 4. gpu places the barrier between the compute pass and the draws.
  • A draw count in a buffer needs OpenGL 4.6 (or GL_ARB_indirect_parameters): dev.info().indirect_count says so, and without it draw_indirect_count stops the program saying why. Metal has it (drawn as max_count draws, the ones past the count with no instances).
  • gpu.instance_index() counts from the record’s first_instance where dev.info().indirect_first_instance (Metal; OpenGL 4.6 or ARB_shader_draw_parameters); per-instance vertex streams start there everywhere.

Tables of textures

A table is many 2D textures a stage samples by index, the index free to differ per invocation or pixel, up to gpu.MAX_TABLE (4096): every material of a scene without a texture binding each. It holds float formats of any sizes, and one sampler.

CallDoes
dev.texture_table(textures, sampler) -> TextureTable or GpuErrorA table of textures, a []const *const Texture
pass.texture_table(slot, &table)Bind it to a gpu.Texture2DTable parameter
table.len()How many it holds
table.release(dev)Free it, before its textures
tape
let table = dev.texture_table(materials[0..], gpu.Sampler { filter: gpu.Filter.Linear; mip: gpu.MipFilter.Linear; }) or return;
...
pass.texture_table(p.slot("mats"), &table);

The shader’s side is in #shader. While bound, the textures are being sampled, so they aren’t that pass’s targets. An index past the table’s end gives what the driver gives. A device without tables (dev.info().texture_tables false: Metal below argument buffers tier 2, OpenGL without GL_ARB_bindless_texture) refuses the table and any pipeline taking one with GpuError.Unsupported.

Storage images

A texture made with storage: true is a storage image: a compute stage (or a pixel stage) reads and writes it by texel. It is of a format with an image type in the shader; it can also be a render target, be sampled and be read back like any texture.

A 3D texture or a 2D array is one too: its types are gpu.Image3dR32f and gpu.ImageArrayR32f, and so on for each format, at an IVec3 whose z is the slice or the layer. pass.image(slot, &tex, level) binds a level whole, and pass.image_layer(slot, &tex, level, layer) binds one layer of a 2D array at a 2D image parameter. A 3D texture’s single slice can’t be bound that way: bind it whole and give z.

tape
import gpu from "gpu";

fn resolve(dev: *gpu.Device, ids: *const gpu.Texture, colour: *const gpu.Texture) -> void or gpu.GpuError {
    let p = dev.compute_pipeline(&resolve_cs) or return;    // Unsupported when the device can't
    var cp = dev.compute();
    cp.pipeline(&p);
    cp.image(p.slot("ids"), ids, 0);          // level 0, read and written
    cp.image(p.slot("colour"), colour, 0);
    cp.dispatch(1920 / 8, 1080 / 8, 1);
    cp.end();                                 // the next pass sees what it wrote
}

fn main() -> i32 { return 0; }

#shader
import gpu from "gpu";

compute(8, 8) fn resolve_cs(ids: gpu.ImageR32u, colour: gpu.ImageRgba16f) {
    let g = gpu.global_id();
    let at = gpu.ivec2(g.x as i32, g.y as i32);
    let id = ids.load(at).x;
    colour.store(at, gpu.vec4((id & 255) as f32 / 255.0, 0.0, 0.0, 1.0));
    ids.atomic_exchange(at, 0);               // cleared for the next frame
}
  • pass.image(slot, &tex, level) binds one level of the texture; the shader’s image type must be the texture’s format (gpu.ImageRgba8, ImageRgba16f, ImageRgba32f, ImageR32f, ImageR16f, ImageRg16f, ImageRg32f, ImageR8, ImageR32u, ImageRg32u).
  • An invocation reads its own writes; another invocation’s are seen in a later pass. Between passes gpu places the barriers.
  • Atomics on ImageR32u texels need OpenGL 4.2 or Metal 3.1 (macOS 14, an Apple GPU); reading and writing other formats than R32f and R32u in one stage needs Metal’s read-write tier 2 (Apple silicon has it). dev.info() says both (image_atomics, image_formats), and a pipeline needing what the device lacks, or a storage image of a format it can’t read and write, is GpuError.Unsupported, naming it.

Levels, arrays and 3D textures

tape
pub enum TextureKind : u8 { Tex2D = 0; Tex2DArray = 1; Tex3D = 2; }
pub struct TextureOptions {
    width: i64;
    height: i64;
    depth: i64 = 1;          // a 3D texture's slices
    layers: i64 = 1;         // a 2D array's layers
    levels: i64 = 1;         // mip levels; 0: the whole chain, down to 1x1
    format: Format = Format.Rgba8;
    target: bool = false;
    kind: TextureKind = TextureKind.Tex2D;
    samples: i64 = 1;                  // 1, 2, 4, 8 (see Multisampling)
}

Level n is width >> n by height >> n (and depth >> n slices), at least 1. write_level and read_level name the level and the layer: a 2D array’s layer, or a 3D texture’s slice (written and read a slice at a time). generate_levels makes levels 1 and on from level 0, in program order; an integer or depth texture’s levels are written instead. A render pass draws into a level and layer of a texture (gpu.Target { texture: &t; level: 2; layer: 1; }, and the same in gpu.DepthTarget): a mip chain rendered level by level, a cascade into a depth array’s layer.

tape
import gpu from "gpu";

fn make_volume(dev: *gpu.Device, slices: [][]const u8) -> gpu.Texture or gpu.GpuError {
    let vol = dev.texture_with(gpu.TextureOptions { width: 32; height: 32; depth: 32;
                                                    kind: gpu.TextureKind.Tex3D; }) or return;
    for (z in 0..32) { vol.write_level(dev, 0, z, 0, 0, 32, 32, slices[z], 32 * 4); }
    return vol;
}

fn make_mipped(dev: *gpu.Device, pixels: []const u8) -> gpu.Texture or gpu.GpuError {
    let t = dev.texture_with(gpu.TextureOptions { width: 256; height: 256; levels: 0; }) or return;
    t.write(dev, 0, 0, 256, 256, pixels, 256 * 4);
    t.generate_levels(dev);                          // 9 levels, 128x128 down to 1x1
    return t;
}

fn main() -> i32 { return 0; }

A shader reads them with gpu.sample_level, gpu.load_level, and the array and 3D forms (#shader); sampling between levels needs a sampler with a mip filter (gpu.Sampler { filter: gpu.Filter.Linear; mip: gpu.MipFilter.Linear; anisotropy: 8; }), else level 0 is read.

Pipelines

tape
pub enum Primitive : u8 { Triangles = 0; TriangleStrip = 1; Lines = 2; Points = 3; }
pub enum Blend : u8 { None = 0; Premultiplied = 1; Alpha = 2; Additive = 3; }
pub enum Compare : u8 { Never = 0; Less = 1; Equal = 2; LessEqual = 3; Greater = 4; NotEqual = 5; GreaterEqual = 6; Always = 7; }

pub struct DepthOptions {
    compare: Compare = Compare.Less;
    write: bool = true;              // false: tested, the depth kept
}

pub struct RenderOptions {
    primitive: Primitive = Primitive.Triangles;
    blend: Blend = Blend.None;
    format: Format = Format.Bgra8;   // the target's: the window's is Bgra8
    formats: []const Format = [];    // several targets: each one's, in the pixel stage's field order
    depth: ?DepthOptions = null;     // drawn with a depth target: its test; null: without one
    cull: Cull = Cull.None;          // the faces not drawn
    front: Winding = Winding.CounterClockwise;  // which way round a front face's vertices go
    samples: i64 = 1;              // the targets' samples a pixel (see Multisampling)
}

pub enum Cull : u8 { None = 0; Back = 1; Front = 2; }
pub enum Winding : u8 { CounterClockwise = 0; Clockwise = 1; }

front is measured in your coordinates, x right and y up in normalized device coordinates, so the same triangles cull the same on every backend and in every target, a window or a texture: gpu accounts for what Vulkan’s viewport and OpenGL’s flip do. A mesh pipeline’s triangles cull the same way; lines and points are never culled.

A pixel stage declared @early_depth pixel fn has the depth test before it runs (a stage with side effects otherwise runs for hidden pixels: #shader).

A pipeline draws in passes of its own shape: the colour targets format (or formats) names, and a depth target exactly when depth is set. Using it in another pass stops the program, saying what differs.

CallDoes
dev.render_pipeline(&vs, &ps, opts) -> Pipeline or GpuErrorA vertex and a pixel shader, drawn with opts
dev.compute_pipeline(&cs) -> Pipeline or GpuErrorA compute shader
dev.mesh_pipeline(&ts, &ms, &ps, opts) -> Pipeline or GpuErrorA task shader (or null), a mesh shader and a pixel shader (Mesh pipelines)
p.slot(name) -> SlotA resource or vertex stream, by its parameter’s name in the shader
p.release(dev)Free it
BlendIs
Nonethe colour replaces what is there
PremultipliedONE, ONE_MINUS_SRC_ALPHA: s.premultiplied_into’s pixels, a shader’s premultiplied colour
AlphaSRC_ALPHA, ONE_MINUS_SRC_ALPHA: a gfx surface’s pixels as they are
AdditiveONE, ONE

Look the slots up once, next to the pipeline, and keep them. A render pipeline joins its two stages by name: a parameter in both is one slot, and their uniforms are one struct. Two pipelines from one shader are fine (the same blit with and without blending).

Ray tracing

A stage ray-queries a scene of triangles (#shader): a Blas (bottom-level acceleration structure) holds triangles from a vertex buffer (and an index buffer), a Tlas (top level) instances of Blases, each with a transform. Both are built between passes, in order with them: a build reads the buffers as the passes before it left them, and the passes after see it (gpu places the barriers).

tape
pub struct BlasOptions {
    vertices: *const Buffer;      // positions: x, y, z as f32 at the start of every `stride` bytes
    vertex_offset: i64 = 0;
    vertex_count: i64;
    stride: i64 = 16;
    indices: ?*const Buffer = null;   // u32, three a triangle; null: three vertices a triangle
    index_offset: i64 = 0;
    triangles: i64;
    updatable: bool = false;      // update() refits it after its vertices move
    opaque: bool = true;          // false: a ray query's loop decides its triangles (alpha)
}
pub struct Instance {
    blas: *const Blas;
    transform: [12]f32 = [1.0, 0.0, 0.0, 0.0, 0.0, 1.0, 0.0, 0.0, 0.0, 0.0, 1.0, 0.0];  // 3 rows of 4, object to world
    id: u32 = 0;                  // what Hit.instance gives (24 bits)
    mask: u32 = 255;
}
CallDoes
dev.blas(opts) -> Blas or GpuErrorA Blas of the triangles opts names (built by build)
blas.build(&dev), blas.update(&dev)Build it from its buffers as they are now; refit it (the same triangles, moved: updatable)
dev.tlas(capacity, updatable) -> Tlas or GpuErrorA Tlas with room for capacity instances
tlas.build(&dev, instances), tlas.update(&dev, instances)Build it of the instances; refit it (the same instances, new transforms)
pass.tlas(slot, &tlas)The scene a stage’s gpu.Tlas parameter queries
blas.release(&dev), tlas.release(&dev)Free them; the GPU keeps them until it is done with them, as a buffer
tape
import gpu from "gpu";

fn scene_of(dev: *gpu.Device, verts: *const gpu.Buffer, idx: *const gpu.Buffer, n: i64,
            blas: *gpu.Blas) -> gpu.Tlas or gpu.GpuError {
    *blas = dev.blas(gpu.BlasOptions { vertices: verts; vertex_count: n; indices: idx; triangles: n / 2; }) or return;
    blas.build(dev);
    var tlas = dev.tlas(2, true) or return;
    var two: [2]gpu.Instance = [gpu.Instance { blas: blas; id: 1; },
                                gpu.Instance { blas: blas; id: 2; transform: [1.0, 0.0, 0.0, 5.0,
                                                                              0.0, 1.0, 0.0, 0.0,
                                                                              0.0, 0.0, 1.0, 0.0]; }];
    tlas.build(dev, two[0..]);
    return tlas;
}

fn main() -> i32 { return 0; }
  • After a Blas is built or updated again, build or update the Tlases that use it before the next ray query.
  • Where the device has no ray tracing (Info.ray_queries false; always on OpenGL 4.3), dev.blas, dev.tlas and a pipeline that ray-queries are GpuError.Unsupported: “ray tracing (OpenGL 4.3 has none: Vulkan or Metal have it)”.

Mesh pipelines

A mesh pipeline draws triangles a mesh shader writes, in workgroups, with no vertex buffers; a task shader before it says how many mesh workgroups to launch (#shader has the stages). It is drawn by workgroups instead of vertices:

MethodDoes
pass.draw_mesh_tasks(x, y, z)x * y * z task workgroups (mesh workgroups when the pipeline has no task shader)
pass.draw_mesh_tasks_indirect(&buf, offset, count)count such draws, their DispatchArgs one after another from offset
tape
import gpu from "gpu";

fn draw_tiles(dev: *gpu.Device, cols: *const gpu.Buffer) -> void or gpu.GpuError {
    if (!dev.info().mesh_shaders) { return; }      // OpenGL, or a GPU without them: draw another way
    let p = dev.mesh_pipeline(&tiles_ts, &tiles_ms, &tile_ps, gpu.RenderOptions {}) or return;
    var rp = dev.render(null, gpu.splat4(0.0));
    rp.pipeline(&p);
    rp.storage(p.slot("cols"), cols, 0);
    rp.draw_mesh_tasks(2, 1, 1);
    rp.end();
}
  • The stages join by name as a render pipeline’s do: resources, the uniform struct, the mesh shader’s vertex struct and the pixel shader’s input, the task shader’s payload struct and the mesh shader’s.
  • A mesh pipeline draws only with draw_mesh_tasks and draw_mesh_tasks_indirect, and they draw only mesh pipelines: anything else stops the program, saying so.
  • Where the device has no mesh shaders (Info.mesh_shaders false; always on OpenGL 4.3), or a stage asks for more vertices, triangles or payload than it has room for, mesh_pipeline is GpuError.Unsupported, naming what and the backend: mesh shaders (OpenGL 4.3 has none: Vulkan or Metal have them), a mesh stage of 300 vertices and 2 triangles (Vulkan: at most 256 and 256).

Passes

A pass begins with dev.render(target, clear) or dev.compute() and ends with pass.end(). A render pass draws into target, a ?*const gpu.Texture: null is the window. clear is a ?gpu.Vec4: a colour clears the target first, null keeps what it holds.

MethodDoes
pass.pipeline(&p)Draw or dispatch with p from here on; its bindings start afresh
uniforms_T(&pass, &u)The uniforms, from a T (made by @tape { gpu.gen_uniforms(T); }); copied at the call
pass.storage(slot, &buf, offset)A storage buffer, from offset: a multiple of 256
pass.vertices(slot, &buf, offset)A vertex or instance stream
pass.texture(slot, &tex, gpu.Sampler {})A texture and how it is sampled
pass.scissor(x, y, w, h)Draw only in this rectangle of the target: integer pixels (render passes)
pass.viewport(x, y, w, h, min_depth, max_depth)Map normalized device coordinates to this rectangle, and z to min_depth..max_depth (render passes)
pass.texture_table(slot, &table)A table of textures (Tables of textures)
pass.draw(vertices, instances)Draw (render passes)
pass.draw_from(first_vertex, vertices, first_instance, instances)Draw part of the bound streams
pass.dispatch(x, y, z)Run x * y * z workgroups (compute passes)
pass.dispatch_for(n)Enough workgroups of the shader’s size for n invocations in x
pass.end()End the pass
  • scissor and viewport count pixels from the target’s top left, y down, like read_frame and a texture’s rows, on every backend. Each pass starts with the whole target and depth 0..1; both may change between draws, and a clear at the pass’s start covers the whole target whatever follows. A scissor out of range is clamped to the target. A viewport partly off the target keeps its size and what falls off is clipped, so tiles of a bigger picture line up; it may be 16384 each way at most, between -32768 and 32767. Either with no pixel left draws nothing. A depth outside 0..1 stops the program; 1, 0 reverses the range.
  • Bindings and the uniforms hold for the draws after them until the next pipeline. Call uniforms_T before each draw to give each its own (blits, each with its rectangle); the struct may change at once.
  • One pass may draw with several pipelines; set the bindings again after each pipeline.
  • pass.indices(&buf, offset, gpu.IndexFormat.U16) (or U32) sets the index buffer, made with gpu.INDEX, from offset (a multiple of 4); pass.draw_indexed(indices, instances) draws with it, and pass.draw_indexed_from(first_index, indices, base_vertex, first_instance, instances) part of it, each index plus base_vertex (with U16, first_index is even). Set the indices after pipeline, as the bindings.
  • storage at an offset lets one buffer be two parameters: a header struct *Head at 0 and a []u32 at 256. The offset is a multiple of 256 on every backend, so a program behaves the same everywhere.
  • After a compute pass, everything it wrote is visible to what follows: vertex input, storage reads, reads back. gpu places the barriers.

Depth and several targets

dev.render_pass(colour, depth) begins a render pass into up to 8 colour targets and a depth target:

tape
pub struct Target {
    texture: ?*const Texture = null;   // null: the window (then the only colour target)
    clear: ?Vec4 = null;
}
pub struct DepthTarget {
    texture: *const Texture;           // a Depth32f texture
    clear: ?f32 = null;                // 1.0 for Compare.Less; 0.0 for reversed Z
}

dev.render(target, clear) is a pass with one colour target and no depth. Every target of a pass has one size: a depth texture beside the window is the window’s size, made again on Resize. A pixel stage writing several targets returns a struct of gpu.Vec4s (and gpu.UVec4s for integer targets), one field per target in order, and its pipeline names their formats in formats; a pixel stage returning nothing draws a depth-only pass (colour empty), a shadow map’s.

tape
import gpu from "gpu";

pub struct Gbuf { albedo: gpu.Vec4; normal: gpu.Vec4; }
pub struct U { mvp: gpu.Mat4; }

@tape { gpu.gen_uniforms(U); }

fn draw_scene(dev: *gpu.Device, mesh: *const gpu.Buffer, idx: *const gpu.Buffer, n: i64,
              albedo: *const gpu.Texture, normal: *const gpu.Texture, depth: *const gpu.Texture,
              u: *const U) -> void or gpu.GpuError {
    let p = dev.render_pipeline(&mesh_vs, &gbuf_ps, gpu.RenderOptions {
        formats: [gpu.Format.Rgba8, gpu.Format.Rgba16f];
        depth: gpu.DepthOptions { compare: gpu.Compare.Greater; };     // reversed Z
    }) or return;
    var rp = dev.render_pass([gpu.Target { texture: albedo; clear: gpu.splat4(0.0); },
                              gpu.Target { texture: normal; clear: gpu.splat4(0.0); }],
                             gpu.DepthTarget { texture: depth; clear: 0.0; });
    rp.pipeline(&p);
    uniforms_U(&rp, u);
    rp.vertices(p.slot("v"), mesh, 0);
    rp.indices(idx, 0, gpu.IndexFormat.U32);
    rp.draw_indexed(n, 1);
    rp.end();
}

fn main() -> i32 { return 0; }

#shader
import gpu from "gpu";

pub struct Vtx { pos: gpu.Vec4; normal: gpu.Vec4; }
pub struct Out { position: gpu.Vec4; normal: gpu.Vec4; }

vertex fn mesh_vs(v: Vtx, u: uniform U) -> Out {
    return Out { position: u.mvp * v.pos; normal: v.normal; };
}

pixel fn gbuf_ps(o: Out) -> Gbuf {
    return Gbuf { albedo: gpu.vec4(0.8, 0.8, 0.8, 1.0); normal: o.normal * 0.5 + gpu.splat4(0.5); };
}

Clip space z is 0 to 1 on every backend, so reversed Z (near at 1, far at 0, Compare.Greater, the depth cleared to 0) keeps a float depth buffer’s precision where dev.info().exact_depth is true: always on Metal and Vulkan, and on OpenGL with clip control (4.5, which current drivers have). The depth texture is then read like any other: sampled or loaded as a gpu.DepthTexture2D, or read back (depth.read(dev, out), an f32 a texel).

Multisampling

Multisampling smooths the edges of what is drawn: a pixel keeps several samples, a triangle covers some of them, and the pixel ends as their average. The pixel stage still runs once a pixel, so it costs memory and a little time, not shading.

The usual frame is a 4x colour texture and a 4x depth texture at the window’s size, resolved into the window as the pass ends:

tape
let scene = dev.render_pipeline(&vs, &ps, gpu.RenderOptions { samples: 4; depth: gpu.DepthOptions {}; }) or return;
var msaa = dev.texture_with(gpu.TextureOptions { width: w; height: h; format: gpu.Format.Bgra8; target: true; samples: 4; }) or return;
var depth = dev.texture_with(gpu.TextureOptions { width: w; height: h; format: gpu.Format.Depth32f; target: true; samples: 4; }) or return;

// each frame: when dev.size() has changed, release both and make them at the new size
var rp = dev.render_pass([gpu.Target { texture: &msaa; clear: ground; resolve_window: true; }],
                         gpu.DepthTarget { texture: &depth; clear: 1.0; });
rp.pipeline(&scene);
// ... draws ...
rp.end();
dev.present() or { ... };
tape
pub struct Target {
    // ...
    resolve: ?*const Texture = null;   // averaged into this texture at the pass's end
    resolve_window: bool = false;      // or into the window
}
  • TextureOptions.samples is 1, 2, 4 or 8. Past 1 the texture is 2D, one level, one layer, made with target: true, of a format a pass can draw into or Depth32f.
  • A multisampled texture is only drawn into. Sampling it, storage: true, read, read_level, write, write_level and generate_levels trap: read or sample its resolve target.
  • RenderOptions.samples is part of a pipeline’s shape: using it in a pass of another count stops the program, as another format does. A pass’s targets, colour and depth, have one count.
  • resolve is a single-sampled texture made with target: true, 2D, of the target’s format and size; its level 0 is replaced whole, whatever the scissor was. resolve_window wants a Bgra8 target at the window’s size. Either happens as the pass ends, whether it drew or not. Integer formats trap if resolved, and a depth target isn’t resolved.
  • The samples stay after a resolve, as anything a target holds does: a later pass with no clear goes on from them, and can resolve again.
  • dev.info().max_samples is the largest count every format has. A count the device lacks is GpuError.Unsupported when the texture or pipeline is made, naming the count and the backend; you never get fewer samples than you asked for. samples: 1 always works.
  • A pass into the window at one sample works as it always did.
  • Shaders don’t change. A stage can’t read a multisampled texture or run per sample.
  • A thin triangle can cover a sample while the pixel’s centre lies outside it, and a varying is then extrapolated, perhaps far out of its range: a colour that flashes through bloom at 4x and never at 1x. Mark such a field of the vertex output @centroid (#shader) to evaluate it at a point the triangle covers. It is explicit because ddx, ddy and fwidth of that field, and so a texture’s mip choice, become less accurate.

Errors

tape
pub enum Stage : u8 { Vertex = 0: "vertex"; Pixel = 1: "pixel"; Compute = 2: "compute"; }

pub tagged GpuError {
    Unsupported { what: string; }                 // the platform or driver lacks it
    NoDevice { reason: string; }                  // no GPU, no Vulkan 1.3 or OpenGL 4.3: what the system gave
    NoWindow;                                     // the window could not be made
    Compile { stage: Stage; log: string; }        // the driver rejected the shader's text
    Link { log: string; }                         // the pipeline could not be made
    OutOfMemory { what: string; }                 // "buffer of 536870912 bytes: ..."
    Lost { reason: string; }                      // the device was lost (driver reset, GPU removed)
}

err.desc() says it in a line: "no GPU device: ...", "pixel shader: the driver rejected it: ...". A shader you wrote wrong never gets this far: it is a compile error at its line. Compile means the driver refused what gpu made, a driver limit or a gpu bug, and carries the driver’s log.

Mistakes in the program trap, saying what was wrong:

  • a range outside a buffer or texture, or an out too small for a read;
  • write, clear or read inside a pass; a second pass begun while one is open; present, finish or read_frame with a pass open;
  • slot with a name the pipeline lacks; a slot of the wrong kind (storage with a texture’s slot);
  • a draw or dispatch with a slot or the uniforms never set (gpu: draw: "atlas" was not set);
  • uniforms of another struct than the pipeline’s, or of another size;
  • a storage offset that is not a multiple of 256;
  • draw on a compute pass, dispatch on a render pass, a compute pipeline in a render pass (or the reverse), a call on a pass that has ended;
  • a render pipeline whose vertex shader’s output is not its pixel shader’s input, or a name that is a different kind of resource in its two stages;
  • rendering into a texture made without target: true, or into the window of an offscreen device;
  • a pass’s targets of different sizes, a depth target that is not Depth32f, the window beside another colour target;
  • a pipeline in a pass of another shape (other target formats, a depth target or none), a pixel stage writing a different number of targets than formats names, an integer target written by a Vec4;
  • a texture of the wrong kind for its shader parameter (a Depth32f texture is a gpu.DepthTexture2D, an R32u one a gpu.UTexture2D, a 2D array a gpu.Texture2DArray, a 3D texture a gpu.Texture3D);
  • a level or layer the texture doesn’t have; generate_levels on an integer or depth texture; an anisotropy outside 1 to 16;
  • image with a texture not made with storage: true, or of another format than the shader’s image type;
  • an indirect draw or dispatch from a buffer without gpu.INDIRECT, an offset that is not a multiple of 4, records past the buffer’s end; an indexed indirect draw with the indices set at another offset than 0; draw_indirect_count where dev.info().indirect_count is false;
  • indices from a buffer without gpu.INDEX, or an offset that is not a multiple of 4; draw_indexed without indices or past their end;
  • a released buffer, texture or pipeline, or a closed device.

Reading results back

tape
import gpu from "gpu";
import io from "io";

fn sum_back(dev: *gpu.Device, vals: *const gpu.Buffer) -> void or gpu.GpuError {
    var out: [256]u32;
    vals.read(dev, 0, (&out[0] as *u8)[0..1024]) or return;     // waits for the work that used vals
    var total: u64 = 0;
    for (i in 0..256) { total = total + out[i] as u64; }
    io.println("sum {total}");
}

fn main() -> i32 { return 0; }

A frame’s GPU time comes a frame late: dev.gpu_ms() is the last finished frame’s, from its first pass to its present.

tape
import gpu from "gpu";

fn show_time(dev: *gpu.Device) {
    let ms = dev.gpu_ms() or { return; };
    dev.set_title("gpu {ms} ms");
}

fn main() -> i32 { return 0; }

Timing passes

A gpu.Timer measures the GPU’s time for the passes between its begin and end, in nanoseconds, and gives it a frame or two later without waiting:

CallDoes
dev.timer() -> Timer or GpuErrorA timer (Unsupported where dev.info().timers is false)
t.begin(dev), t.end(dev)Around passes, between them, never inside one
t.ns(dev) -> ?i64The newest finished measurement, null until one has finished
t.ready(dev) -> boolThe measurement ended last is in (always after dev.finish())
t.release(dev)Free it

On Vulkan with vsync on, a timer around the frame’s first pass into the window also counts the wait for the swapchain’s image: about a refresh, not the pass’s work. Time the work in passes into textures, or with vsync off, to measure it.

tape
import gpu from "gpu";
import io from "io";

fn frame(dev: *gpu.Device, shadow_t: *gpu.Timer, light_t: *gpu.Timer) -> void or gpu.GpuError {
    shadow_t.begin(dev);
    // ... the shadow passes
    shadow_t.end(dev);
    light_t.begin(dev);
    // ... the lighting pass
    light_t.end(dev);
    dev.present() or return;
    let s = shadow_t.ns(dev) or { return; };          // a frame or two late
    let l = light_t.ns(dev) or { return; };
    io.println("shadows {s / 1000} us, lighting {l / 1000} us");
}

fn main() -> i32 { return 0; }

Begin a timer each frame without reading it: four measurements can be in flight. Timers may nest (one around the frame, one per pass). On OpenGL a time runs from the GPU reaching begin to reaching end; on Metal it is the sum of the GPU times of the command buffers between them (begin and end each start a new one), so idle time between passes is not in it. Either is a pass’s cost to the microsecond, not to the nanosecond.

Last modified: