SPB Git

Repository Public

CosmosRender.md 25.7 KB

# CosmosRender — the Metal rendering engine

CosmosRender draws a value-type scene description. It imports CosmosCore only (for ScientificStatus and constants) and simd; it never sees catalogues, ephemerides or simulations. Higher layers assemble a SceneDescription in Double precision each frame and hand it over.

Sources: Packages/CosmosRender/Sources (Swift), Shaders/ (Metal Shading Language), tests in Packages/CosmosRender/Tests (59 tests, reference images in Tests/Fixtures/golden/).

# 1. Architecture

File Role
Scene.swift The public scene description (camera, lights, bodies, star fields, point clouds, polylines, labels, grids, settings)
RenderMath.swift CameraFrame: camera-relative narrowing, reversed-Z projection, frustum and projected-size tests
Photometry.swift Pogson magnitudes, distance modulus, B−V → temperature, black body → CIE xy → linear sRGB
CameraRigs.swift Free-fly, orbit, follow and surface rigs (mathematics only)
Capabilities.swift Runtime device capabilities and fallbacks
FrameGraph.swift Frame graph (validation, culling, encoder grouping, load/store derivation) and the engine's FramePlan
Renderer.swift CosmosRenderer: resources, live rendering with three frames in flight, pass encoders
ScenePreparation.swift CPU side of a frame: culling, LOD, light/occluder selection, uniform blocks, lines, labels
RenderResources.swift Pipeline-state cache, depth/sampler states, per-frame bump allocators, render targets, dynamic resolution
TextureManager.swift Asynchronous multi-resolution textures with a memory budget and LRU eviction
SphereMesh.swift Cube-sphere LODs, LOD rule, camera-centred near-surface patch
LabelLayout.swift, LabelAtlas.swift Label collision by priority; CoreText atlas
ShaderLibrary.swift Shader loading (metallib in the app, runtime compilation elsewhere)
Offscreen.swift Offscreen rendering (tiled above the tile limit), PNG 8/16-bit and OpenEXR export
CosmosMetalView.swift CosmosMetalView (MTKView host) and CosmosViewport (SwiftUI)
TestScenes.swift RendererTestScenes: synthetic scenes and procedural textures for verification only

Threading. CosmosRenderer is not thread-safe: one thread at a time. CosmosMetalView uses the main actor: MetalKit calls draw(in:) on the main thread, the view calls the scene provider on the main actor, encodes and commits; GPU execution is asynchronous with up to three frames in flight (a semaphore blocks the fourth). TextureManager and the statistics collector are thread-safe; texture decoding runs on a background queue.

# 2. Frame graph

FramePlan.graph declares the passes with their attachments and sampled inputs; FrameGraph.compile() validates that every input was written earlier, removes passes that do not reach the output, merges consecutive raster passes that draw into the same attachments into one render encoder, and derives load/store actions.

text
sky+stars ─┐ (MSAA HDR colour + depth, one encoder)
opaque bodies ─┘
atmospheres            samples the scene depth → its own encoder (colour only, dual-source blending)
rings+transparent ─┐   depth test, no depth write
trajectories+grids ─┘
hdr resolve            luminance-weighted MSAA resolve → rgba16Float
bloom                  dual-filter chain, 5 levels (optional)
tone mapping ─┐        exposure, tone curve, dither → output (or → MetalFX input)
[upscale]     │        MetalFX spatial, only when the render scale is below 1 and the device supports it
[present]     │        copy of the upscaled image
labels+overlays ─┘     at output resolution, same encoder as the last pass writing the output

Without atmospheres the first five passes share a single encoder and the multisampled depth is never stored. Without multisampling the resolve disappears. CosmosRenderer.lastFramePasses reports the groups actually executed.

# 3. Depth strategy

One depth range for everything: reversed-Z, 32-bit float depth, infinite far plane. clip = (x·f/aspect, y·f, near, −z_view), so the stored depth is near / distance: 1 at the near plane, 0 at infinity; the depth test is greater, the clear value 0.

