Link Search Menu Expand Document

Configuration

These types control viewport appearance, rendering fidelity, and picking. ViewportConfiguration is the single struct passed to ViewportController(configuration:) that governs everything from camera limits and grid style to anti-aliasing and tessellation quality. ClipPlane defines section cuts. PickingConfiguration gates the GPU pick-ID buffer. EdgeLineConfiguration sets edge line width and dash pattern. The supporting enums — RenderingQuality, UniformTessellationFactor, RenderLayer, AxisStyle, GridStyle, and ViewCubePosition — are referenced by fields inside ViewportConfiguration.

GestureConfiguration and DynamicPivotConfiguration are documented on the Input and Camera pages respectively — ViewportConfiguration embeds them by value.

Topics


ViewportConfiguration

ViewportConfiguration is the master configuration value type for a viewport instance. It is Sendable and can be constructed with any subset of its parameters overridden; every field has a default. Pass it to ViewportController(configuration:), then hand that controller to MetalViewportView(controller:bodies:):

var config = ViewportConfiguration.cad
config.gridStyle = .dots
let controller = ViewportController(configuration: config)
// MetalViewportView(controller: controller, bodies: $bodies)

ViewportController.configuration is a let: the configuration is fixed for the controller’s lifetime. The settings that can change live are mirrored as @Published properties on the controller (displayMode, showAxes, showGrid, lightingConfiguration, enableTAA, the depth-of-field values and so on); to change anything else, build a new controller.


Camera fields

initialCameraState

public var initialCameraState: CameraState  // default: .isometric

The camera state loaded when the viewport first appears. Changing this after the viewport is created has no effect unless the host resets the camera explicitly.


rotationStyle

public var rotationStyle: RotationStyle  // default: .turntable

Controls how drag gestures orbit the camera. See RotationStyle on the Camera page. Which way a drag turns the model is set separately, by gestureConfiguration.dragRotation (default .rotateObject: the model turns with the finger on both axes, in every rotation style).


minDistance

public var minDistance: Float  // default: 0.1

Minimum camera-to-pivot distance in world units. Prevents the camera from passing through the orbit center when the user zooms in.


maxDistance

public var maxDistance: Float  // default: 10000

Maximum camera-to-pivot distance in world units. Caps the zoom-out range.


defaultFieldOfView

public var defaultFieldOfView: Float?  // default: nil (keep initialCameraState.fieldOfView)

Vertical field of view in degrees for the initial perspective camera. When set, ViewportController applies it over initialCameraState.fieldOfView when it is created (effectiveInitialCameraState returns the result). nil keeps the initial camera’s own FOV, including a camera you assign to initialCameraState after creating the configuration. Either way, reset(animated:) returns to that FOV.


gestureConfiguration

public var gestureConfiguration: GestureConfiguration  // default: .default

Platform-specific gesture mapping, including the drag direction (dragRotation). See GestureConfiguration and Drag direction.


Display fields

displayMode

public var displayMode: DisplayMode  // default: .shaded

Geometry display mode (shaded, wireframe, hidden-line, etc.). See DisplayMode.


xrayOpacity

public var xrayOpacity: Float  // default: DisplayMode.defaultXRayOpacity (0.2)

Opacity ceiling for surfaces in .xray mode, clamped to 0...1 on set (and in the initializer) by DisplayMode.clampedXRayOpacity(_:). Seeds ViewportController.xrayOpacity, which is what the renderer reads; change that one to tune it live.


lightingConfiguration

public var lightingConfiguration: LightingConfiguration  // default: .threePoint

Lighting preset and per-light properties. See LightingConfiguration.


showViewCube

public var showViewCube: Bool  // default: true

Whether the 3D navigation cube overlay is visible.


viewCubePosition

public var viewCubePosition: ViewCubePosition  // default: .bottomTrailing

Corner of the viewport where the navigation cube is placed. See ViewCubePosition.


showOrientationGnomon

public var showOrientationGnomon: Bool  // default: false

Whether the screen-space orientation gnomon (corner RGB axis triad HUD) is shown.


showScaleBar

public var showScaleBar: Bool  // default: false

Whether the screen-space scale bar HUD is shown.


scaleBarUnitLabel

public var scaleBarUnitLabel: String  // default: ""

Unit suffix appended to the scale bar readout (e.g. "mm"). Pass an empty string for a bare number.


showAxes

public var showAxes: Bool  // default: false

Whether the world-space coordinate axes are rendered.


axisLength

public var axisLength: Float?  // default: nil (sized to the scene)

Length of each coordinate axis in world units, measured from the origin along +X (red), +Y (green) and +Z (blue). nil sizes the axes to the scene every frame: max(1.5 × reach, 0.5 × diagonal) of the visible geometry-layer bodies’ world bounds, where reach is the bounds’ largest absolute coordinate. The axes start at the origin, so this makes them poke out of a model that contains it at any scale, and keeps them a visible size beside a model that sits away from it. An empty scene gets 2 units. A value you set always wins. OffscreenRenderer resolves nil the same way from the bodies it renders.


axisRadius

public var axisRadius: Float?  // default: nil (automatic)

World-space radius of the axis cylinders for .cylinder; for .constantScreenWidth, the radius they have at the default camera’s zoom (distance 10, 45° FOV), scaled with the zoom from there. nil picks it automatically: for .cylinder, 1 % of the axis length (0.02 at 2 units), so axes sized to a large scene stay proportionate instead of shrinking to a hairline; for .constantScreenWidth, 0.02. A value you set always wins. A 1 px centre line is always drawn as well, so an axis never disappears when its radius falls below a pixel.


axisStyle

public var axisStyle: AxisStyle  // default: .cylinder

Fixed world-space radius or constant on-screen width. See AxisStyle.


showGrid

public var showGrid: Bool  // default: true

Whether the ground grid is rendered. The grid lies in the XY plane at z = 0, matching the Z-up world (turntable orbit, standard views).


gridStyle

public var gridStyle: GridStyle  // default: .plane

Ground plane with grid lines, or adaptive dot grid. See GridStyle.


gridSize

public var gridSize: Float  // default: 100.0

