Link Search Menu Expand Document

Loading Geometry

A loaded model displayed as a ViewportBody.

ViewportBody is the geometry-source-agnostic container that feeds every rendering pass in the Metal viewport. It carries interleaved vertex data, triangle indices, edge polylines, analytic arcs, and a collection of per-body properties — color, material, transform, visibility, and pickability. The viewport has no dependency on OpenCASCADE; bridging from B-Rep to ViewportBody is the responsibility of the consuming app (typically via OCCTSwiftTools).

Bodies are passed to the view through a Binding<[ViewportBody]>:

struct ContentView: View {
    @StateObject private var controller = ViewportController()
    @State private var bodies: [ViewportBody] = []

    var body: some View {
        MetalViewportView(controller: controller, bodies: $bodies)
            .onAppear { bodies = [.box(id: "b1", color: SIMD4<Float>(0.6, 0.8, 1.0, 1.0))] }
    }
}

Appending, replacing, or removing elements from bodies is all that is needed to update the scene.


The vertex buffer layout

ViewportBody.vertexData is a flat [Float] array with stride 6 — six floats per vertex, in this exact order:

Offset Field
0 position X
1 position Y
2 position Z
3 normal X
4 normal Y
5 normal Z

Each stride block is 24 bytes. The renderer reads positions and normals directly from this buffer with no repacking step.

indices is a [UInt32] triangle list parallel to this vertex buffer: every three consecutive values form one triangle.

Building a body by hand

// A single triangle in the XY plane, normal pointing +Z.
let vertexData: [Float] = [
    //  px,   py,   pz,   nx,   ny,   nz
     0.0,  1.0,  0.0,  0.0,  0.0,  1.0,
    -1.0, -1.0,  0.0,  0.0,  0.0,  1.0,
     1.0, -1.0,  0.0,  0.0,  0.0,  1.0,
]
let indices: [UInt32] = [0, 1, 2]

// Wireframe outline — one polyline per logical edge.
let edges: [[SIMD3<Float>]] = [
    [SIMD3(0, 1, 0), SIMD3(-1, -1, 0), SIMD3(1, -1, 0), SIMD3(0, 1, 0)]
]

let triangle = ViewportBody(
    id: "triangle",
    vertexData: vertexData,
    indices: indices,
    edges: edges,
    color: SIMD4<Float>(0.4, 0.7, 1.0, 1.0)
)

All ViewportBody.init parameters after edges have defaults, so passing only the three required arrays is valid.


Primitive factories

Three convenience factories are available for quick prototyping:

// Axis-aligned box (default 1×1×1, grey), 0.5 tall along Z.
let box = ViewportBody.box(
    id: "box",
    width: 2.0,
    height: 0.5,
    depth: 1.0,
    color: SIMD4<Float>(0.8, 0.5, 0.2, 1.0),
    up: .z
)

// Upright cylinder along Z (default radius 0.5, height 1, 64 segments).
let cyl = ViewportBody.cylinder(
    id: "cyl",
    radius: 0.3,
    height: 2.0,
    segments: 64,
    color: SIMD4<Float>(0.6, 0.6, 0.9, 1.0),
    up: .z
)

// UV sphere with its poles on Z (default radius 0.5, 48 segments, 32 rings).
let sphere = ViewportBody.sphere(
    id: "sphere",
    radius: 1.0,
    segments: 48,
    rings: 32,
    color: SIMD4<Float>(0.9, 0.3, 0.3, 1.0),
    up: .z
)

The viewport is Z-up, but the factories default to up: .y so that code written before the parameter existed keeps its geometry. Pass up: .z, as above, to have height (and a cylinder’s axis or a sphere’s poles) run along Z. See PrimitiveUpAxis.

All three factories populate faceIndices so sub-body face selection works out of the box.


Analytic arc edges

Pre-sampled polylines in edges facet circles at a fixed density. For round features that must stay smooth at any zoom level, use arcs instead. The renderer samples each ViewportArc to line segments adaptively per frame based on its projected size.

// A full horizontal circle of radius 1 in the XY plane (the viewport is Z-up).
let circle = ViewportArc.circle(
    center: SIMD3<Float>(0, 0, 0),
    radius: 1.0,
    xAxis: SIMD3<Float>(1, 0, 0),
    yAxis: SIMD3<Float>(0, 1, 0)
)

// A 90° arc (quarter circle).
let arc = ViewportArc(
    center: SIMD3<Float>(0, 0, 0),
    radius: 0.5,
    xAxis: SIMD3<Float>(1, 0, 0),
    yAxis: SIMD3<Float>(0, 1, 0),
    startAngle: 0,
    endAngle: .pi / 2
)