Why this is enough from 1 m to the observable universe: float32 has 24 significant bits at every magnitude down to 1.2×10⁻³⁸. near / distance with near = 0.1 m is 3×10⁻²⁷ at 1 Gpc — still a normal float — so two surfaces are separated whenever their distances differ by more than about 10⁻⁷ relatively, at 3 m as at 1 Gpc. A conventional depth buffer puts everything beyond a few thousand kilometres in its last step. No logarithmic depth (which needs per-fragment depth writes and disables early-Z) and no depth partitioning are required; the near plane only decides how close geometry may come before being clipped (SceneCamera.nearPlane, default 0.1 m).

Evidence (tests in PrecisionAndDepthTests.swift): the float32 depth is strictly ordered for 10⁻⁶ relative separations from 1 m to 10²⁶·⁵ m; on the GPU a 0.5 m sphere at 3 m, a sphere at 1 au and a sphere at 1 Gpc are ordered correctly whatever the submission order; a ladder of 27 overlapping spheres at 1 m, 10 m, … 10²⁵ m and 1 Gpc is ordered correctly at every rung; two surfaces 10⁻⁵ apart in relative depth show zero wrong pixels at 100 m, 1 au and 1 Gpc; a 1 m sphere and a 1 Gpc sphere are shaded identically.

Distances the GPU sees are float32: up to 3.4×10³⁸ m, far beyond the observable universe (4.4×10²⁶ m).

# 4. Precision strategy

  • Absolute positions are SIMD3<Double> in a scene frame chosen by the caller. The engine subtracts the camera position in Double (CameraFrame.relative, viewPosition) and only then narrows to float32. No absolute coordinate is ever uploaded as float32.
  • Bodies: the model-view matrix (view rotation × body rotation × radii, translation = body centre in view space) is formed in Double. In view space the lateral coordinates of an on-screen object are small, so its silhouette is exact to about 6×10⁻⁸ of its distance — below a pixel for any field of view where the body spans more than a few pixels.
  • Shading is body-centric: light, camera and occluder positions are expressed relative to the body centre in body-fixed axes (differences taken in Double) in units of the body's equatorial radius, and the fragment's position comes from the interpolated unit direction. A 1 m object and a 1 Gpc sphere therefore use the same float32 range and squared lengths cannot overflow (lights farther than 10⁹ radii are pulled in along their direction, keeping their angular size). The view vector is taken from the camera-relative position, which stays exact near the ground.
  • Near-surface patch: below 2 % of the radius above a body, the sphere mesh (whose body-centric float32 vertices are only good to 0.5 m on an Earth-sized planet) is replaced by a polar grid centred under the camera whose vertices are computed in Double relative to the camera every frame (72 rings × 192 sectors, geometric spacing out to 2.5 horizon distances).
  • Atmosphere: rays are parametrised from their closest approach to the planet centre (o = −d × (c × d)), so every quantity in the ray-march is planet-centric and small; the result does not degrade with the planet's distance.
  • Polylines: (anchor − camera) + point is evaluated in Double per point per frame. A segment much longer than its distance to the camera is split at its closest approach and at geometrically growing distances (segmentRefinement), otherwise the part of an orbit passing near the camera would inherit the 8 km float32 error of an endpoint 1 au away.
  • Point batches given as positions are float32 offsets from a Double origin; origin − camera is evaluated in Double. The residual error is 2⁻²⁴ of the batch extent: keep batches spatially compact (an octree node). Batches given as unit directions are exact to 0.012″.

Limit of Double itself (tested in doubleResolution): the spacing of Double is 31 µm at 1 au, 3 cm at 1 000 au, 4 m at 1 pc and 4.3×10⁹ m at 1 Gpc from the scene origin. Everything from metres to gigaparsecs is expressible, but metre-scale geometry is only meaningful within about 0.1 pc of the scene origin. The scene frame is therefore expected to be re-centred by the layer that assembles scenes (floating origin of CosmosSpatial): the renderer attaches no meaning to the origin and can be given a different one every frame.

Measured (tests): an object 10 m from a camera that is 1 au, 30 au or 1 000 au from the origin stays within 0.01 px of the exact projection while the camera moves by centimetres; objects at 1 au, 1 pc and 1 Gpc stay within 0.01 px while the camera moves by metres, at 3 456 × 2 234.