Side length, in world units, of the square grid centred on the world origin (it spans ±gridSize / 2 on X and Y). Applies to both styles: no line or dot is drawn outside the square. 0, a negative value or .infinity leaves the grid unbounded. Either way the grid only covers a window around the camera pivot (about ±50 spacings for .plane, ±15 for .dots) at the current spacing level.


gridBaseSpacing

public var gridBaseSpacing: Float  // default: 1.0

Fundamental grid spacing in world units (both styles). The renderer snaps to this value times a power of gridSubdivisions as the camera zooms.


gridSubdivisions

public var gridSubdivisions: Int  // default: 10

Factor between grid spacing levels (both styles). In the .plane style every gridSubdivisions-th line is drawn with more contrast, marking where the next-coarser level’s lines fall.


backgroundColor

public var backgroundColor: SIMD4<Float>  // default: SIMD4<Float>(0.95, 0.95, 0.95, 1.0)

Viewport background color in the light appearance, as sRGB (display) RGBA with premultiplied-alpha conventions, drawn as given. The default is a near-white light grey. In the dark appearance darkModeBackgroundColor replaces it, unless that is nil.


darkModeBackgroundColor

public var darkModeBackgroundColor: SIMD4<Float>?  // default: ViewportConfiguration.defaultDarkModeBackgroundColor

Background colour used in the dark appearance. Following dark mode is on by default, with defaultDarkModeBackgroundColor, a near-black grey (0.12, 0.12, 0.12, 1).

  • Follow dark mode with your own colour: set this to it.
  • Opt out: set it to nil, and backgroundColor applies in both appearances.
  • Force an appearance: MetalViewportView follows the SwiftUI colour scheme of its environment, so .preferredColorScheme(.light) or .environment(\.colorScheme, .dark) on the view (or an ancestor) pins it.

resolvedBackgroundColor(isDark:) returns the colour in effect for an appearance. Headless renders follow the system appearance by default too, through OffscreenRenderOptions.appearance (pin .light/.dark for reproducible output); see Rendering.

Up to v1.2.3 the dark colour was hard-coded and replaced even a custom backgroundColor; it is now this configurable field.


Anti-aliasing

msaaSampleCount

public var msaaSampleCount: Int  // default: 4

Requested Metal MSAA sample count for the main color/depth attachments: 1 for no MSAA, 4 (the default) for 4× MSAA. The renderer clamps the request to a count the device supports — values below 2 mean no MSAA, otherwise the largest of 8, 4 and 2 that does not exceed the request and that MTLDevice.supportsTextureSampleCount(_:) accepts, falling back to 1 — so an unsupported value degrades instead of failing renderer creation. OffscreenRenderOptions.msaaSampleCount uses the same mapping. Use 1 in the .performance preset to reclaim fillrate on mobile.


preferredFramesPerSecond

public var preferredFramesPerSecond: Int  // default: 120

Frame rate the viewport asks for. MTKView picks the supported display rate closest to it, so the default runs at 120 Hz on ProMotion displays and 60 Hz on 60 Hz ones. The camera’s animation and inertia timer runs at the same rate. Set 60 to cap the rate and save power. It is not an init parameter; set it on the value before creating the ViewportController. On iPhone, rates above 60 also need CADisableMinimumFrameDurationOnPhone set to YES in the app’s Info.plist.

var config = ViewportConfiguration.cad
config.preferredFramesPerSecond = 60
let controller = ViewportController(configuration: config)

Earlier releases hard-coded 60 FPS for both the view and the camera timer.


enableTAA

public var enableTAA: Bool  // default: false

Whether temporal anti-aliasing is composited over the rendered frame.