let roundBody = ViewportBody(
    id: "round",
    vertexData: [],   // mesh data omitted for illustration
    indices: [],
    edges: [],
    arcs: [circle, arc],
    color: SIMD4<Float>(0.7, 0.7, 0.7, 1.0)
)

A body may mix edges and arcs, but note that a tap on either reports PickResult.kind == .edge — prefer one representation per body when you need to distinguish pick results.


Per-segment edge colour and a visible range

A long path (a toolpath, a trajectory, a survey line) is one body with a polyline in edges. Two optional fields style it without splitting it into several bodies or rebuilding it every frame:

  • edgeColors gives each flattened segment its own colour. It needs one entry per segment, body.edgeSegmentCount; any other count is ignored and the edges keep the body’s usual colour.
  • edgeDrawRange limits which segments are drawn, and picked, so a playhead can reveal the path.

Colours are sRGB (display) RGBA, drawn as given, by default, like color, vertexColors and TriangleStyle.color. If your data is linear-light, set body.edgeColorSpace = .linear and the colours are converted for display (mid-grey 0.5 reads about 188 instead of 128); changing it costs nothing, as it re-uploads no buffer.

import simd

enum MoveKind { case rapid, cut, plunge }

// One long polyline; segment `i` is the move from points[i] to points[i + 1].
let points: [SIMD3<Float>] = toolpathPoints
let moves: [MoveKind] = toolpathMoves   // points.count - 1 entries

let palette: [MoveKind: SIMD4<Float>] = [
    .rapid: SIMD4<Float>(0.55, 0.55, 0.60, 1),
    .cut: SIMD4<Float>(0.15, 0.75, 0.35, 1),
    .plunge: SIMD4<Float>(0.90, 0.30, 0.15, 1),
]

var path = ViewportBody(
    id: "toolpath",
    vertexData: [], indices: [],
    edges: [points],
    color: SIMD4<Float>(0.8, 0.8, 0.8, 1)   // the fallback colour
)
path.edgeColors = moves.map { palette[$0] ?? path.color }
assert(path.edgeColors.count == path.edgeSegmentCount)

Both are cheap to change on a body that is already on screen. Assigning either leaves generation alone and never re-uploads the polyline: edgeColors re-uploads only its own 16 bytes per segment (about 192 KB for 12,000 segments), and edgeDrawRange uploads nothing, so it can move every frame:

// `bodies` is the array bound to MetalViewportView; `index` is the path's position in it.
func show(upTo playhead: Int) {
    bodies[index].edgeDrawRange = 0..<playhead
}

// Dim what has been played: fade the colours of the first `playhead` segments.
func dimPlayed(upTo playhead: Int) {
    var colors = bodies[index].edgeColors
    for i in 0..<min(playhead, colors.count) { colors[i].w = 0.35 }
    bodies[index].edgeColors = colors
}

The range is clamped, so a playhead may run past the end (0..<Int.max shows everything) and 0..<0 shows nothing. On a meshed body the segment colour replaces the contrast edge colour and edgeIntensity still applies; alpha 0 hides a segment’s drawing but leaves it pickable, so use edgeDrawRange to take segments out of picking too. OffscreenRenderer honours both fields, so a render of frame n of an animation is the same data. Arcs are not affected, and neither is boundingBox, so the camera fit does not change as the path is revealed. See the ViewportBody reference.


faceIndices for sub-body face selection

When faceIndices is populated it must be parallel to the triangle count (indices.count / 3). Each element maps the corresponding triangle back to an integer face ID (e.g., a B-Rep face index). The GPU pick texture encodes objectIndex | (triangleIndex << 16); the controller uses faceIndices[triangleIndex] to resolve which logical face was tapped.

// Two quads forming two logical faces (face 0 and face 1).
// indices: [0,1,2, 0,2,3, 4,5,6, 4,6,7]  → 4 triangles
let faceIndices: [Int32] = [0, 0, 1, 1]  // triangles 0–1 → face 0; 2–3 → face 1

Leave faceIndices empty when face-level selection is not needed.


Per-body transform, color, and material

Each body carries its own model transform applied on top of the scene model matrix in the vertex shader. You can animate a body’s position without re-uploading vertex data:

var body = ViewportBody.box(id: "moving", color: SIMD4<Float>(1, 1, 0, 1))

// Translate 3 units along X.
body.transform = simd_float4x4(
    SIMD4<Float>(1, 0, 0, 0),
    SIMD4<Float>(0, 1, 0, 0),
    SIMD4<Float>(0, 0, 1, 0),
    SIMD4<Float>(3, 0, 0, 1)   // column-major: translation in last column
)