# 5. Shading models, references, assumptions

Radiometric convention. Scene-referred linear sRGB. 1.0 is the radiance of a perfectly white Lambertian surface lit at normal incidence by irradiance 1 (physical radiance × π). In-scattering and the specular lobe carry the same factor π. A disc that delivers irradiance E from solid angle Ω has radiance πE/Ω. SceneCamera.exposure multiplies scene values before tone mapping. Exposure and the brightness of point sources relative to sunlit surfaces are the caller's choice — a physically proportional scale would make stars invisible next to a sunlit planet, as in reality.

Feature Model Assumptions / limits
Diffuse surfaces Lambert, or Lommel–Seeliger for airless regolith (ReflectanceModel) No opposition surge, no roughness model (Hapke, Oren–Nayar not implemented)
Terminator smoothstep over the light's angular radius Light is a uniform disc
Ocean glint Normalised Blinn–Phong lobe gated by a mask texture No wave statistics (Cox–Munk), no Fresnel
Clouds Texture layer blended over the surface, lit as Lambert No cloud shadows, no parallax
Night lights Emissive texture faded in from 5° before to 7° after the terminator Illustrative blend
Eclipses Visible fraction of the light's disc behind a spherical occluder: exact two-circle overlap (umbra, antumbra, penumbra) Small angles; occluders are spheres of the equatorial radius; at most 4 occluders per body, chosen for the primary light; no atmospheric refraction (the Moon in Earth's umbra would be black, not red)
Ring shadow on planet Ray from the surface to the light through the ring plane, opacity from the profile, slant-path optical depth Rings are infinitely thin; primary light at a point for this term
Planet shadow on rings Ray–spheroid test in the space where the spheroid is a unit sphere, penumbra width from the light's angular size Exact umbra edge, approximate penumbra profile
Rings Radial profile (texture or stops) × irradiance; unlit face = diffuse transmission unlitBrightness × (1 − opacity) Illustrative: no phase function, no opposition effect, no planetshine
Atmosphere Single scattering, ray-marched per pixel (default 24 view × 6 light samples): Rayleigh + Mie exponential layers, optional triangular absorption layer (ozone); Rayleigh phase 3/(16π)(1+μ²); Cornette–Shanks Mie phase; dual-source blending applies per-channel transmittance to what is behind. Seen from space and from inside (quadratic sample spacing inside) No multiple scattering: twilight and the day sky are darker and more saturated than reality. Ground skylight is a two-stream estimate (half of the light removed from the direct beam). Oblate planets are handled by stretching space along the pole (path lengths along the pole distorted by up to f). One light. No refraction, no clouds in the volume, no ring shadows in the air
Emissive discs Linear limb darkening I(μ) = I(1)(1 − u(1 − μ)); u = 0.6 is the grey-atmosphere (Eddington) value No wavelength dependence of u, no granulation or spots
Glare Halo I(ρ) ∝ (1 + ρ²)^(−3/2) holding a chosen fraction of the disc's flux Instrumental and illustrative, not a physical PSF; depth-tested at the body centre (a nearer body masks the halo over its own disc only)
Unresolved bodies Below 1 px a body becomes a point sprite with the same flux: emissive L·πr², reflective (2/3)·A·E·Φ(α) with the Lambert-sphere phase function Flat albedo only
Point sources Flux 10^(−0.4 m) (Pogson); absolute magnitudes get the distance modulus in the vertex shader; Gaussian PSF of total energy magnitudeZeroEnergy × flux; when the exposed peak would exceed peakClamp the PSF grows in area instead; objects with a physical radius are drawn at their angular size with the same total flux Magnitudes are treated as V-band luminance; no extinction, no pass-band conversion
Star colour Black body at the given temperature → CIE 1931 XYZ (Wyman–Sloan–Shirley 2013 fit of the colour-matching functions, 360–830 nm) → linear sRGB (IEC 61966-2-1), normalised to unit luminance; B−V → T by Ballesteros (2012) Stars are not black bodies; out-of-gamut components are clipped to 0
Tone mapping linearWithShoulder (default): identity up to 60 % of the headroom, exponential shoulder above; ACES fit (Narkowicz) and pure linear available The default has no toe so that faint stars keep their photometric ratios
MSAA resolve Weighted by 1/(1 + exposed luminance) (Karis 2013) Slightly darkens very bright sub-pixel edges
Bloom Dual-filter down/up chain (Bjørge 2015), mixed by intensity Screen-space, illustrative