TAA works with every display mode and with SSAO and silhouettes on or off. When the SSAO/silhouette composite does not run (SSAO and silhouettes both off, or an .unlit or .wireframe display mode), the TAA output is copied to the drawable by a final pass of its own. Before that pass existed (issue #244) such a frame never reached the drawable: the view stayed blank and a headless readback held uninitialised memory.


taaBlendFactor

public var taaBlendFactor: Float  // default: 0.9

History blend weight for TAA. 0.0 = no history (effectively disables TAA), 1.0 = full history (maximum smoothing, but ghosting on fast camera moves). Meaningful only when enableTAA == true.


Silhouettes

enableSilhouettes

public var enableSilhouettes: Bool  // default: true

Whether a screen-space edge-darkening silhouette pass is applied after geometry rendering. The pass (and SSAO) reads a depth prepass of opaque geometry-layer bodies only: translucent bodies, RenderLayer.overlay bodies (manipulators, gizmos) and point clouds get no silhouette or ambient occlusion.


silhouetteThickness

public var silhouetteThickness: Float  // default: 1.0

Edge thickness multiplier. 1.0 = normal, 2.0 = twice as thick.


silhouetteIntensity

public var silhouetteIntensity: Float  // default: 0.7

Darkness of detected edges. 0.0 = invisible (silhouette pass does nothing), 1.0 = fully darkened.


Selection outline

selectionOutline

public var selectionOutline: SelectionOutlineStyle  // default: .selection

Colour and width of the outline ring drawn around bodies in ViewportController.selectedBodyIDs. The width is in drawable pixels, so the ring looks the same on a millimetre-scale part and a building. Set width to 0 to hide it. Not an init parameter; assign it on the value. See SelectionOutlineStyle.

var config = ViewportConfiguration.cad
config.selectionOutline = SelectionOutlineStyle(color: SIMD3(1.0, 0.6, 0.1), width: 4)

hoverOutline

public var hoverOutline: SelectionOutlineStyle  // default: .hover

Outline for ViewportController.hoveredBodyID when that body is not also selected. Not an init parameter.


selectionTint

public var selectionTint: SelectionTintStyle  // default: .selection

Colour and strength of the surface wash mixed into bodies in ViewportController.selectedBodyIDs, separate from the outline ring around them. The default is the faint blue (15 % of (0.3, 0.5, 1.0)) the shaded pass has always used. Set it to the outline colour so an orange outline does not sit around a blue-tinted body, or to .off (or any style with strength 0) for outline-only selection. Applies in every display mode, .unlit included. Not an init parameter; assign it on the value. See SelectionTintStyle.

var config = ViewportConfiguration.cad
let orange = SIMD3<Float>(1.0, 0.6, 0.1)
config.selectionOutline = SelectionOutlineStyle(color: orange, width: 4)
config.selectionTint = SelectionTintStyle(color: orange, strength: 0.25)
// or outline-only selection:
config.selectionTint = .off
config.hoverTint = .off

hoverTint

public var hoverTint: SelectionTintStyle  // default: .hover

Tint for ViewportController.hoveredBodyID when that body is not also selected (a selected body uses selectionTint). Not an init parameter.

heightfieldMeshCellPixels

public var heightfieldMeshCellPixels: Float  // default: 4

The widest a Heightfield mesh cell may appear on screen, in pixels. Each 64 x 64-cell tile is drawn at the coarsest level of detail whose cell is no wider than this. Clamped to Heightfield.meshCellPixelsRange (1...32) when drawn; the sensible range is 3 to 8. 4 is the balanced default; 2 is a cost cliff, about nine times the 4 px GPU time on an M4 at 1668 x 1194 with 4x MSAA (1.7 million triangles of one to two pixels). OffscreenRenderOptions.heightfieldMeshCellPixels carries the same field, and init(matching:) copies it.

heightfieldLatticePixels

public var heightfieldLatticePixels: Float  // default: 16

How far apart the lines of a Heightfield’s .wireframe lattice are on screen, in drawable pixels. Each tile’s lines are the smallest power-of-two number of cells apart that spans at least this many pixels (so between this and twice this), and never closer than the tile’s mesh cell, so a value at or below heightfieldMeshCellPixels draws one line per mesh cell. Clamped to Heightfield.latticePixelsRange (1...256) when drawn; no effect in other display modes. Width, dash and colour come from edgeLineConfiguration and the body. OffscreenRenderOptions.heightfieldLatticePixels carries the same field, and init(matching:) copies it. See the wireframe lattice.


Edge lines

edgeLineConfiguration

public var edgeLineConfiguration: EdgeLineConfiguration  // default: .default

Width and dash pattern for body edge polylines (wireframe, shaded-with-edges and x-ray modes). See EdgeLineConfiguration.

Example — thick dashed edges:

var config = ViewportConfiguration.cad
config.edgeLineConfiguration = EdgeLineConfiguration(width: 2.5, dashPattern: .dashed)

Frustum culling

enableFrustumCulling

public var enableFrustumCulling: Bool  // default: true

When true, bodies whose world-space bounding box falls entirely outside the camera frustum are skipped during draw encoding. Bodies with no boundingBox are never culled. The shadow map pass is exempt (off-screen casters can shadow visible geometry).

Example — disable for debugging:

var config = ViewportConfiguration.cad
config.enableFrustumCulling = false

Normal smoothing

autoSmoothNormals

public var autoSmoothNormals: Bool  // default: false

When true, crease-aware normal smoothing is applied to each body’s mesh when its GPU buffers are first built. Flat-shaded meshes (per-face normals from some tessellators) cannot be rounded by Phong tessellation alone; this averages normals across shared vertices while preserving hard edges. Computed once per body and cached; the smoothed data feeds the standard, tessellated (.enhanced) and mesh-shader (.maximum) paths alike, since all three read the same vertex buffer. Direct-mesh bodies are not smoothed (their producer supplies the normals). Enabled by the .cadHighQuality preset.


normalSmoothingCreaseAngle

public var normalSmoothingCreaseAngle: Float  // default: 0.524  (~30°, in radians)

Crease angle threshold for autoSmoothNormals, and for the PN-triangle patches of .enhanced and .maximum (hardware tessellation, or the mesh-shader subdivision on an Apple9 GPU). Adjacent face normals that differ by more than this angle are treated as a hard edge and kept sharp; a tessellated patch edge whose end normals differ by more stays flat instead of bulging. It used to be a fixed 30° for tessellation, so a coarse mesh (an 8-segment sphere, say) never rounded; raising the angle rounds one (#202). Raise it with care: with autoSmoothNormals on it also smooths shading across edges up to that angle (a box’s 90° edges at 1.6 rad), and on meshes with per-face vertices a rounded edge can pull away from a neighbouring flat one, opening a crack along it. Fixed for the controller’s lifetime, like the rest of the configuration.


Picking

pickingConfiguration

public var pickingConfiguration: PickingConfiguration  // default: .init()

Governs whether the GPU pick-ID texture is allocated and written. See PickingConfiguration.


Depth of field

enableDepthOfField

public var enableDepthOfField: Bool  // default: false

Whether a post-process depth-of-field blur is applied.


dofAperture

public var dofAperture: Float  // default: 2.8

Simulated f-number. Smaller values produce a shallower (stronger) blur.


dofFocalDistance

public var dofFocalDistance: Float  // default: 0

Focus distance in world units from the camera, measured along the line of sight (in orthographic, from a reference eye in front of the pivot; see below). 0 activates autofocus on the scene centre: the view depth of the mean of the visible geometry-layer bodies’ world-space bounding-box centres (each body’s transform applied). It used to be the straight-line distance from the eye, which put an off-axis centre out of focus (issue #215). In orthographic it is measured from a reference eye in front of the pivot, at the distance a perspective camera showing the same height would sit (orthographicScale / (2 · tan(fieldOfView / 2))), not from the eye, which is only placed in front of the scene and moves back whenever the scene grows; so the focal plane stays put as the eye moves, follows the pivot, and matches the same framing in perspective (issue #217). Following the pivot, it moves when the dynamic pivot slides along the line of sight, by the depth slid; a focal distance equal to that reference distance focuses on the pivot.


dofMaxBlurRadius

public var dofMaxBlurRadius: Float  // default: 8.0

Maximum circle-of-confusion radius in pixels. Clamps the blur on very out-of-focus regions.


Rendering quality

renderingQuality

public var renderingQuality: RenderingQuality  // default: .standard

Controls tessellation tier and mesh-shader usage. See RenderingQuality.


tessellationMaxFactor

public var tessellationMaxFactor: Int  // default: 32

Maximum hardware tessellation factor per edge. Only used when renderingQuality == .enhanced or .maximum. The .cadHighQuality preset raises this to 48. The mesh-shader path of .maximum subdivides each triangle into at most 16 segments per edge, so a value above 16 is capped there (the hardware tessellator of .enhanced allows up to 64).

Metal caps the factor at 64, and the fractional-even partitioning the tessellated pipelines use needs an even value. An out-of-range or odd value used to make pipeline creation fail, silently disabling tessellation; the renderer now clamps it to 2...64 and rounds an odd value up to the next even one. The pipelines are built with the value in effect when the renderer is created, so raising it later is capped to that value.


adaptiveTessellation

public var adaptiveTessellation: Bool  // default: true

When true, the tessellation level adapts per edge to the projected screen-space length (target about 4 px per tessellated edge) and surface curvature, concentrating triangles where the mesh is coarse relative to the viewport, capped at tessellationMaxFactor. Projection uses each body’s transform, so moved and scaled bodies get the right factors.

When false, every patch is tessellated uniformly, whatever its size on screen, at the factor uniformTessellationFactor chooses. A uniform factor f costs roughly f² triangles per input triangle. Requires renderingQuality != .standard.


uniformTessellationFactor

public var uniformTessellationFactor: UniformTessellationFactor  // default: .loadAdaptive()

The factor used when adaptiveTessellation == false. See UniformTessellationFactor.


Dynamic pivot

dynamicPivotConfiguration

public var dynamicPivotConfiguration: DynamicPivotConfiguration  // default: .default

Configuration for the automatic orbit-pivot heuristic that shifts the orbit center from the scene centroid to the surface under the cursor as the user zooms in. See DynamicPivotConfiguration.


init(...)

public init(
    initialCameraState: CameraState = .isometric,
    rotationStyle: RotationStyle = .turntable,
    minDistance: Float = 0.1,
    maxDistance: Float = 10000,
    defaultFieldOfView: Float? = nil,  // nil → keep initialCameraState.fieldOfView
    gestureConfiguration: GestureConfiguration = .default,
    displayMode: DisplayMode = .shaded,
    xrayOpacity: Float = DisplayMode.defaultXRayOpacity,
    lightingConfiguration: LightingConfiguration = .threePoint,
    showViewCube: Bool = true,
    viewCubePosition: ViewCubePosition = .bottomTrailing,
    showAxes: Bool = false,
    axisLength: Float? = nil,  // nil → sized to the scene
    axisRadius: Float? = nil,  // nil → automatic
    axisStyle: AxisStyle = .cylinder,
    showGrid: Bool = true,
    gridStyle: GridStyle = .plane,
    gridSize: Float = 100.0,
    gridBaseSpacing: Float = 1.0,
    gridSubdivisions: Int = 10,
    backgroundColor: SIMD4<Float> = SIMD4<Float>(0.95, 0.95, 0.95, 1.0),
    darkModeBackgroundColor: SIMD4<Float>? = ViewportConfiguration.defaultDarkModeBackgroundColor,
    msaaSampleCount: Int = 4,
    enableSilhouettes: Bool = true,
    silhouetteThickness: Float = 1.0,
    silhouetteIntensity: Float = 0.7,
    edgeLineConfiguration: EdgeLineConfiguration = .default,
    enableFrustumCulling: Bool = true,
    autoSmoothNormals: Bool = false,
    normalSmoothingCreaseAngle: Float = 0.524,
    pickingConfiguration: PickingConfiguration = .init(),
    enableDepthOfField: Bool = false,
    dofAperture: Float = 2.8,
    dofFocalDistance: Float = 0,
    dofMaxBlurRadius: Float = 8.0,
    renderingQuality: RenderingQuality = .standard,
    tessellationMaxFactor: Int = 32,
    adaptiveTessellation: Bool = true,
    uniformTessellationFactor: UniformTessellationFactor = .loadAdaptive(),
    enableTAA: Bool = false,
    taaBlendFactor: Float = 0.9,
    dynamicPivotConfiguration: DynamicPivotConfiguration = .default,
    showOrientationGnomon: Bool = false,
    showScaleBar: Bool = false,
    scaleBarUnitLabel: String = ""
)

All parameters are optional; omit any to accept its default. Construct a preset and then mutate individual fields for targeted changes.

Example — start from .cad, enable scale bar and millimetre label:

var config = ViewportConfiguration.cad
config.showScaleBar = true
config.scaleBarUnitLabel = "mm"

Presets

.cad

public static let cad: ViewportConfiguration

Turntable orbit, ViewCube on, axes on, grid on. All other fields at defaults.


.modelViewer

public static let modelViewer: ViewportConfiguration

Arcball orbit, ViewCube off, axes off, grid off. Suited to 3D model inspection without engineering overlays.


.architectural

public static let architectural: ViewportConfiguration

Turntable orbit, shaded mode, .architectural lighting preset, ViewCube on, grid on, camera pre-positioned at an isometric-front-right view at distance 50.


.performance

public static let performance: ViewportConfiguration

Turntable orbit, shadows disabled, SSAO disabled, MSAA disabled (msaaSampleCount = 1), silhouettes disabled, renderingQuality = .standard. Use on dense many-body scenes (thousands of bodies / hundreds of thousands of triangles) on iPhone or iPad where per-frame whole-scene passes dominate render time.

Example:

let controller = ViewportController(configuration: .performance)
MetalViewportView(controller: controller, bodies: $heavyScene)   // @State var heavyScene: [ViewportBody]

.cadHighQuality

public static let cadHighQuality: ViewportConfiguration

Turntable orbit, ViewCube on, axes on, grid on, autoSmoothNormals = true, renderingQuality = .enhanced, tessellationMaxFactor = 48, adaptiveTessellation = true. Enables GPU PN-triangle Phong tessellation so cylinder and fillet silhouettes stay smooth at any zoom. Requires an Apple3+ GPU; falls back to un-tessellated rendering on older hardware.


RenderingQuality

public enum RenderingQuality: Sendable {
    case standard
    case enhanced
    case maximum
}

Controls the tessellation tier used by ViewportRenderer and, through OffscreenRenderOptions.renderingQuality, by OffscreenRenderer.

Case Description
.standard Finer CPU-side tessellation combined with crease-aware normal smoothing. No GPU hardware tessellation. Runs on all supported hardware.
.enhanced Everything in .standard, plus GPU hardware tessellation using PN triangles (Phong tessellation). Requires an Apple3+ GPU; falls back to .standard if the tessellation pipelines can’t be built.
.maximum Everything in .enhanced, with the surface drawn by mesh shaders: per-meshlet culling, and the same PN-triangle subdivision as .enhanced, done in the mesh stage. Requires an Apple9 GPU (M3 / A17 Pro or later); falls back to .enhanced without one, or if the mesh-shader surface pipeline fails to build. If only the shadow, depth-prepass or pick mesh pipeline fails, the renderer stays on .maximum, draws that pass through the vertex pipeline, and logs which pipeline failed.

Mesh-shader subdivision (.maximum). Until #175 the mesh-shader path drew the input triangles unrefined, so a low-poly body looked faceted next to .enhanced and tessellationMaxFactor, adaptiveTessellation and uniformTessellationFactor did nothing for it. The mesh stage now evaluates each triangle’s PN patch (the one .enhanced builds, with the same crease rule) on a barycentric grid, from the same per-frame factors the hardware tessellator reads, so those three settings and the load governor act on meshlets as they do on patches, and .maximum rounds a coarse sphere or cylinder as .enhanced does. With one even uniform factor the two paths draw the identical surface; with adaptive factors they agree to within a pixel of coverage (the hardware tessellator rounds a factor up to an even number and morphs vertices in, the mesh stage rounds up to an integer). Each edge is capped at 16 segments (a mesh threadgroup writes at most 256 vertices and 512 primitives, and the object stage splits a subdivided meshlet across several threadgroups to fit); a triangle whose edges are subdivided at different levels is snapped so neighbouring triangles, and meshlets, still meet without cracks. Every pass draws the same subdivided surface (shaded and translucent, shadow map, SSAO and silhouette depth, GPU pick, per-triangle highlight, selection mask and stencil), so there is no shadow acne, ring gap or lost highlight. The cost is the PN evaluation per vertex and one mesh threadgroup per chunk of subdivided triangles: with flat or far-away geometry (factor 1) a meshlet draws its triangles without shared vertices, so up to three times the vertex work of the old path for those meshlets. ViewportBody.directMesh bodies and overlay bodies still draw their mesh as given.

Which bodies take which path. Every body with an interleaved mesh (vertexData + indices) is tessellated at .enhanced and drawn through meshlets at .maximum, whether or not it carries faceIndices. Before #161 both paths required faceIndices, so STL/OBJ imports and the Primitives factories silently stayed on the standard path. Bodies built with ViewportBody.directMesh(...) always take the standard direct-mesh path: they bring their own normals and get no PN refinement or meshlets. Overlay-layer bodies always draw through the standard pipelines.

Fallbacks are explicit. When the requested quality can’t run, the renderer logs one line saying why when it is created (no mesh shaders on this GPU, a failed mesh-shader pipeline with Metal’s error, or failed tessellation pipelines; Metal’s error for a tessellation pipeline is logged in debug builds only), and reports what it actually runs:

controller.effectiveRenderingQuality  // RenderingQuality?, nil until a renderer is attached
renderer.effectiveRenderingQuality    // ViewportRenderer, fixed for its lifetime

Example — upgrade quality on a known capable device:

if config.renderingQuality == .standard {
    config.renderingQuality = .enhanced
    config.tessellationMaxFactor = 32
    config.adaptiveTessellation = true
}

UniformTessellationFactor

public enum UniformTessellationFactor: Sendable, Equatable {
    case loadAdaptive(minimum: Int = 4)
    case fixed(Int)
}

How the uniform tessellation factor is chosen when adaptiveTessellation == false.

Case Description
.loadAdaptive(minimum:) Default. The live renderer scales the factor between minimum and tessellationMaxFactor to fit system load. It starts at the maximum. When the smoothed GPU frame time (measured from each frame’s command buffer) rises above 85% of the frame budget (1 / preferredFramesPerSecond, or 1/60), it lowers the factor by 20%. Below 55% it raises the factor by 2. Between the two it holds, and after any change it holds for 30 frames, so the factor never oscillates frame to frame. A frame counts toward lowering the factor only if the GPU was busy for at least 95% of the time since the previous frame ended, that is, only if the GPU is the bottleneck; a frame that follows an idle GPU can confirm headroom but never shows overload (see below). Thermal state caps the ceiling: .fair to 75% of the maximum, .serious to 50%, .critical to minimum. Low Power Mode halves it. A lowered cap applies at once.
.fixed(_:) Always tessellate at this factor, clamped to 1...tessellationMaxFactor.

Off-screen renders (renderHeadless(...) and OffscreenRenderer) never adapt to load: .loadAdaptive uses tessellationMaxFactor there, so the output is deterministic.

var config = ViewportConfiguration.cadHighQuality
config.adaptiveTessellation = false
config.uniformTessellationFactor = .loadAdaptive(minimum: 8)  // or .fixed(12) to pin it

The governor treats a slow frame as overload only when the GPU was saturated (#241). GPU frame time (gpuEndTime - gpuStartTime) is not a property of the scene alone. On Apple silicon the same frame takes longer when the GPU sat idle just before it, and is fast again for the frame submitted straight behind it. On an M4, with 645,000 triangles at 1920x1080 and 4x MSAA, one fixed scene took 10.0 ms as the first frame after a 130 ms pause and 5.0 ms as the next frame; with shadows, SSAO and silhouettes on, it took 15.2 ms and 9.0 ms (#238). The GPU’s clock governor also stretches frames that are submitted at a fixed rate: a 2 ms workload paced at 120 fps took 7.2 ms (87% of the 8.3 ms budget) and was idle for the rest of each interval, while a workload that really overran the budget ran back to back, with no idle gap at all. A debug build leaves the GPU idle for most of each frame (an offscreen frame of that scene took about 130 ms of wall time in debug, against about 10 ms in release, nearly all of it on the CPU), so every frame is a cold one, and the same scene measured 1.6 to 2.5 times slower than in release. The cause is the idle GPU, not the shaders: debug and release link a byte-identical default.metallib, and the run-time compile that SwiftPM’s native build system falls back to runs at the same speed as the offline one.

So the governor pairs each frame’s GPU time with the idle gap before it, both read from the GPU’s own timestamps (the previous frame’s gpuEndTime against this frame’s gpuStartTime):

  • A frame the GPU was busy for at least 95% of the span since the previous frame ended is at face value: frames are running back to back, so the GPU is the bottleneck. This is the only kind of frame that can lower the factor.
  • Any other frame (the first frame after a pause, a frame paced by the display, a frame stretched to fill its interval) is an upper bound on its cost, because the GPU may have been clocked down. It can still pull the smoothed time down, so a light scene earns a higher factor, but it never pushes the smoothed time up. With no smoothed time yet it counts as 70% of the budget, the middle of the hold band. The first frame a renderer measures counts as following an idle GPU.

What follows from that:

  • Cold frames no longer lower the factor. Replaying the measurements above, a stream of 10.0 ms frames that each follow a pause used to lower the factor to minimum at the 8.3 ms budget and now holds it at the maximum, and so does the 15.2 ms stream at 16.7 ms; a scene that is truly over budget, with frames back to back, lowers it exactly as before.
  • The factor now follows missed frames, not near misses. A scene that fits its budget with more than 5% of each interval idle holds the factor even when its frames read above 85% of the budget. Frames the GPU stretches to fill the interval also read 70% to 90% of the budget for a light scene, so the factor rises only once a frame reads under 55%.
  • A debug build, whose CPU-side encoding keeps the GPU idle, never saturates it, so it keeps the maximum factor where a release build of a GPU-bound scene would lower it. Pin the factor with .fixed(_:) when you compare quality across builds. The default, adaptiveTessellation = true, never reads GPU time.
  • Profile GPU time in a release build with frames submitted back to back, and do not read a debug build’s GPU time as the device’s real cost. Metal shader validation (MTL_SHADER_VALIDATION) instruments every shader and made the same scenes 10 to 40 times slower, so leave it off when you measure. Metal API validation (MTL_DEBUG_LAYER) did not measurably change the best-case GPU time in these runs; it costs CPU time, which in turn widens the idle gap.
  • A release build that renders on demand, such as after the view sat idle, sees the same slow first frames. The governor ignores them as overload.

RenderLayer

public enum RenderLayer: Hashable, Sendable {
    case geometry
    case overlay
}

Controls when in the render order a ViewportBody is drawn.

Case Behaviour
.geometry Drawn in the normal geometry pass with standard depth testing.
.overlay Drawn after the selection-outline pass using an always-pass depth state, so the body is visible even when behind other geometry. Overlay bodies get no selection or hover outline (and no per-triangle highlight). Use for manipulator widgets and similar always-on-top affordances.

Overlay bodies are widgets, not model geometry (#170):

  • Their surfaces draw in every display mode, .wireframe included. Their edges and analytic arcs follow the display mode’s edge rule like geometry edges (shown in .wireframe, .shadedWithEdges and .xray, and always for a body without a mesh), and are drawn on top too.
  • They cast no shadows and receive none, so scene geometry never shadows a gizmo.
  • They don’t size the grid, the axes or the shadow map, but they do widen the camera’s near/far fit, so a gizmo in front of or behind a flat model is not clipped away.
  • In the GPU pick pass they stamp exactly what is drawn, with always-pass depth, after all geometry: surfaces, edges (whether or not edgeIndices is set, so a ring drawn as a polyline can be grabbed), arcs and vertices. A widget therefore wins the pick over geometry in front of it, as it is drawn over it, and a later overlay body wins over an earlier one. See Picking.

Set on ViewportBody.renderLayer. See ViewportBody for the full body API.

Example:

var gizmo = ViewportBody(/* … */)
gizmo.renderLayer = .overlay  // always visible, never occluded

SelectionOutlineStyle

public struct SelectionOutlineStyle: Sendable, Hashable

Colour and width of the outline ring the live renderer draws around a selected or hovered body. Used by ViewportConfiguration.selectionOutline and .hoverOutline. The ring is a screen-space dilation of the body’s silhouette: a single-sample pass rasterises the selected and hovered bodies into a selection mask, and the main pass paints every pixel within width pixels of the mask (with a one-pixel soft outer edge), outside the bodies’ stencil footprint. It stays the same thickness at any zoom and model scale, and it rings any mesh whatever its normals; before #209 the ring came from pushing vertices out along their normals, which left no ring around a flat-normal mesh seen face-on (a box from the front). Widths above 32 px are drawn 32 px wide, since the dilation reads every mask pixel within the width. Every meshed body gets the ring in every display mode: a colourless pass stencil-marks each selected or hovered body’s whole silhouette, ignoring depth, so translucent bodies, bodies in .wireframe and bodies partly or wholly behind nearer geometry all get a ring rather than a filled shape. The ring itself is drawn on top, so it stays visible around a hidden body; before #177 the parts of a body covered by nearer geometry were left unmarked and the outline colour painted over the occluder there. Edge-only and point bodies get no ring. OffscreenRenderer draws the same ring from OffscreenRenderOptions.selectionOutline / hoverOutline.

Property Type Default Description
color SIMD3<Float> — Outline colour, sRGB (display) RGB.
width Float 3.0 Outline width in drawable pixels. 0 hides the outline.
Preset Colour Width
.selection (0.1, 0.5, 1.0) bright blue 3 px
.hover (0.4, 0.7, 1.0) light blue 3 px

The faint tint the shaded pass mixes into selected and hovered bodies is separate: see SelectionTintStyle.


SelectionTintStyle

public struct SelectionTintStyle: Sendable, Hashable

Colour and strength of the surface tint blended into a selected or hovered body. Used by ViewportConfiguration.selectionTint and .hoverTint, and mirrored by OffscreenRenderOptions.selectionTint / .hoverTint. The result is mix(displayedColour, color, strength), applied to the colour the body is displayed in (after lighting, tone mapping and sRGB encoding, or to the flat colour in .unlit), so it reads the same in every display mode. It tints the body only; the ring around it is the SelectionOutlineStyle, and the two are independent.

Property Type Default Description
color SIMD3<Float> — Tint colour, sRGB (display) RGB, clamped to 0...1.
strength Float — Share of color mixed in, 0...1 (clamped). 0 turns the tint off.
Preset Colour Strength
.selection (0.3, 0.5, 1.0) blue 0.15
.hover (0.4, 0.6, 1.0) light blue 0.08
.off — 0

The defaults are the values the shader used to hard-code, so a configuration that does not touch the tint renders exactly as before.


EdgeLineConfiguration

public struct EdgeLineConfiguration: Sendable

Controls how body edges are drawn: polyline edges, analytic arcs (sampled each frame, with the dash pattern running continuously round the arc) and the edges of RenderLayer.overlay bodies. With useQuadExpansion on (the default), each edge segment is expanded into a screen-aligned quad, which is what makes widths other than 1 px and dash patterns possible. Width is constant in screen space regardless of camera distance. Both ViewportRenderer (via ViewportConfiguration.edgeLineConfiguration) and OffscreenRenderer (via OffscreenRenderOptions.edgeLineConfiguration) honour it.

Quad edges are shaded like native ones: ViewportController.edgeIntensity (or OffscreenRenderOptions.edgeIntensity) dims and depth-fades them (the fade is linear in view distance from the near to the far clip plane), and they are depth-biased toward the viewer so an edge lying on a face is not lost to it. The bias grows with the line width: each edge vertex is pulled toward the viewer by twice (half the width + 1 px), measured as world distance per pixel at its depth, so a wide edge keeps its full width on faces tilted up to about 63° from the view plane. Only a face less than that distance in front of an edge can let it show through.

Native edges (useQuadExpansion off) are biased the same way, by a fixed 3 px (what a quad edge gets for a 1 px line) in world units at each vertex’s depth, so a native edge also keeps winning over faces tilted up to about 63° from the view plane. The 3 px are pixels of the render target (the drawable, or the offscreen image), not a fraction of its height: the shader used to pull by 0.6% of the NDC height, which is about 3 px at 1000 px tall but under one pixel’s depth on a drawable under about 256 px tall, where the face then won, for the drawn edge and its pick alike (issue #193). Neither path uses a constant NDC depth offset, whose world-space size depends on the near/far range: under a wide range it let hidden back edges show through faces (issue #157). Neither bias can push an edge past the near plane. The 1x pick pass applies the same bias to native edge and arc picks as to the drawn edges, so an edge drawn over a tilted face picks as the edge, not the face (issue #182).

With PickingConfiguration.isEnabled, edge and arc picks cover the same width as the drawn edge (at least 1 pt), so a wide edge is clickable across its whole width. Dash gaps are pickable too. See Picking.

Property Type Default Notes
width Float 1.0 Line width in pixels.
dashPattern EdgeLineDashPattern .solid See EdgeLineDashPattern.
useQuadExpansion Bool true false falls back to native 1 px Metal lines; width and dashPattern are then ignored.
public init(
    width: Float = 1.0,
    dashPattern: EdgeLineDashPattern = .solid,
    useQuadExpansion: Bool = true
)
Preset Value
.default 1 px solid
.bold 3 px solid
.dashed 1 px, EdgeLineDashPattern.dashed

Edge-only bodies (wires, sketches, sampled curves) take the body colour directly rather than the contrast-adaptive edge colour, and are dashed like any other edge. Dash patterns need useQuadExpansion: with it off, every edge draws as a solid 1 px line.


EdgeLineDashPattern

public struct EdgeLineDashPattern: Sendable, Hashable

A dash pattern measured along each edge polyline in world units (the cumulative arc length of the polyline, starting at its first point). Because lengths are in world units, the dashes scale on screen with zoom.

Property Type Notes
kind EdgeLineDashKind Pattern kind.
dashLength Float Length of each dash.
gapLength Float Length of each gap.
dotLength Float Length of the dot in .dashDot. Unused by other kinds.
phase Float Offset added to the arc length before the pattern is applied.
// kind is inferred: .dashed when dashLength > 0, otherwise .solid
public init(dashLength: Float = 0, gapLength: Float = 0, dotLength: Float = 2, phase: Float = 0)

public init(kind: EdgeLineDashKind, dashLength: Float, gapLength: Float, dotLength: Float = 2, phase: Float = 0)
Preset Kind dash / gap / dot
.solid .solid —
.dashed .dashed 10 / 5 / —
.dotted .dotted 2 / 3 / — (very short square-ended dashes; round dots are not supported)
.dashDot .dashDot 8 / 3 / 2

Pick lengths relative to your model’s scale: the presets suit models a few hundred units across.

Example — dashes sized for a 50 mm part:

let pattern = EdgeLineDashPattern(kind: .dashed, dashLength: 2, gapLength: 1)
config.edgeLineConfiguration = EdgeLineConfiguration(width: 1.5, dashPattern: pattern)

EdgeLineDashKind

public enum EdgeLineDashKind: UInt32, Sendable, Hashable {
    case solid
    case dashed
    case dotted
    case dashDot
}

The pattern kind of an EdgeLineDashPattern. .dotted is drawn with the same dash/gap logic as .dashed; .dashDot alternates dash, gap, dot, gap.


AxisStyle

public enum AxisStyle: Sendable {
    case cylinder
    case constantScreenWidth
}

Rendering style for the world-space coordinate axes. Each axis is an unlit cylinder axisLength long from the origin (X red, Y green, Z blue) over a 1 px centre line.

Case Behaviour
.cylinder Axis cylinders have a fixed world-space radius (axisRadius; automatically 1 % of the axis length). They appear thinner on screen as the camera zooms out, down to the 1 px centre line. Default.
.constantScreenWidth The radius scales with the view’s visible height at the pivot (camera distance and FOV in perspective, orthographicScale in orthographic), so the axes keep the on-screen width axisRadius gives at the default camera (distance 10, 45° FOV). The width is exact at the pivot’s depth; nearer and farther parts of an axis still follow perspective.

GridStyle

public enum GridStyle: Sendable {
    case plane
    case dots
}

Rendering style for the ground grid.

Case Behaviour
.plane Ground plane: a faint translucent fill (depth-tested but not depth-writing, so it only tints what lies behind it) under 1 px grid lines, every gridSubdivisions-th line with more contrast. Default.
.dots Instanced adaptive dot grid.

Both styles lie in the XY plane at z = 0 (drawn 0.01 below it so faces resting on the ground win the depth test), use spacing gridBaseSpacing × gridSubdivisionsⁿ chosen for the current zoom, centre on the camera pivot, and stop at the gridSize square around the origin. Line and dot colours are derived from the background the frame clears to (mixed toward black over a light background, toward white over a dark one), so the grid keeps the same modest contrast in light and dark appearance. Up to v1.2.3 the dot grid was drawn in the XZ plane, standing vertical in the Z-up world, and the .plane style, gridStyle and gridSize were ignored.


ViewCubePosition

public enum ViewCubePosition: String, CaseIterable, Sendable {
    case topLeading
    case topTrailing
    case bottomLeading
    case bottomTrailing
}

Corner of the viewport that hosts the navigation cube overlay. Assigned to ViewportConfiguration.viewCubePosition (default .bottomTrailing).

Example — move cube to top-right:

var config = ViewportConfiguration.cad
config.viewCubePosition = .topTrailing

PickingConfiguration

PickingConfiguration controls whether the GPU-accelerated pick-ID texture is allocated and written each frame. When disabled, the second color attachment is not used and no GPU picking results are produced; ViewportController.pickResult will never fire.


isEnabled

public var isEnabled: Bool  // default: false

When false, the pick texture is not allocated and no pick-ID pass is rendered. Set to true to enable tap/click picking via ViewportController.pickResult or ViewportController.widgetPickResult.


pickRadius

public var pickRadius: Int  // default: 0

Pick tolerance in pixels for a point pick. At 0 the pick reads the single pixel under the cursor. Above 0 it reads the (2 * pickRadius + 1)² square around it and returns the best hit: a vertex beats an edge, an edge beats a face, and among hits of the same kind the one nearest the cursor wins. Background pixels are ignored, so a click just beside a thin edge still lands on it.

Values are clamped to 0...32, both in the initializer and when the pick runs, to bound GPU readback size. 2–4 px suits CAD interaction. Region picks (performRegionPick) are unaffected.


init(isEnabled:pickRadius:)

public init(isEnabled: Bool = false, pickRadius: Int = 0)

Creates a picking configuration.

Example — enable picking with a 3 px tolerance for edges and vertices:

var config = ViewportConfiguration.cad
config.pickingConfiguration = PickingConfiguration(isEnabled: true, pickRadius: 3)

ClipPlane

ClipPlane defines a half-space clipping plane for section views. It is a Sendable, Equatable value type. Fragments where dot(normal, point) + distance < 0 are discarded by the Metal shader. Pass clip planes to ViewportController.clipPlanes to activate them.

Every pass that draws scene geometry honours the planes: shaded surfaces, edges, arcs, highlights, point clouds, the selection outline, the SSAO/silhouette depth prepass, the shadow map and the GPU pick pass, so clipped geometry is neither visible nor pickable and casts no shadow. Under MSAA the clip test uses a centroid-sampled world position, so partly covered pixels at a cut do not keep samples of the removed part. CPU SceneRaycast skips clipped hits when given the planes (clipPlanes:), which the dynamic pivot does. OffscreenRenderer applies them too, shadow map included (OffscreenRenderOptions.clipPlanes).

Limit: the renderer applies at most ClipPlane.maxActivePlanes (4) enabled planes at once, taken in array order. Enabled planes past the fourth are not applied, and debug builds log a warning when ViewportController.clipPlanes is set with more. Disabled planes don’t count.

The plane equation is:

dot(normal, P) + distance = 0

Points on the normal side (positive half-space) are kept; points on the opposite side are clipped.


maxActivePlanes

public static let maxActivePlanes: Int  // 4

Maximum number of enabled clip planes the renderer applies at once. The shader uniform holds four planes.


normal

public var normal: SIMD3<Float>

Outward-facing unit normal of the clip plane. The initializer normalizes the input automatically. Fragments are discarded when they fall on the opposite side from the normal.


distance

public var distance: Float

Signed distance from the world origin along the normal. Positive values shift the clipping boundary away from the origin in the normal direction; negative values shift it toward the origin.

Example — clip at Z = 5 (keep Z > 5):

// dot((0,0,1), P) + (-5) = 0  →  plane at Z=5
let plane = ClipPlane(normal: SIMD3(0, 0, 1), distance: -5)

isEnabled

public var isEnabled: Bool

Whether this plane is active. A disabled plane in the clipPlanes array is ignored by the renderer without requiring removal from the array.


init(normal:distance:isEnabled:)

public init(
    normal: SIMD3<Float> = SIMD3(0, 0, 1),
    distance: Float = 0,
    isEnabled: Bool = true
)

Creates a clip plane. The normal is normalized at init time.

  • normal: Outward-facing normal (default: +Z, the viewport’s up axis, so ClipPlane() equals .groundPlane and clips below Z = 0). Up to v1.2.3 the default was +Y, a vertical cut in the Z-up world; pass SIMD3(0, 1, 0) or use .yPlane for that plane.
  • distance: Signed distance from origin along the normal (default: 0).
  • isEnabled: Whether the plane is active immediately (default: true).

Example — section cut at X = 2 (keep X > 2):

let plane = ClipPlane(normal: SIMD3(1, 0, 0), distance: -2)

asFloat4

public var asFloat4: SIMD4<Float> { get }

The plane equation packed as (normal.x, normal.y, normal.z, distance) for direct upload to a Metal uniform buffer.

Example:

uniforms.clipPlane = plane.asFloat4

Presets

.groundPlane

public static let groundPlane: ClipPlane

Ground plane of the Z-up world: discards all geometry below Z = 0 (the same plane as .zPlane). Up to v1.2.3 this cut at Y = 0; use .yPlane for that.

.yPlane

public static let yPlane: ClipPlane

Y plane at the origin — discards geometry on the negative-Y side.

.xPlane

public static let xPlane: ClipPlane

X-right plane at the origin — discards geometry on the negative-X side.

.zPlane

public static let zPlane: ClipPlane

Z-up plane at the origin — discards geometry on the negative-Z side. Same plane as .groundPlane.

Example — combine two planes for a quadrant section view:

controller.clipPlanes = [
    ClipPlane(normal: SIMD3(1, 0, 0), distance: 0),   // keep X ≥ 0
    ClipPlane(normal: SIMD3(0, 1, 0), distance: 0),   // keep Y ≥ 0
]