For simple shading, set color (RGBA), roughness (0 = mirror, 1 = rough, default 0.5), and metallic (0 = dielectric, 1 = metal, default 0.0):

body.color = SIMD4<Float>(0.9, 0.6, 0.1, 1.0)  // gold-ish
body.roughness = 0.2
body.metallic = 0.9

For full PBR control — clearcoat, IOR, emission — assign a PBRMaterial, which overrides the three shorthand fields:

body.material = PBRMaterial(
    baseColor: SIMD3<Float>(0.05, 0.05, 0.05),
    metallic: 1.0,
    roughness: 0.05,
    clearcoat: 1.0,
    clearcoatRoughness: 0.03
)

Surface transparency is driven by color.w (or PBRMaterial.opacity). Bodies with opacity < 1 are sorted back-to-front and rendered in a separate translucent pass. Their edges are still drawn, and a selected translucent body gets the usual selection tint and outline ring. The .xray display mode sends every body’s surface through this pass.


Point-cloud bodies

Set primitiveKind to .point to skip the triangle/edge passes and render vertices as point sprites instead. vertexData and indices are ignored in this mode.

let points: [SIMD3<Float>] = [
    SIMD3<Float>(0, 0, 0),
    SIMD3<Float>(1, 0, 0),
    SIMD3<Float>(0, 1, 0),
]

// Optional per-point colors (parallel to vertices).
let colors: [SIMD4<Float>] = [
    SIMD4<Float>(1, 0, 0, 1),
    SIMD4<Float>(0, 1, 0, 1),
    SIMD4<Float>(0, 0, 1, 1),
]

let cloud = ViewportBody(
    id: "cloud",
    vertexData: [],
    indices: [],
    edges: [],
    vertices: points,
    vertexColors: colors,
    color: SIMD4<Float>(1, 1, 1, 1),   // fallback when vertexColors is empty
    pointRadius: 0.03,                  // world-space radius; clamped 1–64 px on screen
    primitiveKind: .point
)

boundingBox falls back to the vertices array when vertexData is empty, so CameraState.fit(to:) and frustum culling work correctly for point clouds.


Per-vertex colours on a mesh (scalar fields, analysis maps)

vertexColors also colours a mesh: one RGBA per mesh vertex, interpolated across each triangle. It is opt-in, so existing bodies draw as before: set vertexColorMode to .replace (the vertex colour is the surface colour) or .multiply (it tints the body color).

// Colour each vertex of a mesh by its height: blue at the bottom, red at the top.
var body = ViewportBody(id: "part", vertexData: vertexData, indices: indices, edges: [],
                        color: SIMD4<Float>(1, 1, 1, 1))
let zs = stride(from: 0, to: vertexData.count, by: 6).map { vertexData[$0 + 2] }
let (lo, hi) = (zs.min() ?? 0, zs.max() ?? 1)
body.vertexColors = zs.map { z in
    let t = (z - lo) / max(hi - lo, .leastNonzeroMagnitude)
    return SIMD4<Float>(t, 0, 1 - t, 1)        // parallel to the mesh vertices
}
body.vertexColorMode = .replace               // the default, .ignored, leaves the body colour

The same two properties are parameters of ViewportBody.directMesh(...), so a kernel’s flat position/normal arrays take a flat colour array too (vertexColors must have one entry per position, so positions.count / 3).

Things to know:

  • Colour space. sRGB (display) values by default, like color, so a ramp built from an sRGB colour table looks as it does in an image tool. If your field is linear light, set body.vertexColorSpace = .linear instead (it applies to point clouds too): lit surfaces then use the values as linear albedo and unlit surfaces and points encode them for display. Only RGB is read; opacity still comes from color.w.
  • Fallback. An empty array, or one whose count differs from the mesh’s vertex count, is ignored and the body keeps its colour.
  • Everywhere the surface is drawn. All rendering qualities (including PN tessellation and mesh shaders), the x-ray and translucent passes, the .unlit display mode (which shows the ramp exactly, with no lighting), overlay bodies, and OffscreenRenderer.
  • Cost. Assigning vertexColors counts as a geometry change (new generation), so the body re-uploads. Switching vertexColorMode alone does not.

Visibility and pickability

Two independent switches control how a body participates in rendering and picking:

Property Default Effect when false
isVisible true Body is not drawn at all
isPickable true Body is excluded from the pick buffer (still drawn)

Setting isPickable = false is useful for datum planes or reference overlays that should never steal a pick from the geometry behind them.

var ground = ViewportBody.box(id: "ground", width: 20, height: 0.01, depth: 20,
                              color: SIMD4<Float>(0.5, 0.5, 0.5, 0.3), up: .z)