References: Pogson 1856 (MNRAS 17, 12); Ballesteros 2012 (EPL 97, 34008); Wyman, Sloan & Shirley 2013 (JCGT 2(2)); Nishita et al. 1993 (SIGGRAPH); Bruneton & Neyret 2008 (EGSR); Hillaire 2020 (EGSR, atmosphere parameters); Cornette & Shanks 1992 (Appl. Opt. 31, 3152); Reinhard et al. 2002; Karis 2013 (SIGGRAPH course); Narkowicz 2016; Lommel 1887 / Seeliger 1884 as given in Hapke 2012.

# 6. Capabilities and fallbacks

DeviceCapabilities is queried at start-up (CosmosRenderer.capabilities, also written in benchmark reports).

Capability Use Fallback
MSAA 4× on rgba16Float Scene target 2×, then 1× (the resolve pass disappears, atmosphere reads a single-sample depth)
MetalFX spatial scaler Upscaling when the dynamic render scale is below 1 Bilinear filtering in the tone-mapping pass
EDR display CosmosMetalView switches to rgba16Float + extended linear sRGB and passes the current headroom to the tone curve bgra8Unorm_srgb with dithering
Metal 4 family Reported only The engine uses the Metal 3 feature set
Dual-source blending, depth32Float, float filtering Required None (available on every Mac that runs macOS 15)

Dynamic resolution (DynamicResolutionController): render scale steps 0.5 … 1.0, lowered when the median GPU time of the last 20 frames exceeds 90 % of the budget, raised only when the predicted time at the next step is below 70 % of it, 30 frames of cooldown. Labels are always drawn at output resolution.

# 7. Scene-description API (what the interface layer uses)

swift
public struct SceneDescription: Sendable {
    var camera: SceneCamera            // position (Double, m), orientation (simd_quatd, camera→scene), verticalFieldOfView, exposure, nearPlane
    var lights: [SceneLight]           // position, color, intensity, falloff (.constant | .inverseSquare(referenceDistance:)), radius
    var bodies: [SceneBody]            // id, position, radius, oblateness, orientation, surface, atmosphere?, rings?, emission?, shadows, status
    var starFields: [SceneStarField]   // id, version, PointSourceBatch (.directions | .positions(origin:), .apparent | .absolute), status
    var pointClouds: [ScenePointCloud] // same batch type + layer (.background | .depthTested), tint
    var polylines: [ScenePolyline]     // anchor (Double), points (Double, relative), closed, color, width (pt), fade, depthTested, status
    var labels: [SceneLabel]           // anchor (.position | .direction), text, priority, style, anchorRadius, offset, occludable, status
    var grids: [SceneGrid]             // orientation (grid→scene), meridianStep, parallelStep, graduationStep, colours, status
    var settings: RenderSettings       // toneMapping, bloom, pointSources, backgroundColor, statusStyles, labels, atmosphereQuality
}
  • Body-fixed axes: +Z north pole, +X prime meridian; orientation rotates them to scene axes. Textures are equirectangular, u = 0.5 at longitude 0, east positive, v = 0 at the north pole (verified by the orientation test scene).
  • PointSourceBatch.Builder builds star and galaxy batches (append(location:magnitude:temperatureKelvin:), …colorIndexBV:, …color:radius:). A batch is uploaded once per (id, version).
  • ScientificStatus on every item; RenderSettings.statusStyles maps it to a dash pattern, an opacity and italic labels (defaults: observed/computed solid; estimated long dashes; reconstructed short dashes; hypothetical dotted, dimmed, italic).
  • Screen-space sizes are in points; the view supplies pixels per point.

