diff options
Diffstat (limited to 'src/gpu')
| -rw-r--r-- | src/gpu/Cells.zig | 452 | ||||
| -rw-r--r-- | src/gpu/Present.zig | 343 |
2 files changed, 790 insertions, 5 deletions
diff --git a/src/gpu/Cells.zig b/src/gpu/Cells.zig index 78d7f22..9ed1741 100644 --- a/src/gpu/Cells.zig +++ b/src/gpu/Cells.zig @@ -1,10 +1,452 @@ -//! pardes's cell renderer on SDL_GPU, part 1: the shaders' instance ABI -//! (src/gpu/shaders/*.glsl), the pipelines over it and the resource helpers, -//! moved from pardes's gui.zig as they were. `c` is the embedder's own SDL -//! translation (pardes's: SDL3 and font.h), so the embedder's SDL is the one -//! linked. +//! pardes's cell renderer on SDL_GPU: the shaders' instance ABI +//! (src/gpu/shaders/*.glsl), the pipelines over it, the glyph atlas's +//! texture and its upload, the pictures' textures and their draws, the +//! overlay's triangles, a frame's uploads and its render pass, and the +//! resource helpers, moved from pardes's +//! gui.zig as they were. `c` is the embedder's own SDL translation (pardes's: +//! SDL3 and font.h), so the embedder's SDL is the one linked; the SPIR-V is +//! the build's (`<name>.spv` imports, from src/gpu/shaders/). const std = @import("std"); const c = @import("c"); +const Atlas = @import("font_atlas"); + +const Cells = @This(); + +/// The embedder's device (Present's), which everything here is made on. +device: *c.SDL_GPUDevice, +/// What every pipeline draws into: the swapchain's format. +format: c.SDL_GPUTextureFormat, +pipeline: *c.SDL_GPUGraphicsPipeline, +decor_pipeline: *c.SDL_GPUGraphicsPipeline, +overlay_pipeline: *c.SDL_GPUGraphicsPipeline, +image_pipeline: *c.SDL_GPUGraphicsPipeline, +/// Premultiplied pictures' (an addon's), made on first use +/// (makeAddonPipeline). +addon_pipeline: ?*c.SDL_GPUGraphicsPipeline = null, +atlas_tex: *c.SDL_GPUTexture, +atlas_sampler: *c.SDL_GPUSampler, +linear_sampler: *c.SDL_GPUSampler, +atlas_xfer: *c.SDL_GPUTransferBuffer, +vbuf: ?*c.SDL_GPUBuffer = null, +vxfer: ?*c.SDL_GPUTransferBuffer = null, +vbuf_cells: u32 = 0, +overlay_vbuf: *c.SDL_GPUBuffer, +overlay_vxfer: *c.SDL_GPUTransferBuffer, +image_vbuf: ?*c.SDL_GPUBuffer = null, +image_vxfer: ?*c.SDL_GPUTransferBuffer = null, +image_capacity: u32 = 0, +/// The textures of the pictures shown, by key (image). +native_images: std.AutoHashMapUnmanaged(u64, *c.SDL_GPUTexture) = .empty, +/// The frame's pictures, instance by instance (mapImages, drawImages). +images: std.ArrayListUnmanaged(ImageDraw) = .empty, + +const vert_spv = @embedFile("ui.vert.spv"); +const frag_spv = @embedFile("ui.frag.spv"); +const decor_frag_spv = @embedFile("decor.frag.spv"); +const overlay_vert_spv = @embedFile("overlay.vert.spv"); +const overlay_frag_spv = @embedFile("overlay.frag.spv"); +const image_vert_spv = @embedFile("image.vert.spv"); +const image_frag_spv = @embedFile("image.frag.spv"); + +/// The atlas's texture, sampler and upload buffer, the pictures' sampler, +/// the four pipelines drawing into `swapchain_format`, and the overlay's +/// buffers, `max_overlay_vertices` long, made on `device`. +pub fn init(device: *c.SDL_GPUDevice, swapchain_format: c.SDL_GPUTextureFormat, max_overlay_vertices: usize) !Cells { + const atlas_tex = texture2d(device, c.SDL_GPU_TEXTUREFORMAT_R8_UNORM, c.SDL_GPU_TEXTUREUSAGE_SAMPLER, Atlas.atlas_w, Atlas.atlas_h) orelse return error.GpuCreate; + + var samp_info = std.mem.zeroes(c.SDL_GPUSamplerCreateInfo); + samp_info.min_filter = c.SDL_GPU_FILTER_NEAREST; + samp_info.mag_filter = c.SDL_GPU_FILTER_NEAREST; + samp_info.mipmap_mode = c.SDL_GPU_FILTER_NEAREST; + samp_info.address_mode_u = c.SDL_GPU_SAMPLERADDRESSMODE_CLAMP_TO_EDGE; + samp_info.address_mode_v = c.SDL_GPU_SAMPLERADDRESSMODE_CLAMP_TO_EDGE; + samp_info.address_mode_w = c.SDL_GPU_SAMPLERADDRESSMODE_CLAMP_TO_EDGE; + const atlas_sampler = c.SDL_CreateGPUSampler(device, &samp_info) orelse return error.GpuCreate; + samp_info.min_filter = c.SDL_GPU_FILTER_LINEAR; + samp_info.mag_filter = c.SDL_GPU_FILTER_LINEAR; + samp_info.mipmap_mode = c.SDL_GPU_FILTER_LINEAR; + const linear_sampler = c.SDL_CreateGPUSampler(device, &samp_info) orelse return error.GpuCreate; + + var ax_info = c.SDL_GPUTransferBufferCreateInfo{ .usage = c.SDL_GPU_TRANSFERBUFFERUSAGE_UPLOAD, .size = Atlas.atlas_w * Atlas.atlas_h, .props = 0 }; + const atlas_xfer = c.SDL_CreateGPUTransferBuffer(device, &ax_info) orelse return error.GpuCreate; + + const pipeline = try makePipeline(device, swapchain_format, vert_spv, frag_spv, 1, 1, cell_input, std.mem.zeroes(c.SDL_GPUColorTargetBlendState)); + const decor_pipeline = try makePipeline(device, swapchain_format, vert_spv, decor_frag_spv, 0, 1, cell_input, backgroundLayerBlend()); + const overlay_pipeline = try makePipeline(device, swapchain_format, overlay_vert_spv, overlay_frag_spv, 0, 1, overlay_input, backgroundLayerBlend()); + const image_pipeline = try makePipeline(device, swapchain_format, image_vert_spv, image_frag_spv, 1, 1, image_input, backgroundLayerBlend()); + + const overlay_buffer_size: u32 = @intCast(max_overlay_vertices * @sizeOf(OverlayVertex)); + var ovb_info = c.SDL_GPUBufferCreateInfo{ .usage = c.SDL_GPU_BUFFERUSAGE_VERTEX, .size = overlay_buffer_size, .props = 0 }; + const overlay_vbuf = c.SDL_CreateGPUBuffer(device, &ovb_info) orelse return error.GpuCreate; + var ovx_info = c.SDL_GPUTransferBufferCreateInfo{ .usage = c.SDL_GPU_TRANSFERBUFFERUSAGE_UPLOAD, .size = overlay_buffer_size, .props = 0 }; + const overlay_vxfer = c.SDL_CreateGPUTransferBuffer(device, &ovx_info) orelse return error.GpuCreate; + + return .{ + .device = device, + .format = swapchain_format, + .pipeline = pipeline, + .decor_pipeline = decor_pipeline, + .overlay_pipeline = overlay_pipeline, + .image_pipeline = image_pipeline, + .atlas_tex = atlas_tex, + .atlas_sampler = atlas_sampler, + .linear_sampler = linear_sampler, + .atlas_xfer = atlas_xfer, + .overlay_vbuf = overlay_vbuf, + .overlay_vxfer = overlay_vxfer, + }; +} + +/// The pipelines, textures and buffers, whatever they were regrown to, and +/// the pictures' textures let go (the device stays: Present's). +pub fn deinit(cells: *Cells, gpa: std.mem.Allocator) void { + const device = cells.device; + c.SDL_ReleaseGPUGraphicsPipeline(device, cells.image_pipeline); + if (cells.addon_pipeline) |pipeline_| c.SDL_ReleaseGPUGraphicsPipeline(device, pipeline_); + cells.clearImages(); + cells.native_images.deinit(gpa); + cells.images.deinit(gpa); + c.SDL_ReleaseGPUGraphicsPipeline(device, cells.pipeline); + c.SDL_ReleaseGPUGraphicsPipeline(device, cells.decor_pipeline); + c.SDL_ReleaseGPUGraphicsPipeline(device, cells.overlay_pipeline); + c.SDL_ReleaseGPUTexture(device, cells.atlas_tex); + c.SDL_ReleaseGPUSampler(device, cells.atlas_sampler); + c.SDL_ReleaseGPUSampler(device, cells.linear_sampler); + c.SDL_ReleaseGPUTransferBuffer(device, cells.atlas_xfer); + c.SDL_ReleaseGPUBuffer(device, cells.overlay_vbuf); + c.SDL_ReleaseGPUTransferBuffer(device, cells.overlay_vxfer); + if (cells.vbuf) |buffer| c.SDL_ReleaseGPUBuffer(device, buffer); + if (cells.vxfer) |transfer| c.SDL_ReleaseGPUTransferBuffer(device, transfer); + if (cells.image_vbuf) |buffer| c.SDL_ReleaseGPUBuffer(device, buffer); + if (cells.image_vxfer) |transfer| c.SDL_ReleaseGPUTransferBuffer(device, transfer); +} + +/// The pipeline of premultiplied pictures (an addon's GPU scene), made the +/// first time one is drawn. +pub fn makeAddonPipeline(cells: *Cells) !void { + if (cells.addon_pipeline != null) return; + var blend = backgroundLayerBlend(); + blend.src_color_blendfactor = c.SDL_GPU_BLENDFACTOR_ONE; + cells.addon_pipeline = try makePipeline(cells.device, cells.format, image_vert_spv, image_frag_spv, 1, 1, image_input, blend); +} + +/// What one group draws, in this order: its cells, its images, then its +/// decor. +pub const Group = struct { + cell_start: u32 = 0, + cell_count: u32 = 0, + image_start: u32 = 0, + image_count: u32 = 0, + decor_start: u32 = 0, + decor_count: u32 = 0, +}; + +/// The frame's command buffer: null when the device gives none. +pub fn begin(cells: *Cells) ?*c.SDL_GPUCommandBuffer { + return c.SDL_AcquireGPUCommandBuffer(cells.device); +} + +/// A frame given up: what it recorded so far is submitted, nothing drawn. +pub fn submit(cmd: *c.SDL_GPUCommandBuffer) void { + _ = c.SDL_SubmitGPUCommandBuffer(cmd); +} + +/// The frame's cell and decor instances, room for `n`, mapped for the +/// caller to write; uploadCells sends them. Null when the buffer will not +/// map. +pub fn mapCells(cells: *Cells, n: u32) !?[*]CellInstance { + try growInstances(cells.device, &cells.vbuf, &cells.vxfer, &cells.vbuf_cells, n, @sizeOf(CellInstance)); + const vptr: [*]u8 = @ptrCast(c.SDL_MapGPUTransferBuffer(cells.device, cells.vxfer.?, false) orelse return null); + return @ptrCast(@alignCast(vptr)); +} + +/// The first `n` instances mapCells gave, sent after the atlas's rows drawn +/// since the last upload (uploadAtlas). +pub fn uploadCells(cells: *Cells, cmd: *c.SDL_GPUCommandBuffer, n: u32, atlas: *Atlas) void { + c.SDL_UnmapGPUTransferBuffer(cells.device, cells.vxfer.?); + + if (atlas.atlas_dirty_top < atlas.atlas_dirty_bottom) cells.uploadAtlas(cmd, atlas); + + const copy = c.SDL_BeginGPUCopyPass(cmd); + const src = c.SDL_GPUTransferBufferLocation{ .transfer_buffer = cells.vxfer.?, .offset = 0 }; + const dst = c.SDL_GPUBufferRegion{ .buffer = cells.vbuf.?, .offset = 0, .size = n * @sizeOf(CellInstance) }; + c.SDL_UploadToGPUBuffer(copy, &src, &dst, false); + c.SDL_EndGPUCopyPass(copy); +} + +/// The frame's render pass into `target`, `sw` by `sh`, cleared to `clear`: +/// group by group, bottom to top, its cells (the first group's followed by +/// a scroll's `shifted` rows, after the `cell_total` instances, clipped to +/// `scroll_clip`), its pictures and its decor (after the shifted rows), at +/// the layer opacity `opacity`, the `ink` group's decor at 1; then the +/// overlay's first `overlay_count` vertices. +pub fn record( + cells: *Cells, + cmd: *c.SDL_GPUCommandBuffer, + target: *c.SDL_GPUTexture, + sw: u32, + sh: u32, + clear: c.SDL_FColor, + opacity: f32, + groups: []const Group, + ink: usize, + cell_total: u32, + shifted: u32, + scroll_clip: c.SDL_Rect, + overlay_count: u32, +) void { + var color_target = std.mem.zeroes(c.SDL_GPUColorTargetInfo); + color_target.texture = target; + color_target.clear_color = clear; + color_target.load_op = c.SDL_GPU_LOADOP_CLEAR; + color_target.store_op = c.SDL_GPU_STOREOP_STORE; + + const rp = c.SDL_BeginGPURenderPass(cmd, &color_target, 1, null); + pushLayerOpacity(cmd, rp, opacity); + const whole = c.SDL_Rect{ .x = 0, .y = 0, .w = @intCast(sw), .h = @intCast(sh) }; + const decor_base = cell_total + shifted; + for (groups, 0..) |group, index| { + const has_shifted = index == 0 and shifted != 0; + if ((group.cell_count != 0 or has_shifted) and cells.vbuf != null) { + c.SDL_BindGPUGraphicsPipeline(rp, cells.pipeline); + const samp_binding = c.SDL_GPUTextureSamplerBinding{ .texture = cells.atlas_tex, .sampler = cells.atlas_sampler }; + c.SDL_BindGPUFragmentSamplers(rp, 0, &samp_binding, 1); + if (group.cell_count != 0) { + const binding = c.SDL_GPUBufferBinding{ .buffer = cells.vbuf.?, .offset = group.cell_start * @sizeOf(CellInstance) }; + c.SDL_BindGPUVertexBuffers(rp, 0, &binding, 1); + c.SDL_DrawGPUPrimitives(rp, 6, group.cell_count, 0, 0); + } + if (has_shifted) { + c.SDL_SetGPUScissor(rp, &scroll_clip); + const binding = c.SDL_GPUBufferBinding{ .buffer = cells.vbuf.?, .offset = cell_total * @sizeOf(CellInstance) }; + c.SDL_BindGPUVertexBuffers(rp, 0, &binding, 1); + c.SDL_DrawGPUPrimitives(rp, 6, shifted, 0, 0); + c.SDL_SetGPUScissor(rp, &whole); + } + } + if (group.image_count != 0) cells.drawImages(rp, group.image_start, group.image_count, whole); + if (group.decor_count != 0 and cells.vbuf != null) { + c.SDL_BindGPUGraphicsPipeline(rp, cells.decor_pipeline); + // Ink keeps its colour at any WindowOpacity. + pushLayerOpacity(cmd, rp, if (index == ink) 1 else opacity); + const binding = c.SDL_GPUBufferBinding{ .buffer = cells.vbuf.?, .offset = (decor_base + group.decor_start) * @sizeOf(CellInstance) }; + c.SDL_BindGPUVertexBuffers(rp, 0, &binding, 1); + c.SDL_DrawGPUPrimitives(rp, 6, group.decor_count, 0, 0); + } + } + cells.drawOverlay(cmd, rp, overlay_count, opacity); + c.SDL_EndGPURenderPass(rp); +} + +/// Uploads only the atlas rows drawn into since the last upload. Glyphs fill +/// the atlas pen-style, a band of rows at a time, so new glyphs are a band a +/// cell or two tall, not the whole 4 MB texture. The band sits at the same +/// offset in the transfer buffer as in the stage, and the texture keeps the +/// rows outside it. +fn uploadAtlas(cells: *Cells, cmd: *c.SDL_GPUCommandBuffer, atlas: *Atlas) void { + const atlas_w = Atlas.atlas_w; + const top = atlas.atlas_dirty_top; + const rows = atlas.atlas_dirty_bottom - top; + const ptr = c.SDL_MapGPUTransferBuffer(cells.device, cells.atlas_xfer, false) orelse return; + const dst: [*]u8 = @ptrCast(ptr); + @memcpy(dst[top * atlas_w ..][0 .. rows * atlas_w], atlas.atlas_stage[top * atlas_w ..][0 .. rows * atlas_w]); + c.SDL_UnmapGPUTransferBuffer(cells.device, cells.atlas_xfer); + + const copy = c.SDL_BeginGPUCopyPass(cmd); + const src = c.SDL_GPUTextureTransferInfo{ .transfer_buffer = cells.atlas_xfer, .offset = top * atlas_w, .pixels_per_row = atlas_w, .rows_per_layer = rows }; + const dstregion = c.SDL_GPUTextureRegion{ .texture = cells.atlas_tex, .mip_level = 0, .layer = 0, .x = 0, .y = top, .z = 0, .w = atlas_w, .h = rows, .d = 1 }; + c.SDL_UploadToGPUTexture(copy, &src, &dstregion, false); + c.SDL_EndGPUCopyPass(copy); + atlas.atlas_dirty_top = Atlas.atlas_h; + atlas.atlas_dirty_bottom = 0; +} + +/// A picture of the frame: its texture (one of `native_images`, or the +/// caller's, borrowed: an addon's, premultiplied) and the target rectangle +/// it is clipped to. +pub const ImageDraw = struct { + premultiplied: bool = false, + texture: *c.SDL_GPUTexture, + clip: c.SDL_Rect, +}; + +/// Rows of a picture that alone differ from the picture under the key +/// `from` (image). +pub const Dirty = struct { from: u64, y: u32, h: u32 }; + +pub fn releaseImage(cells: *Cells, key: u64) void { + if (cells.native_images.fetchRemove(key)) |removed| + c.SDL_ReleaseGPUTexture(cells.device, removed.value); +} + +pub fn clearImages(cells: *Cells) void { + var iterator = cells.native_images.valueIterator(); + while (iterator.next()) |texture| c.SDL_ReleaseGPUTexture(cells.device, texture.*); + cells.native_images.clearRetainingCapacity(); +} + +/// The texture of the picture `key`, `w` by `h` RGBA pixels in `rgba`, a +/// row `stride` bytes: uploaded unless it is held already, or, where +/// `dirty_rows` names a picture held, only those rows written into that +/// picture's texture, which takes the new key. +pub fn image( + cells: *Cells, + gpa: std.mem.Allocator, + cmd: *c.SDL_GPUCommandBuffer, + key: u64, + rgba: []const u8, + w: u32, + h: u32, + stride: u32, + dirty_rows: ?Dirty, +) !void { + if (cells.native_images.contains(key)) return; + const row = stride; + if (dirty_rows) |dirty| dirty: { + // The core changed only these rows since a picture we still hold: + // write them into that texture rather than sending the whole page. + if (dirty.y + dirty.h > h) break :dirty; + const texture = cells.native_images.get(dirty.from) orelse break :dirty; + try uploadTextureRows(cells, cmd, texture, rgba[dirty.y * row ..][0 .. dirty.h * row], w, dirty.y, dirty.h); + try cells.native_images.put(gpa, key, texture); + _ = cells.native_images.remove(dirty.from); + return; + } + + const texture = texture2d(cells.device, c.SDL_GPU_TEXTUREFORMAT_R8G8B8A8_UNORM, c.SDL_GPU_TEXTUREUSAGE_SAMPLER, w, h) orelse return error.GpuCreate; + errdefer c.SDL_ReleaseGPUTexture(cells.device, texture); + try uploadTextureRows(cells, cmd, texture, rgba, w, 0, h); + try cells.native_images.put(gpa, key, texture); +} + +/// Copy `rows` rows of RGBA, `width` pixels each, into `texture` at row `y`. +fn uploadTextureRows( + cells: *Cells, + cmd: *c.SDL_GPUCommandBuffer, + texture: *c.SDL_GPUTexture, + rgba: []const u8, + width: usize, + y: usize, + rows: usize, +) !void { + var xf_info = c.SDL_GPUTransferBufferCreateInfo{ + .usage = c.SDL_GPU_TRANSFERBUFFERUSAGE_UPLOAD, + .size = @intCast(rgba.len), + .props = 0, + }; + const transfer = c.SDL_CreateGPUTransferBuffer(cells.device, &xf_info) orelse return error.GpuCreate; + defer c.SDL_ReleaseGPUTransferBuffer(cells.device, transfer); + const mapped: [*]u8 = @ptrCast(c.SDL_MapGPUTransferBuffer(cells.device, transfer, false) orelse return error.GpuMap); + @memcpy(mapped[0..rgba.len], rgba); + c.SDL_UnmapGPUTransferBuffer(cells.device, transfer); + + const copy = c.SDL_BeginGPUCopyPass(cmd); + const src = c.SDL_GPUTextureTransferInfo{ + .transfer_buffer = transfer, + .offset = 0, + .pixels_per_row = @intCast(width), + .rows_per_layer = @intCast(rows), + }; + const dst = c.SDL_GPUTextureRegion{ + .texture = texture, + .mip_level = 0, + .layer = 0, + .x = 0, + .y = @intCast(y), + .z = 0, + .w = @intCast(width), + .h = @intCast(rows), + .d = 1, + }; + c.SDL_UploadToGPUTexture(copy, &src, &dst, false); + c.SDL_EndGPUCopyPass(copy); +} + +/// The frame's `n` picture instances, mapped for the caller to write, and +/// `images` emptied with room for as many draws; uploadImages sends them. +/// Null when the buffers will not grow or map. +pub fn mapImages(cells: *Cells, gpa: std.mem.Allocator, n: u32) ?[*]ImageInstance { + growInstances(cells.device, &cells.image_vbuf, &cells.image_vxfer, &cells.image_capacity, n, @sizeOf(ImageInstance)) catch return null; + cells.images.clearRetainingCapacity(); + cells.images.ensureTotalCapacity(gpa, n) catch return null; + const ptr: [*]u8 = @ptrCast(c.SDL_MapGPUTransferBuffer(cells.device, cells.image_vxfer.?, false) orelse return null); + return @ptrCast(@alignCast(ptr)); +} + +/// The first `n` instances mapImages gave, sent. +pub fn uploadImages(cells: *Cells, cmd: *c.SDL_GPUCommandBuffer, n: u32) void { + c.SDL_UnmapGPUTransferBuffer(cells.device, cells.image_vxfer.?); + + const copy = c.SDL_BeginGPUCopyPass(cmd); + const src = c.SDL_GPUTransferBufferLocation{ .transfer_buffer = cells.image_vxfer.?, .offset = 0 }; + const dst = c.SDL_GPUBufferRegion{ .buffer = cells.image_vbuf.?, .offset = 0, .size = n * @sizeOf(ImageInstance) }; + c.SDL_UploadToGPUBuffer(copy, &src, &dst, false); + c.SDL_EndGPUCopyPass(copy); +} + +/// Draws `count` of the frame's pictures from `start`, each clipped to its +/// rectangle; the scissor is the whole target, `whole`, after. +fn drawImages(cells: *Cells, rp: ?*c.SDL_GPURenderPass, start: u32, count: u32, whole: c.SDL_Rect) void { + const pass = rp orelse return; + c.SDL_BindGPUGraphicsPipeline(pass, cells.image_pipeline); + var idx = start; + const end = start + count; + for (cells.images.items[start..end]) |prepared| { + c.SDL_BindGPUGraphicsPipeline(pass, if (prepared.premultiplied) cells.addon_pipeline.? else cells.image_pipeline); + const clip = prepared.clip; + if (clip.w > 0 and clip.h > 0) { + c.SDL_SetGPUScissor(pass, &clip); + const sampler = c.SDL_GPUTextureSamplerBinding{ .texture = prepared.texture, .sampler = cells.linear_sampler }; + c.SDL_BindGPUFragmentSamplers(pass, 0, &sampler, 1); + const binding = c.SDL_GPUBufferBinding{ .buffer = cells.image_vbuf.?, .offset = idx * @sizeOf(ImageInstance) }; + c.SDL_BindGPUVertexBuffers(pass, 0, &binding, 1); + c.SDL_DrawGPUPrimitives(pass, 6, 1, 0, 0); + } + idx += 1; + } + std.debug.assert(idx == start + count); + // Back to the whole target: what draws after a picture may run on past + // the grid, as a rule and a band do. + c.SDL_SetGPUScissor(pass, &whole); +} + +/// The overlay's triangles, `vertices`, sent. +pub fn uploadOverlay(cells: *Cells, cmd: *c.SDL_GPUCommandBuffer, vertices: []const OverlayVertex) bool { + const vertex_count: u32 = @intCast(vertices.len); + const byte_len: u32 = vertex_count * @sizeOf(OverlayVertex); + const ptr = c.SDL_MapGPUTransferBuffer(cells.device, cells.overlay_vxfer, false) orelse return false; + const dst: [*]u8 = @ptrCast(ptr); + const src: [*]const u8 = @ptrCast(vertices.ptr); + @memcpy(dst[0..byte_len], src[0..byte_len]); + c.SDL_UnmapGPUTransferBuffer(cells.device, cells.overlay_vxfer); + const copy = c.SDL_BeginGPUCopyPass(cmd); + const src_loc = c.SDL_GPUTransferBufferLocation{ .transfer_buffer = cells.overlay_vxfer, .offset = 0 }; + const dst_region = c.SDL_GPUBufferRegion{ .buffer = cells.overlay_vbuf, .offset = 0, .size = byte_len }; + c.SDL_UploadToGPUBuffer(copy, &src_loc, &dst_region, false); + c.SDL_EndGPUCopyPass(copy); + return true; +} + +fn pushLayerOpacity(cmd: *c.SDL_GPUCommandBuffer, pass: ?*c.SDL_GPURenderPass, opacity: f32) void { + const uniforms = [4]f32{ opacity, 0, 0, 0 }; + c.SDL_PushGPUFragmentUniformData(cmd, 0, &uniforms, @sizeOf(@TypeOf(uniforms))); + // The source alpha is geometric/image coverage, not window opacity. Its + // alpha contribution is multiplied by this constant separately, so a + // rail repainted over a gutter still has alpha p, not p + p*(1-p). + c.SDL_SetGPUBlendConstants(pass, .{ .r = opacity, .g = opacity, .b = opacity, .a = opacity }); +} + +/// The overlay's first `vertex_count` vertices (uploadOverlay), drawn at +/// the layer opacity `opacity`. +fn drawOverlay(cells: *Cells, cmd: *c.SDL_GPUCommandBuffer, rp: ?*c.SDL_GPURenderPass, vertex_count: u32, opacity: f32) void { + if (vertex_count == 0) return; + const pass = rp orelse return; + c.SDL_BindGPUGraphicsPipeline(pass, cells.overlay_pipeline); + const binding = c.SDL_GPUBufferBinding{ .buffer = cells.overlay_vbuf, .offset = 0 }; + c.SDL_BindGPUVertexBuffers(pass, 0, &binding, 1); + pushLayerOpacity(cmd, pass, opacity); + c.SDL_DrawGPUPrimitives(pass, vertex_count, 1, 0, 0); +} pub const CellInstance = extern struct { x0: f32, 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)); +} |
