diff --git a/.github/workflows/build.yml b/.github/workflows/build.yml index 9bf7971c..abb30582 100644 --- a/.github/workflows/build.yml +++ b/.github/workflows/build.yml @@ -118,6 +118,8 @@ jobs: nim r ${{ matrix.build_flags }} tests/test_button_vertices.nim nim r -d:silkyTesting tests/test_layout.nim nim r -d:silkyTesting tests/test_layout_regressions.nim + nim r -d:silkyTesting tests/test_isolated_drawing.nim + nim r ${{ matrix.build_flags }} tests/test_isolated_drawing.nim nim r ${{ matrix.build_flags }} tests/test_layout_clips.nim nim r ${{ matrix.build_flags }} tests/test_cpu_backend.nim @@ -145,6 +147,10 @@ jobs: (cd examples/the7gui && nim c -d:emscripten the7gui.nim) (cd examples/todomvc && nim c -d:emscripten todomvc.nim) + - name: Compile Metal compositing test + if: matrix.build_flags == '-d:useMetal4' + run: nim c -d:useMetal4 tests/test_metal_compositing.nim + - name: Run example tests if: ${{ !matrix.emscripten }} shell: bash diff --git a/docs/metal-embedding.md b/docs/metal-embedding.md new file mode 100644 index 00000000..06894eb0 --- /dev/null +++ b/docs/metal-embedding.md @@ -0,0 +1,83 @@ +# Embedding Silky in a Metal renderer + +Build the application with `-d:useMetal4`. Applications that already own a +Metal device and frame can supply an external drawer to `newSilky`: + +```nim +import pixie, silky, silky/drawers/metal4 +import pkg/metal4 as metal + +let + atlasData = readAtlas("atlas.png") + drawer = newDrawer(device, atlasData.image, window.size) + sk = newSilky(window, atlasData.image, atlasData.atlas, drawer) +``` + +The application owns `device`, its command queue, its window's Metal layer, +and frame submission. The external drawer does not create a layer or queue. +Call `drawer.close()` after outstanding GPU work completes, before releasing +the device. The ordinary `newSilky` constructors still own their frame when +no drawer is supplied. + +For each UI pass, end the application's current render encoder and select +the destination before calling `sk.endUi()`: + +```nim +sk.beginUi(window, window.size) +# Build the UI with the normal Silky drawing and widget APIs. +drawer.setExternalFrame(commandBuffer, colorTexture) +sk.endUi() +# Encode any remaining application passes, then present and commit once. +``` + +Silky creates a separate color-only render pass with `MTLLoadActionLoad`, +preserving the application's existing pixels. It does not clear, present, +commit, or wait. `clearScreen` has no effect on external targets; clear them +in the application's own pass. Set the external frame before every `endUi`. +The target dimensions set the UI viewport, including after a resize. + +The command buffer and target must use the supplied device. The command +buffer must be uncommitted and retain its resources. The target must have +one sample and match the drawer's pixel format, which defaults to +`MTLPixelFormatBGRA8Unorm`. Pass `pixelFormat = MTLPixelFormatRGBA8Unorm` +to `newDrawer` for an RGBA target. Resolve multisample scene rendering before +the UI pass. + +Each UI pass uses a separate vertex buffer, so multiple passes may share +one command buffer without overwriting earlier vertex data. Atlas and +independent image textures remain mutable resources: complete pending GPU +work before changing pixels that earlier passes still need. + +`drawer.atlasTexture()` returns the current borrowed Metal atlas texture for +application shaders. Read it again after atlas uploads because atlas growth +can replace the texture. Retain it explicitly if the application stores it +beyond the drawer's lifetime. + +The atlas has a full mip chain. Before application shaders sample it, end the +active encoder and call `drawer.prepareAtlas(commandBuffer)`. This encodes mip +generation only when uploads have made the atlas dirty; it never commits or +waits. Place this before the application's sampling pass in the command buffer. +Ordinary `endUi` prepares the atlas automatically. Complete pending GPU work before +mutating atlas pixels, as with other shared image textures. + +## Offscreen drawing during a UI frame + +Use `sk.isolatedDrawing(bounds):` to bake images while the current UI frame +already has queued geometry. The scope is available on every rendering backend: + +```nim +sk.isolatedDrawing(rect(0, 0, width.float32, height.float32)): + # Queue the image's rectangles, text, and atlas sprites here. + # Flush these queues to the offscreen target before leaving this scope. +``` + +The scope starts with empty queues on the normal layer and an independent root +layout and clip rectangle. It restores the caller's queues, layer stack, layout, +and deferred clip captures when the body exits, including after an exception. +Scopes can nest. This keeps an offscreen bake from changing the placement of a +surrounding deferred layout such as a `hug()` group. + +This is a drawing scope, not another UI frame. Use drawing procedures inside it +and flush through the drawer; do not call `beginUi` or `endUi`, start another +`ui` DSL block, or process interactive widgets. The application still owns GPU +target selection and submission, and must restore its previous target itself. diff --git a/nimby.lock b/nimby.lock index a0839aca..8777bbe2 100644 --- a/nimby.lock +++ b/nimby.lock @@ -1,4 +1,4 @@ -shady 0.1.5 https://github.com/treeform/shady c899f7cd17dbe7021d6e3aa2908e6de6549c47f1 +shady 0.1.5 https://github.com/treeform/shady de68342e4d46288a565dc6dc37aa6600c626ec27 vmath 2.0.1 https://github.com/treeform/vmath ddfcd738578c47ed3330b917f5efecf5a15128b2 pixie 5.1.0 https://github.com/treeform/pixie 5eda4949a3c8bea318cfac8e42060a8f90f3f35d chroma 1.0.0 https://github.com/treeform/chroma 2381748f92e5ea16cb2403ff7e20c6dd5443a59d diff --git a/src/silky/contexts.nim b/src/silky/contexts.nim index a747ea8a..13f339a3 100644 --- a/src/silky/contexts.nim +++ b/src/silky/contexts.nim @@ -117,6 +117,16 @@ type ## Logical window offset applied when the app removes safe-area insets. window: Window + IsolatedDrawingState = object + ## Suspended drawing queues and the metadata that indexes those queues. + layers: array[2, seq[DrawerVertex]] + vertexClips: array[2, seq[int]] + clipStack: ClipStack + layoutStack: seq[LayoutScope] + currentLayer: int + layerStack: seq[int] + inputs: TextInputs + proc currentDrawLayer*(sk: Silky): int = sk.drawer.currentLayer @@ -240,6 +250,33 @@ proc clipRect*(sk: Silky): Rect = ## Returns the current clip intersection. sk.clipStack.clipRect() +proc swapDrawingState(sk: Silky, state: var IsolatedDrawingState) = + ## Exchanges all state whose indices refer to the active draw queues. + swap(sk.drawer.layers, state.layers) + swap(sk.vertexClips, state.vertexClips) + swap(sk.clipStack, state.clipStack) + swap(sk.layoutStack, state.layoutStack) + swap(sk.drawer.currentLayer, state.currentLayer) + swap(sk.drawer.layerStack, state.layerStack) + swap(sk.inputs, state.inputs) + +template isolatedDrawing*(sk: Silky, bounds: Rect, body: untyped) = + ## Runs drawing in fresh queues and restores the caller's state on exit. + ## Flush isolated geometry inside the body using the active drawer. + ## This does not start a UI frame or isolate interactive widget state. + block: + let + drawingContext = sk + drawingBounds = bounds + var drawingState: IsolatedDrawingState + drawingContext.swapDrawingState(drawingState) + try: + drawingContext.pushLayout(drawingBounds.xy, drawingBounds.wh) + drawingContext.pushRawClipRect(drawingBounds) + body + finally: + drawingContext.swapDrawingState(drawingState) + proc instanceCount*(sk: Silky): int = ## Returns the number of queued drawer vertices. for i in 0 ..< sk.drawer.layers.len: @@ -812,22 +849,28 @@ proc getTextSize*(sk: Silky, font: string, text: string): Vec2 {.measure.} = proc newSilky*( window: Window, image: Image, - atlas: SilkyAtlas + atlas: SilkyAtlas, + drawer: Drawer = nil ): Silky {.measure.} = ## Creates a new Silky context and eagerly initializes its drawer. + ## A supplied drawer lets an application own the rendering surface. ## Automatically installs input handling on the window. result = Silky() result.image = image result.atlas = atlas result.builder = newAtlasBuilderFromAtlas(atlas, image) result.window = window - result.drawer = newDrawer(window, image) + result.drawer = if drawer.isNil: newDrawer(window, image) else: drawer result.inputs = newTextInputs(window) -proc newSilky*(window: Window, atlasPngPath: string): Silky {.measure.} = +proc newSilky*( + window: Window, + atlasPngPath: string, + drawer: Drawer = nil +): Silky {.measure.} = ## Creates a new Silky from one atlas PNG file. let atlasData = readAtlas(atlasPngPath) - newSilky(window, atlasData.image, atlasData.atlas) + newSilky(window, atlasData.image, atlasData.atlas, drawer) proc uploadAtlas*(sk: Silky) = ## Push the current CPU atlas image to the GPU drawer. diff --git a/src/silky/drawers/metal4.nim b/src/silky/drawers/metal4.nim index 9d6b121e..e25cab0d 100644 --- a/src/silky/drawers/metal4.nim +++ b/src/silky/drawers/metal4.nim @@ -28,6 +28,12 @@ type texture: MTLTexture size: IVec2 + TextureUpload = object + buffer: MTLBuffer + texture: MTLTexture + region: MTLRegion + bytesPerRow: uint + ShaderUniforms = object ## Matches the Shady vertex shader's constant buffer layout. viewportSize: Vec2 @@ -44,12 +50,19 @@ type maxVertexCount: int viewportSize: IVec2 atlasSize: IVec2 + atlasMipmapsDirty: bool + uploads: seq[TextureUpload] textureLimit: int textures: Table[uint32, DrawerTexture] nextTexture: uint32 clearColor: MTLClearColor + pixelFormat: MTLPixelFormat = MTLPixelFormatBGRA8Unorm + external: bool + commandBuffer: MTLCommandBuffer + target: MTLTexture when defined(silkyMetalTesting): ownsTestDevice: bool + vertexBufferAllocations, externalRenderPasses: int layers*: array[2, seq[DrawerVertex]] currentLayer*: int layerStack*: seq[int] @@ -62,6 +75,15 @@ static: objc: proc supportsFamily(self: MTLDevice, x: int): bool + proc device(self: MTLCommandBuffer): MTLDevice + proc device(self: MTLTexture): MTLDevice + proc pixelFormat(self: MTLTexture): MTLPixelFormat + proc sampleCount(self: MTLTexture): uint + proc retainedReferences(self: MTLCommandBuffer): bool + proc copyFromBuffer(self: MTLBlitCommandEncoder, x: MTLBuffer, + sourceOffset, sourceBytesPerRow, sourceBytesPerImage: uint, + sourceSize: MTLSize, toTexture: MTLTexture, + destinationSlice, destinationLevel: uint, destinationOrigin: MTLOrigin) proc textureSizeLimit(device: MTLDevice): int = ## Reads Metal's family-specific 2D texture limit, including Simulator. @@ -85,9 +107,17 @@ proc clampViewport(size: IVec2): IVec2 = ivec2(max(1'i32, size.x), max(1'i32, size.y)) proc close*(drawer: Drawer) = - ## Releases all drawer-owned Metal resources after its synchronous frames. + ## Releases drawer-owned resources after pending GPU work completes. if drawer.isNil: return + drawer.commandBuffer.release() + drawer.commandBuffer = 0.MTLCommandBuffer + drawer.target.release() + drawer.target = 0.MTLTexture + for upload in drawer.uploads: + upload.buffer.release() + upload.texture.release() + drawer.uploads.setLen(0) for texture in drawer.textures.values: texture.texture.release() drawer.textures.clear() @@ -107,7 +137,11 @@ proc close*(drawer: Drawer) = drawer.ownsTestDevice = false drawer.ctx.destroy() -proc newTexture(state: Drawer, width, height: int): MTLTexture = +proc newTexture( + state: Drawer, + width, height: int, + mipmapped = false +): MTLTexture = ## Allocates a shader-readable texture using the supported 2D size limit. if width <= 0 or height <= 0: raise newException(SilkyError, "Image texture dimensions must be positive.") @@ -120,7 +154,7 @@ proc newTexture(state: Drawer, width, height: int): MTLTexture = MTLPixelFormatRGBA8Unorm, width.uint, height.uint, - false + mipmapped ) descriptor.setUsage(MTLTextureUsageShaderRead) result = state.ctx.device.newTextureWithDescriptor(descriptor) @@ -128,11 +162,42 @@ proc newTexture(state: Drawer, width, height: int): MTLTexture = raise newException(SilkyError, "Could not allocate a Metal image texture.") proc uploadRegion( + drawer: Drawer, texture: MTLTexture, image: Image, x, y, width, height: int ) = - ## Uploads image pixels with their original row stride into a texture region. + ## Stages external texture writes in queue order without CPU/GPU waits. + if drawer.external: + let + rowBytes = width * sizeof(ColorRGBX) + alignedRowBytes = (rowBytes + 255) and not 255 + buffer = drawer.ctx.device.newBufferWithLength( + (alignedRowBytes * height).uint, + 0 + ) + checkNil(buffer, "Could not stage an external Metal texture upload") + let pixels = cast[ptr UncheckedArray[uint8]](buffer.contents()) + if pixels.isNil: + buffer.release() + raise newException(SilkyError, "Could not map a Metal texture upload") + for row in 0 ..< height: + copyMem( + pixels[row * alignedRowBytes].addr, + unsafeAddr image.data[(y + row) * image.width + x], + rowBytes + ) + texture.retain() + drawer.uploads.add(TextureUpload( + buffer: buffer, + texture: texture, + region: MTLRegion( + origin: MTLOrigin(x: x.uint, y: y.uint, z: 0), + size: MTLSize(width: width.uint, height: height.uint, depth: 1) + ), + bytesPerRow: alignedRowBytes.uint + )) + return texture.replaceRegion( MTLRegion( origin: MTLOrigin(x: x.uint, y: y.uint, z: 0), @@ -156,6 +221,8 @@ proc createVertexBuffer(state: Drawer, maxVertexCount: int) = state.vertexBuffer = buffer state.vertexBufferPtr = bufferPtr state.maxVertexCount = maxVertexCount + when defined(silkyMetalTesting): + inc state.vertexBufferAllocations proc uploadTexture(state: Drawer, image: Image) = ## Uploads the atlas image into one Metal texture. @@ -163,11 +230,12 @@ proc uploadTexture(state: Drawer, image: Image) = raise newException(SilkyError, "Cannot upload an empty atlas image.") if state.texture.isNil or state.atlasSize != ivec2(image.width.int32, image.height.int32): - let texture = state.newTexture(image.width, image.height) + let texture = state.newTexture(image.width, image.height, mipmapped = true) state.texture.release() state.texture = texture - state.texture.uploadRegion(image, 0, 0, image.width, image.height) + state.uploadRegion(state.texture, image, 0, 0, image.width, image.height) state.atlasSize = ivec2(image.width.int32, image.height.int32) + state.atlasMipmapsDirty = state.texture.mipmapLevelCount() > 1 proc allocateTexture*(drawer: Drawer, width, height: int): uint32 = ## Allocates a separate image texture, reserving handle zero for the atlas. @@ -197,7 +265,7 @@ proc uploadTextureRows*( raise newException(SilkyError, "Image texture upload bounds are invalid.") if rowCount == 0: return - target.texture.uploadRegion(image, 0, firstRow, image.width, rowCount) + drawer.uploadRegion(target.texture, image, 0, firstRow, image.width, rowCount) proc deleteTexture*(drawer: Drawer, texture: uint32) = ## Releases an independent image texture; deleting a missing handle is safe. @@ -226,7 +294,15 @@ proc uploadAtlasRegion*( bottom = clamp(y.int64 + height.int64, 0'i64, image.height.int64).int if right <= left or bottom <= top: return - drawer.texture.uploadRegion(image, left, top, right - left, bottom - top) + drawer.uploadRegion( + drawer.texture, + image, + left, + top, + right - left, + bottom - top + ) + drawer.atlasMipmapsDirty = drawer.texture.mipmapLevelCount() > 1 proc initRenderer(state: Drawer, image: Image, size: IVec2) = ## Creates the Metal pipeline, atlas texture, and dynamic buffers. @@ -291,7 +367,7 @@ proc initRenderer(state: Drawer, image: Image, size: IVec2) = pipelineDescriptor.colorAttachments().objectAtIndexedSubscript(0) pipelineDescriptor.setVertexFunction(vertexFunction) pipelineDescriptor.setFragmentFunction(fragmentFunction) - colorAttachment.setPixelFormat(MTLPixelFormatBGRA8Unorm) + colorAttachment.setPixelFormat(state.pixelFormat) colorAttachment.setBlendingEnabled(true) colorAttachment.setSourceRGBBlendFactor(MTLBlendFactorOne) colorAttachment.setDestinationRGBBlendFactor( @@ -333,6 +409,50 @@ proc uploadAtlas*(drawer: Drawer, image: Image) = ## Replaces the atlas texture after runtime glyph or image additions. drawer.uploadTexture(image) +proc atlasTexture*(drawer: Drawer): MTLTexture = + ## Borrows the current atlas texture; uploads may replace this handle. + drawer.texture + +proc needsAtlasPreparation*(drawer: Drawer): bool = + ## Reports pending texture uploads or mipmaps that need an encoder break. + drawer.uploads.len > 0 or drawer.atlasMipmapsDirty + +proc prepareAtlas*(drawer: Drawer, commandBuffer: MTLCommandBuffer) = + ## Encodes texture uploads and mipmaps before application shaders sample them. + ## End active encoding and submit buffers in order on the same command queue. + ## The normal endFrame and endUi paths perform this preparation themselves. + if commandBuffer.isNil or + cast[int](commandBuffer.device()) != cast[int](drawer.ctx.device): + raise newException(SilkyError, + "Atlas preparation needs a command buffer from the drawer's device.") + if commandBuffer.status() >= MTLCommandBufferStatusCommitted or + not commandBuffer.retainedReferences(): + raise newException(SilkyError, + "Atlas commands must be uncommitted and retain resources.") + if not drawer.needsAtlasPreparation(): + return + let encoder = commandBuffer.blitCommandEncoder() + checkNil(encoder, "Could not create the atlas preparation encoder") + for upload in drawer.uploads: + encoder.copyFromBuffer( + upload.buffer, + 0, + upload.bytesPerRow, + 0, + upload.region.size, + upload.texture, + 0, + 0, + upload.region.origin + ) + upload.buffer.release() + upload.texture.release() + drawer.uploads.setLen(0) + if drawer.atlasMipmapsDirty: + encoder.generateMipmapsForTexture(drawer.texture) + encoder.endEncoding() + drawer.atlasMipmapsDirty = false + proc newDrawer*(window: Window, image: Image): Drawer = ## Creates a new Metal drawer and eagerly initializes its resources. let safeSize = clampViewport(window.size) @@ -351,11 +471,61 @@ proc newDrawer*(window: Window, image: Image): Drawer = result.close() raise +proc newDrawer*( + device: MTLDevice, + image: Image, + size: IVec2, + pixelFormat = MTLPixelFormatBGRA8Unorm +): Drawer = + ## Creates an embeddable drawer borrowing an application's Metal device. + ## Each frame needs setExternalFrame; the application submits GPU work. + if device.isNil: + raise newException(SilkyError, "An external Metal drawer needs a device.") + result = Drawer(external: true, pixelFormat: pixelFormat) + result.ctx.device = device + try: + result.initRenderer(image, size) + except: + result.close() + raise + +proc setExternalFrame*( + drawer: Drawer, + commandBuffer: MTLCommandBuffer, + target: MTLTexture +) = + ## Selects a single-sample color target for the next endFrame or endUi. + ## End the application's encoder first. Silky loads the existing color and + ## never presents or submits this resource-retaining command buffer. + if not drawer.external: + raise newException(SilkyError, "This Metal drawer owns its frame.") + if commandBuffer.isNil or target.isNil: + raise newException(SilkyError, "An external Metal frame needs a target.") + if commandBuffer.status() >= MTLCommandBufferStatusCommitted or + not commandBuffer.retainedReferences(): + raise newException(SilkyError, + "External Metal commands must be uncommitted and retain resources.") + if cast[int](commandBuffer.device()) != cast[int](drawer.ctx.device) or + cast[int](target.device()) != cast[int](drawer.ctx.device): + raise newException(SilkyError, + "External Metal frame resources must use the drawer's device.") + if target.pixelFormat() != drawer.pixelFormat or target.sampleCount() != 1: + raise newException(SilkyError, + "External Metal targets must match the drawer format with one sample.") + commandBuffer.retain() + target.retain() + drawer.commandBuffer.release() + drawer.target.release() + drawer.commandBuffer = commandBuffer + drawer.target = target + drawer.viewportSize = ivec2(target.width().int32, target.height().int32) + proc beginFrame*(drawer: Drawer, window: Window, size: IVec2) = ## Prepares the Metal drawer for a new frame. drawer.ctx.window = window drawer.viewportSize = clampViewport(size) - drawer.ctx.updateDrawableSize() + if not drawer.external: + drawer.ctx.updateDrawableSize() proc clearScreen*(drawer: Drawer, color: ColorRGBX) = ## Sets the Metal clear color used at frame submission. @@ -428,8 +598,9 @@ proc recordDraw(state: Drawer, vertexCount: int) = let drawable = state.ctx.currentDrawable() if drawable.isNil: return + let commandBuffer = state.ctx.newCommandBuffer() + state.prepareAtlas(commandBuffer) let - commandBuffer = state.ctx.newCommandBuffer() renderPass = state.ctx.clearPass(drawable, state.clearColor) encoder = commandBuffer.renderCommandEncoderWithDescriptor(renderPass) size = state.ctx.layer.drawableSize() @@ -449,6 +620,8 @@ proc uploadVertices( vertexCount: int ) = ## Updates the atlas and shared vertex buffer before a render pass. + if vertexCount < 0 or (vertexCount > 0 and vertices.isNil): + raise newException(SilkyError, "Metal vertex data is invalid.") if drawer.atlasSize != ivec2(image.width.int32, image.height.int32): drawer.uploadTexture(image) drawer.ensureVertexCapacity(vertexCount) @@ -468,6 +641,47 @@ proc endFrame*( ) = ## Flushes the queued quads through Metal 4. discard size + if drawer.external: + if drawer.commandBuffer.isNil: + raise newException(SilkyError, + "Call setExternalFrame before drawing with an external Metal drawer.") + defer: + drawer.commandBuffer.release() + drawer.commandBuffer = 0.MTLCommandBuffer + drawer.target.release() + drawer.target = 0.MTLTexture + if drawer.commandBuffer.status() >= MTLCommandBufferStatusCommitted: + raise newException(SilkyError, + "Submit external Metal commands after drawing the UI.") + if quadCount == 0: + drawer.uploadVertices(image, quads, quadCount) + drawer.prepareAtlas(drawer.commandBuffer) + return + # A command buffer retains each pass's buffer until GPU work completes. + # Later UI passes must not overwrite vertices already queued for drawing. + drawer.createVertexBuffer(max(1, quadCount)) + drawer.uploadVertices(image, quads, quadCount) + drawer.prepareAtlas(drawer.commandBuffer) + let + renderPass = MTLRenderPassDescriptor.renderPassDescriptor() + attachment = renderPass.colorAttachments().objectAtIndexedSubscript(0) + attachment.setTexture(drawer.target) + attachment.setLoadAction(MTLLoadActionLoad) + attachment.setStoreAction(MTLStoreActionStore) + let encoder = drawer.commandBuffer.renderCommandEncoderWithDescriptor( + renderPass + ) + checkNil(encoder, "Could not create an external Metal render encoder") + when defined(silkyMetalTesting): + inc drawer.externalRenderPasses + drawer.encodeDraw( + encoder, + drawer.target.width().float64, + drawer.target.height().float64, + quadCount + ) + encoder.endEncoding() + return drawer.uploadVertices(image, quads, quadCount) drawer.recordDraw(quadCount) @@ -482,6 +696,11 @@ when defined(silkyMetalTesting): mipmapLevel: uint ) + proc recordedWorkForTesting*(drawer: Drawer): + tuple[vertexBufferAllocations, externalRenderPasses: int] = + ## Reports allocations and external passes without altering GPU work. + (drawer.vertexBufferAllocations, drawer.externalRenderPasses) + proc newOffscreenDrawerForTesting*(image: Image, size: IVec2): Drawer = ## Creates the production drawer without a window for GPU pixel tests. result = Drawer( @@ -523,8 +742,9 @@ when defined(silkyMetalTesting): if vertices.len > 0: unsafeAddr vertices[0] else: nil, vertices.len ) + let commandBuffer = drawer.ctx.newCommandBuffer() + drawer.prepareAtlas(commandBuffer) let - commandBuffer = drawer.ctx.newCommandBuffer() renderPass = MTLRenderPassDescriptor.renderPassDescriptor() attachment = renderPass.colorAttachments().objectAtIndexedSubscript(0) attachment.setTexture(target) diff --git a/src/silky/drawers/shaders/silky.frag b/src/silky/drawers/shaders/silky.frag index 560ef281..52e85bdc 100644 --- a/src/silky/drawers/shaders/silky.frag +++ b/src/silky/drawers/shaders/silky.frag @@ -12,13 +12,15 @@ layout(location = 5) in vec2 fragmentMaskUv; layout(location = 0) out vec4 fragColor; void main() { + vec4 base = texture(atlasSampler, fragmentUv); + vec4 shaded = base * fragmentColor; + if (0.0 <= float(fragmentMaskUv.x)) { + float maskR = (texture(atlasSampler, fragmentMaskUv)).r; + shaded = vec4(base.rgb * mix(vec3(1.0, 1.0, 1.0), fragmentColor.rgb, maskR), base.a * fragmentColor.a); + } if ((((fragmentPos.x < fragmentClipPos.x) || (fragmentPos.y < fragmentClipPos.y)) || (fragmentClipPos.x + fragmentClipSize.x < fragmentPos.x)) || (fragmentClipPos.y + fragmentClipSize.y < fragmentPos.y)) { discard; - } else if (0.0 <= float(fragmentMaskUv.x)) { - vec4 base = texture(atlasSampler, fragmentUv); - float maskR = (texture(atlasSampler, fragmentMaskUv)).r; - fragColor = vec4(base.rgb * mix(vec3(1.0, 1.0, 1.0), fragmentColor.rgb, maskR), base.a * fragmentColor.a); } else { - fragColor = texture(atlasSampler, fragmentUv) * fragmentColor; + fragColor = shaded; } } diff --git a/src/silky/drawers/shaders/silky.frag.hlsl b/src/silky/drawers/shaders/silky.frag.hlsl index 14789c87..be7f02ef 100644 --- a/src/silky/drawers/shaders/silky.frag.hlsl +++ b/src/silky/drawers/shaders/silky.frag.hlsl @@ -1,4 +1,14 @@ // target hlsl dx12 +int2 shadyTextureSize(Texture2D image, int level) { + uint width, height, levels; + image.GetDimensions(level, width, height, levels); + return int2(width, height); +} +int2 shadyTextureSize(Texture2D image, int level) { + uint width, height, levels; + image.GetDimensions(level, width, height, levels); + return int2(width, height); +} // from silkyFrag Texture2D atlasSampler : register(t0); @@ -23,14 +33,16 @@ float4 PSMain(PSInput input) : SV_TARGET { float2 fragmentPos = input.fragmentPos; float2 fragmentMaskUv = input.fragmentMaskUv; float4 fragColor = float4(0.0, 0.0, 0.0, 0.0); + float4 base = atlasSampler.Sample(atlasSamplerSampler, fragmentUv); + float4 shaded = base * fragmentColor; + if (0.0 <= float(fragmentMaskUv.x)) { + float maskR = (atlasSampler.Sample(atlasSamplerSampler, fragmentMaskUv)).r; + shaded = float4(base.rgb * lerp(float3(1.0, 1.0, 1.0), fragmentColor.rgb, maskR), base.a * fragmentColor.a); + } if ((((fragmentPos.x < fragmentClipPos.x) || (fragmentPos.y < fragmentClipPos.y)) || (fragmentClipPos.x + fragmentClipSize.x < fragmentPos.x)) || (fragmentClipPos.y + fragmentClipSize.y < fragmentPos.y)) { discard; - } else if (0.0 <= float(fragmentMaskUv.x)) { - float4 base = atlasSampler.Sample(atlasSamplerSampler, fragmentUv); - float maskR = (atlasSampler.Sample(atlasSamplerSampler, fragmentMaskUv)).r; - fragColor = float4(base.rgb * lerp(float3(1.0, 1.0, 1.0), fragmentColor.rgb, maskR), base.a * fragmentColor.a); } else { - fragColor = atlasSampler.Sample(atlasSamplerSampler, fragmentUv) * fragmentColor; + fragColor = shaded; } return fragColor; } diff --git a/src/silky/drawers/shaders/silky.frag.spv b/src/silky/drawers/shaders/silky.frag.spv index 6afcc4ec..0b8d2faf 100644 Binary files a/src/silky/drawers/shaders/silky.frag.spv and b/src/silky/drawers/shaders/silky.frag.spv differ diff --git a/src/silky/drawers/shaders/silky.ps.cso b/src/silky/drawers/shaders/silky.ps.cso index 61896d78..c3de265a 100644 Binary files a/src/silky/drawers/shaders/silky.ps.cso and b/src/silky/drawers/shaders/silky.ps.cso differ diff --git a/src/silky/drawers/shaders/silky.vert.hlsl b/src/silky/drawers/shaders/silky.vert.hlsl index 71e43174..b52758e5 100644 --- a/src/silky/drawers/shaders/silky.vert.hlsl +++ b/src/silky/drawers/shaders/silky.vert.hlsl @@ -1,4 +1,14 @@ // target hlsl dx12 +int2 shadyTextureSize(Texture2D image, int level) { + uint width, height, levels; + image.GetDimensions(level, width, height, levels); + return int2(width, height); +} +int2 shadyTextureSize(Texture2D image, int level) { + uint width, height, levels; + image.GetDimensions(level, width, height, levels); + return int2(width, height); +} // from silkyVert cbuffer ShadyUniforms0 : register(b0) { diff --git a/src/silky/semantics.nim b/src/silky/semantics.nim index 9a949446..873dba04 100644 --- a/src/silky/semantics.nim +++ b/src/silky/semantics.nim @@ -316,6 +316,16 @@ type ## Logical window offset applied when the app removes safe-area insets. window*: Window + IsolatedDrawingState = object + ## Suspended drawing and semantic capture state for an isolated pass. + layers: array[2, seq[SilkyVertex]] + clipStack: ClipStack + layoutStack: seq[LayoutScope] + currentLayer: int + layerStack: seq[int] + inputs: TextInputs + semantic: SemanticCapture + proc currentDrawLayer*(sk: Silky): int = sk.currentLayer @@ -480,6 +490,33 @@ proc clipRect*(sk: Silky): Rect = ## Returns the current clip intersection. sk.clipStack.clipRect() +proc swapDrawingState(sk: Silky, state: var IsolatedDrawingState) = + ## Exchanges drawing queues and their layout and semantic metadata. + swap(sk.layers, state.layers) + swap(sk.clipStack, state.clipStack) + swap(sk.layoutStack, state.layoutStack) + swap(sk.currentLayer, state.currentLayer) + swap(sk.layerStack, state.layerStack) + swap(sk.inputs, state.inputs) + swap(sk.semantic, state.semantic) + +template isolatedDrawing*(sk: Silky, bounds: Rect, body: untyped) = + ## Runs drawing in fresh queues and restores the caller's state on exit. + ## Matches the native drawing scope without creating a window or GPU. + block: + let + drawingContext = sk + drawingBounds = bounds + var drawingState: IsolatedDrawingState + drawingContext.swapDrawingState(drawingState) + try: + drawingContext.semantic.reset() + drawingContext.pushLayout(drawingBounds.xy, drawingBounds.wh) + drawingContext.pushRawClipRect(drawingBounds) + body + finally: + drawingContext.swapDrawingState(drawingState) + proc advance*(sk: Silky, amount: Vec2, spacing: float32) = ## Advances the current layout cursor with explicit spacing. sk.layoutStack[^1].advancePen(amount, spacing) diff --git a/tests/test_isolated_drawing.nim b/tests/test_isolated_drawing.nim new file mode 100644 index 00000000..ff388bb2 --- /dev/null +++ b/tests/test_isolated_drawing.nim @@ -0,0 +1,179 @@ +import + bumpy, chroma, vmath, + silky + +when defined(silkyTesting): + from silky/semantics import textInputs +else: + from silky/contexts import textInputs + +const + Viewport = rect(0, 0, 400, 300) + Red = rgbx(255, 0, 0, 255) + Green = rgbx(0, 255, 0, 255) + Blue = rgbx(0, 0, 255, 255) + +template layers(sk: Silky): untyped = + ## Reads native queues or the test window's matching queue representation. + when defined(silkyTesting): + sk.layers + else: + sk.drawer.layers + +proc fixture(): Silky = + ## Creates drawing state without a graphics context on either test path. + let builder = newAtlasBuilder(64, 2) + when defined(silkyTesting): + let window = newWindow(400, 300) + result = newSilky(window, builder.atlas) + result.beginUi(window, window.size) + else: + result = Silky(atlas: builder.atlas, image: builder.atlasImage) + new(result.drawer) + result.pushLayout(Viewport.xy, Viewport.wh) + result.pushClipRect(Viewport) + +proc paint(sk: Silky, position, size: Vec2, color: ColorRGBX) = + ## Exercises real native vertices and queues equivalent semantic markers. + sk.drawRect(position, size, color) + when defined(silkyTesting): + sk.layers[sk.currentDrawLayer].add(SilkyVertex( + pos: position, + size: size, + color: color, + clipPos: sk.clipRect.xy, + clipSize: sk.clipRect.wh + )) + +proc bake(sk: Silky, fail = false) = + ## Draws a nested offscreen pass while an outer deferred span is active. + let + queued = sk.layers + layouts = sk.layoutStack + layer = sk.currentDrawLayer + clip = sk.clipRect + inputs = sk.textInputs() + var raised = false + try: + sk.isolatedDrawing(rect(0, 0, 80, 60)): + doAssert sk.layers[0].len == 0 and sk.layers[1].len == 0 + doAssert sk.currentDrawLayer == NormalLayer + doAssert sk.rootSize == vec2(80, 60) + doAssert sk.clipRect == rect(0, 0, 80, 60) + doAssert sk.textInputs().isNil + sk.beginWidget("Offscreen", "isolated") + sk.pushClipRect(rect(4, 5, 40, 30)) + let span = sk.beginVertexSpan() + sk.paint(vec2(7, 8), vec2(10, 12), Green) + sk.pushLayer(PopupsLayer) + sk.paint(vec2(10, 11), vec2(12, 13), Blue) + let + nestedQueued = sk.layers + nestedLayouts = sk.layoutStack + nestedClip = sk.clipRect + sk.isolatedDrawing(rect(2, 3, 16, 12)): + doAssert sk.currentDrawLayer == NormalLayer + doAssert sk.clipRect == rect(2, 3, 16, 12) + sk.paint(vec2(2, 3), vec2(4, 5), Red) + sk.pushLayer(PopupsLayer) + sk.pushClipRect(rect(3, 4, 5, 6)) + discard sk.beginVertexSpan() + # Unfinished local drawing stacks must not escape the scope. + doAssert sk.layers == nestedQueued + doAssert sk.layoutStack == nestedLayouts + doAssert sk.clipRect == nestedClip + doAssert sk.currentDrawLayer == PopupsLayer + sk.popLayer() + sk.endVertexSpan(span, vec2(1, 2)) + sk.popClipRect() + sk.endWidget() + if fail: + sk.pushLayer(PopupsLayer) + sk.pushClipRect(rect(1, 1, 2, 2)) + discard sk.beginVertexSpan() + raise newException(ValueError, "Offscreen drawing failed") + except ValueError: + raised = true + doAssert raised == fail + doAssert sk.layers == queued + doAssert sk.layoutStack == layouts + doAssert sk.currentDrawLayer == layer + doAssert sk.clipRect == clip + doAssert sk.textInputs() == inputs + +proc testScopes(fail: bool) = + ## Preserves both layer queues and active capture metadata through nesting. + let sk = fixture() + sk.paint(vec2(1, 2), vec2(3, 4), Blue) + let span = sk.beginVertexSpan() + sk.pushClipRect(rect(10, 20, 100, 80)) + sk.paint(vec2(12, 23), vec2(10, 11), Red) + sk.pushLayer(PopupsLayer) + sk.paint(vec2(14, 25), vec2(12, 13), Green) + sk.bake(fail) + sk.paint(vec2(16, 27), vec2(14, 15), Red) + sk.popLayer() + sk.paint(vec2(18, 29), vec2(16, 17), Green) + sk.popClipRect() + sk.endVertexSpan(span, vec2(30, 40)) + doAssert sk.currentDrawLayer == NormalLayer + doAssert sk.clipRect == Viewport + when not defined(silkyTesting): + doAssert sk.drawer.layers[NormalLayer].len == 18 + doAssert sk.drawer.layers[PopupsLayer].len == 12 + doAssert sk.drawer.layers[NormalLayer][0].pos == vec2(1, 2) + for layer in 0 .. 1: + let first = if layer == NormalLayer: 6 else: 0 + for vertex in sk.drawer.layers[layer][first .. ^1]: + doAssert vertex.clipPos == vec2(40, 60) + doAssert vertex.clipSize == vec2(100, 80) + +proc drawHud(isolate: bool, direction: StackDirection): Silky = + ## Inserts offscreen drawing between children of nested deferred layouts. + result = fixture() + let + sk = result + window = Window(nil) + sk.pushLayer(PopupsLayer) + sk.paint(vec2(2, 3), vec2(4, 5), Blue) + sk.popLayer() + ui: + group "outer": + box 50, 50, 200, 200 + rectangle "hugger": + hug() + layout direction + itemSpacing 0 + tint "#0000ff" + rectangle "nested": + hug() + layout BottomToTop + itemSpacing 0 + rectangle "before": + size 40, 20 + clipContent() + tint "#ff0000" + if isolate: + sk.pushLayer(PopupsLayer) + sk.bake() + sk.bake(fail = true) + sk.popLayer() + rectangle "after": + size 30, 10 + clipContent() + tint "#00ff00" + +echo "Testing isolated drawing queues, nested scopes, and exception cleanup" +for fail in [false, true]: + testScopes(fail) +for direction in StackDirection: + let + reference = drawHud(false, direction) + actual = drawHud(true, direction) + doAssert actual.layers == reference.layers + doAssert actual.layoutStack == reference.layoutStack + doAssert actual.currentDrawLayer == reference.currentDrawLayer + doAssert actual.clipRect == reference.clipRect + when defined(silkyTesting): + doAssert actual.semantic.toSnapshot() == reference.semantic.toSnapshot() +echo "Isolated drawing preserves deferred HUD placement and clips." diff --git a/tests/test_metal_compositing.nim b/tests/test_metal_compositing.nim new file mode 100644 index 00000000..7eb69492 --- /dev/null +++ b/tests/test_metal_compositing.nim @@ -0,0 +1,552 @@ +## Exercises Metal UI compositing into an externally owned command buffer. +## Run on macOS with nim r -d:useMetal4 tests/test_metal_compositing.nim. + +when defined(useMetal4) and (defined(macosx) or defined(ios)): + import + pixie, vmath, + pkg/metal4 as gpu, + silky, silky/common, silky/drawers/metal4 as drawers + + const + White = ColorRGBX(r: 255, g: 255, b: 255, a: 255) + Red = ColorRGBX(r: 255, g: 0, b: 0, a: 255) + Blue = ColorRGBX(r: 0, g: 0, b: 255, a: 255) + HalfGreen = ColorRGBX(r: 0, g: 128, b: 0, a: 128) + + objc: + proc commandBufferWithUnretainedReferences( + self: MTLCommandQueue + ): MTLCommandBuffer + + template expectSilkyError(message: string, body: untyped) = + ## Requires invalid embedding input to report a library-specific error. + block: + var rejected = false + try: + body + except SilkyError: + rejected = true + doAssert rejected, message + + proc newTarget( + device: MTLDevice, + size: IVec2, + pixelFormat: MTLPixelFormat + ): MTLTexture = + ## Creates a CPU-readable color target without a window or drawable layer. + let descriptor = MTLTextureDescriptor.texture2DDescriptorWithPixelFormat( + pixelFormat, + size.x.uint, + size.y.uint, + false + ) + descriptor.setUsage(MTLTextureUsageRenderTarget) + descriptor.setStorageMode(MTLStorageModeShared) + result = device.newTextureWithDescriptor(descriptor) + checkNil(result, "Could not create the external render target") + + proc encodeBackground(commandBuffer: MTLCommandBuffer, target: MTLTexture) = + ## Models the scene pass that has already rendered behind the UI. + let + pass = MTLRenderPassDescriptor.renderPassDescriptor() + color = pass.colorAttachments().objectAtIndexedSubscript(0) + color.setTexture(target) + color.setLoadAction(MTLLoadActionClear) + color.setStoreAction(MTLStoreActionStore) + color.setClearColor(MTLClearColor(red: 0, green: 0, blue: 1, alpha: 1)) + let encoder = commandBuffer.renderCommandEncoderWithDescriptor(pass) + checkNil(encoder, "Could not begin the scene pass") + encoder.endEncoding() + + proc quad(position, size, clipSize: Vec2, color: ColorRGBX): + array[6, DrawerVertex] = + ## Builds a solid UI rectangle sampling the center of the white atlas. + const Corners = [ + vec2(0, 0), vec2(1, 0), vec2(1, 1), + vec2(0, 0), vec2(1, 1), vec2(0, 1) + ] + for index, corner in Corners: + result[index] = DrawerVertex( + pos: position + corner * size, + uv: vec2(0.5), + color: color, + clipPos: vec2(0), + clipSize: clipSize, + maskUv: vec2(-1), + texture: 0 + ) + + proc readPixels(target: MTLTexture, size: IVec2, + pixelFormat: MTLPixelFormat, mipmapLevel = 0'u): Image = + ## Reads the completed target into ordinary RGBA image storage. + result = newImage(size.x.int, size.y.int) + target.getBytes( + result.data[0].addr, + (size.x.int * sizeof(ColorRGBX)).uint, + MTLRegion( + origin: MTLOrigin(x: 0, y: 0, z: 0), + size: MTLSize(width: size.x.uint, height: size.y.uint, depth: 1) + ), + mipmapLevel + ) + if pixelFormat == MTLPixelFormatBGRA8Unorm: + for pixel in result.data.mitems: + swap(pixel.r, pixel.b) + + proc checkPixel(image: Image, x, y: int, expected: ColorRGBX, + message: string) = + ## Permits one byte of blend rounding on each color channel. + let actual = image[x, y] + doAssert abs(actual.r.int - expected.r.int) <= 1 and + abs(actual.g.int - expected.g.int) <= 1 and + abs(actual.b.int - expected.b.int) <= 1 and + abs(actual.a.int - expected.a.int) <= 1, + message & ": got " & $actual & ", expected " & $expected + + proc checkComposite(device: MTLDevice, queue: MTLCommandQueue, + pixelFormat: MTLPixelFormat) = + ## Checks scene retention and independent UI uploads before one commit. + let + atlas = newImage(2, 2) + initialSize = ivec2(32, 24) + atlas.fill(White) + let drawer = newDrawer( + device, + atlas, + initialSize, + pixelFormat = pixelFormat + ) + defer: drawer.close() + for size in [initialSize, ivec2(56, 40)]: + let + target = device.newTarget(size, pixelFormat) + commandBuffer = queue.commandBuffer() + first = quad( + vec2(2), + vec2(size.x.float32 * 0.75'f - 2, size.y.float32 - 4), + size.vec2, + Red + ) + second = quad( + vec2(size.x.float32 * 0.5'f, 2), + vec2(size.x.float32 * 0.5'f - 2, size.y.float32 * 0.5'f - 2), + size.vec2, + HalfGreen + ) + defer: target.release() + checkNil(commandBuffer, "Could not create the external command buffer") + commandBuffer.encodeBackground(target) + drawer.setExternalFrame(commandBuffer, target) + drawer.endFrame(atlas, size.vec2, unsafeAddr first[0], first.len) + doAssert commandBuffer.status() == MTLCommandBufferStatusNotEnqueued, + "The UI must leave command-buffer submission to its owner" + drawer.setExternalFrame(commandBuffer, target) + drawer.endFrame(atlas, size.vec2, unsafeAddr second[0], second.len) + doAssert commandBuffer.status() == MTLCommandBufferStatusNotEnqueued, + "A second UI pass must remain in the same uncommitted buffer" + + expectSilkyError("Each UI pass must receive an explicit target"): + drawer.endFrame(atlas, size.vec2, nil, 0) + + commandBuffer.commit() + commandBuffer.waitUntilCompleted() + checkNSError(commandBuffer.error(), "External UI compositing failed") + let pixels = target.readPixels(size, pixelFormat) + pixels.checkPixel(0, 0, Blue, "Scene background survives the UI") + pixels.checkPixel(3, size.y.int div 4, Red, + "The first UI pass retains its vertices after the second upload") + pixels.checkPixel(size.x.int * 5 div 8, size.y.int div 4, + rgbx(127, 128, 0, 255), "Alpha blending over the first UI pass") + pixels.checkPixel(size.x.int - 3, size.y.int div 4, + rgbx(0, 128, 127, 255), "Alpha blending over the scene") + pixels.checkPixel(size.x.int - 3, size.y.int - 3, Blue, + "The resized viewport retains uncovered scene pixels") + + proc checkAtlasMipmaps(device: MTLDevice, queue: MTLCommandQueue) = + ## Checks prepared mip averages and regeneration after partial atlas edits. + const + Purple = ColorRGBX(r: 128, g: 0, b: 128, a: 255) + Green = ColorRGBX(r: 0, g: 255, b: 0, a: 255) + Mixed = ColorRGBX(r: 96, g: 64, b: 96, a: 255) + let + atlas = newImage(4, 4) + size = ivec2(8, 8) + for y in 0 ..< atlas.height: + for x in 0 ..< atlas.width: + atlas[x, y] = if (x + y) mod 2 == 0: Red else: Blue + let drawer = newDrawer(device, atlas, size) + defer: drawer.close() + doAssert drawer.needsAtlasPreparation(), + "A newly uploaded mipmapped atlas must report pending preparation" + let texture = drawer.atlasTexture() + doAssert texture.mipmapLevelCount() == 3, + "The atlas must allocate every mip level down to 1x1" + let initialCommands = queue.commandBuffer() + checkNil(initialCommands, "Could not create the atlas command buffer") + drawer.prepareAtlas(initialCommands) + doAssert not drawer.needsAtlasPreparation(), + "Recorded mipmap work must not require another encoder break" + drawer.prepareAtlas(initialCommands) + doAssert initialCommands.status() == MTLCommandBufferStatusNotEnqueued, + "Atlas preparation must leave submission to the application" + initialCommands.commit() + initialCommands.waitUntilCompleted() + checkNSError(initialCommands.error(), "Initial atlas mipmaps failed") + let + initialMip = texture.readPixels( + ivec2(2), + MTLPixelFormatRGBA8Unorm, + 1 + ) + initialLastMip = texture.readPixels( + ivec2(1), + MTLPixelFormatRGBA8Unorm, + 2 + ) + for y in 0 ..< 2: + for x in 0 ..< 2: + initialMip.checkPixel(x, y, Purple, "Mip one averages atlas texels") + initialLastMip.checkPixel(0, 0, Purple, "The last mip averages the atlas") + + for y in 0 ..< 2: + for x in 0 ..< 2: + atlas[x, y] = Green + drawer.uploadAtlasRegion(atlas, 0, 0, 2, 2) + doAssert drawer.needsAtlasPreparation(), + "Partial atlas uploads must invalidate the preparation query" + let updateCommands = queue.commandBuffer() + checkNil(updateCommands, "Could not create the atlas update buffer") + drawer.prepareAtlas(updateCommands) + doAssert not drawer.needsAtlasPreparation(), + "Partial atlas preparation must become clean after encoding" + doAssert updateCommands.status() == MTLCommandBufferStatusNotEnqueued, + "Preparing changed atlas pixels must not submit the command buffer" + updateCommands.commit() + updateCommands.waitUntilCompleted() + checkNSError(updateCommands.error(), "Partial atlas mipmaps failed") + let + updatedMip = texture.readPixels( + ivec2(2), + MTLPixelFormatRGBA8Unorm, + 1 + ) + updatedLastMip = texture.readPixels( + ivec2(1), + MTLPixelFormatRGBA8Unorm, + 2 + ) + updatedMip.checkPixel(0, 0, Green, "A partial upload regenerates its mip") + updatedMip.checkPixel(1, 1, Purple, "Unchanged mip regions are preserved") + updatedLastMip.checkPixel( + 0, + 0, + Mixed, + "The last mip includes partial edits" + ) + + atlas.fill(Red) + drawer.uploadAtlas(atlas) + doAssert drawer.needsAtlasPreparation(), + "Full atlas uploads must invalidate the preparation query" + let target = device.newTarget(size, MTLPixelFormatBGRA8Unorm) + defer: target.release() + let + frameCommands = queue.commandBuffer() + vertices = quad(vec2(0), size.vec2, size.vec2, White) + checkNil(frameCommands, "Could not create the mipmap frame buffer") + frameCommands.encodeBackground(target) + drawer.setExternalFrame(frameCommands, target) + drawer.endFrame(atlas, size.vec2, unsafeAddr vertices[0], vertices.len) + doAssert frameCommands.status() == MTLCommandBufferStatusNotEnqueued, + "Automatic atlas preparation must not submit the UI frame" + frameCommands.commit() + frameCommands.waitUntilCompleted() + checkNSError(frameCommands.error(), "Automatic atlas mipmaps failed") + let + finalMip = drawer.atlasTexture().readPixels( + ivec2(1), + MTLPixelFormatRGBA8Unorm, + 2 + ) + rendered = target.readPixels(size, MTLPixelFormatBGRA8Unorm) + finalMip.checkPixel(0, 0, Red, "EndFrame regenerates dirty atlas mipmaps") + rendered.checkPixel(4, 4, Red, "The UI samples the updated atlas") + + expectSilkyError("Atlas preparation must reject a missing buffer"): + drawer.prepareAtlas(0.MTLCommandBuffer) + expectSilkyError("Atlas preparation must reject a submitted buffer"): + drawer.prepareAtlas(frameCommands) + let unretained = queue.commandBufferWithUnretainedReferences() + checkNil(unretained, "Could not create the unretained validation buffer") + expectSilkyError("Atlas preparation requires retained GPU resources"): + drawer.prepareAtlas(unretained) + + proc checkEmptyFrames(device: MTLDevice, queue: MTLCommandQueue) = + ## Checks empty UI preserves the scene and still prepares changed atlases. + let + atlas = newImage(2, 2) + size = ivec2(8, 8) + atlas.fill(Red) + let drawer = newDrawer(device, atlas, size) + defer: drawer.close() + when defined(silkyMetalTesting): + let initialWork = drawer.recordedWorkForTesting() + for atlasSize in [2, 4]: + let image = newImage(atlasSize, atlasSize) + image.fill(Red) + let + target = device.newTarget(size, MTLPixelFormatBGRA8Unorm) + commandBuffer = queue.commandBuffer() + defer: target.release() + checkNil(commandBuffer, "Could not create the empty UI command buffer") + commandBuffer.encodeBackground(target) + for _ in 0 .. 1: + drawer.setExternalFrame(commandBuffer, target) + drawer.endFrame(image, size.vec2, nil, 0) + doAssert not drawer.needsAtlasPreparation(), + "Empty UI must prepare initial and resized atlas mipmaps" + doAssert commandBuffer.status() == MTLCommandBufferStatusNotEnqueued, + "Empty UI must leave submission to the application" + when defined(silkyMetalTesting): + doAssert drawer.recordedWorkForTesting() == initialWork, + "Empty UI must not allocate vertex buffers or open render passes" + expectSilkyError("An empty UI pass must release its borrowed frame"): + drawer.endFrame(image, size.vec2, nil, 0) + commandBuffer.commit() + commandBuffer.waitUntilCompleted() + checkNSError(commandBuffer.error(), "Empty UI compositing failed") + let pixels = target.readPixels(size, MTLPixelFormatBGRA8Unorm) + for y in 0 ..< size.y.int: + for x in 0 ..< size.x.int: + pixels.checkPixel(x, y, Blue, "Empty UI must preserve every scene pixel") + let mip = drawer.atlasTexture().readPixels( + ivec2(1), + MTLPixelFormatRGBA8Unorm, + if atlasSize == 2: 1'u else: 2'u + ) + mip.checkPixel(0, 0, Red, "Empty UI must prepare the full atlas mip chain") + + let singleTexel = newImage(1, 1) + singleTexel.fill(White) + drawer.uploadAtlas(singleTexel) + doAssert drawer.needsAtlasPreparation(), + "An external single-level atlas must stage its initial upload" + let singleCommands = queue.commandBuffer() + drawer.prepareAtlas(singleCommands) + doAssert not drawer.needsAtlasPreparation(), + "A prepared single-level atlas must not require mipmap work" + singleTexel.fill(Red) + drawer.uploadAtlasRegion(singleTexel, 0, 0, 1, 1) + doAssert drawer.needsAtlasPreparation(), + "A single-level atlas update must be ordered after earlier draws" + drawer.prepareAtlas(singleCommands) + doAssert not drawer.needsAtlasPreparation(), + "A prepared single-level atlas update must become clean" + singleCommands.commit() + singleCommands.waitUntilCompleted() + checkNSError(singleCommands.error(), "Single-level atlas uploads failed") + let singlePixel = drawer.atlasTexture().readPixels( + ivec2(1), + MTLPixelFormatRGBA8Unorm + ) + singlePixel.checkPixel(0, 0, Red, "Single-level uploads execute in order") + + proc checkQueuedUploads(device: MTLDevice, queue: MTLCommandQueue) = + ## Preserves atlas, image, and vertex contents across queued UI frames. + const Colors = [Red, HalfGreen, White] + let + initialAtlas = newImage(2, 2) + image = newImage(2, 2) + size = ivec2(12, 8) + initialAtlas.fill(White) + let drawer = newDrawer( + device, + initialAtlas, + size, + pixelFormat = MTLPixelFormatRGBA8Unorm + ) + defer: drawer.close() + let imageId = drawer.allocateTexture(2, 2) + var + commands: seq[MTLCommandBuffer] + targets: seq[MTLTexture] + defer: + for commandBuffer in commands: + commandBuffer.release() + for target in targets: + target.release() + for index, value in Colors: + let atlas = newImage(if index == 2: 4 else: 2, 2) + atlas.fill(value) + image.fill(value) + drawer.uploadAtlas(atlas) + drawer.uploadTextureRows(imageId, image, 0, image.height) + doAssert drawer.needsAtlasPreparation(), + "Atlas and independent image updates must be prepared before sampling" + # Staging must own its pixels, including after the caller edits the image. + atlas.fill(Blue) + image.fill(Blue) + let + commandBuffer = queue.commandBuffer() + target = device.newTarget(size, MTLPixelFormatRGBA8Unorm) + checkNil(commandBuffer, "Could not create a queued UI command buffer") + commandBuffer.retain() + commands.add(commandBuffer) + targets.add(target) + commandBuffer.encodeBackground(target) + drawer.setExternalFrame(commandBuffer, target) + drawer.endFrame(atlas, size.vec2, nil, 0) + doAssert not drawer.needsAtlasPreparation(), + "An empty UI frame must encode pending uploads without submitting them" + var vertices: seq[DrawerVertex] + vertices.add(quad(vec2(0), vec2(6, 8), size.vec2, White)) + var imageVertices = quad(vec2(6, 0), vec2(6, 8), size.vec2, White) + for vertex in imageVertices.mitems: + vertex.texture = imageId + vertices.add(imageVertices) + drawer.setExternalFrame(commandBuffer, target) + drawer.endFrame(atlas, size.vec2, vertices[0].addr, vertices.len) + doAssert commandBuffer.status() == MTLCommandBufferStatusNotEnqueued, + "Multiple queued UI frames must remain application-owned" + # Encoding every frame before any commit exposes CPU texture overwrites. + for commandBuffer in commands: + commandBuffer.commit() + commands[^1].waitUntilCompleted() + for index, target in targets: + checkNSError(commands[index].error(), "Queued external UI frame failed") + let + pixels = target.readPixels(size, MTLPixelFormatRGBA8Unorm) + expected = if Colors[index] == HalfGreen: + rgbx(0, 128, 127, 255) + else: + Colors[index] + pixels.checkPixel(2, 4, expected, + "A queued frame must sample its original atlas upload") + pixels.checkPixel(9, 4, expected, + "A queued frame must sample its original independent image upload") + + let atlas = newImage(2, 2) + atlas.fill(Red) + drawer.uploadAtlas(atlas) + let + commandBuffer = queue.commandBuffer() + target = device.newTarget(size, MTLPixelFormatRGBA8Unorm) + left = quad(vec2(0), vec2(6, 8), size.vec2, White) + right = quad(vec2(6, 0), vec2(6, 8), size.vec2, White) + defer: target.release() + commandBuffer.encodeBackground(target) + drawer.setExternalFrame(commandBuffer, target) + drawer.endFrame(atlas, size.vec2, unsafeAddr left[0], left.len) + atlas[0, 0] = White + drawer.uploadAtlasRegion(atlas, 0, 0, 1, 1) + drawer.setExternalFrame(commandBuffer, target) + drawer.endFrame(atlas, size.vec2, unsafeAddr right[0], right.len) + commandBuffer.commit() + commandBuffer.waitUntilCompleted() + checkNSError(commandBuffer.error(), "Same-buffer atlas update failed") + let pixels = target.readPixels(size, MTLPixelFormatRGBA8Unorm) + pixels.checkPixel(2, 4, Red, + "An atlas edit must not change earlier draws in the same command buffer") + pixels.checkPixel(9, 4, White, + "Later draws must see the partial atlas edit in queue order") + + proc checkInvalidFrames(device: MTLDevice, queue: MTLCommandQueue) = + ## Rejects invalid handles, incompatible formats, and submitted buffers. + let + image = newImage(2, 2) + size = ivec2(8, 8) + drawer = newDrawer(device, image, size) + defer: drawer.close() + let target = device.newTarget(size, MTLPixelFormatBGRA8Unorm) + defer: target.release() + let otherTarget = device.newTarget(size, MTLPixelFormatRGBA8Unorm) + defer: otherTarget.release() + let commandBuffer = queue.commandBuffer() + checkNil(commandBuffer, "Could not create the validation command buffer") + + expectSilkyError("An external drawer must reject a missing device"): + discard newDrawer(0.MTLDevice, image, size) + expectSilkyError("A frame must reject a missing command buffer"): + drawer.setExternalFrame(0.MTLCommandBuffer, target) + expectSilkyError("A frame must reject a missing render target"): + drawer.setExternalFrame(commandBuffer, 0.MTLTexture) + expectSilkyError("The target must match the pipeline pixel format"): + drawer.setExternalFrame(commandBuffer, otherTarget) + + commandBuffer.encodeBackground(target) + commandBuffer.commit() + commandBuffer.waitUntilCompleted() + checkNSError(commandBuffer.error(), "Validation background failed") + expectSilkyError("A frame must reject a submitted command buffer"): + drawer.setExternalFrame(commandBuffer, target) + + when defined(macosx): + proc checkSilkyInterface(device: MTLDevice, queue: MTLCommandQueue) = + ## Exercises real window input and public UI with an injected drawer. + let + size = ivec2(32, 24) + builder = newAtlasBuilder(32, 1) + window = newWindow( + "Silky Metal compositing test", + size, + visible = false, + vsync = false + ) + defer: window.close() + let drawer = newDrawer( + device, + builder.atlasImage, + size, + pixelFormat = MTLPixelFormatRGBA8Unorm + ) + defer: drawer.close() + let + sk = newSilky(window, builder.atlasImage, builder.atlas, drawer) + target = device.newTarget(size, MTLPixelFormatRGBA8Unorm) + defer: target.release() + doAssert sk.drawer == drawer, "Silky must use the supplied drawer" + doAssert not window.visible, "The integration window must stay hidden" + doAssert window.onButtonPress != nil, + "The real constructor must install the window's input handling" + let commandBuffer = queue.commandBuffer() + checkNil(commandBuffer, "Could not create the UI command buffer") + commandBuffer.encodeBackground(target) + sk.uiScale = 2 + sk.beginUi(window, size) + sk.drawRect(vec2(2), vec2(4), Red) + drawer.setExternalFrame(commandBuffer, target) + sk.endUi() + doAssert commandBuffer.status() == MTLCommandBufferStatusNotEnqueued, + "Public endUi must leave the application in charge of submission" + commandBuffer.commit() + commandBuffer.waitUntilCompleted() + checkNSError(commandBuffer.error(), "Public Silky compositing failed") + let pixels = target.readPixels(size, MTLPixelFormatRGBA8Unorm) + pixels.checkPixel(0, 0, Blue, "Public endUi preserves the scene") + pixels.checkPixel(5, 5, Red, "Public endUi renders scaled UI geometry") + pixels.checkPixel(10, 10, Red, "Injected drawers honor Silky's UI scale") + pixels.checkPixel(13, 13, Blue, "The UI leaves uncovered pixels intact") + + proc main() = + ## Owns the device and submission queue independently of every UI drawer. + let device = MTLCreateSystemDefaultDevice() + checkNil(device, "The compositing test requires a Metal device") + defer: device.release() + let queue = device.newCommandQueue() + checkNil(queue, "Could not create the compositing queue") + defer: queue.release() + for pixelFormat in [MTLPixelFormatBGRA8Unorm, MTLPixelFormatRGBA8Unorm]: + checkComposite(device, queue, pixelFormat) + checkAtlasMipmaps(device, queue) + checkEmptyFrames(device, queue) + checkQueuedUploads(device, queue) + checkInvalidFrames(device, queue) + when defined(macosx): + checkSilkyInterface(device, queue) + echo "Metal compositing passed: rendering, atlas mips, empty UI, and validation." + + main() + when defined(ios): + quit(0) +else: + echo "Skipped Metal compositing: requires macOS or iOS with useMetal4."