View and renderer:

swift
CosmosViewport(configuration:inputDelegate:onViewReady:scene:)        // SwiftUI; scene: @MainActor (CosmosFrameContext) -> SceneDescription
CosmosMetalView(frame:configuration:)                                 // NSView; .renderer, .sceneProvider, .inputDelegate, .onFrame, .allowsExtendedDynamicRange
protocol CosmosViewInputDelegate { func cosmosView(_:didReceive: NSEvent, kind: CosmosInputKind) }   // raw events, not interpreted
CosmosRenderer(device:configuration:)                                 // throws without Metal or shaders
renderer.render(scene:to:pointScale:edrHeadroom:)                     // live, into a CAMetalDrawable
renderer.renderImage(scene:width:height:options:) -> RenderedImage    // offscreen; .writePNG / .writePNG16 / .writeEXR
renderer.statistics() -> FrameStatisticsSnapshot                      // cpu/gpu/frameInterval {median, p95, p99…}, draw calls, memory
renderer.textures.register(_:descriptor:)                             // TextureManager

Camera rigs (FreeFlyRig, OrbitRig, FollowRig, SurfaceRig, CameraNavigation) take explicit deltas and return a CameraPose; the interface binds events to them.

# 8. Textures

swift
renderer.textures.register("earth.albedo", descriptor: TextureDescriptor(levels: [
    TextureLevel(source: .file(previewURL), width: 512, height: 256),      // level 0: small, loaded first, kept while in use
    TextureLevel(source: .file(fullURL), width: 8192, height: 4096),       // refined in the background when the budget allows
], isSRGB: true))
body.surface.albedo = "earth.albedo"

TextureHandle is a name: scenes can reference textures before they are registered or loaded (the flat colour is used meanwhile). Sources are files readable by MetalKit or closures returning RGBA8 pixels. Colour maps are sRGB (isSRGB: true), masks and normal maps linear. Policy (TextureBudget, tested without a GPU): level 0 of every texture in use first; then the next level of the coarsest displayed texture if it fits in memoryBudgetBytes once unused textures are evicted; over budget, unused textures go first (least recently used first), then the fine level of textures in use; level 0 of a texture in use is never evicted. A refinement may overshoot the budget by one level until the following frame. Offscreen rendering waits for the textures (OffscreenOptions.waitForTextures).

# 9. Shaders

MSL sources live in Shaders/: CosmosShared.h (uniform layouts mirrored by GPUTypes.swift, projection, eclipse and atmosphere functions — all static inline) and one .metal file per feature.

  • App: project.yml lists Shaders/ as a source directory; Xcode compiles each .metal file and links default.metallib into the app bundle. #include "CosmosShared.h" is resolved by the Metal compiler.
  • Package tests and tools: swift build does not compile Metal. ShaderLoader reads the same directory, replaces the first #include "CosmosShared.h" by the header's text and drops the others, concatenates the files and calls makeLibrary(source:). Function names are therefore unique across files.
  • Lookup order (ShaderSource.automatic): the main bundle's metallib; the directory named by COSMOS_SHADER_DIR; Shaders/ of the source tree (path derived from #filePath). renderer.shaderOrigin says which one was used.

# 10. Verification

  • swift test --scratch-path .build-render --filter CosmosRenderTests — 59 tests: precision, depth, culling and LOD, photometry against published values, frame graph, texture budget, label collision, camera rigs, eclipse and ring shadows measured on pixels, energy conservation of star sprites, limb darkening, tiling, export formats, upscaling, tone-mapping range, and 10 golden images (640 × 360, mean absolute difference < 1.5/255 and < 1 % of pixels beyond 24/255). GPU tests record a failure when Metal is unavailable.
  • Regenerating golden images after an intended change: COSMOS_UPDATE_GOLDEN=1 swift test … --filter GoldenImage, then look at every PNG. COSMOS_RENDER_DUMP=<dir> additionally writes 1 920 × 1 080 renders for inspection.
  • App: "ORIX Cosmos" --render-test out.png [--scene planet|stars|scale|labels|ground|eclipse|rings|sun|orientation|demo] [--width W --height H] [--point-scale S] and --benchmark <seconds> out.json [--scene …].

