Ductane v1.6.0
Contents

Docs / Characters

Skinned characters on the GPU

SkinnedModel loads a rigged character and keeps it on the GPU at rest. SkinnedInstance is one copy of it in the world, with its own pose. SkinningPass skins every instance once a frame in a compute pass, writing the posed vertices into buffers laid out exactly like your game's static meshes. The scene pass and every shadow cascade then draw the character with the pipelines you already use for props: no skinned vertex shader, no second vertex layout, no skinned shadow pipeline.

It builds on skeletons and clips, which covers posing a rig with SkeletonPose and leaves the skinning shader to you. Here the engine does the skinning.

The types

TypeWhat it is
SkinnedGeometryA character's geometry at rest, read from a file with no GPU.
SkinnedModelOne per character file: the rig, the rest mesh and the skinning data in GPU buffers. Shared by every copy.
SkinnedInstanceOne per character drawn: its pose, its joint palette and its posed vertices.
SkinningPassThe compute pipeline that skins instances. One per game.
SkinnedModelError.assetNotFound, .noSkinnedMeshes, .unsupportedLayout, .jointOutOfRange(file:joint:jointCount:) or .couldNotCreate, each printing as a sentence.

Loading a character

public convenience init(url: URL, device: MTLDevice, vertexDescriptor: MTLVertexDescriptor,
                        semantics: [Int: String]) throws

Pass your game's static vertex descriptor and semantics, the ones your prop pipeline was built with. The layout carries no joints and no weights, because the posed character is drawn by that pipeline. The engine reads the influences separately. Position must be float3. If there's a normal, it must be float3 too, and a tangent can be float3 or float4. Anything else throws .unsupportedLayout.

USD or glTF: the extension says which. The skeleton and every clip come through RigLoader, so model.rig is the same Rig that page describes, and a glTF file is read once for the rig and the meshes together. A glTF character comes out as the same character in USD would: its vertices in skeleton space at rest, a mesh hung under a joint without a skin (a sword in a hand) bound wholly to that joint, its texture coordinates and materials as meshes reads them. A vertex with eight influences (JOINTS_1/WEIGHTS_1) keeps its four strongest. Then every skinned mesh in the file is merged into one. A character creator usually exports each part as its own skinned mesh: body, head, hair, each piece of armor. Drawn as they arrive, that's a draw per part per pass, re-skinned for every shadow cascade. Merged, it's one vertex buffer and one draw per material.

Triangles are grouped by what their material is, not what it's called. Parts often bring materials with different names that describe the same surface: one palette texture, the same factors. They count as one. model.mesh has one submesh per entry in model.materials, and partCount says how many meshes were merged.

Reading a character takes a second or more, so do it off the main thread. SkinnedModel.read(url:vertexDescriptor:semantics:reportingTo:) can run on any thread and returns a SkinnedModel.Source; reportingTo hears of a glTF clip left out, as on the skeletons page. Finish it on the main thread with init(_:device:vertexDescriptor:semantics:), passing the same descriptor and semantics:

let source = try await Task.detached {
    try SkinnedModel.read(url: url, vertexDescriptor: layout, semantics: semantics)
}.value
let model = try SkinnedModel(source, device: device, vertexDescriptor: layout, semantics: semantics)

SkinnedGeometry.read(url:vertexDescriptor:semantics:skeletonJointCount:) reads the same geometry with no device, for a tool or a test. It returns the merged layouts, the rest positions and normals, four joints and four weights per vertex, and the parts and their materials.

What reading checks and fixes:

One instance per character

let guardA = try model.makeInstance()   // your game
let guardB = try model.makeInstance()
guardA.pose.set(to: idle)

pose is a SkeletonPose for the model's skeleton. A new one starts at rest. Set it each frame with a clip, a cross-fade, a mix or an overlay, exactly as skeletons describes. Then leave it: the skinning pass reads it from there.

An instance keeps its GPU memory once per frame in flight, because the GPU may still be drawing the previous frame while the next one's pose is written. A single copy would be overwritten mid-draw.

Skinning, once a frame

Make one SkinningPass(device:) and encode it first in encodePrePasses, before the shadow passes, because everything that draws a character reads what it writes:

func encodePrePasses(into commandBuffer: MTL4CommandBuffer, frameSlot: Int, interpolation: Float) {
    skinning.encode(into: commandBuffer, frameSlot: frameSlot, instances: characters)   // your game's
    // then your shadow passes
}

encode(into:frameSlot:instances:) copies each instance's pose.skinningMatrices into that frame slot's palette, then dispatches one thread per vertex. It does linear blend skinning: the four joint matrices are blended into one matrix, which is then applied to the vertex. The upper 3×3 of that matrix turns normals and tangents, which are renormalized, and a tangent's handedness passes through unchanged. Whatever your layout holds that skinning doesn't write, such as texture coordinates and colors, stays as it was at rest.

The engine's own passes wait for the compute work before their vertex stage: the scene, ShadowMap, ShadowAtlas and ShadowCubes. A render pass of your own that draws a character must open with a barrier, because Metal 4 tracks no hazards between passes for you:

encoder.barrier(afterQueueStages: .dispatch, beforeStages: .vertex, visibilityOptions: .device)

writePalette(frameSlot:) is public only for a game that skins some other way. The pass calls it for you.

Drawing the posed vertices

Draw model.mesh as you draw any loaded mesh, but bind each vertex buffer from the instance. vertexBufferAddress(_:frameSlot:) returns the posed copy for a layout that skinning writes into, and the shared rest buffer for one it doesn't:

// your game, in encode
let mesh = character.model.mesh
for layout in mesh.vertexBuffers.indices {
    argumentTable.setAddress(character.vertexBufferAddress(layout, frameSlot: frameSlot), index: layout)
}
for (index, submesh) in mesh.submeshes.enumerated() {
    bindSurface(character.model.materials[index])   // your game
    encoder.drawIndexedPrimitives(primitiveType: submesh.primitiveType, indexCount: submesh.indexCount,
                                  indexType: submesh.indexType,
                                  indexBuffer: submesh.indexBuffer.buffer.gpuAddress + UInt64(submesh.indexBuffer.offset),
                                  indexBufferLength: submesh.indexBuffer.length)
}

Never bind mesh's own vertex buffers for a character. They're the rest pose. The posed vertices are in skeleton space, so the model matrix is your placement times model.rig.nodeTransform, as for any loaded rig.

posedBuffer(_:frameSlot:) returns a slot's posed vertices for reading back, from a test or a tool measuring what was drawn.

Part of a character

triangles(boundTo:least:) returns, for each submesh, the triangles whose every corner is weighted at least least (0.5 by default) to the joints a mask covers. Build the mask with Skeleton.mask(from:weight:). Use it for a first-person view's arms, a hidden head or a severed limb. The indices point into the merged vertices, so make an index buffer of them and draw an instance's posed vertices with it.

Memory and residency

Add model.allocations once, and each instance's allocations, to the renderer's residency set and commit it. A buffer the GPU can't reach draws garbage, not nothing.

An instance costs, for each frame in flight:

bounds is the rest pose, in skeleton space. A raised arm leaves it, so cull with bounds.expanded(by:) and a margin, or a character's shadow disappears just as it moves.

What it does not do