SPB Git

Repository Public

Body.metal 10.9 KB 248 lines

1/**2 * =============================================================================3 *                  SP BOUCHER | SOFTWARE & RESEARCH4 *             ARTIFICIAL INTELLIGENCE • FINANCE • ENGINEERING5 * =============================================================================6 *7 * PROJECT METADATA8 * -----------------------------------------------------------------------------9 * Project          : ORIX Cosmos10 * File             : Shaders/Body.metal11 * Description      : Oblate textured bodies: day/night terminator, night12 *                    lights, clouds, ocean glint, eclipse and ring shadows,13 *                    sunlight reddening under an atmosphere, emissive discs14 *                    with limb darkening.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 * =============================================================================92 */9394#include "CosmosShared.h"9596struct BodyVertexIn {97    float3 position [[attribute(0)]];98    float3 unit [[attribute(1)]];99};100101struct BodyVaryings {102    float4 position [[position]];103    float3 unit [[centroid_perspective]];104    float3 viewPos [[centroid_perspective]];105};106107vertex BodyVaryings body_vertex(BodyVertexIn in [[stage_in]],108                                constant FrameUniforms &frame [[buffer(1)]],109                                constant BodyUniforms &body [[buffer(2)]]) {110    BodyVaryings out;111    float3 viewPos = (body.modelView * float4(in.position, 1.0f)).xyz;112    out.position = cosmos_crop(frame, cosmos_clip(frame, viewPos, 1.0f));113    out.unit = in.unit;114    out.viewPos = viewPos;115    return out;116}117118fragment float4 body_fragment(BodyVaryings in [[stage_in]],119                              constant FrameUniforms &frame [[buffer(1)]],120                              constant BodyUniforms &body [[buffer(2)]],121                              texture2d<float> albedoTex [[texture(0)]],122                              texture2d<float> nightTex [[texture(1)]],123                              texture2d<float> cloudTex [[texture(2)]],124                              texture2d<float> specularTex [[texture(3)]],125                              texture2d<float> normalTex [[texture(4)]],126                              texture2d<float> ringTex [[texture(5)]],127                              sampler surfaceSampler [[sampler(0)]],128                              sampler ringSampler [[sampler(1)]]) {129    float3 u = normalize(in.unit);130    float3 radii = body.radii.xyz;131    float3 p = u * radii;132    float3 n = normalize(u / radii);133    // The view vector comes from the camera-relative position, which stays exact at any altitude; the134    // body-centric point p is only good to float32 resolution of the planet's radius (0.5 m for an Earth).135    float3 v = normalize((body.viewToBody * float4(-in.viewPos, 0.0f)).xyz);136    uint texBits = body.flags.x;137138    if ((body.flags.w & 1u) != 0u) {139        // Emissive photosphere, linear limb darkening I(mu) = I(1) (1 - u (1 - mu)).140        float mu = clamp(dot(n, v), 0.0f, 1.0f);141        float limb = 1.0f - body.emission.w * (1.0f - mu);142        return float4(body.emission.rgb * limb, 1.0f);143    }144145    CosmosEquirect eq = cosmos_equirect(u, dfdx(in.unit), dfdy(in.unit));146    float3 albedo = body.baseColor.rgb;147    if ((texBits & 1u) != 0u) {148        albedo = albedoTex.sample(surfaceSampler, eq.uv, gradient2d(eq.ddx, eq.ddy)).rgb;149    }150    float4 cloud = float4(0.0f);151    if ((texBits & 4u) != 0u) {152        cloud = cloudTex.sample(surfaceSampler, eq.uv, gradient2d(eq.ddx, eq.ddy));153        cloud.a *= body.material.y;154    }155    float specMask = 0.0f;156    if (body.material.z > 0.0f) {157        specMask = (texBits & 8u) != 0u ? specularTex.sample(surfaceSampler, eq.uv, gradient2d(eq.ddx, eq.ddy)).r : 1.0f;158    }159    float3 ns = n;160    if ((texBits & 16u) != 0u) {161        // Tangent frame of the spheroid: east, north, up.162        float3 east = normalize(float3(-u.y, u.x, 0.0f) + float3(1e-12f, 0.0f, 0.0f));163        float3 north = cross(n, east);164        float3 t = normalTex.sample(surfaceSampler, eq.uv, gradient2d(eq.ddx, eq.ddy)).xyz * 2.0f - 1.0f;165        t.xy *= body.material2.x;166        ns = normalize(east * t.x + north * t.y + n * t.z);167    }168169    float3 color = albedo * body.material2.z;170    float nightFactor = 1.0f;171    uint lightCount = min(body.flags.y, uint(COSMOS_MAX_LIGHTS));172    uint occluderCount = min(body.flags.z, uint(COSMOS_MAX_OCCLUDERS));173    for (uint i = 0u; i < lightCount; ++i) {174        float3 lpos = body.lights[i].positionRadius.xyz;175        float lradius = body.lights[i].positionRadius.w;176        float3 lv = lpos - p;177        float ldist = length(lv);178        float3 l = lv / ldist;179        float3 irradiance = body.lights[i].irradiance.rgb;180181        // Soft terminator: fraction of the light's disc above the local horizon.182        float sinAlpha = clamp(lradius / ldist, 1e-4f, 0.2f);183        float geomNdotL = dot(n, l);184        float horizon = smoothstep(-sinAlpha, sinAlpha, geomNdotL);185        float ndotl = max(dot(ns, l), 0.0f) * horizon;186        if (i == 0u) { nightFactor = 1.0f - smoothstep(-0.12f, 0.08f, geomNdotL); }187        if (horizon <= 0.0f) { continue; }188189        float visibility = 1.0f;190        for (uint k = 0u; k < occluderCount; ++k) {191            visibility *= cosmos_light_visibility(p, lpos, lradius, body.occluders[k].xyz, body.occluders[k].w);192        }193        if (body.ring.w > 0.5f && abs(l.z) > 1e-5f) {194            float t = -p.z / l.z;195            if (t > 0.0f) {196                float2 hit = p.xy + l.xy * t;197                float rr = length(hit);198                float s = (rr - body.ring.x) / (body.ring.y - body.ring.x);199                if (s > 0.0f && s < 1.0f) {200                    float opacity = ringTex.sample(ringSampler, float2(s, 0.5f)).a * body.ring.z;201                    // Slant path through the ring plane increases the optical depth.202                    float slant = 1.0f / max(abs(l.z), 0.08f);203                    visibility *= pow(max(1.0f - opacity, 0.0f), slant);204                }205            }206        }207        if ((body.flags.w & 2u) != 0u) {208            // Sunlight is attenuated by the air mass it crosses: reddening at the terminator.209            // The atmosphere model works in metres, in the space where the spheroid is a sphere.210            float stretch = body.radii.x / body.radii.z;211            float3 ps = float3(p.xy, p.z * stretch) * (body.radii.w * (1.0f + 1e-6f));212            float3 ls = normalize(float3(l.xy, l.z * stretch));213            float3 direct = exp(-cosmos_atmo_optical_depth(body.atmosphere, ps, ls, 8));214            // Skylight: half of what the direct beam lost on its way down reaches the ground as diffuse light215            // (two-stream estimate standing in for multiple scattering, which the model does not compute).216            irradiance *= direct + 0.5f * (1.0f - direct);217        }218        irradiance *= visibility;219220        float3 diffuse;221        if (body.material2.y > 0.5f) {222            // Lommel-Seeliger, normalised to `albedo` at normal incidence and emergence.223            float mu0 = ndotl;224            float mu = max(dot(ns, v), 0.0f);225            diffuse = albedo * (2.0f * mu0 / max(mu0 + mu, 1e-4f));226        } else {227            diffuse = albedo * ndotl;228        }229        float3 lit = diffuse * irradiance;230        if (specMask > 0.0f && ndotl > 0.0f) {231            float3 h = normalize(l + v);232            float e = body.material.w;233            // Normalised Blinn-Phong lobe, (e + 8) / (8 pi), times pi for the scene radiance convention.234            float spec = (e + 8.0f) / 8.0f * pow(max(dot(n, h), 0.0f), e);235            lit += irradiance * (specMask * body.material.z * spec * ndotl * (1.0f - cloud.a));236        }237        if (cloud.a > 0.0f) {238            lit = mix(lit, cloud.rgb * irradiance * (max(dot(n, l), 0.0f) * horizon), cloud.a);239        }240        color += lit;241    }242    if ((texBits & 2u) != 0u) {243        float3 night = nightTex.sample(surfaceSampler, eq.uv, gradient2d(eq.ddx, eq.ddy)).rgb;244        color += night * (body.material.x * nightFactor * (1.0f - cloud.a));245    }246    return float4(color, 1.0f);247}248
Files main
Menu

Theme