ground.isPickable = false
ground.material = PBRMaterial(baseColor: SIMD3(0.5, 0.5, 0.5), opacity: 0.3)

Bridging from OCCTSwift geometry

The viewport has no OpenCASCADE dependency. Tessellation is handled by OCCTSwiftTools (import OCCTSwiftTools), which lives in a separate package:

import OCCTSwiftTools

// shape: an OCCTSwift Shape (solid, face, compound, etc.)
// deflection: chord-height tolerance for triangulation (smaller = finer)
if let (body, metadata) = try? CADFileLoader.shapeToBodyAndMetadata(
    shape,
    id: "part",
    deflection: 0.01,
    color: SIMD4<Float>(0.7, 0.8, 0.9, 1.0)
) {
    bodies.append(body)
    // metadata contains face/edge maps for selection round-tripping
}

shapeToBodyAndMetadata tessellates the B-Rep, interleaves position+normal into vertexData, builds edge polylines for silhouette and feature edges, and populates faceIndices so every triangle traces back to its source B-Rep face. The consuming app stores the returned metadata to resolve PickResult.triangleIndex → B-Rep face → downstream selection operations.


Direct-mesh bodies (skip the interleave)

ViewportBody.directMesh(...) takes de-interleaved position and normal arrays and uploads them as two separate GPU buffers, instead of one interleaved stride-6 buffer. Reach for it when your geometry source already gives you flat, contiguous position and normal arrays — which is exactly what a CAD kernel’s triangulation hands you.

let body = ViewportBody.directMesh(
    id: "bracket",
    positions: mesh.vertexData,     // [Float] — flat [px, py, pz, …]
    normals: mesh.normalData,       // [Float] — flat [nx, ny, nz, …], parallel
    indices: mesh.indices,
    color: SIMD4<Float>(0.72, 0.74, 0.76, 1.0),
    faceIndices: mesh.faceIndices
)

Why

The interleaved path has to walk every vertex and repack position+normal into one array before upload. That is a full extra pass and an extra copy of the mesh in memory — pure overhead when the kernel already stores the two arrays contiguously. Skipping it is a load-time and peak-memory win, and it grows with mesh size (it matters on a 700k-triangle part, not on a box).

It also skips NormalSmoothing entirely, which is the right thing when your normals come from OCCT: they are already analytically correct, so re-deriving them is wasted work — and, on highly anisotropic meshes, re-deriving them from face normals was the source of the “brushed” striations fixed in v1.1.22.

What to know before switching

  • It is opt-in and additive. Bodies built with init(vertexData:) are untouched; both kinds can coexist in one scene.
  • Your normals are used verbatim. ViewportConfiguration.autoSmoothNormals does not apply to direct bodies. If your source normals are flat/faceted and you were relying on auto-smoothing to round them, stay on the interleaved path (or smooth them yourself before handing them over).
  • Tessellation is skipped for direct bodies — renderingQuality = .enhanced has no effect on them.
  • Everything else works: bounding box, CameraState.fit(to:), CPU raycasting, shadows, SSAO, silhouettes, the overlay layer, transparency, and GPU picking all support direct bodies, in both ViewportRenderer and OffscreenRenderer. The selection/hover outline and triangleStyles highlights work on direct bodies in ViewportRenderer.
  • Pick caveat: a direct body’s vertices holds its mesh vertices, so it does not additionally carry B-Rep corner-vertex or per-segment edge pick indices. Face picking, CPU raycast, and edge display are unaffected.

usesDirectMesh tells you which path a body will take:

if body.usesDirectMesh {
    // renderer binds positions @ buffer 0, normals @ buffer 2
}

Generation counter and cache invalidation

Each ViewportBody.init call atomically increments a static counter and stamps the new body’s generation property with a unique UInt64. Assigning or mutating a geometry field (vertexData, indices, edges, arcs, faceIndices, edgeIndices, vertices, vertexIndices, vertexColors, meshPositions, meshNormals) takes a fresh value too. The renderer compares generations to detect geometry changes and decide whether to re-upload vertex, index, or edge buffers to the GPU. This means:

  • Mutating an appearance or placement property on an existing body (e.g., changing color or transform) does not re-upload vertex buffers — only the uniform is updated.
  • Mutating geometry in place (e.g., body.vertexData = deformed for a live deformation) and handing the body back re-uploads that body’s buffers on the next frame.
  • Replacing a body with a new ViewportBody(...) (new generation) forces a full buffer re-upload.
  • Bulk-replacing all bodies triggers re-uploads for every body whose generation changed.

For live editing workflows where you change color frequently but geometry rarely, update color in place rather than constructing a new body.