diff options
| author | Gabriel Schneider <[email protected]> | 2026-11-17 03:50:16 -0300 |
|---|---|---|
| committer | Gabriel Schneider <[email protected]> | 2026-11-17 12:15:01 -0300 |
| commit | df1d47d4fddd4165bdf511f4056d8075562a663e (patch) | |
| tree | dec3d7f7ad2d2d5f3a7fdfdb0be5167f2b973695 /src/gpu/Present.zig | |
| parent | 6af3c07190e7aec46596e00afb3c6b613c9e02eb (diff) | |
| download | sketchbook-df1d47d4fddd4165bdf511f4056d8075562a663e.tar.gz sketchbook-df1d47d4fddd4165bdf511f4056d8075562a663e.zip | |
Add pardes's presentation on SDL_GPU
Moved from pardes's src/gui/gui.zig (step S3 of moving its renderer
here): src/gpu/Present.zig, the device, the window's claim or a software
presenter through SDL_Renderer (a transparent window, which the GPU API
will not claim, or a claim refused), the present mode and frames in
flight, detach and attach for a window closed and opened again, the
frame's target (the swapchain's image, or a capture texture in test mode
and for the soft presenter), the soft present (the frame read back, put
in a streaming texture and flipped) and a captured frame's read back.
The window stays the embedder's and is passed in where it is used. What
pardes did inside these with its own state comes back instead: a soft
present's phase times (Timings), each presented frame's pixels through a
frame tap, a captured frame's mapped bytes and times (readFrame, then
releaseFrame) and their byte order (bgr). Present.zig imports the
embedder's SDL translation as `c` and Cells.zig as `gpu_cells`.
Diffstat (limited to 'src/gpu/Present.zig')
| -rw-r--r-- | src/gpu/Present.zig | 343 |
1 files changed, 343 insertions, 0 deletions
diff --git a/src/gpu/Present.zig b/src/gpu/Present.zig new file mode 100644 index 0000000..a6a2dbf --- /dev/null +++ b/src/gpu/Present.zig @@ -0,0 +1,343 @@ +//! pardes's presentation on SDL_GPU: the device, the window's claim (or a +//! software presenter where the GPU API will not take the window), the +//! present mode, the frame's target (the swapchain's image, or a capture +//! texture), the read back of a captured frame and the soft present, moved +//! from pardes's gui.zig as they were. The window is the embedder's, passed +//! in where it is used; `c` is the embedder's own SDL translation, so the +//! embedder's SDL is the one linked. +const std = @import("std"); +const c = @import("c"); +const Cells = @import("gpu_cells"); + +// pardes's scope, so its log reads as it did before the move. +const log = std.log.scoped(.gui); + +const Present = @This(); + +device: *c.SDL_GPUDevice, +swapchain_format: c.SDL_GPUTextureFormat, + +/// Test mode: every frame goes to the capture texture, read back, never +/// presented. +capture: bool = false, +capture_tex: ?*c.SDL_GPUTexture = null, +capture_tex_w: u32 = 0, +capture_tex_h: u32 = 0, +capture_xfer: ?*c.SDL_GPUTransferBuffer = null, +capture_xfer_size: u32 = 0, + +soft_present: bool = false, +surface_opacity: bool = false, +soft_renderer: ?*c.SDL_Renderer = null, +soft_texture: ?*c.SDL_Texture = null, +/// What a window is attached with again (attach). +present_mode: c.SDL_GPUPresentMode = c.SDL_GPU_PRESENTMODE_VSYNC, +soft_tex_w: u32 = 0, +soft_tex_h: u32 = 0, + +/// The device for `window`, which it claims, or a software presenter when +/// `surface_opacity` (a transparent window, which the GPU API will not +/// claim) or the claim fails. `test_mode` renders every frame into the +/// capture texture. +pub fn init(window: *c.SDL_Window, test_mode: bool, surface_opacity: bool) !Present { + const device = c.SDL_CreateGPUDevice(c.SDL_GPU_SHADERFORMAT_SPIRV, true, null) orelse { + log.err("SDL_CreateGPUDevice: {s}", .{c.SDL_GetError()}); + return error.SdlInit; + }; + errdefer c.SDL_DestroyGPUDevice(device); + var soft_present = false; + var soft_renderer: ?*c.SDL_Renderer = null; + if (surface_opacity or !c.SDL_ClaimWindowForGPUDevice(device, window)) { + if (surface_opacity) + log.info("transparent window: the GPU API will not claim one, presenting through SDL_Renderer", .{}) + else + log.warn("ClaimWindowForGPUDevice: {s}; presenting in software", .{c.SDL_GetError()}); + soft_renderer = c.SDL_CreateRenderer(window, null) orelse { + log.err("SDL_CreateRenderer: {s}", .{c.SDL_GetError()}); + return error.SdlInit; + }; + soft_present = true; + } + const present_mode: c.SDL_GPUPresentMode = blk: { + if (soft_present) break :blk c.SDL_GPU_PRESENTMODE_VSYNC; + for ([_]c.SDL_GPUPresentMode{ c.SDL_GPU_PRESENTMODE_IMMEDIATE, c.SDL_GPU_PRESENTMODE_MAILBOX, c.SDL_GPU_PRESENTMODE_VSYNC }) |mode| { + if (c.SDL_WindowSupportsGPUPresentMode(device, window, mode)) break :blk mode; + } + break :blk c.SDL_GPU_PRESENTMODE_VSYNC; + }; + if (!test_mode) _ = c.SDL_SetGPUAllowedFramesInFlight(device, 1); + if (!soft_present) { + _ = c.SDL_SetGPUSwapchainParameters(device, window, c.SDL_GPU_SWAPCHAINCOMPOSITION_SDR, present_mode); + } + const swapchain_format = if (soft_present) + softTargetFormat(device) + else + c.SDL_GetGPUSwapchainTextureFormat(device, window); + return .{ + .device = device, + .swapchain_format = swapchain_format, + .capture = test_mode, + .soft_present = soft_present, + .surface_opacity = surface_opacity, + .soft_renderer = soft_renderer, + .present_mode = present_mode, + }; +} + +/// The capture's texture and transfer buffer, and the device, let go: what +/// was made on the device is released first. +pub fn deinit(p: *Present) void { + if (p.capture_tex) |texture| c.SDL_ReleaseGPUTexture(p.device, texture); + if (p.capture_xfer) |transfer| c.SDL_ReleaseGPUTransferBuffer(p.device, transfer); + c.SDL_DestroyGPUDevice(p.device); +} + +/// The window is closing: its renderer (and the soft texture) or its claim +/// let go; the device stays for the next window (attach). +pub fn detach(p: *Present, window: *c.SDL_Window) void { + if (p.soft_renderer) |renderer| { + if (p.soft_texture) |texture| c.SDL_DestroyTexture(texture); + p.soft_texture = null; + p.soft_tex_w = 0; + p.soft_tex_h = 0; + c.SDL_DestroyRenderer(renderer); + p.soft_renderer = null; + } else c.SDL_ReleaseWindowFromGPUDevice(p.device, window); +} + +/// A new window presented to as the first was: false when it will not take +/// a renderer or the claim (the caller destroys it). +pub fn attach(p: *Present, window: *c.SDL_Window) bool { + if (p.soft_present) { + p.soft_renderer = c.SDL_CreateRenderer(window, null) orelse return false; + } else { + if (!c.SDL_ClaimWindowForGPUDevice(p.device, window)) return false; + _ = c.SDL_SetGPUSwapchainParameters(p.device, window, c.SDL_GPU_SWAPCHAINCOMPOSITION_SDR, p.present_mode); + } + return true; +} + +pub const Target = struct { texture: *c.SDL_GPUTexture, w: u32, h: u32 }; + +/// What this frame draws into: the capture texture in test mode (the grid's +/// size plus PARDES_TEST_PAD) or with a soft presenter, else the swapchain's +/// image; null when there is none to be had this time. +pub fn acquireTarget(p: *Present, cmd: *c.SDL_GPUCommandBuffer, window: *c.SDL_Window, capture_w: u32, capture_h: u32) !?Target { + if (p.capture) { + if (capture_w == 0 or capture_h == 0) return null; + try p.ensureCaptureTexture(capture_w, capture_h); + return .{ .texture = p.capture_tex.?, .w = capture_w, .h = capture_h }; + } + if (p.soft_present) { + var pw: c_int = 0; + var ph: c_int = 0; + if (!c.SDL_GetWindowSizeInPixels(window, &pw, &ph) or pw <= 0 or ph <= 0) return null; + try p.ensureCaptureTexture(@intCast(pw), @intCast(ph)); + return .{ .texture = p.capture_tex.?, .w = @intCast(pw), .h = @intCast(ph) }; + } + var swap_tex: ?*c.SDL_GPUTexture = null; + var sw: u32 = 0; + var sh: u32 = 0; + if (!c.SDL_AcquireGPUSwapchainTexture(cmd, window, &swap_tex, &sw, &sh)) return null; + // A busy swapchain skips the frame. + return .{ .texture = swap_tex orelse return null, .w = sw, .h = sh }; +} + +/// What a soft present's phases took, ns: the wait for the GPU, the frame's +/// upload (to the end of the present) and the flip. +pub const Timings = struct { wait_ns: u64 = 0, upload_ns: u64 = 0, flip_ns: u64 = 0 }; + +/// Submits the frame: handed to the soft presenter (`took` its phases, +/// `frame_tap` its pixels as they go out), or presented. A capture's frame +/// is read back instead (readFrame). +pub fn finishFrame( + p: *Present, + cmd: *c.SDL_GPUCommandBuffer, + target: Target, + frame_tap: *const fn (pixels: []const u8, w: u32, h: u32) void, + took: *Timings, +) !bool { + if (p.soft_present) { + took.* = try p.softPresentFrame(cmd, target.texture, target.w, target.h, frame_tap); + return true; + } + return c.SDL_SubmitGPUCommandBuffer(cmd); +} + +fn ensureCaptureTexture(p: *Present, width: u32, height: u32) !void { + if (p.capture_tex != null and p.capture_tex_w == width and p.capture_tex_h == height) return; + const next = Cells.texture2d(p.device, p.swapchain_format, c.SDL_GPU_TEXTUREUSAGE_COLOR_TARGET, width, height) orelse return error.GpuCreate; + if (p.capture_tex) |texture| c.SDL_ReleaseGPUTexture(p.device, texture); + p.capture_tex = next; + p.capture_tex_w = width; + p.capture_tex_h = height; +} + +fn softTargetFormat(device: *c.SDL_GPUDevice) c.SDL_GPUTextureFormat { + const candidates = [_]c.SDL_GPUTextureFormat{ + c.SDL_GPU_TEXTUREFORMAT_B8G8R8A8_UNORM, + c.SDL_GPU_TEXTUREFORMAT_R8G8B8A8_UNORM, + }; + for (candidates) |format| { + if (c.SDL_GPUTextureSupportsFormat( + device, + format, + c.SDL_GPU_TEXTURETYPE_2D, + c.SDL_GPU_TEXTUREUSAGE_COLOR_TARGET | c.SDL_GPU_TEXTUREUSAGE_SAMPLER, + )) return format; + } + return c.SDL_GPU_TEXTUREFORMAT_B8G8R8A8_UNORM; +} + +fn softPixelFormat(format: c.SDL_GPUTextureFormat) ?c.SDL_PixelFormat { + return switch (format) { + c.SDL_GPU_TEXTUREFORMAT_B8G8R8A8_UNORM, + c.SDL_GPU_TEXTUREFORMAT_B8G8R8A8_UNORM_SRGB, + => c.SDL_PIXELFORMAT_ARGB8888, + c.SDL_GPU_TEXTUREFORMAT_R8G8B8A8_UNORM, + c.SDL_GPU_TEXTUREFORMAT_R8G8B8A8_UNORM_SRGB, + => c.SDL_PIXELFORMAT_ABGR8888, + else => null, + }; +} + +fn ensureSoftTexture(p: *Present, width: u32, height: u32) !*c.SDL_Texture { + if (p.soft_texture) |texture| { + if (p.soft_tex_w == width and p.soft_tex_h == height) return texture; + c.SDL_DestroyTexture(texture); + p.soft_texture = null; + } + const renderer = p.soft_renderer orelse return error.GpuCreate; + const pixel_format = softPixelFormat(p.swapchain_format) orelse return error.UnsupportedCaptureFormat; + const next = c.SDL_CreateTexture( + renderer, + pixel_format, + c.SDL_TEXTUREACCESS_STREAMING, + @intCast(width), + @intCast(height), + ) orelse return error.GpuCreate; + _ = c.SDL_SetTextureScaleMode(next, c.SDL_SCALEMODE_NEAREST); + _ = c.SDL_SetTextureBlendMode(next, c.SDL_BLENDMODE_NONE); + p.soft_texture = next; + p.soft_tex_w = width; + p.soft_tex_h = height; + return next; +} + +/// The frame in `target`, `size` bytes, copied down into `capture_xfer` +/// (grown to it first) by `cmd`, which the caller submits and waits for. +/// With no buffer to be had the command buffer is submitted as it is. +fn downloadTarget(p: *Present, cmd: *c.SDL_GPUCommandBuffer, target: *c.SDL_GPUTexture, sw: u32, sh: u32, size: u32) !*c.SDL_GPUTransferBuffer { + if (p.capture_xfer == null or p.capture_xfer_size < size) { + var info = c.SDL_GPUTransferBufferCreateInfo{ .usage = c.SDL_GPU_TRANSFERBUFFERUSAGE_DOWNLOAD, .size = size, .props = 0 }; + const next = c.SDL_CreateGPUTransferBuffer(p.device, &info) orelse { + _ = c.SDL_SubmitGPUCommandBuffer(cmd); + return error.GpuCreate; + }; + if (p.capture_xfer) |transfer| c.SDL_ReleaseGPUTransferBuffer(p.device, transfer); + p.capture_xfer = next; + p.capture_xfer_size = size; + } + const xfer = p.capture_xfer.?; + const copy = c.SDL_BeginGPUCopyPass(cmd); + const src = c.SDL_GPUTextureRegion{ .texture = target, .mip_level = 0, .layer = 0, .x = 0, .y = 0, .z = 0, .w = sw, .h = sh, .d = 1 }; + const dst = c.SDL_GPUTextureTransferInfo{ .transfer_buffer = xfer, .offset = 0, .pixels_per_row = sw, .rows_per_layer = sh }; + c.SDL_DownloadFromGPUTexture(copy, &src, &dst); + c.SDL_EndGPUCopyPass(copy); + return xfer; +} + +fn softPresentFrame(p: *Present, cmd: *c.SDL_GPUCommandBuffer, target: *c.SDL_GPUTexture, sw: u32, sh: u32, frame_tap: *const fn (pixels: []const u8, w: u32, h: u32) void) !Timings { + const bpp = c.SDL_GPUTextureFormatTexelBlockSize(p.swapchain_format); + const size = c.SDL_CalculateGPUTextureFormatSize(p.swapchain_format, sw, sh, 1); + if (size == 0 or bpp != 4) { + _ = c.SDL_SubmitGPUCommandBuffer(cmd); + return error.UnsupportedCaptureFormat; + } + const xfer = try p.downloadTarget(cmd, target, sw, sh, size); + + const fence = c.SDL_SubmitGPUCommandBufferAndAcquireFence(cmd) orelse return error.GpuSubmit; + defer c.SDL_ReleaseGPUFence(p.device, fence); + var fences = [_]*c.SDL_GPUFence{fence}; + const probe_wait = monoNs(); + if (!c.SDL_WaitForGPUFences(p.device, true, &fences, 1)) return error.GpuSubmit; + const wait_ns = monoNs() -| probe_wait; + + const mapped = c.SDL_MapGPUTransferBuffer(p.device, xfer, false) orelse return error.GpuMap; + defer c.SDL_UnmapGPUTransferBuffer(p.device, xfer); + + const texture = try p.ensureSoftTexture(sw, sh); + const renderer = p.soft_renderer orelse return error.GpuCreate; + const probe_upload = monoNs(); + if (!c.SDL_UpdateTexture(texture, null, mapped, @intCast(sw * bpp))) return error.GpuMap; + // PARDES_FRAMES_CAPTURE: every presented frame's pixels as they went + // out, and when, for a recording at the frames' own times. One write a + // frame; nothing else. + frame_tap(@as([*]const u8, @ptrCast(mapped))[0..size], sw, sh); + // The cell shader already produced premultiplied backgrounds with opaque + // foreground ink. Copy that alpha unchanged; never modulate the full frame. + _ = c.SDL_SetRenderDrawBlendMode(renderer, c.SDL_BLENDMODE_NONE); + _ = c.SDL_SetRenderDrawColor(renderer, 0, 0, 0, if (p.surface_opacity) 0 else 255); + _ = c.SDL_RenderClear(renderer); + _ = c.SDL_RenderTexture(renderer, texture, null, null); + const probe_flip = monoNs(); + _ = c.SDL_RenderPresent(renderer); + const end = monoNs(); + return .{ .wait_ns = wait_ns, .upload_ns = end -| probe_upload, .flip_ns = end -| probe_flip }; +} + +/// A captured frame read back (readFrame): its bytes, mapped until +/// releaseFrame, and when it was submitted and its fence passed +/// (CLOCK_MONOTONIC ns). +pub const Frame = struct { + pixels: []const u8, + xfer: *c.SDL_GPUTransferBuffer, + fence: *c.SDL_GPUFence, + submit_ns: u64, + fence_ns: u64, +}; + +/// Submits the frame, waits for it and maps it, read back into the capture +/// transfer buffer. +pub fn readFrame(p: *Present, cmd: *c.SDL_GPUCommandBuffer, target: *c.SDL_GPUTexture, sw: u32, sh: u32) !Frame { + const size = c.SDL_CalculateGPUTextureFormatSize(p.swapchain_format, sw, sh, 1); + if (size == 0) { + _ = c.SDL_SubmitGPUCommandBuffer(cmd); + return error.UnsupportedCaptureFormat; + } + const xfer = try p.downloadTarget(cmd, target, sw, sh, size); + + const submit_ns = monoNs(); + const fence = c.SDL_SubmitGPUCommandBufferAndAcquireFence(cmd) orelse return error.GpuSubmit; + errdefer c.SDL_ReleaseGPUFence(p.device, fence); + var fences = [_]*c.SDL_GPUFence{fence}; + if (!c.SDL_WaitForGPUFences(p.device, true, &fences, 1)) return error.GpuSubmit; + const fence_ns = monoNs(); + + const mapped = c.SDL_MapGPUTransferBuffer(p.device, xfer, false) orelse return error.GpuMap; + const pixels: [*]const u8 = @ptrCast(mapped); + return .{ .pixels = pixels[0..size], .xfer = xfer, .fence = fence, .submit_ns = submit_ns, .fence_ns = fence_ns }; +} + +/// The frame readFrame mapped let go: unmapped, then its fence released. +pub fn releaseFrame(p: *Present, frame: Frame) void { + c.SDL_UnmapGPUTransferBuffer(p.device, frame.xfer); + c.SDL_ReleaseGPUFence(p.device, frame.fence); +} + +/// Whether a frame read back is B, G, R, A in memory (else R, G, B, A). +pub fn bgr(p: *const Present) !bool { + const bpp = c.SDL_GPUTextureFormatTexelBlockSize(p.swapchain_format); + if (bpp != 4) return error.UnsupportedCaptureFormat; + return switch (p.swapchain_format) { + c.SDL_GPU_TEXTUREFORMAT_R8G8B8A8_UNORM, c.SDL_GPU_TEXTUREFORMAT_R8G8B8A8_UNORM_SRGB => false, + c.SDL_GPU_TEXTUREFORMAT_B8G8R8A8_UNORM, c.SDL_GPU_TEXTUREFORMAT_B8G8R8A8_UNORM_SRGB => true, + else => error.UnsupportedCaptureFormat, + }; +} + +fn monoNs() u64 { + var ts: std.c.timespec = undefined; + if (std.c.clock_gettime(.MONOTONIC, &ts) != 0) return 0; + return @as(u64, @intCast(ts.sec)) * std.time.ns_per_s + @as(u64, @intCast(ts.nsec)); +} |
