//! 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, 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 (`.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); } /// 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. pub 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. pub 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; } pub 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`. pub 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, y0: f32, x1: f32, y1: f32, u0: f32, v0: f32, u1: f32, v1: f32, fr: f32, fg: f32, fb: f32, br: f32, bg: f32, bb: f32, /// The flags (the high bits, ui.vert.glsl). effect: u32 = 0, /// A clip rectangle in target pixels; x1 < x0 is none (ui.vert.glsl). clip_x0: f32 = 0, clip_y0: f32 = 0, clip_x1: f32 = -1, clip_y1: f32 = -1, }; pub const OverlayVertex = extern struct { x: f32, y: f32, r: f32, g: f32, b: f32, a: f32, }; pub const ImageInstance = extern struct { x0: f32, y0: f32, x1: f32, y1: f32, u0: f32, v0: f32, u1: f32, v1: f32, }; pub const opaque_bg_bit: u32 = 0x2000_0000; /// A vertex buffer and its upload buffer holding at least `needed` /// elements of `stride` bytes: those there when they do, else twice as /// many again until they would (the old ones let go). pub fn growInstances(device: *c.SDL_GPUDevice, buffer: *?*c.SDL_GPUBuffer, transfer: *?*c.SDL_GPUTransferBuffer, capacity: *u32, needed: u32, stride: u32) !void { if (needed <= capacity.* and buffer.* != null and transfer.* != null) return; var grown = @max(@as(u32, 1), capacity.*); while (grown < needed) grown = std.math.mul(u32, grown, 2) catch return error.GpuCapacity; const size = std.math.mul(u32, grown, stride) catch return error.GpuCapacity; var vb_info = c.SDL_GPUBufferCreateInfo{ .usage = c.SDL_GPU_BUFFERUSAGE_VERTEX, .size = size, .props = 0 }; const next_buffer = c.SDL_CreateGPUBuffer(device, &vb_info) orelse return error.GpuCreate; errdefer c.SDL_ReleaseGPUBuffer(device, next_buffer); var xf_info = c.SDL_GPUTransferBufferCreateInfo{ .usage = c.SDL_GPU_TRANSFERBUFFERUSAGE_UPLOAD, .size = size, .props = 0 }; const next_transfer = c.SDL_CreateGPUTransferBuffer(device, &xf_info) orelse return error.GpuCreate; if (buffer.*) |old| c.SDL_ReleaseGPUBuffer(device, old); if (transfer.*) |old| c.SDL_ReleaseGPUTransferBuffer(device, old); buffer.* = next_buffer; transfer.* = next_transfer; capacity.* = grown; } /// One vertex buffer of a pipeline: `pitch` bytes an element, read per /// vertex or per instance through `attrs`. pub const VertexInput = struct { pitch: u32, rate: c.SDL_GPUVertexInputRate, attrs: []const c.SDL_GPUVertexAttribute }; /// The cells' and the decor's instances (ui.vert.glsl). pub const cell_input: VertexInput = .{ .pitch = @sizeOf(CellInstance), .rate = c.SDL_GPU_VERTEXINPUTRATE_INSTANCE, .attrs = &.{ .{ .location = 0, .buffer_slot = 0, .format = c.SDL_GPU_VERTEXELEMENTFORMAT_FLOAT4, .offset = @offsetOf(CellInstance, "x0") }, .{ .location = 1, .buffer_slot = 0, .format = c.SDL_GPU_VERTEXELEMENTFORMAT_FLOAT4, .offset = @offsetOf(CellInstance, "u0") }, .{ .location = 2, .buffer_slot = 0, .format = c.SDL_GPU_VERTEXELEMENTFORMAT_FLOAT3, .offset = @offsetOf(CellInstance, "fr") }, .{ .location = 3, .buffer_slot = 0, .format = c.SDL_GPU_VERTEXELEMENTFORMAT_FLOAT3, .offset = @offsetOf(CellInstance, "br") }, .{ .location = 4, .buffer_slot = 0, .format = c.SDL_GPU_VERTEXELEMENTFORMAT_UINT, .offset = @offsetOf(CellInstance, "effect") }, .{ .location = 5, .buffer_slot = 0, .format = c.SDL_GPU_VERTEXELEMENTFORMAT_FLOAT4, .offset = @offsetOf(CellInstance, "clip_x0") }, } }; pub const overlay_input: VertexInput = .{ .pitch = @sizeOf(OverlayVertex), .rate = c.SDL_GPU_VERTEXINPUTRATE_VERTEX, .attrs = &.{ .{ .location = 0, .buffer_slot = 0, .format = c.SDL_GPU_VERTEXELEMENTFORMAT_FLOAT2, .offset = @offsetOf(OverlayVertex, "x") }, .{ .location = 1, .buffer_slot = 0, .format = c.SDL_GPU_VERTEXELEMENTFORMAT_FLOAT4, .offset = @offsetOf(OverlayVertex, "r") }, } }; pub const image_input: VertexInput = .{ .pitch = @sizeOf(ImageInstance), .rate = c.SDL_GPU_VERTEXINPUTRATE_INSTANCE, .attrs = &.{ .{ .location = 0, .buffer_slot = 0, .format = c.SDL_GPU_VERTEXELEMENTFORMAT_FLOAT4, .offset = @offsetOf(ImageInstance, "x0") }, .{ .location = 1, .buffer_slot = 0, .format = c.SDL_GPU_VERTEXELEMENTFORMAT_FLOAT4, .offset = @offsetOf(ImageInstance, "u0") }, } }; /// A pipeline drawing triangles into `color_format`: `vert`, and `frag` /// with its samplers and uniform buffers, over one vertex buffer of /// `input` (none: the post chain's triangle over the whole frame). pub fn makePipeline( device: *c.SDL_GPUDevice, color_format: c.SDL_GPUTextureFormat, vert: []const u8, frag: []const u8, samplers: u32, uniforms: u32, input: ?VertexInput, blend: c.SDL_GPUColorTargetBlendState, ) !*c.SDL_GPUGraphicsPipeline { const vs = try makeShader(device, vert, c.SDL_GPU_SHADERSTAGE_VERTEX, 0, 0); defer c.SDL_ReleaseGPUShader(device, vs); const fs = try makeShader(device, frag, c.SDL_GPU_SHADERSTAGE_FRAGMENT, samplers, uniforms); defer c.SDL_ReleaseGPUShader(device, fs); var col_desc = c.SDL_GPUColorTargetDescription{ .format = color_format, .blend_state = blend }; var vbuf_desc: c.SDL_GPUVertexBufferDescription = undefined; var info = std.mem.zeroes(c.SDL_GPUGraphicsPipelineCreateInfo); info.vertex_shader = vs; info.fragment_shader = fs; info.primitive_type = c.SDL_GPU_PRIMITIVETYPE_TRIANGLELIST; if (input) |in| { vbuf_desc = .{ .slot = 0, .pitch = in.pitch, .input_rate = in.rate, .instance_step_rate = 0 }; info.vertex_input_state = .{ .vertex_buffer_descriptions = &vbuf_desc, .num_vertex_buffers = 1, .vertex_attributes = in.attrs.ptr, .num_vertex_attributes = @intCast(in.attrs.len), }; } info.rasterizer_state.fill_mode = c.SDL_GPU_FILLMODE_FILL; info.rasterizer_state.cull_mode = c.SDL_GPU_CULLMODE_NONE; info.multisample_state.sample_count = c.SDL_GPU_SAMPLECOUNT_1; info.target_info = .{ .color_target_descriptions = &col_desc, .num_color_targets = 1 }; return c.SDL_CreateGPUGraphicsPipeline(device, &info) orelse error.GpuCreate; } pub fn backgroundLayerBlend() c.SDL_GPUColorTargetBlendState { var blend = std.mem.zeroes(c.SDL_GPUColorTargetBlendState); blend.src_color_blendfactor = c.SDL_GPU_BLENDFACTOR_SRC_ALPHA; blend.dst_color_blendfactor = c.SDL_GPU_BLENDFACTOR_ONE_MINUS_SRC_ALPHA; blend.color_blend_op = c.SDL_GPU_BLENDOP_ADD; blend.src_alpha_blendfactor = c.SDL_GPU_BLENDFACTOR_CONSTANT_COLOR; blend.dst_alpha_blendfactor = c.SDL_GPU_BLENDFACTOR_ONE_MINUS_SRC_ALPHA; blend.alpha_blend_op = c.SDL_GPU_BLENDOP_ADD; blend.enable_blend = true; return blend; } fn makeShader(device: *c.SDL_GPUDevice, code: []const u8, stage: c.SDL_GPUShaderStage, n_samplers: u32, n_uniform_buffers: u32) !*c.SDL_GPUShader { var info = std.mem.zeroes(c.SDL_GPUShaderCreateInfo); info.code = code.ptr; info.code_size = code.len; info.entrypoint = "main"; info.format = c.SDL_GPU_SHADERFORMAT_SPIRV; info.stage = stage; info.num_samplers = n_samplers; info.num_uniform_buffers = n_uniform_buffers; return c.SDL_CreateGPUShader(device, &info) orelse error.GpuCreate; } /// A 2D texture of one level, one layer and one sample. pub fn texture2d(device: *c.SDL_GPUDevice, format: c.SDL_GPUTextureFormat, usage: c.SDL_GPUTextureUsageFlags, width: u32, height: u32) ?*c.SDL_GPUTexture { var info = std.mem.zeroes(c.SDL_GPUTextureCreateInfo); info.type = c.SDL_GPU_TEXTURETYPE_2D; info.format = format; info.usage = usage; info.width = width; info.height = height; info.layer_count_or_depth = 1; info.num_levels = 1; info.sample_count = c.SDL_GPU_SAMPLECOUNT_1; return c.SDL_CreateGPUTexture(device, &info); } test "the shader instance ABI: the flags after the colours, the clip after them" { try std.testing.expectEqual(@as(usize, 76), @sizeOf(CellInstance)); try std.testing.expectEqual(@as(usize, 56), @offsetOf(CellInstance, "effect")); try std.testing.expectEqual(@as(usize, 60), @offsetOf(CellInstance, "clip_x0")); try std.testing.expectEqual(@as(usize, 32), @sizeOf(ImageInstance)); }