# 11. Measured performance

One run of "ORIX Cosmos" --benchmark 15 Benchmarks/render/benchmark-demo-release.json --scene demo on 2026-11-24 (the JSON file holds the full record, including device capabilities):

Item Value
Machine MacBook Pro (Mac17,6), Apple M5 Max, 18 CPU cores, 48 GB, macOS 27.0
Build Release configuration (optimised), ad-hoc signed local build; shaders from the app's metallib
Display Built-in Retina display, 120 Hz, EDR output active (headroom 4.97)
Drawable 3 456 × 2 234 px (the panel's native resolution), render scale 1.00 (dynamic resolution off), MSAA 4×
Scene demo renderer test scene (synthetic): textured oblate planet with atmosphere and rings, moon, emissive Sun with glare, 40 000 star sprites, 6 000 extended sources, orbit line, grid, labels; bloom on
Presentation Display-synchronised MTKView, 15.0 s measured after a 1.5 s warm-up, 1 800 frames
Frame interval median 8.33 ms, p95 8.61 ms, p99 8.74 ms, max 8.87 ms → 120.0 fps (capped by the display)
GPU time per frame median 4.88 ms, p95 6.00 ms, p99 6.43 ms, max 6.91 ms
CPU time per frame (scene preparation + encoding) median 0.24 ms, p95 0.53 ms, p99 0.62 ms
Work per frame 22 draw calls, 50 171 instances, 115 717 triangles, 6 render-pass groups
Memory render targets 453 MB, textures 31 MB, buffers 14 MB; Metal device allocation 694 MB; process footprint 967 MB

Conditions: other processes were compiling on the machine during the run (1-minute load average 14), and the benchmark window was ordered behind the other windows (it reported itself visible). An earlier run of the same binary a few minutes before, at load average 9, gave GPU median 4.11 ms (p95 5.44, p99 6.12) and CPU median 0.19 ms: run-to-run variation under load is about 20 %. The frame rate is limited by the display; GPU time (a little over half the 8.33 ms budget) is the meaningful headroom figure. The measured binary predates a last change to the demo camera path (same content, the camera now circles about the scene's Z axis). Numbers from a Debug build differ mainly in CPU time. In a Debug build the procedural test textures take 10–15 s to generate on first use (they stream in at low resolution first); this is the test-texture generator, not the renderer.

Not measured: other GPUs, external displays, scenes with real catalogues (millions of stars), thermal behaviour over long runs, energy use.

# 12. Limitations and what is not implemented

  • No multiple scattering, no precomputed atmosphere tables, no volumetric clouds, no aurorae, no refraction.
  • No terrain: bodies are smooth spheroids; normal maps only perturb shading. No tessellated or quadtree surfaces, no virtual texturing (multi-resolution is whole-image levels, not tiles).
  • One atmosphere light, eclipse occluders for the primary light only, no shadows cast by rings on other bodies or by bodies on other bodies' atmospheres, no shadows between ring particles.
  • No order-independent transparency: rings are sorted by body distance; a ring seen through another body's atmosphere is not attenuated by it.
  • Glare is not occlusion-queried; point clouds of the background layer are always behind bodies.
  • No temporal anti-aliasing or MetalFX temporal upscaling (no motion vectors). MetalFX spatial upscaling is exercised by tests but its visual benefit over bilinear has not been evaluated on a display.
  • No picking/selection buffer, no GPU-driven culling, no mesh instancing of bodies (one draw per body; point sprites, line segments and labels are instanced).
  • Labels: one line of text, system font, no leader lines, no fading between frames (a label appears or disappears from one frame to the next when priorities collide); the atlas (2 048², 16 MB) is rebuilt when full.
  • Polylines have butt joints (no miters): fine for thin smooth curves, visible on thick polylines with sharp turns.
  • EDR output and the live view were exercised by the benchmark run, not inspected on the display by a person; input forwarding has no automated test.
  • The procedural textures and every object of RendererTestScenes are synthetic.
Files main
Menu

Theme