Skip to content
Draft
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
6 changes: 6 additions & 0 deletions .github/workflows/build.yml
Original file line number Diff line number Diff line change
Expand Up @@ -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

Expand Down Expand Up @@ -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
Expand Down
83 changes: 83 additions & 0 deletions docs/metal-embedding.md
Original file line number Diff line number Diff line change
@@ -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.
2 changes: 1 addition & 1 deletion nimby.lock
Original file line number Diff line number Diff line change
@@ -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
Expand Down
51 changes: 47 additions & 4 deletions src/silky/contexts.nim
Original file line number Diff line number Diff line change
Expand Up @@ -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

Expand Down Expand Up @@ -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:
Expand Down Expand Up @@ -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.
Expand Down
Loading
Loading