The Relativistic Engine is an ISO C++23 simulation and visualization framework for relativistic mechanics and raytracing. The system is structured into six functional layers:
LinearMemoryArena, include/relativistic/core/memory_arena.hpp) aligned to 64-byte and 128-byte cache boundaries (Technical Manual).SpacetimeMetric, include/relativistic/metrics/spacetime_concept.hpp) and template specializations.SimdVec<T, Width>, SimdMask<T, Width>, include/relativistic/core/simd.hpp, and GeodesicBundle<T, Width>, include/relativistic/core/geodesic_bundle.hpp) processing multiple geodesic rays and phase states concurrently across AVX2, AVX-512, and ARM Neon architectures (Section 4.3).PCG64Engine, include/relativistic/core/pcg64.hpp) and fixed-step temporal scheduling (Section 3.1).The system architecture is organized into modular subsystems operating across decoupled boundaries:
Tensor<T, Rank, Dim> (include/relativistic/core/tensor.hpp) defines cache-aligned multidimensional tensor storage with compile-time rank, dimension, and flat index resolution (Technical Manual).inverse_metric_4x4 and determinant_4x4 perform analytical cofactor inversions for 4D spacetime metrics; contract and contract_tensors (include/relativistic/core/tensor_ops.hpp) execute general Einstein summation contractions.compute_christoffel (include/relativistic/core/christoffel.hpp) dynamically dispatches to exact analytical formulations when provided by the metric or evaluates numerical derivatives via 8th-order centered finite difference stencils (compute_christoffel_numerical; see Mathematical Formulation).RiemannComputer (include/relativistic/core/riemann.hpp) computes the Riemann tensor $R^\rho_{\phantom{\rho}\sigma\mu\nu}$, Ricci tensor $R_{\mu\nu}$, Ricci scalar $R$, and Kretschmann invariant $K_1 = R^{\alpha\beta\gamma\delta} R_{\alpha\beta\gamma\delta}$ (Mathematical Formulation).Every spacetime implementation satisfies the SpacetimeMetric concept (include/relativistic/metrics/spacetime_concept.hpp), requiring metric_tensor, inverse_metric, christoffel_symbols, and speed_of_light:
FlatMinkowskiMetric (MATHEMATICAL_FORMULATION.md Section 1.1), SchwarzschildMetric (Section 1.2), and KerrMetric (Section 1.3).SchwarzschildIsotropicMetric, PainleveGullstrandMetric, EddingtonFinkelsteinMetric, and Cartesian KerrSchildMetric (Section 1.3).ReissnerNordstromMetric (Section 1.4), KerrNewmanMetric (Section 1.5), SchwarzschildDeSitterMetric (Section 1.6), FLRWMetric (Section 1.7), LemaitreTolmanBondiMetric (LtbProfile, Section 1.10), QuintessenceCosmologyMetric (QuintessenceBackground, ExpansionHistoryBuilder, Section 1.11), and ChaplyginCosmologyMetric (ExpansionHistoryBuilder::build_chaplygin, Section 1.12).MorrisThorneWormholeMetric (Section 1.8), AlcubierreWarpMetric (Section 1.9), EvaporatingVaidyaMetric (HawkingRadiation, RenormalizedStressTensor, EvaporatingBlackHole, UnruhEffect, Section 1.13), and TeVeSSpacetimeMetric (Section 1.14).BssnGrid (include/relativistic/metrics/bssn_grid.hpp) manages 3D spatial field representations ($\phi, K, \tilde{\gamma}{ij}, \tilde{A}{ij}, \tilde{\Gamma}^i, \alpha, \beta^i$), BssnEvolution (include/relativistic/metrics/bssn_evolution.hpp) implements 4th-order spatial finite differencing with RK4 time stepping, BssnConstraints (include/relativistic/metrics/bssn_constraints.hpp) evaluates Hamiltonian constraint residuals, and TricubicInterpolator / QuinticHermiteTimeInterpolator (include/relativistic/metrics/bssn_interpolation.hpp) provide spatial and temporal metric field evaluations (Description).Embedded Adaptive Solvers: RK45AdaptiveIntegrator (Dormand-Prince 5(4), include/relativistic/integrators/rk45_adaptive.hpp) and CashKarpIntegrator (include/relativistic/integrators/cash_karp.hpp) provide variable-step integration with automatic infalling radial step-size regulation ($0.5 r / |
u^r | $) and algebraic constraint projection ($g_{\mu\nu} u^\mu u^\nu = \text{const}$) solving the quadratic polynomial for $u^0$ to machine precision (MATHEMATICAL_FORMULATION.md Section 18.1 and Section 18.6). |
Vernier9Integrator (include/relativistic/integrators/vernier9.hpp) implements a 16-stage 9(8) embedded Runge-Kutta scheme optimizing truncation error bounds for long orbital baselines (MATHEMATICAL_FORMULATION.md Section 18.2).GaussLegendreIntegrator (include/relativistic/integrators/symplectic_gauss_legendre.hpp) provides implicit Runge-Kutta schemes (orders 4 and 6, GaussLegendre4 and GaussLegendre6) satisfying $b_i A_{ij} + b_j A_{ji} - b_i b_j = 0$ with Picard fixed-point stage iterations to tolerance $10^{-14}$, preserving phase-space symplectic 2-forms and Killing invariants (MATHEMATICAL_FORMULATION.md Section 18.3).Hermite4AarsethIntegrator (include/relativistic/integrators/hermite4_aarseth.hpp) evaluates acceleration $\mathbf{a}$, 4th-order centered finite difference jerk $\mathbf{j}$, snap $\mathbf{s}$, and crackle $\mathbf{c}$ with Aarseth variable timestep regulation $\Delta t \propto \sqrt{(|\mathbf{a}| |\mathbf{s}| + |\mathbf{j}|^2) / (|\mathbf{j}| |\mathbf{c}| + |\mathbf{s}|^2)}$ for close gravitational encounters (MATHEMATICAL_FORMULATION.md Section 18.4).AdaptiveStepController (include/relativistic/integrators/step_controller.hpp) implements Standard (integral filter), PI30 (proportional-integral filter), and PID42 (proportional-integral-derivative filter) to eliminate step-size chattering across sharp curvature gradients (MATHEMATICAL_FORMULATION.md Section 18.5).HorizonDetector (include/relativistic/integrators/horizon_manager.hpp) evaluates a state machine tracking trajectory radial distance against horizon radius $r_s$ and singularity threshold $\delta_{\text{sing}} r_s$, executing absorption or interior continuity (MATHEMATICAL_FORMULATION.md Section 18.6).step_planar_null_rk4 (include/relativistic/core/spherical_planar_null_integrator.hpp), step_schwarzschild_null_rk4 (include/relativistic/core/schwarzschild_null_integrator.hpp), and Cartesian step_kerr_schild_null_rk4 (include/relativistic/core/kerr_schild_null_integrator.hpp) provide optimized RK4 geodesic stepping with angular momentum conservation, exact central potential accelerations, and Gram-Schmidt observer tetrad constructions (MATHEMATICAL_FORMULATION.md Section 18.7).PostNewtonianSolver (include/relativistic/dynamics/pn_acceleration.hpp) and PostNewtonianSystem (include/relativistic/dynamics/pn_nbody_system.hpp) evaluate multi-body equations of motion from Newtonian up to 3.5PN order, including 2.5PN radiation damping, spin-orbit, spin-spin, and self-spin interactions (Mathematical Formulation).GravitationalWaveCalculator (include/relativistic/dynamics/pn_gravitational_waves.hpp) extracts trace-free quadrupole moments and evaluates radiation reaction power $P_{\text{GW}}$ and waveform strain polarizations $(h_+, h_\times)$ (MATHEMATICAL_FORMULATION.md Section 3.4).SphericalHarmonicsGravityModel (include/relativistic/gravimetry/spherical_harmonics.hpp) and AssociatedLegendreTable (include/relativistic/gravimetry/legendre_table.hpp) execute fully normalized spherical harmonic potential and acceleration evaluations up to degree and order 32, coupled with TidalPerturbationModel (include/relativistic/gravimetry/tidal_perturbations.hpp) Love number modifications (Description).OrbitalPrecessionAnalytic (include/relativistic/gravimetry/orbital_precession.hpp) computes secular nodal and apsidal drift rates ($J_2, J_4$).DarkMatterProfileMath (include/relativistic/dark_matter/dark_matter_field.hpp) evaluates enclosed mass, radial derivative, and density for 13 analytic profiles: NavarroFrenkWhite, Hernquist, Burkert, Einasto, Plummer, CoredIsothermal, SingularIsothermal, Dehnen, PointMass, Jaffe, Moore, Soliton, and BetaModel (Mathematical Formulation Section 17.1); standalone templates NFWProfile, EinastoProfile, BurkertProfile, and HernquistProfile (include/relativistic/dark_matter/dark_matter_profiles.hpp) evaluate analytical gravitational potentials, accelerations, and circular velocity curves.DarkMatterHaloSettings and DarkMatterFieldSettings (include/relativistic/dark_matter/dark_matter_field.hpp) manage catalog storage up to 32 halos, 11 archetypes (DarkMatterHaloPreset), triaxial axis ratios ($q_y, q_z$), Tait-Bryan Euler orientations, and Keplerian orbital kinematics (DarkMatterHaloOrbit). DarkMatterLensing evaluates perpendicular geodesic deflection kicks with step limiters, while ResolvedDarkMatterField evaluates N-body body accelerations and emissive density/field/velocity rendering.DarkMatterFieldSettings::spawn_layout synthesizes five geometric configurations (DarkMatterLayoutPattern: Ring, BinaryPair, LinearChain, CubicLattice, SphericalShell); DarkMatterFieldSettings::spawn_population generates subhalo populations with power-law mass and radial distributions (DarkMatterPopulationSettings).BarnesHutOctree (include/relativistic/dark_matter/barnes_hut.hpp) executes hierarchical octree spatial partitioning with quadrupole multipole expansions and symplectic leapfrog advancement for collisionless particle collections (CollisionlessParticle).CompositeGalaxyGenerator (include/relativistic/dark_matter/galaxy_model.hpp) synthesizes multi-component galaxies comprising exponential disks, Hernquist bulges, and NFW halos with dispersion kinematics and barycenter evaluation.MondFramework (include/relativistic/modified_gravity/mond.hpp) implements non-linear MOND interpolation functions ($\mu, \nu$), TeVeSSpacetimeMetric (include/relativistic/modified_gravity/teves.hpp) solves the covariant Tensor-Vector-Scalar metric, and FRChameleonModel (include/relativistic/modified_gravity/f_r_gravity.hpp) computes scalar-tensor field screening.PrimitiveVariables, ConservedVariables, and FluxVariables (include/relativistic/hydro/hydro_types.hpp) encapsulate rest-mass density $\rho$, isotropic gas pressure $p$, 3-velocity components $(v_x, v_y, v_z)$, lab-frame magnetic components $(B_x, B_y, B_z)$, specific internal energy $\varepsilon$, Lorentz factor $W$, specific enthalpy $h$, and comobile magnetic energy density $b^2$ aligned to 64-byte cache boundaries, with recompute_derived enforcing velocity sub-luminality $v^2 \le 1 - 10^{-15}$ (Mathematical Formulation).prim_to_con_flat converts primitive arrays into conserved variables $(D, S_x, S_y, S_z, \tau, B_x, B_y, B_z)$, while compute_flux_1d_x evaluates the 1D directional physical flux vector along grid axes, and Metric3Plus1 defines lapse $\alpha$, shift $\beta^i$, 3-metric $\gamma_{ij}$, and extrinsic curvature $K_{ij}$ (Mathematical Formulation).High-Order Spatial Reconstruction: WENO5Reconstructor evaluates 5th-order weighted essentially non-oscillatory interface stencils supporting Jiang-Shu and WENO-Z $\tau_5 = |
\beta_0 - \beta_2 | $ smoothness indicators; MP5Reconstructor applies Suresh-Huynh monotonicity-preserving limiters with minmod4 curvature bounds and median selection ($\alpha = 4.0$); TVDReconstructor provides second-order MinMod and Monotonized Central (MC) slope-limited cell interfaces, applied across primitive states with physical density and pressure floors ($\rho \ge 10^{-15}, p \ge 10^{-15}$) via reconstruct_primitive_variable_component (include/relativistic/hydro/solvers/reconstruction.hpp, Mathematical Formulation). |
HLLRiemannSolver computes two-wave intermediate state fluxes; HLLCRiemannSolver restores the central contact wave structure by solving the quadratic dispersion relation for star-state wave speed $\lambda_$ and pressure $p_$; HLLDRiemannSolver resolves five-wave intermediate Alfvén and slow magnetosonic discontinuities when transverse magnetic fields are non-zero (include/relativistic/hydro/solvers/riemann_solvers.hpp, Mathematical Formulation).Con2PrimSolver (include/relativistic/hydro/solvers/con2prim.hpp) converts conserved states to primitives via solve_hydro executing bracketed 1D Newton-Raphson root-finding on gas pressure $p$ with analytical derivatives $df/dp = \Gamma - (\Gamma - 1)v^2(1 - 1/h)$ and bisection fallbacks on $[p_{\min}, p_{\max}]$, and via solve_mhd executing 1D root-finding on scalar $z = \rho h W^2$ with comobile magnetic field coupling $b^2 = B^2/W^2 + (\mathbf{S}\cdot\mathbf{B})^2/z^2$ and explicit 3-velocity vector reconstruction (Mathematical Formulation).ConstrainedTransport2D (include/relativistic/hydro/solvers/constrained_transport.hpp) maintains staggered face-centered magnetic fields ($B_{x,\text{face}}, B_{y,\text{face}}$) on $(n_x + 1) \times n_y$ and $n_x \times (n_y + 1)$ grids, evaluates vertex electric fields $E_{z, i+1/2, j+1/2} = -\frac{1}{4}\sum(v_x B_y - v_y B_x)$, advances face inductions via discrete curls, averages magnetic components to cell centers, and preserves $\nabla \cdot \mathbf{B} = 0$ to machine precision (Mathematical Formulation).One-Dimensional Relativistic Fluid Engine: RelativisticHydroSolver1D (include/relativistic/hydro/solvers/grhd_solver.hpp) evaluates 1D grid evolutions of $n_x$ cells with 3 ghost cells on each boundary, Outflow, Periodic, and Reflecting boundary conditions ($v_x \leftarrow -v_x$), acoustic CFL timestep regulation $\Delta t = \text{CFL} \cdot \Delta x / \max_i ( |
v_{x,i} | + c_{s,i}) / (1 + | v_{x,i} | c_{s,i})$, and third-order Strong Stability Preserving Runge-Kutta (SSP-RK3) temporal advancement, with automated setup for relativistic Sod shock tubes and Balsara-1 MHD shock tubes (Description). |
TOVSolver (include/relativistic/hydro/solvers/tov_solver.hpp) integrates the coupled Tolman-Oppenheimer-Volkoff system $(dm/dr, dm_b/dr, dp/dr, d\Phi/dr)$ using 4th-order Runge-Kutta stepping with origin quadratic Taylor series initialization, adaptive pressure scale-height regulation $\Delta r_{\text{opt}} = \operatorname{clamp}(0.05 h_p, \Delta r_{\min}, \Delta r_{\max})$, sub-step linear interpolation at the stellar surface $p \le 0$, and exterior Schwarzschild metric potential matching $\Phi(R) = \frac{1}{2}\ln(1 - 2GM/(c^2 R))$, evaluating gravitational mass $M$, baryonic mass $M_b$, compactness $C$, surface redshift $z_s$, central redshift $z_c$, and complete mass-radius equilibrium sequences $M(R)$ with radial stability boundaries $\partial M / \partial \rho_c \le 0$ and $1.4 M_\odot$ radius interpolation (MATHEMATICAL_FORMULATION.md Section 4.8).IdealGasEOS, SyngeEOS, MathewsEOS, RelativisticFermiGasEOS, PolytropicEOS, PiecewisePolytropicEOS, and TabulatedNuclearEOS (include/relativistic/hydro/eos.hpp) model fluid thermodynamics across ideal, kinetic, degenerate, and dense nuclear regimes, supporting analytical enthalpy and sound speed evaluations, low-$x$ kinetic energy density expansions ($x < 0.05$), Newton-Raphson density-from-pressure inversions ($dp/dx = 8 p_0 x^4 / \sqrt{1 + x^2}$), multi-piece enthalpy continuity constants $a_i$, 3D trilinear table interpolations over $(\log_{10}\rho, \log_{10}T, Y_e)$ across 5 nuclear presets (SFHo, Shen, LS220, SLy4, APR4), and HDF5 container serialization (MATHEMATICAL_FORMULATION.md Section 4.9 and FILE_FORMATS.md Section 3.2).NovikovThorneDisk (include/relativistic/hydro/novikov_thorne.hpp, MATHEMATICAL_FORMULATION.md Section 5.1) integrates Page-Thorne analytical flux distributions around Kerr black holes; FishboneMoncriefTorus (include/relativistic/hydro/fishbone_moncrief.hpp, Section 5.2) evaluates stationary barotropic thick tori with constant specific angular momentum $l$; BlandfordZnajekModel (include/relativistic/magnetosphere/blandford_znajek.hpp, Section 5.3) models horizon-threading force-free jet magnetospheres with Znajek boundary conditions.StokesVector (include/relativistic/optics/stokes_vector.hpp), StokesEmissivity, and StokesTransferMatrix represent full-Stokes polarized transport with linear/circular/total polarization intensities, DoLP, DoCP, DoP, EVPA, and Mueller reference frame rotations (MATHEMATICAL_FORMULATION.md Section 6.2).RadiativeProcessEngine (include/relativistic/optics/radiative_processes.hpp) computes non-thermal synchrotron emission/absorption, thermal synchrotron with Faraday rotation ($\rho_V$) and conversion ($\rho_Q$), and relativistic Bremsstrahlung with thermal Gaunt factor corrections (MATHEMATICAL_FORMULATION.md Section 6.4).PolarizedRadiativeTransfer (include/relativistic/optics/polarized_radiative_transfer.hpp) executes analytical matrix exponential integration along ray segments via Delano’s scaling and squaring method with 12th-order Taylor series expansions of $\Psi(A)$, RK4 fallbacks, relativistic frequency shift scaling ($g^2$ emissivity and $g^{-1}$ transfer matrix scaling), and hybrid plasma integration (MATHEMATICAL_FORMULATION.md Section 6.3).PolarizedSpectrumSynthesizer (include/relativistic/optics/polarization_spectrum.hpp) synthesizes polarized multi-wavelength spectra across non-thermal, thermal, and hybrid models, evaluating polarization summaries, EVPA rotation measure (RM) fitting, and spectral index fitting.MaxwellJuttnerDistribution (include/relativistic/optics/maxwell_juttner.hpp) samples thermal relativistic electron distributions via a 4-regime decomposition algorithm with rational Bessel approximations; InverseComptonEngine (include/relativistic/optics/inverse_compton.hpp) performs Monte Carlo photon packet scatterings via the Klein-Nishina differential cross section and evaluates Compton $y$-parameters (MATHEMATICAL_FORMULATION.md Section 6.5 and Section 6.6).ContinuousSpectrum (include/relativistic/optics/spectrum.hpp) manages 4096-bin logarithmic radiances ($10^{-14}$ to $10^3\,\text{m}$) with Planck blackbody, synchrotron, and monochromatic generators; CIE1931Observer (include/relativistic/optics/cie_observer.hpp) convolves radiances to XYZ and linear sRGB; Tonemapper (include/relativistic/optics/tonemapping.hpp) applies ACES filmic, logarithmic HDR, and extended Reinhard tonemapping curves (MATHEMATICAL_FORMULATION.md Section 6.7 and Section 6.8).CarterPhaseClassifier (include/relativistic/optics/carter_ray_classifier.hpp) analytically pre-classifies Kerr null geodesics via Cardano cubic and Ferrari depressed quartic root extractions; GeodesicRayProbe (include/relativistic/optics/geodesic_ray_probe.hpp) traces exact null geodesics under screen pixels resolving constants of motion ($E, L_z, \xi, \mathcal{Q}, \eta, b$), sub-step disk crossings, observed temperatures, image orders, and deflection angles (MATHEMATICAL_FORMULATION.md Section 6.9 and Section 6.10).TerrellPenroseOptics (include/relativistic/optics/terrell_penrose.hpp) evaluates forward/backward relativistic aberration for arbitrary 3-velocity $\boldsymbol{\beta}$, apparent visual Terrell rotation angle $\arcsin(\beta)$, and moving sphere analytical spacetime ray intersections with retarded time solving (MATHEMATICAL_FORMULATION.md Section 6.11).VisibilitySynthesizer (include/relativistic/interferometry/visibility_synthesis.hpp), VlbiArrayCatalog (include/relativistic/interferometry/vlbi_array.hpp), and InterferometryPanel (include/relativistic/ui/interferometry_panel.hpp) execute Fourier visibility synthesis on synthetic antenna arrays, generating UV coverage, visibility amplitudes, closure phases, and OIFITS data products (Description, Mathematical Formulation).The uncertainty quantification subsystem (include/relativistic/uncertainty/) provides rigorous bounds and stochastic propagation across deterministic and perturbed spacetimes:
Interval<Scalar> (interval.hpp) implements IEEE 1788 interval arithmetic operations, directed division with zero-inclusion branches, integer powers with parity, hull, intersection, and transcendental functions (sqrt, exp, log, sin, cos with critical period detection; MATHEMATICAL_FORMULATION.md Section 7.1).Zonotope<Scalar, Dim> (zonotope.hpp) encapsulates affine generator sets $\mathcal{Z} = \mathbf{c} \oplus \sum \alpha_i \mathbf{g}i$. Supports interval box bounding, Minkowski sums, linear matrix transformations, scaling, translation, exact 2D volume, and Girard order reduction based on $L_1 - L\infty$ generator scoring (Section 7.2).CovarianceMatrix<Scalar, Dim> (covariance.hpp) implements continuous Jacobi-Lyapunov differential propagation ($\dot{\mathbf{\Sigma}} = \mathbf{J}\mathbf{\Sigma} + \mathbf{\Sigma}\mathbf{J}^T + \mathbf{Q}$), explicit Euler and RK4 integrators, cyclic Jacobi eigensystem decomposition with Givens rotations, $n$-sigma confidence hypervolumes, and multivariate Gaussian sampling via eigensystem square roots and Box-Muller PCG64 variates (Section 7.3).VariationalGeodesicIntegrator (variational_geodesic.hpp) integrates joint 8D phase states $(\mathbf{x}, \mathbf{p})$, state covariance matrices $\mathbf{\Sigma} \in \mathbb{R}^{8 \times 8}$, and variational transition matrices $\mathbf{\Phi} \in \mathbb{R}^{8 \times 8}$. Evaluates exact $8 \times 8$ phase Jacobians $\mathbf{J}$ via 8th-order centered finite difference derivatives of Christoffel symbols (GeodesicJacobianComputer) and monitors symplectic phase volume preservation via Gaussian elimination determinants (Section 7.4).MonteCarloCovarianceValidator (variational_geodesic.hpp) generates antithetic Gaussian ensembles with whitening transformations matching analytical initial covariance, integrates trajectories across worker threads, and validates empirical covariance semi-axes against analytical predictions. MonteCarloGeodesicSampler (monte_carlo_bundle.hpp) runs multithreaded ensemble batches and evaluates statistical moments (mean, variance, skewness, kurtosis; Section 7.6).PolynomialChaosExpansion (polynomial_chaos.hpp) executes spectral stochastic projections on orthogonal Hermite and Legendre bases with total degree truncation. GaussQuadrature generates nodes and weights via the Golub-Welsch symmetric tridiagonal QL algorithm. Evaluates mean, variance, statistical moments, and quantile estimation (compute_quantiles) via the Beasley-Springer-Moro inverse normal CDF approximation (Section 7.5).PceGeodesicPropagator (pce_geodesic.hpp) propagates 8D phase states through multidimensional tensor-grid quadrature points, solving trajectory ensembles with RK45 integration and projecting final states onto polynomial chaos basis functions.OrbitalWrappingBenchmark (orbital_wrapping_benchmark.hpp) benchmarks interval box wrapping against zonotope Girard reduction under rotational dynamics (Section 7.7).MetrologyVisualizer (metrology.hpp) constructs triangulated 3D covariance ellipsoid meshes with analytical surface normals, generates 2D bivariate Gaussian probability heatmaps via inverse covariance Mahalanobis metrics, evaluates empirical 2D spatial point heatmaps, and extracts time-series quantile bands (Section 7.7).UncertainQuantity<T, Method> (uncertain_quantity.hpp) provides unified arithmetic operator overloading across interval, zonotope, covariance, and polynomial chaos representations.GeodesicComputePipeline (include/relativistic/render/geodesic_compute_pipeline.hpp) owns a front and a back framebuffer of GpuPixelOutput. In windowed mode a worker thread renders the most recent pending request (GpuCameraPushConstants and body list); a request arriving while a frame is rendering raises a cancellation flag, so superseded frames are abandoned. In headless mode dispatch renders synchronously. After each frame the pipeline classifies pixels (horizon absorbed, celestial escape, accretion disk hit, step saturated), computes iteration statistics and records tile statistics of the adaptive sky prepass.
Path selection. When the distributed compute extension is bound and operational (is_cluster_active), frame rendering delegates eligible tile workloads across connected worker nodes via dispatch_distributed. In standalone mode, or when uncompleted tiles are reclaimed via work stealing, the Vulkan path is attempted when GPU compute is enabled and the executor is ready, and all of the following hold:
SoftwareComputeEngine::requires_exact_metric_path).Otherwise SoftwareComputeEngine::dispatch_fp64 or dispatch_double_single renders on the CPU thread pool, with the precision taken from the custom parameter precision_mode. Capture rendering uses the same selection through render_capture and render_capture_band.
Vulkan execution (include/relativistic/render/vulkan_context.hpp, include/relativistic/render/vulkan_compute_executor.hpp).
scalarBlockLayout, and shaderFloat64 when FP64 is requested. The score favors discrete GPUs, vendor identifier 0x10DE and FP64 support. When no device qualifies, the context stays initialized without a compute device and the CPU path is used.shaders/geodesic_tracer_fp64.comp.spv is searched in shaders, ../shaders, ./shaders and ../../shaders. CMake compiles it with glslangValidator when available.GpuBodyGpuLayout), 3 panorama combined image sampler, 4 persistent counter storage buffer.sky_background_source is not zero, the selected panorama (SkyPanoramaLoader) is uploaded as an R8G8B8A8_SRGB image.Viewport frame logic (ViewportPrimaryWindow, include/relativistic/ui/viewport_primary_window.hpp).
RGBA32F texture.BodyLighting, include/relativistic/render/bodies/body_lighting.hpp) evaluates one of 7 selectable light source modes: CentralSource (0, fixed at coordinate origin $(0, 0, 0)$), CameraHeadlight (1, co-located with the observer’s spatial position $\mathbf{x}{\text{obs}}$), FixedDirection (2, distant celestial key light with spherical horizontal azimuth $\phi_L \in [-180^\circ, 180^\circ]$ and vertical elevation $\theta_L \in [-90^\circ, 90^\circ]$), FixedPoint (3, localized point light source at Cartesian coordinates $\mathbf{x}{\text{light}}$), NearestEmissiveBody (4, dynamic nearest-neighbor emitter search across active bodies where $I_{\text{em}} > 10^{-3}$, modulated by the emitter’s primary color), SpecificBody (5, assigned emitting catalog body $B_{\text{id}}$ with primary color modulation), and Unlit (6, uniform unit diffuse shading without direct lighting, attenuation, or shadow calculations). Illuminance supports inverse-square distance attenuation $\mathcal{E}(d) = I_{\text{light}} \min((d_{\text{ref}}/d)^2, 64.0)$ under LightAttenuationMode::InverseSquare, terminator transition softness width $s \in [0, 1]$ via wrapped diffuse shading $D(s) = \operatorname{clamp}((\mu + s)/(1 + s), 0, 1)$ with smooth quintic/cubic twilight blending on planetary textures, Blinn-Phong specular reflections with microfacet roughness exponents $n_{\text{spec}} = 4 + 80(1 - \varrho)$, inter-body shadow occlusion rays tested against body bounding ellipsoids and central horizon spheres, and multi-source inter-body emission lighting accumulating radiant flux from active emitters with inverse-square falloff clamped to $16.0\times$ maximum gain (MATHEMATICAL_FORMULATION.md Section 8.4). Execution detail is regulated across three quality presets (Minimal, Reduced, Full), with configurable integer caps on tested shadow occluders (body_shadow_caster_limit, 1 to 512) and active radiant emitters (body_emission_source_limit, 1 to 512). Six standardized scene lighting presets (Stellar Default, Headlight, Studio Key, Unlit, Dramatic, Reset) provide repeatable illumination configurations across CPU and GPU pipelines.SkyboxRenderer, include/relativistic/render/skybox_renderer.hpp) evaluates equal-area spherical voxel partitioning ($N_{\text{grid}} \approx 14\sqrt{\rho_{\text{stars}} Q_{\text{eff}}}$) and 8 analytical star point spread functions (Gaussian, Lorentzian, Moffat, Airy diffraction with rational Chebyshev Bessel $J_1(x)$ polynomial approximation, HardDisc, DiffractionSpikes with configurable 4/6/8 spikes, PinpointDirac with concentration control, and CinematicBloom with secondary wide-angle exponential halos), 6 star placement density laws (UniformEqualArea, GalacticDisk, FractalClustered, DualPopulation, SpiralArmDensity, ConstellationAssociations), 4 parameter sampling distributions (Uniform, PowerLaw/Pareto, Exponential, LogNormal), blackbody chromaticity lookup via Wien displacement temperature intervals, multi-layer FBM nebulae with divergence-free 3D curl-noise advection, ionization emission, and gas contrast exponents, open and globular star clusters with Plummer density profiles and member star sampling via cumulative mass inversion, fractal interstellar dust extinction lanes via Beer-Lambert absorption, deep-field background galaxies across 6 morphologies (Grand Design, Flocculent, Barred, Elliptical with de Vaucouleurs Sersic radial profiles, Lenticular, Ring) with inclined dust extinction, quasars with collimated relativistic jets and Doppler boosting ($\delta^3$), pulsars with rotating magnetic dipole sweep beams and wind nebulae, supernova remnant shells with filamentary turbulence and reverse-shock interior glow, and a 3D spherical coordinate grid with major/minor lines, degree ticks, polar singularity tapering $\kappa_{\text{pole}}$, and 5 cell fill modes (None, Checkerboard2Color, CyclicPalette, CheckerboardPattern, RandomHashFill) indexing an editable 16-color palette (MATHEMATICAL_FORMULATION.md Section 12). Environment settings are encapsulated in the 1808-byte GpuSkyProfile uniform structure transferred to the GPU compute shaders. A dedicated Skybox & Environment Editor window provides real-time control over all parameters.preset_3d == 8), execution routes to superposed Kerr-Schild null geodesic integration ($g_{\mu\nu} = \eta_{\mu\nu} + 2 \sum_i H_i k_\mu^{(i)} k_\nu^{(i)}$). On GPU (geodesic_tracer_fp64.comp), workgroup thread 0 compiles up to 16 horizon centroids, masses, spins, orientation triads, and accretion disk boundaries into workgroup shared memory (ms_position_mass, ms_axis_spin, ms_frame_x_horizon, ms_frame_y_equatorial, ms_disk_range, ms_body_slot) followed by memoryBarrierShared(); barrier();. All workgroup threads then execute trace_multi_source in native FP64 without CPU readback. On CPU, SoftwareComputeEngine populates MultiSourceData and executes trace_multi_source. Both paths evaluate Hamiltonian null geodesic equations of motion driven by analytical gradients $\nabla H_i$ and $\nabla(\mathbf{k}^{(i)} \cdot \mathbf{p})$ (ks_source_terms), observer tetrad lifting via Gram-Schmidt orthonormalization in the superposed metric (ms_initial_momentum), simultaneous analytical oblate horizon entry resolution (ms_horizon_entry), and local accretion disk crossings (ms_disk_crossing) (MATHEMATICAL_FORMULATION.md Section 1.3).Coordinator. CaptureCoordinator (include/relativistic/capture/capture_coordinator.hpp) manages one capture session at a time. update(dt) is called once per UI frame and prepares frames; a worker thread executes the queued tasks (frame rendering, file writing, ffmpeg assembly). The capture constants are derived from the last constants dispatched by the viewport, with the current camera, exposure and mass parameters substituted (ViewportPrimaryWindow::build_capture_constants).
Frame rendering.
clamp(2^21 / (width * k^2), 1, height) rows, where k is the supersampling factor. Each band is traced at $k$ times the output resolution through GeodesicComputePipeline::render_capture_band and streamed to an ImageStreamWriter, so memory use does not depend on the output height. When cluster compute offload is active, record_cluster_stages logs network tile dispatch and decompression timings (ClusterNetworkDispatch, ClusterTileDecompress) to the profiler.step_size_factor, min_step_size and max_step_size by the step refinement factor.ColorGrade), and 8-bit triangular dither strength (triangular_noise) preventing quantization banding (Section 9.5).Deterministic mode. For each frame the coordinator processes script events, then for each of the temporal_samples sub-frame times: advances the simulation (ticks_per_frame multiplied by the script simulation rate and divided by the sample count, accumulated as a fractional tick count), applies the script pose (resolved against CameraCollisionField when camera collision is enabled), and stores constants and bodies. The shutter offsets are centered on the frame time, span shutter_fraction of the frame interval, and incorporate shutter_phase shifts in $[-1.0, 1.0]$. At most two frames are queued at once (kMaxQueuedFrames = 2). World advance modes: frozen, fixed ticks per frame, or simulation seconds per video second (ticks per frame = s / (fps * tick_dt)). With the trigger PathDuration, the frame index is mapped linearly onto the script duration. Continuous parameter and warp ramps are evaluated at each sub-step by ScriptEventDispatcher. Pause and resume events freeze and release the world. Manual stepping renders one frame per request (at most 64 pending). The live viewport render is suppressed unless preview_in_viewport is set.
Real-time mode. The front framebuffer is copied at the frame interval. Pacing either drops late frames or duplicates the last frame to fill gaps; frames waiting for disk writing are limited by the queue depth. The viewport resolution multiplier is locked, and frames whose size changes are resampled by nearest neighbor to the first frame size. Real-time post-processing applies the color grade and triangular dither directly before disk queuing.
Session end. The recorder is finalized, the camera, field of view, exposure, camera mode, warp factor and pause state are restored (the camera only when restore_camera_after_capture is set or a script was used), sequence_info.txt is written (documenting execution mode, submitted/written/dropped/duplicated frames, camera collision state, recording path, resolution, and assembly command), motion_script.cfg is archived, and ffmpeg is invoked through std::system when assembly is enabled and the session completed. Output files are described in FILE_FORMATS.md.
Motion script (include/relativistic/capture/motion_script.hpp). A script is an ordered list of segments with a global easing and an end behavior (clamp, loop, ping-pong).
projection_mode), and a transition blending from the previous segment (orientation, position, lens, and projection mode transitions).DriverSpec): Maps live measurements onto channel values via 12 signal sources (Distance to Target, Distance to Origin, Position X/Y/Z, Camera Speed, Segment/Script Progress, Segment/Script Time, Event Time Offset, Custom Expression), configurable input/output bounds, response easing, and blend modes (Replace, Add, Multiply).ProjectionTransitionMode: StepAtMidpoint, StepAtStart, StepAtEnd, SmoothMorph, FovCompensatedMorph, CrossZoom, WarpCurvature) with projection blend factor and FOV compensation (MATHEMATICAL_FORMULATION.md Section 9.4).Expression language (include/relativistic/capture/expression.hpp). Expressions compile to a stack program. Variables: t (segment time), u (progress), d (duration), g (script time), a, b, c, k (parameters), r (radius), x, y, z (position), v (speed), m (driven measurement), p (script progress), s (segment index). Constants: pi, tau, e. Operators: + - * / % ^, < > <= >= == !=. Functions: sin cos tan asin acos atan sinh cosh tanh exp log ln log2 log10 sqrt cbrt abs floor ceil round fract sign rad deg saturate smooth noise tri saw square atan2 min max hypot step pow mod clamp mix if smoothstep. Division by zero evaluates to 0 and non-finite results are replaced by 0.
Recording and preview. PhysicsRecorder derives kinematic and relativistic channels from the live camera pose and the orchestrator state for each frame (FILE_FORMATS.md). build_path_preview (include/relativistic/capture/path_preview_builder.hpp) samples the script into a PathPreview (vertices, reference path without shake and transitions, markers, camera frustum) drawn by the schematic renderer.
PerformanceProfiler (include/relativistic/orchestrator/performance_profiler.hpp) keeps a ring of FrameSample records (default capacity 3600, minimum 16). Stage durations are accumulated through ScopedStageTimer and attached to the next recorded frame. The stages are FrameTotal, RenderDispatch, TextureUpload, HudOverlay, CameraUpdate, SchematicOverlay, PostProcessing, FramebufferReadback, GpuDispatchExecution, CpuDispatchExecution, AdaptiveTilePrepassSky, PixelClassification and CameraConstantsBuild.
StatisticalSummary provides mean, median, minimum, maximum, population standard deviation and the 95th and 99th percentiles (linear interpolation).analyze_bottleneck selects the dominant stage among all stages except FrameTotal and the five render sub-stages, reports ray step saturation when the mean saturated ray fraction exceeds 0.35, and flags a window without any GPU frame.EngineSignature::compute (include/relativistic/core/engine_signature.hpp) is the first 8 bytes (16 hexadecimal characters) of the SHA-256 digest of the build tag relativistic-engine-perf-abi, the structural revision, and sizeof(GpuCameraPushConstants) and sizeof(GpuPixelOutput). Runs with a different signature are marked as not directly comparable.BenchmarkWorkbench, include/relativistic/ui/benchmark_workbench.hpp): Multidimensional performance analysis tool in PerformanceAnalysisWindow supporting multi-run comparative charting (Grouped Bars, Lines, Scatter, Stacked Stages), eight normalization transforms (Raw, Log10, Ln, Log2, Ratio to Baseline, Percent Delta, Min-Max, Z-score), statistical significance evaluation (Welch’s $t$-test, $p$-value, Cohen’s $d$, 95% confidence intervals), and TSV clipboard export (MATHEMATICAL_FORMULATION.md Section 14).Logging. EngineLog (include/relativistic/core/engine_log.hpp) keeps the last 4096 entries with a timestamp and severity (info, warning, error) and mirrors them to standard output or standard error.
Settings & Persistence. UserSettings uses format version 7 and partitions persistence across nine modular domain files under config/preferences/: general.cfg, camera.cfg, render_sky.cfg, interface.cfg, units.cfg, physics.cfg, celestial_bodies.cfg, capture.cfg, and cluster.cfg. Legacy unified config/user_settings.cfg files are migrated on launch. CaptureStudioSettings manages session capture parameters. Crash detection is governed by config/.session_active, which forces default resets if a session aborts unexpectedly (FILE_FORMATS.md Section 10.1).
Core::Diagnostics): DiagnosticsRegistry (diagnostics_registry.hpp) maintains sequential ring buffers with sequence ordering for command journaling (CommandRing, 256 slots of 384 bytes), logged warnings and errors (ProblemRing, 128 slots of 448 bytes), system milestones (MilestoneRing, 192 slots of 320 bytes), recent event lines (EventSlot, 512 slots of 320 bytes), double-buffered 16 KiB state snapshots (scene, render, startup, Vulkan, OpenGL), an activity table tracking up to 64 active threads with thread names and RAII ActivityScope duration timers, a 256-slot environment table, and atomic activity counters tracking frames, heartbeats, commands, warnings, and errors across application phases (AppPhase: Launching, Startup, Running, Headless, ShuttingDown). DiagnosticsLocator (diagnostics_paths.hpp) resolves log directories with fallback across working directories, %LOCALAPPDATA%, $XDG_STATE_HOME, and temporary folders using .write_probe_<pid> verification, enforcing retention limits (40 session logs, 25 crash directories) and managing crash markers (last_crash.txt, last_crash_acknowledged.txt). SystemReport (system_report.hpp) extracts CPUID leaf features (AVX, AVX2, AVX-512, FMA, BMI1/2, Neon), logical core topologies, L1/L2/L3 cache hierarchies, virtual/physical memory usage, process working sets, GDI/USER object counts, open handles, and loaded module maps. CrashReporter (crash_reporter.hpp) intercepts fatal aborts via Windows Vectored Exception Handlers (AddVectoredExceptionHandler), Unhandled Exception Filters (SetUnhandledExceptionFilter), CRT invalid parameter handlers, pure virtual call handlers, and POSIX signal handlers (sigaction with SA_SIGINFO | SA_ONSTACK over a dedicated 64 KiB alternate stack sigaltstack for SIGSEGV, SIGBUS, SIGFPE, SIGILL, and SIGABRT). Reports written to timestamped directories under logs/crashes/ include CPU register dumps (RAX-R15, RIP, RSP, RBP, EFLAGS, MXCSR on x86-64), 16-byte instruction memory disassembly at RIP, 24-word stack dump at RSP, DbgHelp or backtrace symbol-resolved backtraces with source file lines, target memory page attributes via VirtualQuery (committed/reserved state, protection flags, allocation base), heuristic module classification (graphics drivers, system runtime, application), loaded module maps, thread context tables, process minidumps (minidump.dmp), active configuration preferences, and session log tails up to 16 MiB.HangWatchdog): An autonomous monitoring thread (std::jthread, hang_watchdog.hpp) polling at 500 ms intervals inspects monotonic timestamps of UI frame completions (last_frame_ns) and simulation tick heartbeats (simulation_heartbeat_ns). Stalls exceeding 20 seconds for the interface thread (suppressed when Windows GetGUIThreadInfo detects active modal loops GUI_INMOVESIZE, GUI_INMENUMODE, GUI_POPUPMENUMODE, or GUI_SYSTEMMENUMODE) or 45 seconds for the simulation thread trigger CrashReporter::report_hang, capturing the faulting thread context via OpenThread/SuspendThread/GetThreadContext/ResumeThread and writing live diagnostic dumps and minidumps without process termination, while sleep/suspend resume intervals (> 5 s) grant an automatic 3-second grace period.SystemConsole): Manages native console attachment and allocation (system_console.hpp) via AttachConsole(ATTACH_PARENT_PROCESS) or AllocConsole, rebinds standard streams (stdin, stdout, stderr) to CONIN$ and CONOUT$ with unbuffered I/O (_IONBF), disables the console window close menu item (SC_CLOSE) to prevent accidental process termination, replays pre-allocation log history from EngineLog, and exposes visibility toggling synchronized with user settings.DiagnosticsSession): Coordinates process lifecycle initialization (diagnostics_session.hpp), binds EngineLog to the diagnostics event sink, announces unacknowledged previous crash markers, publishes comprehensive platform environment keys (compiler version, pointer bits, compile-time SIMD flags, disk space for working/logs/temp, executable timestamps, and graphics environment variables), attaches startup progress monitoring, and logs clean session termination summaries.SchematicViewRenderer (include/relativistic/ui/schematic_view_renderer.hpp) draws bodies, the central object, background grid, field lines, trails, orbit predictions, vectors and the capture path preview as a projected overlay, using the camera tetrad and the selected projection (pinhole when human_perspective_mode is set). Objects are depth-sorted and path segments are split at occlusion boundaries so that spheres cover the segments behind them. Orbit predictions integrate a two-body orbit around the central mass with a velocity Verlet scheme. Spacetime source bodies are drawn with a horizon disc, ISCO and disk outer rings and a spin axis. The overlay can be shown on top of the ray-traced image, optionally applying a first-order deflection $4M/b$ (limited to 0.35 rad) to body positions.
SpatialReferenceRenderer (include/relativistic/ui/spatial_reference/spatial_reference_renderer.hpp) renders 3D Cartesian coordinate planes (XY, XZ, YZ), equatorial reference rings, polar axes, graduation ticks, origin markers, and screen-space scale bars centered at the origin, a designated body, a custom point, or a camera-snapped local frame (SpatialCenterMode). It evaluates adaptive logarithmic “nice number” spacing, continuous distance depth-fading, radial grid edge falloff, horizon sphere ray-intersection occlusion, and weak-field gravitational light deflection (MATHEMATICAL_FORMULATION.md Section 15).
SecondaryViewportManager (include/relativistic/ui/secondary_viewport_manager.hpp) coordinates independent auxiliary observer viewports (SecondaryViewWindow, include/relativistic/ui/secondary_view_window.hpp) executing synchronous native FP64 raytracing across four operational roles (FreeObserver, ComovingProbe, AsymptoticGlobal, Equirectangular360) and five target modes (CentralObject, PrimaryCameraPosition, PrimaryCameraFocus, TrackedBody, CustomPoint). Secondary observers evaluate comoving free-fall velocity boosts with relativistic aberration, asymptotic telephoto framing, multi-view target synchronization, dynamic resolution auto-throttling ($s = \max(\lambda^{N-1}, 0.15)$), and 3D beacon markers with golden-ratio chromatic dispersion injected into the primary raytraced scene (MATHEMATICAL_FORMULATION.md Section 16).
The HUD (HudLayoutConfig, include/relativistic/ui/hud/hud_layout_config.hpp) consists of 34 configurable elements:
FrameTimeReadout (0, instant/rolling average FPS and frame times), CameraDistanceReadout (1), CameraAnglesReadout (2), CameraOrientationReadout (3), CameraPositionReadout (31, dual-coordinate system display), ArrowKeysModeReadout (33), NavigationControlsPanel (6), SimulationClockReadout (9), WarpFactorReadout (10).MetricSummaryReadout (4), RayStatisticsReadout (5), LoadingIndicator (8), PerformancePresetReadout (11), TelemetryQuickReadout (12), SpectrographQuickReadout (13), DiagnosticsQuickReadout (14), ProfilerFrameTimeReadout (15), ProfilerBottleneckReadout (16), ProfilerStageBreakdownReadout (17), ProfilerRayClassificationReadout (18), ProfilerIterationRangeReadout (19), ProfilerGpuCpuSplitReadout (20), BodyCountReadout (21), GpuComputeStatusReadout (22), IntegratorStatsReadout (23), ConstantsQuickReadout (24).RayProbeReadout (25), RayProbeEmissionReadout (26), PolarizationQuickReadout (27), InterferometryQuickReadout (28), RayProbeGeometryReadout (29), DarkMatterQuickReadout (30), CursorReadout (32).ViewportToolbar (7), providing 26 configurable shortcuts via ToolbarButtonVisibility (Play/Pause, Step, Reset View, Look-At Target combo with dynamic body/landmark distance list, Jump to Target, Camera Mode combo, HUD master toggle, Screenshot, Fullscreen, GPU compute, Space-Skip, LOD, EV-/EV+, Warp-/Warp+, Tonemapper cycle, Projection cycle, Skybox toggle, Metric cycle, Integrator cycle, Performance preset combo, QSave/QLoad, StepCtrl cycle, Render Distance toggle, Pole-/Pole+ precision nudge buttons, Arrow Keys Mode toggle, and Coordinate system cycle buttons) with adjustable button padding scale ($0.4\times$ to $3.0\times$).Each element supports anchor corner placement, offset, fine-tuning nudge, scale, text color, background panel opacity, display mode (compact, standard, extended), horizontal layout, draw priority, decimal precision (0 to 6), and dual dynamic threshold color rules (HudColorRule) tinting readouts to warning or critical hues. The automatic layout engine (HudAutoArranger) stacks shared-anchor elements without gaps based on draw priorities, calculating element bounding boxes and adding user nudges. Dual coordinate system displays (HudCoordinateDisplay) simultaneously format primary and secondary coordinates across 9 coordinate systems (Cartesian, spherical, cylindrical, Boyer-Lindquist, metric-adapted tortoise $r^*$, isotropic, Kruskal, Painlevé, Eddington). Off-screen object indicators (OffscreenIndicatorConfig) render edge markers (triangles, chevrons, diamonds, dots) scaled and faded by distance. Frame time readouts evaluate a rolling average over rolling_average_frame_count samples (2 to 120).
ConstantsEngine (include/relativistic/core/physical_constants_engine.hpp) stores the simulation values of $c$, $G$, $h$, $k_B$, $N_A$, $K_e$ and $K_{cd}$. It is constructed with the Planck preset ($c = G = k_B = K_e = K_{cd} = 1$, $h = 2\pi$, $N_A$ unchanged); UiManager then applies the preset stored in the user settings (SI by default). Setting any constant switches the preset to Custom. Each value is clamped to at least $10^{-300}$. The post-Newtonian solver uses the engine values of $c$ and $G$.
The scale factors between simulation units and SI units are:
\[T_0 = \sqrt{\frac{G_{SI}}{G}\frac{h_{SI}}{h}\left(\frac{c}{c_{SI}}\right)^5}, \quad L_0 = \frac{c_{SI} T_0}{c}, \quad M_0 = \frac{G}{G_{SI}}\frac{L_0^3}{T_0^2}\] \[Q_0 = \sqrt{\frac{K_e}{K_{e,SI}}\frac{M_0 L_0^3}{T_0^2}}, \quad K_0 = \frac{k_B}{k_{B,SI}}\frac{M_0 L_0^2}{T_0^2}, \quad N_0 = \frac{N_A}{N_{A,SI}}, \quad I_0 = K_{cd}, \quad A_0 = \frac{Q_0}{T_0}\]Derived simulation quantities include the reduced Planck constant $h / 2\pi$, the Stefan-Boltzmann constant $2\pi^5 k_B^4 / (15 h^3 c^2)$, the vacuum permittivity $1 / (4\pi K_e)$, the vacuum permeability $4\pi K_e / c^2$, the magnetic coupling $K_e / c^2$ and astronomical quantities (solar mass, astronomical unit, Earth and Jupiter masses, parsec, light year, particle masses, solar Schwarzschild radius, Thomson cross section, Wien constant) divided by the corresponding scale.
The unit display and conversion subsystem (include/relativistic/units/unit_system.hpp) provides selectable units across 19 physical categories:
User selections are managed in UnitDisplayPreferences (config/preferences/units.cfg). The mathematical expression evaluator (include/relativistic/units/expression_engine.hpp) implements recursive descent parsing with dimensional analysis over a 6D base dimension vector (DimensionVector: $[L, M, T, I, \Theta, A]$) and a 164-token unit registry (UnitRegistry). It validates dimensional homogeneity in additive expressions, verifies dimensionless exponents, checks even dimension powers for square roots, handles affine temperature offsets, and parses unit suffixes with integer exponents (evaluate_expect_dimension, evaluate_dimensionless; MATHEMATICAL_FORMULATION.md Section 19). UI widgets (include/relativistic/units/unit_aware_widgets.hpp) integrate unit conversion and label formatting directly into ImGui sliders and input fields.
The distributed compute subsystem extends the execution capabilities of the engine without modifying its single-node determinism or introducing heap allocations in inner computational loops:
cluster.enabled = 0. Local execution performance on Vulkan FP64 or CPU SIMD remains identical to non-distributed builds.ClusterMaster (interactive host or headless batch coordinator), ComputeWorker (autonomous lightweight worker cluster_worker without graphical dependencies), HybridNode (co-evaluating local and remote partitions), or Standalone (isolated single-machine execution).Unauthenticated, Handshaking, Synchronized, Ready, Computing, Stalled, and Disconnected. Transitions are strictly enforced by is_valid_node_transition. Stalled nodes automatically trigger work-stealing reclamation.CryptoChannel): All datagrams enforce AEAD encapsulation using ephemeral X25519 Diffie-Hellman key exchange, HKDF-SHA256 key derivation with "RelativisticEngineV1" domain separation, and ChaCha20-Poly1305 authenticated symmetric encryption with a 64-packet anti-replay sliding window. Every packet begins with a 48-byte aligned PacketEnvelope (0x52454C44 magic identifier, 28-byte authenticated header as AAD, and 16-byte Poly1305 MAC tag; FILE_FORMATS.md Section 11.1).resolve_tile_geometry ($N_{\text{cols}} = \lceil W / 32 \rceil, N_{\text{rows}} = \lceil H / 32 \rceil$), evaluated via Vulkan compute (cluster_tile_tracer_fp64.comp) or multi-threaded CPU SIMD (TileRenderer).GpuNBodyExecutor executing nbody_accel_fp64.comp in FP64 on Vulkan or CPU evaluate_nbody_accelerations_local across Newtonian and 1PN/2.5PN phases.run_geodesic_ensemble_local).run_stochastic_pce_quadrature_local).SlurmInterface detects MPI rank and task allocation (SLURM_PROCID, SLURM_NTASKS, SLURM_STEP_NODELIST). Rank 0 configures and starts ClusterOrchestrator with local GPU compute offload, while higher ranks execute autonomous ClusterWorkerService daemons connecting back to rank 0.DirectRaw: Uncompressed raw 32-byte pixel output with zero CPU overhead for low-latency 10GbE LAN environments.QoiHdrRle: Radiance quantization into IEEE 754 half-precision (FP16) floats with run-length encoding for flags and iteration counts.Lz4Block: SIMD channel-shuffled block compression delivering $> 3.5\,\text{GB/s}$ decompression throughput.GpuPixelOutput payloads undergo explicit SIMD vector scanning guarding against NaNs, infinities, and unphysical negative radiances, clamping radiant flux to $[0.0, 1.0 \times 10^8]\,\text{W/m}^2/\text{sr}$.239.255.77.88:42424 with CRC32 verification and cluster namespace hashing for zero-configuration LAN clustering.The application lifecycle and initialization pipeline are managed by decoupled startup primitives (include/relativistic/startup/):
PlatformBootstrap (platform_bootstrap.hpp) enforces per-monitor DPI scaling awareness via SetProcessDpiAwarenessContext on Windows, registers the explicit Application User Model ID (Wartets.RelativisticEngine), activates heap termination on memory corruption, resolves the canonical executable directory, normalizes the working directory across up to 4 parent levels until asset roots (shaders, scenarios) are detected, and dispatches native modal message boxes for critical faults.SingleInstanceGuard (single_instance_guard.hpp) prevents concurrent execution on identical host contexts using a named Win32 mutex (Local\Wartets.RelativisticEngine.SingleInstance) or a POSIX file lock descriptor (/tmp/wartets-relativistic-engine-<uid>.lock via flock). When an instance is already running, activate_existing_instance locates the visible main window handle (find_visible_window), restores minimized windows via ShowWindow(SW_RESTORE), and transfers OS focus to the foreground (SetForegroundWindow).StartupProgress (startup_progress.hpp) coordinates staged progress reporting across nine sequential ranges (StartupStage: Runtime, Settings, Simulation, WindowSystem, GraphicsContext, RenderBackend, Interface, Content, Finalize). It exposes thread-safe observer and listener callbacks, asymptotic creep limit smoothing, and cooperative startup cancellation handling (request_cancel, throw_if_cancelled).set_compilation_state, reflecting live compilation status on the progress bar and stage readouts.StartupWindow (startup_window.hpp) creates and manages a dedicated Win32 progress window running on an independent background thread synchronized via std::promise<bool>. It evaluates custom GDI double-buffering, per-monitor DPI font generation, animated progress easing via a 15 ms timer, elapsed clock tracking via a 100 ms timer, and interactive controls (minimize, cancel/close, and repository/docs/license actions) with custom theme palette rendering.The system employs a multi-threaded execution model designed to eliminate synchronization stalls & lock contention:
The execution flow is governed by Scheduler, maintaining a fixed logical clock frequency (10 to 1000 Hz) decoupled from visual presentation refresh rates:
request_steps), & continuous time dilation scaling (warp_factor).Communication between the master terminal/UI & the simulation core is mediated by SpscQueue (Single-Producer Single-Consumer lock-free ring buffer):
std::memory_order_acquire, std::memory_order_release) with cache-line-isolated pointers (64-byte padding) to eliminate false sharing.ThreadPool manages a static pool of std::jthread workers synchronized via condition variables, executing chunked parallel loops (parallel_for).SimulationOrchestrator::advance_simulation(dt) (include/relativistic/orchestrator/simulation_orchestrator.hpp) performs the following steps:
Central Object of mass $M$, radius $2M$ and spin $(0, 0, aM)$ is registered as the spacetime source, unless an enabled body of mass above $0.5M$ already sits at the origin.Symplectic or Gauss, and the fourth-order Runge-Kutta post-Newtonian integrator otherwise, followed by the interaction step and the horizon absorption step. Bodies disabled before the step keep their state.Horizon absorption and black hole merging (handle_horizon_absorption) operates on the central mass with spin clamped to $\pm 0.999M$ and outer horizon radius $r_h = M + \sqrt{M^2 - a^2}$:
enabled = false, integrity = 0.0).enforce_spacetime_source_invariants reclamps dimensionless spin parameter $a{*, i} \in [-0.9999, 0.9999]$ and updates the horizon radius.Core::Diagnostics::record_milestone).Command application, including the Reset semantics, is described in CLI_REFERENCE.md. Changes to $c$ and $G$ in the constants engine are copied to the N-body configuration.
ScenarioLocator (include/relativistic/io/scenario_locator.hpp) resolves files and the scenario directory relative to the working directory and up to four parent levels (kMaxAncestorDepth). A requested path is tried as given, then prefixed by up to four .. components, then, when its parent directory is named scenarios, against the located scenario directory. portable_path stores paths inside the scenario directory in the form scenarios/<file>.
At startup UiManager::queue_startup_scenario loads the configured default_scenario_path when load_scenario_on_startup is set. If the file cannot be resolved, parsed or validated, the built-in scenarios/schwarzschild_accretion.yaml is loaded instead and becomes the stored startup path; when it is also unavailable, the simulation starts empty. The Scenario Manager scans the directory for .yaml and .yml files, marks files that fail parsing or validation as incompatible, protects the built-in startup file from deletion, and saves new presets under collision-free file and scenario names (<stem>_<n>.yaml and <name> (<n>)).
DistributionScheduler (include/relativistic/distributed/distribution_scheduler.hpp) partitions visual frames, post-Newtonian N-body systems, and stochastic ensembles:
kTileEdgePixels = 32). Initial integer quotas $K_i = \lfloor \Omega_i(t) \cdot N_{\text{active}} \rfloor$ conserve work by assigning remaining deficit tiles to the local node (local_slot). Quota distribution supports Interleaved mode (Bresenham-style credit accumulation distributing adjacent tiles across different nodes) and Contiguous mode (sequential tile block assignment).TileStatus (Skipped, Queued, InFlight, Reclaimed, CompletedRemote, CompletedLocal). Tasks carry dynamic deadlines $t_{\text{deadline}} = t_{\text{dispatch}} + \operatorname{clamp}(\overline{\text{RTT}}i + 3.5 \sigma{\text{RTT}, i} + t_{\text{compute}, i}, t_{\min}, t_{\max})$. Work stealing operates across three triggers:
collect_expired: Reclaims tiles whose deadlines have elapsed (ReclaimReason::Timeout).steal_speculative: Reclaims in-flight tiles when elapsed time exceeds a configurable fraction ($\text{speculative_fraction} \in [0.05, 1.0]$, default 0.5) of the deadline window, sorted by earliest dispatch time (ReclaimReason::Speculative).reclaim_node: Immediately reclaims all in-flight tiles assigned to a disconnected or stalled node (ReclaimReason::NodeLost).
Reclaimed tiles execute on the local thread pool (should_compute_local) and complete via atomic compare-and-swap (try_complete_local). Duplicate remote completions increment late_results_discarded telemetry without state corruption.The engine provides multi-tiered precision configurations to balance numerical accuracy & throughput:
double) across all tensor algebra, Christoffel derivations, variational mechanics, & geodesic integration loops.DoubleSingle (include/relativistic/render/double_single.hpp) emulates extended precision (approx. 48 bits of mantissa, matching $\approx 14$ decimal digits) using pairs of IEEE 754 single-precision floats (hi, lo). The functions ds_sin, ds_cos and ds_atan2 evaluate in double and split the result.two_sum, Dekker’s two_diff, and Veltkamp-Dekker two_prod (using hardware fma).SoftwareComputeEngine::dispatch_double_single on the CPU (Technical Manual). The Vulkan compute path requires native FP64 and is skipped when double-single precision is selected (see Section 2.9).SimdVec<T, Width> and SimdMask<T, Width> (include/relativistic/core/simd.hpp) map to native SIMD registers across AVX2, AVX-512, and ARM Neon (Technical Manual).GeodesicBundle (include/relativistic/core/geodesic_bundle.hpp) formats ray coordinates and four-momenta in Structure-of-Arrays (SoA) layout, executing vectorized RK4 updates across concurrent ray lanes (GeodesicBundle4d and GeodesicBundle8f; see TECHNICAL_MANUAL.md Section 2.9).The platform provides decoupled interfaces for interactive exploration & batch execution:
MasterTerminalRepl provides an asynchronous, non-blocking command-line interface.CommandParser) translates text commands into strongly-typed Command structures dispatched to the simulation orchestrator without graphical dependencies. A line is rejected when the queue (capacity 1024) is full; applied commands report their outcome through the result queue. Command processing rules are listed in CLI_REFERENCE.md.When executing in interactive mode, UiManager coordinates GLFW windowing, OpenGL 3.3+ rendering contexts, & ImGui/ImPlot multi-viewport docking:
ViewportPrimaryWindow): High-resolution display of the raytraced image stream with interactive HUD telemetry overlays & camera transport toolbars.ControlPanelWindow, include/relativistic/ui/control_panel_window.hpp): Central simulation management console organized across 14 functional tabs managed via MultiRowTabBar:
SpacetimeSourcePanel with HorizonRegimeAnalyzer evaluating sub-extremal, extremal, and super-extremal states, horizon lock enforcement, and visual horizon zone strips; primary accretion disk editor (procedural thin disk, Novikov-Thorne, Fishbone-Moncrief torus); and Blandford-Znajek jet magnetosphere editor.MultiRowTabBar, include/relativistic/ui/multi_row_tab_bar.hpp): Dynamic multi-row tab container providing:
AutoTwoRowsBalanced (dynamic bisection search balancing widths across 2 rows), AutoWrap (greedy line wrap), and FixedRows (enforces explicit row assignments).MultiRowLabelFitMode): FullOnly, ShortOnly, and SmartAdaptive (dynamically falls back from full title to medium abbreviated dictionary words, short initial phrase, or compact uppercase acronym).MRT_TAB_REORDER) with drop indicator insertion lines, and right-click context menu (Move Left, Move Right, Move to First, Move to Last, Reset Default Order).active_elevation with accent highlight lines.WindowChromeController, include/relativistic/ui/window_chrome.hpp): Manages thematic window accent styling and multi-monitor window placement:
WindowThemeId): Viewport, Controls, Scenarios, Bodies, Performance, Telemetry, Spectrograph, Diagnostics, Analysis, Keybinds, Constants, LogConsole, CaptureStudio, SecondaryViews.WindowThemePalette): derives active/inactive title bar backgrounds, borders, headers, slider grabs, check marks, and docking tabs from a single accent color. Enforces relative luminance clamping ($Y \le 0.14$) to maintain high contrast with text.kWindowThemeSwatches) with per-window and global reset actions.WindowGeometry), fitting them dynamically to monitor work areas (fit_to_monitors) to prevent windows from opening off-screen across display changes.CoordinateAwareWidgets, include/relativistic/ui/coordinate_aware_widgets.hpp): Multi-coordinate input fields supporting 9 coordinate systems (Cartesian, Spherical, Cylindrical, Boyer-Lindquist, Metric-Adapted, Isotropic, Kruskal-Szekeres, Painlevé-Gullstrand, Eddington-Finkelstein) with field-level coordinate override popups and global default synchronization.ScenarioSelectorWindow): Scenario browser supporting preset loading & YAML file serialization.TelemetryWindow, VisualDiagnosticsWindow): Real-time numerical display & temporal history graphs of Ricci scalar curvature $R$, Kretschmann invariant $K_1$, metric tensor components $g_{\mu\nu}$, & horizon radii.SpectrographWindow): Real-time plotting of spectral radiance curves $I(\lambda)$ with $1\sigma$ confidence bands & perceived CIE sRGB color swatches.PerformanceSettingsWindow): Profiles, internal render scale adjustment, ray budget limits, & arithmetic precision toggling.InteractiveCameraController): Manages six navigation modes (Free-Fly 6-DOF, Orbit Center, Spherical Boyer-Lindquist, Rocket Thrust, Surface Walk on celestial bodies, and Planet Orbit) with mouse-look, gamepad flight controls, hotkey shortcuts, hold-to-zoom magnification, and 8 projection modes (Pinhole, AutoZoom, FisheyeStereographic, Equirectangular360, FisheyeEquidistant, FisheyeOrthographic, PaniniCylindrical, HammerAitoff). Dual-stick gamepad input (GamepadConfig, GamepadState, include/relativistic/ui/gamepad_input.hpp) maps left stick translation (LX, LY), right stick look inclination (RX, RY), trigger vertical translation (LT, RT), and bumper roll axes (LB, RB) with quadratic deadzone filtering, 10 virtual stick/trigger buttons, dual-button chords (such as RB + LB roll reset), and configurable action execution modes (Hold, Toggle, Tap, Double-Tap). Arrow keys support four operational modes via ArrowKeysMode (Movement, LookPitchYaw, LookPitchRoll, LookRollYaw) with adjustable sensitivity and axis inversions. Mode behaviors are detailed in CLI_REFERENCE.md Section 3.2 and MATHEMATICAL_FORMULATION.md Section 8.6.BodyManagerWindow organized into seven functional tabs:
HudManagerWindow (on-screen telemetry layout and element styling), ConstantsWindow (physical constants presets and dimensional expressions), KeybindSettingsWindow (keyboard layout presets, Xbox/USB gamepad axis deadzones, stick sensitivity, trigger elevation, bumper roll, and chord mapping with tap and double-tap detection), LogConsoleWindow (engine log viewer with severity filters and system console toggle), PerformanceAnalysisWindow (benchmark capture, bottleneck analysis, A/B run comparison with Welch’s $t$-test, and the multi-series Comparison Workbench), SecondaryViewportManager (auxiliary observer viewports, comoving free-fall probes, asymptotic telephoto cameras, and 3D observer beacon markers, described in Section 2.12), SpatialReferenceEditor (3D coordinate planes, axes, ticks, rings, scale bar, and horizon occlusion, described in Section 2.12), SkyboxEditorWindow (procedural skybox and panorama asset configuration), and CaptureStudioWindow (screenshots, sequences, motion scripts, data recording and video encoding settings, described in Section 2.10).UiManager provides the presets MultiWindowDetached, DockedWorkspace, ViewportFocused and DeepAnalysis, applied on the next frame; global hotkeys are processed only when no text widget captures the keyboard.The engine interfaces with standard astronomical data formats & ephemeris services:
HorizonsInterface: Formulates REST queries & parses NASA JPL Horizons CSV vector tables, converting barycentric state vectors to SI units.SpkKernel & SpkChebyshevSegment: Evaluates Type 2 (position-only) and Type 3 (position/velocity) Chebyshev segments via polynomial recurrence relations. parse_daf_spk_bytes validates the file header only; segment loading from DAF records is not implemented (see FILE_FORMATS.md).FrameTransformer: Converts state vectors & four-vectors between ICRF J2000, Heliocentric Ecliptic, Geocentric Equatorial, & comobile boosted reference frames.ScenarioSerializer: Reads & writes declarative YAML scenario files (.yaml).FitsExporter: Generates 2D radiance images & 3D spectral data cubes $(X, Y, \lambda)$ adhering to the FITS Standard 4.0 with WCS astrometric headers & big-endian IEEE 754 formatting.OifitsWriter: Generates Optical/Infrared/Radio Interferometry Exchange Format files (.oifits) containing OI_TARGET, OI_ARRAY, OI_WAVELENGTH, OI_VIS, OI_VIS2, and OI_T3 binary tables adhering to the IAU OIFITS specification (FILE_FORMATS.md Section 2.3).Hdf5Container: Serializes hierarchical binary datasets including worldlines, metric series, covariance matrices, & tabulated nuclear equations of state.VtkExporter: Generates VTK XML PolyData files (.vtp) for polyline trajectories & event horizon surface meshes.ImageCodecs, ImageStreamWriter and ScreenshotExporter: Encode and stream ten image formats (FILE_FORMATS.md).TelemetryTable and write_telemetry_table: Store and serialize recorded channels in seven formats (FILE_FORMATS.md).UserSettings, CaptureStudioSettings and PerformanceProfiler persistence: Key-value configuration files under config/ (FILE_FORMATS.md).