SPB Git

Repository Public

CosmosShared.h 14.9 KB 307 lines c

1// =============================================================================2//                  SP BOUCHER | SOFTWARE & RESEARCH3//             ARTIFICIAL INTELLIGENCE • FINANCE • ENGINEERING4// =============================================================================5//6// PROJECT METADATA7// -----------------------------------------------------------------------------8// Project          : ORIX Cosmos9// File             : Shaders/CosmosShared.h10// Description      : Shared Metal Shading Language declarations: uniform block11//                    layouts (mirrored in12//                    Packages/CosmosRender/Sources/GPUTypes.swift), projection13//                    helpers, eclipse geometry and the single-scattering14//                    atmosphere model.15// Module           : Shaders16// Repository       : https://git.spboucher.ai/orix-cosmos17// Project Website  : https://www.orixlab.dev18// Created          : 2026-11-2419// Last Modified    : 2026-11-2420//21// =============================================================================22// AUTHOR & PROFESSIONAL AFFILIATION23// =============================================================================24//25// Author           : Simon-Pierre Boucher26// Position         : Professor of Finance27// Institution      : Université du Québec en Outaouais (UQO)28// Department       : Département des sciences administratives29// Organization     : SP Boucher30//31// Website          : https://spboucher.ai32// Git              : https://git.spboucher.ai33//34// =============================================================================35// OFFICIAL CONTACT DIRECTORY36// =============================================================================37//38// General          : info@spboucher.ai39// Professional     : contact@spboucher.ai40// Direct           : simon@spboucher.ai41// Research         : research@spboucher.ai42// Development      : dev@spboucher.ai43// Support          : support@spboucher.ai44// Security/Admin   : admin@spboucher.ai45// Notifications    : notifications@spboucher.ai46//47// Preferred Contact: support@spboucher.ai48//49// =============================================================================50// COPYRIGHT & INTELLECTUAL PROPERTY51// =============================================================================52//53// Copyright (c) 202654// Simon-Pierre Boucher55//56// All rights reserved where applicable.57//58// This file is governed by the applicable project license,59// copyright notices, institutional agreements and relevant law.60//61// Unless expressly authorized by the applicable license or62// rights holder, copying, redistribution, sublicensing,63// publication and commercial exploitation are not permitted.64//65// Existing third-party rights and notices remain unaffected.66//67// =============================================================================68// CONFIDENTIALITY & SECURITY69// =============================================================================70//71// Classification   : Public72// Distribution     : Public repository; use is governed by the project license73// Security Contact : admin@spboucher.ai74//75// Access to this source does not independently grant permission76// to redistribute or disclose confidential materials.77//78// Do not embed credentials, private keys, access tokens,79// certificates or confidential personal information.80//81// =============================================================================82// LICENSE & MAINTENANCE83// =============================================================================84//85// License          : None specified (no license file in this repository)86// Maintainer       : Simon-Pierre Boucher87// Technical Contact: dev@spboucher.ai88//89// =============================================================================90// END OF SP BOUCHER SOURCE HEADER91// =============================================================================9293#ifndef COSMOS_SHARED_H94#define COSMOS_SHARED_H9596#include <metal_stdlib>97using namespace metal;9899// Every helper in this header is `static inline`: the app compiles each .metal file as its own100// translation unit and links them into one metallib, while the runtime loader concatenates all101// files into a single translation unit. Both must see exactly one definition.102103#define COSMOS_PI 3.14159265358979323846f104#define COSMOS_MAX_LIGHTS 4105#define COSMOS_MAX_OCCLUDERS 4106107// Body-centric shading works in units of the body's equatorial radius: a 1 m test object and a 1 Gpc108// sphere then use the same float32 range, and squared lengths cannot overflow.109//110// Buffer binding convention (all stages): 0 = vertex/instance data, 1 = FrameUniforms, 2 = per-draw uniforms.111112struct FrameUniforms {113    float4x4 viewRot;      // scene axes -> view axes (rotation only; positions are already camera-relative)114    float4x4 proj;         // reversed-Z, infinite far plane: clip = (x f/aspect, y f, near, -z)115    float4 crop;           // tile transform: clip.xy = clip.xy * crop.xy + crop.zw * clip.w116    float4 viewport;       // full image size in target pixels (w, h, 1/w, 1/h)117    float4 projParams;     // tan(fovX/2), tan(fovY/2), near (m), focal length in target pixels118    float4 scaleParams;    // x: target pixels per point, y: exposure, z: time (s), w: MSAA sample count119    float4 pointParams;    // x: energy of a magnitude-0 source (scene units * pt^2), y: PSF sigma (pt), z: peak clamp, w: max sigma (pt)120    float4 tileParams;     // xy: tile origin in full-image target pixels, zw: tile size in pixels121};122123struct AtmosphereParams {124    float4 rayleigh;       // rgb: Rayleigh scattering coefficient at ground (1/m), w: scale height (m)125    float4 mie;            // rgb: Mie scattering coefficient at ground (1/m), w: scale height (m)126    float4 mieExt;         // rgb: Mie extinction coefficient at ground (1/m), w: asymmetry g127    float4 absorption;     // rgb: absorption coefficient at layer centre (1/m), w: layer centre height (m)128    float4 shape;          // x: ground radius (m), y: top radius (m), z: absorption layer half width (m), w: 1 when enabled129};130131struct LightGPU {132    float4 positionRadius; // xyz: light position relative to the body centre, body-fixed axes; w: light radius. Unit: the body's equatorial radius133    float4 irradiance;     // rgb: irradiance at the body centre (scene units)134};135136struct BodyUniforms {137    float4x4 modelView;    // mesh position -> view space138    float4x4 viewToBody;   // rotation view axes -> body-fixed axes139    float4 radii;          // xyz: spheroid radii in units of the equatorial radius (1, 1, 1 - f); w: equatorial radius (m)140    float4 cameraPos;      // camera relative to body centre, body-fixed axes, in equatorial radii141    float4 baseColor;      // rgb: flat albedo142    float4 emission;       // rgb: emitted radiance at disc centre, w: linear limb-darkening coefficient143    float4 material;       // x: night-light intensity, y: cloud opacity, z: specular strength, w: specular exponent144    float4 material2;      // x: normal-map strength, y: reflectance model (0 Lambert, 1 Lommel-Seeliger), z: ambient, w: unused145    float4 ring;           // x: inner radius, y: outer radius (equatorial radii), z: opacity scale, w: 1 when a ring shadow applies146    uint4 flags;           // x: texture bits (1 albedo, 2 night, 4 clouds, 8 specular, 16 normal), y: light count, z: occluder count, w: 1 emissive | 2 atmosphere147    AtmosphereParams atmosphere;148    LightGPU lights[COSMOS_MAX_LIGHTS];149    float4 occluders[COSMOS_MAX_OCCLUDERS]; // xyz: centre relative to the body centre, body-fixed axes; w: radius (equatorial radii)150};151152struct AtmosphereUniforms {153    float4 centerView;     // planet centre in view space (m)154    float4 poleView;       // xyz: pole axis in view space, w: 1/(1-f) - 1 (polar stretch that turns the spheroid into a sphere)155    float4 lightDirView;   // unit direction from the planet towards the light, view space156    float4 irradiance;     // rgb: irradiance at the planet157    float4 rect;           // screen rectangle in full-image NDC (xmin, ymin, xmax, ymax)158    float4 steps;          // x: view samples, y: light samples159    AtmosphereParams atmosphere;160};161162struct RingUniforms {163    float4x4 modelView;    // body-fixed axes (in equatorial radii) -> view space (m)164    float4 radii;          // spheroid radii in units of the equatorial radius (1, 1, 1 - f)165    float4 ring;           // x: inner radius, y: outer radius (equatorial radii), z: opacity scale, w: brightness of the unlit face166    float4 cameraPos;      // body-fixed axes, equatorial radii167    float4 color;          // rgb tint, a: 1 when the profile texture is used168    LightGPU light;        // primary light169};170171struct PointUniforms {172    float4 originRel;      // xyz: batch origin minus camera (scene axes, m); w: 1 when records are unit directions173    float4 params;         // x: 1 when magnitudes are absolute, y: magnitude offset, z: intensity multiplier, w: profile (0 Gaussian, 1 glare)174    float4 tint;           // rgb multiplier175};176177struct LineUniforms {178    float4 offsetRel;      // xyz: added to the points (scene axes, m); w: 1 when points are unit directions179    float4 color;          // straight (non-premultiplied) linear rgba180    float4 params;         // x: width (pt), y: dash on (pt), z: dash off (pt), w: scale applied to the stored dash coordinate181};182183struct PostUniforms {184    float4 a;              // tonemap: exposure, operator, headroom, bloom mix | resolve: exposure | bloom: texel size xy185    float4 b;              // tonemap: dither amplitude, seed, bloom normalisation, unused186};187188// ---------------------------------------------------------------------------------------------189// Projection190191static inline float4 cosmos_crop(const FrameUniforms f, float4 clip) {192    clip.xy = clip.xy * f.crop.xy + f.crop.zw * clip.w;193    return clip;194}195196/// View-space position (w = 1) or direction (w = 0) to clip space, before the tile crop.197static inline float4 cosmos_clip(const FrameUniforms f, float3 viewPos, float w) {198    return f.proj * float4(viewPos, w);199}200201/// Fragment coordinate (pixels in the current target) to full-image NDC.202static inline float2 cosmos_frag_to_ndc(const FrameUniforms f, float2 fragCoord) {203    float2 px = fragCoord + f.tileParams.xy;204    return float2(px.x * f.viewport.z * 2.0f - 1.0f, 1.0f - px.y * f.viewport.w * 2.0f);205}206207static inline float cosmos_luma(float3 c) { return dot(c, float3(0.2126f, 0.7152f, 0.0722f)); }208209// ---------------------------------------------------------------------------------------------210// Eclipses: visible fraction of a spherical light of radius `lightRadius` seen from `p` when a211// sphere (occPos, occRadius) may stand in front of it. Small-angle disc-overlap geometry212// (two circles on the tangent plane): exact umbra / antumbra / penumbra boundaries.213214static inline float cosmos_light_visibility(float3 p, float3 lightPos, float lightRadius, float3 occPos, float occRadius) {215    float3 lv = lightPos - p;216    float3 ov = occPos - p;217    float dl = length(lv);218    float dOcc = length(ov);219    if (dOcc <= occRadius) { return 0.0f; }220    if (dOcc >= dl) { return 1.0f; }221    float3 ld = lv / dl;222    float3 od = ov / dOcc;223    if (dot(ld, od) <= 0.0f) { return 1.0f; }224    float aS = lightRadius / dl;225    float aO = occRadius / sqrt(max(dOcc * dOcc - occRadius * occRadius, 1e-12f * dOcc * dOcc));226    float sep = length(cross(ld, od)) / max(dot(ld, od), 1e-6f);227    if (aS < 1e-9f) { return sep < aO ? 0.0f : 1.0f; }228    if (sep >= aS + aO) { return 1.0f; }229    if (sep <= aO - aS) { return 0.0f; }230    if (sep <= aS - aO) { return 1.0f - (aO * aO) / (aS * aS); }231    float x = (sep * sep + aS * aS - aO * aO) / (2.0f * sep * aS);232    float y = (sep * sep + aO * aO - aS * aS) / (2.0f * sep * aO);233    float k = max(0.0f, (-sep + aS + aO) * (sep + aS - aO) * (sep - aS + aO) * (sep + aS + aO));234    float lens = aS * aS * acos(clamp(x, -1.0f, 1.0f)) + aO * aO * acos(clamp(y, -1.0f, 1.0f)) - 0.5f * sqrt(k);235    return clamp(1.0f - lens / (COSMOS_PI * aS * aS), 0.0f, 1.0f);236}237238// ---------------------------------------------------------------------------------------------239// Atmosphere (single scattering, exponential Rayleigh and Mie layers, optional absorption layer).240// All positions are planet-centric, in metres, in a frame where the spheroid has been stretched241// along its pole into a sphere of the equatorial radius.242243static inline bool cosmos_ray_sphere(float3 o, float3 d, float r, thread float &t0, thread float &t1) {244    float b = dot(o, d);245    float c = dot(o, o) - r * r;246    float disc = b * b - c;247    if (disc < 0.0f) { return false; }248    float s = sqrt(disc);249    t0 = -b - s;250    t1 = -b + s;251    return true;252}253254/// Relative densities (Rayleigh, Mie, absorber) at height h above the ground.255static inline float3 cosmos_atmo_density(const AtmosphereParams a, float h) {256    h = max(h, 0.0f);257    float absorber = a.shape.z > 0.0f ? max(0.0f, 1.0f - abs(h - a.absorption.w) / a.shape.z) : 0.0f;258    return float3(exp(-h / a.rayleigh.w), exp(-h / a.mie.w), absorber);259}260261static inline float3 cosmos_atmo_extinction(const AtmosphereParams a, float3 density) {262    return a.rayleigh.rgb * density.x + a.mieExt.rgb * density.y + a.absorption.rgb * density.z;263}264265/// Optical depth from p to the top of the atmosphere along unit direction l.266static inline float3 cosmos_atmo_optical_depth(const AtmosphereParams a, float3 p, float3 l, int steps) {267    float t0, t1;268    if (!cosmos_ray_sphere(p, l, a.shape.y, t0, t1) || t1 <= 0.0f) { return float3(0.0f); }269    float ds = t1 / float(steps);270    float3 tau = float3(0.0f);271    for (int i = 0; i < steps; ++i) {272        float3 q = p + l * ((float(i) + 0.5f) * ds);273        tau += cosmos_atmo_extinction(a, cosmos_atmo_density(a, length(q) - a.shape.x)) * ds;274    }275    return tau;276}277278static inline float cosmos_phase_rayleigh(float mu) {279    return 3.0f / (16.0f * COSMOS_PI) * (1.0f + mu * mu);280}281282/// Cornette-Shanks phase function (Cornette & Shanks 1992), normalised over the sphere.283static inline float cosmos_phase_mie(float mu, float g) {284    float g2 = g * g;285    float denom = max(1.0f + g2 - 2.0f * g * mu, 1e-6f);286    return 3.0f / (8.0f * COSMOS_PI) * ((1.0f - g2) * (1.0f + mu * mu)) / ((2.0f + g2) * denom * sqrt(denom));287}288289// ---------------------------------------------------------------------------------------------290// Equirectangular lookup with analytic gradients (no seam at the +/-180 degree meridian).291// Body-fixed convention: +Z north pole, +X prime meridian. u = 0.5 at longitude 0, east positive;292// v = 0 at the north pole.293294struct CosmosEquirect { float2 uv; float2 ddx; float2 ddy; };295296static inline CosmosEquirect cosmos_equirect(float3 u, float3 dudx, float3 dudy) {297    CosmosEquirect r;298    float rho2 = max(u.x * u.x + u.y * u.y, 1e-12f);299    float cz = sqrt(max(1.0f - u.z * u.z, 1e-8f));300    r.uv = float2(atan2(u.y, u.x) / (2.0f * COSMOS_PI) + 0.5f, 0.5f - asin(clamp(u.z, -1.0f, 1.0f)) / COSMOS_PI);301    r.ddx = float2((u.x * dudx.y - u.y * dudx.x) / rho2 / (2.0f * COSMOS_PI), -dudx.z / (cz * COSMOS_PI));302    r.ddy = float2((u.x * dudy.y - u.y * dudy.x) / rho2 / (2.0f * COSMOS_PI), -dudy.z / (cz * COSMOS_PI));303    return r;304}305306#endif307
Files main
Menu

Theme