GameCrew AIEarly access
Sign in
Unity 6atmosphereRevision 1 · By @maddmann

Neural Multiple-Scattering Shader for Volumetric Clouds in Unity 6 URP

Updated

Replace the in-scatter term of a raymarched cloud with a 13-16-16-3 squared-ReLU MLP trained against a path tracer: multi-scale density descriptor in metres, in-editor C# reference tracer and trainer, weights as shader constants, plain HLSL inference with a safe fallback.

  • clouds
  • volumetric
  • neural shader
  • mlp
  • multiple scattering
  • raymarch
  • path tracing
  • urp
  • hlsl
  • machine learning

No demo.

When to Use

Use this for a hero cloud seen close up (a single cumulus or storm cell inside a bounding box) when the usual real-time lighting model reads grey and flat, or changes character as the sun moves. It keeps an ordinary raymarcher and swaps exactly one quantity, the light scattered toward the camera at each step, for a tiny trained network.

Why bother: the common real-time model (Henyey-Greenstein phase plus a few Wrenninge multiple-scattering octaves) has an error that moves with the sun. Charles Grassi measured it against a path tracer across a 13-position sun sweep: the approximation ran from about 0.21x to 2.17x of true brightness, while the network stayed within about 10% at twelve of thirteen positions (about 1.2x when looking straight into the sun). His measured cost was about 1.2x the approximation's GPU time (laptop RTX 4080, Unity 6 URP, D3D12). Those numbers are his, on his cloud; treat them as the target to reproduce, not as a guarantee for this implementation.

Not the right tool for: a full sky of clouds (no LOD here; the height-band dome in volumetric-clouds covers that), stylised clouds, or low-end mobile.

The Idea

At every march step two questions are asked: how much light is blocked (easy, local density) and how much light scatters toward the camera (hard: every bounce path into that point). The second is the source function

$J(p, ω) = varpi int Phi(ω' · ω)\, L(p, ω')\, dω'$

A path tracer can compute $J$ offline. A small MLP then learns $J$ from a description of the neighbourhood, never of the object:

  • 6 values: mean density around the point at radii 6 / 12 / 24 / 48 / 96 / 192 metres
  • 6 values: the same radii, measured toward the sun (in this guide: sampled at p + toSun * r, a design choice of this implementation)
  • 1 value: cos(view ray, sun)

Mean density at a radius is one fetch from the density volume's mip chain, so a coarse radius costs the same as a fine one. Radii are fixed in metres, not texels, so the descriptor means the same thing at any bake resolution.

Network: 13 inputs, two hidden layers of 16, 3 outputs (sun, sky, ground bounce), all sharing the hidden layers. Activation is squared ReLU a(x) = max(x,0)^2 and the output is squared (y = s^2), which keeps it non-negative without a dead-gradient clamp.

Composition per step, identical for both lighting models:

$C mathrel+= T\,(1 - e^-σ rho Δ s)\,(E_sun\, y_0 + L_sky\, y_1 + L_ground\, y_2), T mathrel*= e^-σ rho Δ s$

with E_sun = π · _MainLightColor (Unity light colour is irradiance divided by π).

Labels come from a backward path tracer. For a ray travelling along d that collided at p: at each vertex add w\,Phi(d·L)\,T_sun to the sun label (next-event estimation), sample a new direction from the phase function, find the next collision with delta tracking, multiply $w$ by the albedo; on escape add $w$ to the sky label if the direction points up, else to the ground label.

Implementation

Three files. Everything is trained and baked in the editor once; the player only loads a density Texture3D and a 2,560-byte weights file.

1. Shader (Assets/Game/Resources/Shaders/NeuralCloud.shader)

The weights live in one global float4 _Net[160] so every dot product is a 4-wide operation and the uniform count stays at 160 vectors.

| vec4 index | content | |---|---| | 0-63 | W0, 4 rows per hidden neuron (13 used, 3 zero pad) | | 64-127 | W1 | | 128-139 | W2, 4 rows per output | | 140-143 / 144-147 / 148 | b0 / b1 / b2 | | 149-152 / 153-156 | input mean / input 1/std | | 157 | output clamp (xyz) | | 159 | sentinel (x = 1234.5) |

Shader "Custom/NeuralCloud"
{
    Properties
    {
        _CloudDensity ("Density volume (R, with mips)", 3D) = "black" {}
        _CloudBoxMin ("Box min (world)", Vector) = (-192, 0, -192, 0)
        _CloudBoxSize ("Box size xyz, voxel metres w", Vector) = (384, 384, 384, 3)
        _CloudLod ("Descriptor lod0 x, skip mip y", Vector) = (1, 3, 0, 0)
        _Extinction ("Extinction per metre at density 1 (baked into weights)", Float) = 0.08
        _StepScale ("Step in voxels", Float) = 1.0
        _SkyColor ("Sky radiance", Color) = (0.45, 0.62, 0.95, 1)
        _GroundColor ("Ground bounce radiance", Color) = (0.25, 0.23, 0.20, 1)
        [Toggle] _UseNet ("Use network", Float) = 1
    }
    SubShader
    {
        Tags { "RenderPipeline" = "UniversalPipeline" "Queue" = "Transparent" "RenderType" = "Transparent" }
        Pass
        {
            Name "NeuralCloud"
            Tags { "LightMode" = "UniversalForward" }
            Cull Front
            ZWrite Off
            ZTest Always
            Blend One OneMinusSrcAlpha

            HLSLPROGRAM
            #pragma vertex vert
            #pragma fragment frag
            #pragma target 3.5

            #include "Packages/com.unity.render-pipelines.universal/ShaderLibrary/Core.hlsl"
            #include "Packages/com.unity.render-pipelines.universal/ShaderLibrary/Lighting.hlsl"
            #include "Packages/com.unity.render-pipelines.universal/ShaderLibrary/DeclareDepthTexture.hlsl"

            #define MAX_STEPS 128

            TEXTURE3D(_CloudDensity);
            SAMPLER(sampler_CloudDensity);
            float4 _Net[160];

            CBUFFER_START(UnityPerMaterial)
                float4 _CloudBoxMin;
                float4 _CloudBoxSize;
                float4 _CloudLod;
                half4 _SkyColor;
                half4 _GroundColor;
                float _Extinction;
                float _StepScale;
                float _UseNet;
            CBUFFER_END

            struct Attributes { float4 positionOS : POSITION; };
            struct Varyings { float4 positionCS : SV_POSITION; float3 positionWS : TEXCOORD0; };

            Varyings vert(Attributes v)
            {
                Varyings o;
                o.positionWS = TransformObjectToWorld(v.positionOS.xyz);
                o.positionCS = TransformWorldToHClip(o.positionWS);
                return o;
            }

            float IGN(float2 px) { return frac(52.9829189 * frac(dot(px, float2(0.06711056, 0.00583715)))); }

            // Zero outside the box, so coarse mips never smear cloud past the walls.
            float Density(float3 p, float lod)
            {
                float3 uvw = (p - _CloudBoxMin.xyz) / _CloudBoxSize.xyz;
                float inside = (all(uvw > 0.0) && all(uvw < 1.0)) ? 1.0 : 0.0;
                return SAMPLE_TEXTURE3D_LOD(_CloudDensity, sampler_CloudDensity, saturate(uvw), lod).r * inside;
            }

            // Four neurons at once: weight rows start at w, biases are _Net[b].
            float4 Quad(float4 a[4], int w, int b)
            {
                float4 s = _Net[b];
                [unroll] for (int c = 0; c < 4; c++)
                    s[c] += dot(a[0], _Net[w + 4 * c]) + dot(a[1], _Net[w + 4 * c + 1])
                          + dot(a[2], _Net[w + 4 * c + 2]) + dot(a[3], _Net[w + 4 * c + 3]);
                float4 r = max(s, 0.0);
                return r * r; // squared ReLU: smooth, so no shell-shaped creases
            }

            float3 CloudNet(float4 x[4])
            {
                [unroll] for (int i = 0; i < 4; i++) x[i] = (x[i] - _Net[149 + i]) * _Net[153 + i];
                float4 h0[4];
                float4 h1[4];
                [unroll] for (int q = 0; q < 4; q++) h0[q] = Quad(x, 16 * q, 140 + q);
                [unroll] for (int q2 = 0; q2 < 4; q2++) h1[q2] = Quad(h0, 64 + 16 * q2, 144 + q2);
                float3 y;
                [unroll] for (int k = 0; k < 3; k++)
                {
                    float s = _Net[148][k] + dot(h1[0], _Net[128 + 4 * k]) + dot(h1[1], _Net[129 + 4 * k])
                            + dot(h1[2], _Net[130 + 4 * k]) + dot(h1[3], _Net[131 + 4 * k]);
                    y[k] = s * s; // non-negative by construction
                }
                return min(y, _Net[157].xyz);
            }

            float HG(float c, float g)
            {
                float k = max(1e-3, 1.0 + g * g - 2.0 * g * c);
                return (1.0 - g * g) / (4.0 * PI * k * sqrt(k));
            }

            // (sun, sky, ground) source terms per unit light. THE ONE QUANTITY THE NETWORK REPLACES.
            half3 Shade(float3 p, float3 toSun, float mu)
            {
                float l = _CloudLod.x;
                float4 x[4];
                x[0] = float4(Density(p, l), Density(p, l + 1.0), Density(p, l + 2.0), Density(p, l + 3.0));
                x[1] = float4(Density(p, l + 4.0), Density(p, l + 5.0),
                              Density(p + toSun * 6.0, l), Density(p + toSun * 12.0, l + 1.0));
                x[2] = float4(Density(p + toSun * 24.0, l + 2.0), Density(p + toSun * 48.0, l + 3.0),
                              Density(p + toSun * 96.0, l + 4.0), Density(p + toSun * 192.0, l + 5.0));
                x[3] = float4(mu, 0.0, 0.0, 0.0);

                if (_UseNet > 0.5 && abs(_Net[159].x - 1234.5) < 0.01)
                    return CloudNet(x);

                // Fallback (weights missing or toggled off): single scatter from the same fetches.
                float tau = _Extinction * (9.0 * (x[1].z + x[1].w) + 18.0 * x[2].x + 36.0 * x[2].y
                                         + 72.0 * x[2].z + 144.0 * x[2].w);
                float amb = exp(-_Extinction * 48.0 * x[0].w);
                return half3(HG(mu, 0.85) * exp(-tau), 0.6 * amb, 0.4 * amb);
            }

            half4 frag(Varyings i) : SV_Target
            {
                float3 ro = GetCameraPositionWS();
                float3 rd = normalize(i.positionWS - ro);
                float3 safe = float3(abs(rd.x) < 1e-6 ? 1e-6 : rd.x, abs(rd.y) < 1e-6 ? 1e-6 : rd.y, abs(rd.z) < 1e-6 ? 1e-6 : rd.z);
                float3 ta = (_CloudBoxMin.xyz - ro) / safe;
                float3 tb = (_CloudBoxMin.xyz + _CloudBoxSize.xyz - ro) / safe;
                float3 lo = min(ta, tb);
                float3 hi = max(ta, tb);
                float tNear = max(max(lo.x, lo.y), max(lo.z, 0.0));
                float tFar = min(hi.x, min(hi.y, hi.z));

                // Clip against opaque scene depth so the cloud sorts around geometry.
                float2 uv = i.positionCS.xy / _ScaledScreenParams.xy;
                float raw = SampleSceneDepth(uv);
                #if !UNITY_REVERSED_Z
                    raw = lerp(UNITY_NEAR_CLIP_VALUE, 1.0, raw);
                #endif
                float3 scene = ComputeWorldSpacePosition(uv, raw, UNITY_MATRIX_I_VP);
                tFar = min(tFar, dot(scene - ro, rd));
                if (tFar <= tNear) return half4(0, 0, 0, 0);

                Light sun = GetMainLight();
                float3 toSun = normalize(sun.direction);
                float mu = dot(rd, toSun);
                half3 sunE = PI * sun.color;

                float voxel = _CloudBoxSize.w;
                float ds = voxel * _StepScale;
                float skip = voxel * exp2(_CloudLod.y) * 0.5; // provably empty for half a coarse cell
                float t = tNear + ds * IGN(i.positionCS.xy);
                half3 scattered = 0;
                half T = 1;

                [loop]
                for (int s = 0; s < MAX_STEPS; s++)
                {
                    if (t >= tFar || T < 0.01) break;
                    float3 p = ro + rd * t;
                    if (Density(p, _CloudLod.y) <= 0.0) { t += skip; continue; }
                    float d = Density(p, 0.0);
                    if (d > 1e-4)
                    {
                        half3 y = Shade(p, toSun, mu);
                        half stepT = exp(-d * _Extinction * ds);
                        scattered += T * (1.0 - stepT) * (sunE * y.x + _SkyColor.rgb * y.y + _GroundColor.rgb * y.z);
                        T *= stepT;
                    }
                    t += ds;
                }
                return half4(scattered, 1.0 - T);
            }
            ENDHLSL
        }
    }
}

2. Runtime (Assets/Game/Runtime/Rendering/NeuralCloud.cs)

CloudVolume is the CPU twin of the GPU texture: the trainer must read exactly what the shader reads, so both use the same box-filtered mips, trilinear sampling, mip blending and zero-outside-box rule. The constructor uses Parallel.For and is only called in the editor; the player loads the baked assets.

using System;
using System.Threading.Tasks;
using UnityEngine;

namespace Game.Rendering
{
    public sealed class CloudVolume
    {
        public readonly int N;            // voxels per side, power of two
        public readonly float Voxel;      // metres per voxel, at most 6
        public readonly Vector3 Min;
        public readonly float[][] Mips;
        public float Size => N * Voxel;
        public float DescLod0 => Mathf.Log(6f / Voxel, 2f);

        public CloudVolume(int n, float voxel, Vector3 min, Func<Vector3, float> density)
        {
            N = n; Voxel = voxel; Min = min;
            int levels = 1;
            while ((n >> levels) > 0) levels++;
            Mips = new float[levels][];
            var m0 = new float[n * n * n];
            Parallel.For(0, n, z =>
            {
                for (int y = 0; y < n; y++)
                for (int x = 0; x < n; x++)
                {
                    bool edge = x == 0 || y == 0 || z == 0 || x == n - 1 || y == n - 1 || z == n - 1;
                    float d = edge ? 0f : density(min + new Vector3(x + 0.5f, y + 0.5f, z + 0.5f) * voxel);
                    m0[(z * n + y) * n + x] = Mathf.Clamp01(d);
                }
            });
            Mips[0] = m0;
            for (int l = 1; l < levels; l++)
            {
                int s = n >> l, ps = s * 2;
                var src = Mips[l - 1];
                var dst = new float[s * s * s];
                for (int z = 0; z < s; z++)
                for (int y = 0; y < s; y++)
                for (int x = 0; x < s; x++)
                {
                    float sum = 0f;
                    for (int k = 0; k < 8; k++)
                        sum += src[((2 * z + (k >> 2)) * ps + 2 * y + ((k >> 1) & 1)) * ps + 2 * x + (k & 1)];
                    dst[(z * s + y) * s + x] = sum * 0.125f;
                }
                Mips[l] = dst;
            }
        }

        public Vector3 Uvw(Vector3 p) => (p - Min) / Size;

        public static float Tri(float[] d, int s, Vector3 uvw)
        {
            float fx = Mathf.Clamp(uvw.x * s - 0.5f, 0f, s - 1f);
            float fy = Mathf.Clamp(uvw.y * s - 0.5f, 0f, s - 1f);
            float fz = Mathf.Clamp(uvw.z * s - 0.5f, 0f, s - 1f);
            int x0 = (int)fx, y0 = (int)fy, z0 = (int)fz;
            int x1 = Math.Min(x0 + 1, s - 1), y1 = Math.Min(y0 + 1, s - 1), z1 = Math.Min(z0 + 1, s - 1);
            float tx = fx - x0, ty = fy - y0, tz = fz - z0;
            float c00 = Mathf.Lerp(d[(z0 * s + y0) * s + x0], d[(z0 * s + y0) * s + x1], tx);
            float c10 = Mathf.Lerp(d[(z0 * s + y1) * s + x0], d[(z0 * s + y1) * s + x1], tx);
            float c01 = Mathf.Lerp(d[(z1 * s + y0) * s + x0], d[(z1 * s + y0) * s + x1], tx);
            float c11 = Mathf.Lerp(d[(z1 * s + y1) * s + x0], d[(z1 * s + y1) * s + x1], tx);
            return Mathf.Lerp(Mathf.Lerp(c00, c10, ty), Mathf.Lerp(c01, c11, ty), tz);
        }

        public float Sample(Vector3 p, float lod)
        {
            Vector3 u = Uvw(p);
            if (u.x <= 0f || u.y <= 0f || u.z <= 0f || u.x >= 1f || u.y >= 1f || u.z >= 1f) return 0f;
            int l0 = Mathf.Clamp((int)lod, 0, Mips.Length - 1), l1 = Math.Min(l0 + 1, Mips.Length - 1);
            float a = Tri(Mips[l0], N >> l0, u), f = lod - l0;
            return f <= 0f ? a : Mathf.Lerp(a, Tri(Mips[l1], N >> l1, u), f);
        }

        // Must stay in step with Shade() in the shader.
        public void Descriptor(Vector3 p, Vector3 toSun, float cosViewSun, float[] x, int o)
        {
            float lod0 = DescLod0;
            for (int i = 0; i < 6; i++)
            {
                float r = 6f * (1 << i);
                x[o + i] = Sample(p, lod0 + i);
                x[o + 6 + i] = Sample(p + toSun * r, lod0 + i);
            }
            x[o + 12] = cosViewSun;
        }
    }

    public sealed class NeuralCloud : MonoBehaviour
    {
        public const int N = 128;
        public const float Voxel = 3f, Extinction = 0.08f, Sentinel = 1234.5f;
        public static readonly Vector3 BoxMin = new Vector3(-192f, 0f, -192f);

        private Material _material;

        public static CloudVolume BuildVolume() => new CloudVolume(N, Voxel, BoxMin, CumulusDensity);

        public static NeuralCloud Attach(Shader shader, Texture3D density, TextAsset weights)
        {
            var go = GameObject.CreatePrimitive(PrimitiveType.Cube); // bounding proxy for the march, never visible as a box
            go.name = "NeuralCloud";
            Destroy(go.GetComponent<Collider>());
            float size = N * Voxel;
            go.transform.position = BoxMin + Vector3.one * (size * 0.5f);
            go.transform.localScale = Vector3.one * size;
            var cloud = go.AddComponent<NeuralCloud>();
            cloud.Init(go.GetComponent<MeshRenderer>(), shader, density, weights);
            return cloud;
        }

        private void Init(MeshRenderer mr, Shader shader, Texture3D density, TextAsset weights)
        {
            float size = N * Voxel;
            _material = new Material(shader);
            _material.SetTexture("_CloudDensity", density);
            _material.SetVector("_CloudBoxMin", BoxMin);
            _material.SetVector("_CloudBoxSize", new Vector4(size, size, size, Voxel));
            _material.SetVector("_CloudLod", new Vector4(Mathf.Log(6f / Voxel, 2f), 3f, 0f, 0f));
            _material.SetFloat("_Extinction", Extinction);
            string gpu = (SystemInfo.graphicsDeviceName ?? string.Empty).ToLowerInvariant();
            bool software = gpu.Contains("llvmpipe") || gpu.Contains("softpipe") || gpu.Contains("swiftshader");
            _material.SetFloat("_StepScale", software ? 3f : 1f);
            mr.sharedMaterial = _material;
            mr.shadowCastingMode = UnityEngine.Rendering.ShadowCastingMode.Off;
            mr.receiveShadows = false;

            // Always upload all 160 vectors: the array length is fixed by the first upload of the session.
            var net = new Vector4[160];
            if (weights != null && weights.bytes.Length == 2560)
            {
                var f = new float[640];
                Buffer.BlockCopy(weights.bytes, 0, f, 0, 2560);
                for (int i = 0; i < 160; i++) net[i] = new Vector4(f[4 * i], f[4 * i + 1], f[4 * i + 2], f[4 * i + 3]);
            }
            Shader.SetGlobalVectorArray("_Net", net);
        }

        private void OnDestroy() { if (_material != null) Destroy(_material); }

        // ---- Cloud shape: welded spheres, flat base, fractal erosion. Pure function, thread safe. ----
        private static readonly Vector4[] Lobes =
        {
            new Vector4(0f, 110f, 0f, 80f), new Vector4(-60f, 95f, 20f, 60f),
            new Vector4(55f, 100f, -25f, 65f), new Vector4(10f, 150f, 10f, 55f)
        };

        public static float CumulusDensity(Vector3 p)
        {
            float d = -1e9f;
            for (int i = 0; i < Lobes.Length; i++)
            {
                Vector4 l = Lobes[i];
                d = SMax(d, l.w - Vector3.Distance(p, new Vector3(l.x, l.y, l.z)), 30f);
            }
            d = -SMax(-d, -(p.y - 60f), 12f);                       // flat base at y = 60
            float fade = Mathf.SmoothStep(0f, 1f, (p.y - 60f) / 40f); // erosion spares the base
            d += (Fbm(p / 40f) - 0.5f) * 44f * fade;
            return d / 20f;                                          // 20 m soft edge; clamped by the volume
        }

        private static float SMax(float a, float b, float k)
        {
            float h = Mathf.Max(k - Mathf.Abs(a - b), 0f) / k;
            return Mathf.Max(a, b) + h * h * k * 0.25f;
        }

        private static float Hash(int x, int y, int z)
        {
            uint h = (uint)(x * 73856093 ^ y * 19349663 ^ z * 83492791);
            h ^= h >> 13; h *= 0x5bd1e995u; h ^= h >> 15;
            return (h & 0xffffffu) / 16777215f;
        }

        private static float Noise(Vector3 p)
        {
            int x = Mathf.FloorToInt(p.x), y = Mathf.FloorToInt(p.y), z = Mathf.FloorToInt(p.z);
            float fx = p.x - x, fy = p.y - y, fz = p.z - z;
            fx = fx * fx * (3f - 2f * fx); fy = fy * fy * (3f - 2f * fy); fz = fz * fz * (3f - 2f * fz);
            float a = Mathf.Lerp(Mathf.Lerp(Hash(x, y, z), Hash(x + 1, y, z), fx), Mathf.Lerp(Hash(x, y + 1, z), Hash(x + 1, y + 1, z), fx), fy);
            float b = Mathf.Lerp(Mathf.Lerp(Hash(x, y, z + 1), Hash(x + 1, y, z + 1), fx), Mathf.Lerp(Hash(x, y + 1, z + 1), Hash(x + 1, y + 1, z + 1), fx), fy);
            return Mathf.Lerp(a, b, fz);
        }

        private static float Fbm(Vector3 p)
        {
            float amp = 0.5f, sum = 0f;
            for (int o = 0; o < 4; o++) { sum += amp * Noise(p); p = p * 2.03f + Vector3.one * 17.1f; amp *= 0.5f; }
            return sum / 0.9375f;
        }
    }
}

3. Reference path tracer and trainer (Assets/Game/Editor/NeuralCloudTrainer.cs)

Runs once in the editor: bakes the density Texture3D (with the exact CPU mips), generates labels with the path tracer, fits the network with Adam, logs a held-out score, and writes both assets under Resources.

Cost control: a per-bounce march toward the sun would dominate everything, so the sun is restricted to 24 directions and each gets a precomputed half-resolution transmittance grid. The view/sun angle stays continuous because view rays are random.

#if UNITY_EDITOR
using System;
using System.IO;
using System.Threading.Tasks;
using UnityEditor;
using UnityEngine;

namespace Game.Rendering
{
    public static class NeuralCloudTrainer
    {
        const float G = 0.85f, Albedo = 0.999f;       // baked into the weights
        const int In = 13, H = 16, Out = 3, P = 547, SunDirs = 24;
        const int W0 = 0, B0 = 208, W1 = 224, B1 = 480, W2 = 496, B2 = 544;

        struct Rng
        {
            uint s;
            public Rng(uint seed) { s = seed * 747796405u + 2891336453u; if (s == 0u) s = 1u; }
            public float Next() { s ^= s << 13; s ^= s >> 17; s ^= s << 5; return (s >> 8) * (1f / 16777216f); }
        }

        [MenuItem("Game/Train Neural Cloud")]
        public static void TrainAndSave()
        {
            CloudVolume vol = NeuralCloud.BuildVolume();
            SaveDensity(vol, "Assets/Game/Resources/NeuralCloudDensity.asset");

            int count = 120000, paths = 64;
            var X = new float[count * In];
            var Y = new float[count * Out];
            for (int k = 0; k < SunDirs; k++)
            {
                // Fibonacci spread over the upper hemisphere, never below 3 degrees.
                float y = 0.05f + 0.95f * (k + 0.5f) / SunDirs, r = Mathf.Sqrt(1f - y * y), a = k * 2.3999632f;
                Vector3 toSun = new Vector3(r * Mathf.Cos(a), y, r * Mathf.Sin(a));
                float[] sunT = SunGrid(vol, toSun, NeuralCloud.Extinction);
                int kk = k;
                Parallel.For(0, count, i =>
                {
                    if (i % SunDirs == kk) MakeSample(vol, sunT, toSun, NeuralCloud.Extinction, i, paths, X, Y);
                });
            }

            byte[] packed = Train(X, Y, count, 40, 20260819u);
            File.WriteAllBytes("Assets/Game/Resources/NeuralCloudWeights.bytes", packed);
            AssetDatabase.Refresh();
        }

        static void SaveDensity(CloudVolume vol, string path)
        {
            var tex = new Texture3D(vol.N, vol.N, vol.N, TextureFormat.RHalf, true)
            {
                wrapMode = TextureWrapMode.Clamp, filterMode = FilterMode.Trilinear, name = "NeuralCloudDensity"
            };
            for (int l = 0; l < vol.Mips.Length; l++)
            {
                float[] src = vol.Mips[l];
                var half = new ushort[src.Length];
                for (int i = 0; i < src.Length; i++) half[i] = Mathf.FloatToHalf(src[i]);
                tex.SetPixelData(half, l);
            }
            tex.Apply(false, false);
            AssetDatabase.DeleteAsset(path);
            AssetDatabase.CreateAsset(tex, path);
        }

        // ---------- reference light transport ----------

        static bool Box(CloudVolume v, Vector3 o, Vector3 d, out float t0, out float t1)
        {
            t0 = 0f; t1 = float.MaxValue;
            for (int a = 0; a < 3; a++)
            {
                float inv = 1f / (Mathf.Abs(d[a]) < 1e-6f ? 1e-6f : d[a]);
                float ta = (v.Min[a] - o[a]) * inv, tb = (v.Min[a] + v.Size - o[a]) * inv;
                if (ta > tb) { float tmp = ta; ta = tb; tb = tmp; }
                t0 = Mathf.Max(t0, ta); t1 = Mathf.Min(t1, tb);
            }
            return t1 > t0;
        }

        // Delta (Woodcock) tracking; the majorant is sigma because density never exceeds 1.
        static bool Track(CloudVolume v, Vector3 o, Vector3 d, float sigma, ref Rng rng, out Vector3 p)
        {
            p = o;
            if (!Box(v, o, d, out float t, out float t1)) return false;
            while (true)
            {
                t -= Mathf.Log(1f - rng.Next()) / sigma;
                if (t >= t1) return false;
                p = o + d * t;
                if (rng.Next() < v.Sample(p, 0f)) return true;
            }
        }

        static float[] SunGrid(CloudVolume v, Vector3 toSun, float sigma)
        {
            int m = v.N / 2;
            float cell = v.Voxel * 2f;
            var g = new float[m * m * m];
            Parallel.For(0, m, z =>
            {
                for (int y = 0; y < m; y++)
                for (int x = 0; x < m; x++)
                {
                    Vector3 x0 = v.Min + new Vector3(x + 0.5f, y + 0.5f, z + 0.5f) * cell;
                    float tau = 0f;
                    if (Box(v, x0, toSun, out _, out float t1))
                        for (float t = cell * 0.5f; t < t1; t += cell) tau += v.Sample(x0 + toSun * t, 1f);
                    g[(z * m + y) * m + x] = Mathf.Exp(-tau * sigma * cell);
                }
            });
            return g;
        }

        static float Phase(float c)
        {
            float k = 1f + G * G - 2f * G * c;
            return (1f - G * G) / (12.566371f * k * Mathf.Sqrt(k));
        }

        static Vector3 Unit(ref Rng rng)
        {
            float z = 1f - 2f * rng.Next(), r = Mathf.Sqrt(Mathf.Max(0f, 1f - z * z)), a = 6.2831853f * rng.Next();
            return new Vector3(r * Mathf.Cos(a), z, r * Mathf.Sin(a));
        }

        static Vector3 SampleHG(Vector3 w, ref Rng rng)
        {
            float s = (1f - G * G) / (1f - G + 2f * G * rng.Next());
            float c = Mathf.Clamp((1f + G * G - s * s) / (2f * G), -1f, 1f);
            float sn = Mathf.Sqrt(1f - c * c), phi = 6.2831853f * rng.Next();
            Vector3 up = Mathf.Abs(w.y) < 0.99f ? Vector3.up : Vector3.right;
            Vector3 t = Vector3.Cross(up, w).normalized, b = Vector3.Cross(w, t);
            return (t * (Mathf.Cos(phi) * sn) + b * (Mathf.Sin(phi) * sn) + w * c).normalized;
        }

        // Source function at p for a camera ray travelling along view: (sun, sky, ground) per unit light.
        static Vector3 Estimate(CloudVolume v, float[] sunT, Vector3 toSun, float sigma, Vector3 p, Vector3 view, int paths, ref Rng rng)
        {
            double sun = 0, sky = 0, ground = 0;
            int m = v.N / 2;
            for (int n = 0; n < paths; n++)
            {
                Vector3 x = p, d = view;
                float w = Albedo;
                for (int bounce = 0; bounce < 256; bounce++)
                {
                    sun += w * Phase(Vector3.Dot(d, toSun)) * CloudVolume.Tri(sunT, m, v.Uvw(x));
                    d = SampleHG(d, ref rng);
                    if (!Track(v, x, d, sigma, ref rng, out x))
                    {
                        if (d.y > 0f) sky += w; else ground += w;
                        break;
                    }
                    w *= Albedo;
                }
            }
            return new Vector3((float)(sun / paths), (float)(sky / paths), (float)(ground / paths));
        }

        static void MakeSample(CloudVolume v, float[] sunT, Vector3 toSun, float sigma, int i, int paths, float[] X, float[] Y)
        {
            var rng = new Rng((uint)i + 1u);
            Vector3 centre = v.Min + Vector3.one * (v.Size * 0.5f), p = centre, d = Vector3.forward;
            // Sample the way a camera does: where a ray first collides, not uniformly through the interior.
            for (int attempt = 0; attempt < 64; attempt++)
            {
                Vector3 o = centre + Unit(ref rng) * v.Size;
                Vector3 target = centre + (new Vector3(rng.Next(), rng.Next(), rng.Next()) - Vector3.one * 0.5f) * (v.Size * 0.6f);
                d = (target - o).normalized;
                if (Track(v, o, d, sigma, ref rng, out p)) break;
                p = centre;
            }
            v.Descriptor(p, toSun, Vector3.Dot(d, toSun), X, i * In);
            Vector3 y = Estimate(v, sunT, toSun, sigma, p, d, paths, ref rng);
            Y[i * Out] = y.x; Y[i * Out + 1] = y.y; Y[i * Out + 2] = y.z;
        }

        // ---------- training ----------

        public static byte[] Train(float[] X, float[] Y, int n, int epochs, uint seed)
        {
            int nTrain = n * 9 / 10;
            var mean = new float[In]; var inv = new float[In];
            for (int m = 0; m < In; m++)
            {
                double s = 0, s2 = 0;
                for (int i = 0; i < nTrain; i++) { float a = X[i * In + m]; s += a; s2 += a * a; }
                mean[m] = (float)(s / nTrain);
                inv[m] = 1f / Mathf.Max(1e-4f, Mathf.Sqrt((float)(s2 / nTrain) - mean[m] * mean[m]));
            }
            var wOut = new float[Out]; var clamp = new float[Out]; var yMean = new float[Out];
            for (int k = 0; k < Out; k++)
            {
                double s = 0, s2 = 0; float mx = 0f;
                for (int i = 0; i < nTrain; i++) { float a = Y[i * Out + k]; s += a; s2 += a * a; mx = Mathf.Max(mx, a); }
                yMean[k] = (float)(s / nTrain);
                wOut[k] = 1f / Mathf.Max(1e-6f, (float)(s2 / nTrain) - yMean[k] * yMean[k]); // balance the three heads
                clamp[k] = mx * 1.25f;
            }

            var th = new float[P]; var g = new float[P]; var m1 = new float[P]; var m2 = new float[P];
            var rng = new Rng(seed);
            for (int q = 0; q < P; q++) th[q] = (rng.Next() * 2f - 1f) * (q < B0 ? 0.28f : 0.25f);
            for (int j = 0; j < H; j++) { th[B0 + j] = 0.3f; th[B1 + j] = 0.3f; }
            for (int k = 0; k < Out; k++) th[B2 + k] = Mathf.Sqrt(Mathf.Max(1e-4f, yMean[k])); // start alive, not at zero

            var x = new float[In]; var r0 = new float[H]; var h0 = new float[H]; var r1 = new float[H]; var h1 = new float[H];
            var s3 = new float[Out]; var dz0 = new float[H]; var dz1 = new float[H];

            void Forward(int i)
            {
                for (int m = 0; m < In; m++) x[m] = (X[i * In + m] - mean[m]) * inv[m];
                for (int j = 0; j < H; j++)
                {
                    float z = th[B0 + j];
                    for (int m = 0; m < In; m++) z += th[W0 + j * In + m] * x[m];
                    r0[j] = Mathf.Max(z, 0f); h0[j] = r0[j] * r0[j];
                }
                for (int j = 0; j < H; j++)
                {
                    float z = th[B1 + j];
                    for (int a = 0; a < H; a++) z += th[W1 + j * H + a] * h0[a];
                    r1[j] = Mathf.Max(z, 0f); h1[j] = r1[j] * r1[j];
                }
                for (int k = 0; k < Out; k++)
                {
                    float z = th[B2 + k];
                    for (int a = 0; a < H; a++) z += th[W2 + k * H + a] * h1[a];
                    s3[k] = z;
                }
            }

            int batch = 256, steps = (int)((long)epochs * nTrain / batch);
            for (int step = 1; step <= steps; step++)
            {
                Array.Clear(g, 0, P);
                for (int bi = 0; bi < batch; bi++)
                {
                    int i = Math.Min(nTrain - 1, (int)(rng.Next() * nTrain));
                    Forward(i);
                    Array.Clear(dz1, 0, H); Array.Clear(dz0, 0, H);
                    for (int k = 0; k < Out; k++)
                    {
                        // Loss is plain squared error on the RAW label: L = w (s^2 - t)^2, dL/ds = 4 w (s^2 - t) s
                        float ds = 4f * wOut[k] * (s3[k] * s3[k] - Y[i * Out + k]) * s3[k];
                        g[B2 + k] += ds;
                        for (int a = 0; a < H; a++) { g[W2 + k * H + a] += ds * h1[a]; dz1[a] += ds * th[W2 + k * H + a]; }
                    }
                    for (int j = 0; j < H; j++)
                    {
                        float dz = dz1[j] * 2f * r1[j];
                        g[B1 + j] += dz;
                        for (int a = 0; a < H; a++) { g[W1 + j * H + a] += dz * h0[a]; dz0[a] += dz * th[W1 + j * H + a]; }
                    }
                    for (int j = 0; j < H; j++)
                    {
                        float dz = dz0[j] * 2f * r0[j];
                        g[B0 + j] += dz;
                        for (int m = 0; m < In; m++) g[W0 + j * In + m] += dz * x[m];
                    }
                }
                double norm = 0;
                for (int q = 0; q < P; q++) { g[q] /= batch; norm += g[q] * g[q]; }
                float clip = Mathf.Min(1f, 1f / Mathf.Max(1e-8f, Mathf.Sqrt((float)norm)));
                float lr = 1e-5f + 2e-3f * 0.5f * (1f + Mathf.Cos(Mathf.PI * step / steps));
                float c1 = 1f - Mathf.Pow(0.9f, step), c2 = 1f - Mathf.Pow(0.999f, step);
                for (int q = 0; q < P; q++)
                {
                    float gq = g[q] * clip;
                    m1[q] = 0.9f * m1[q] + 0.1f * gq;
                    m2[q] = 0.999f * m2[q] + 0.001f * gq * gq;
                    th[q] -= lr * (m1[q] / c1) / (Mathf.Sqrt(m2[q] / c2) + 1e-8f);
                }
            }

            // Held-out score: mean brightness ratio and correlation per head.
            for (int k = 0; k < Out; k++)
            {
                double sp = 0, st = 0, spp = 0, stt = 0, spt = 0; int c = n - nTrain;
                for (int i = nTrain; i < n; i++)
                {
                    Forward(i);
                    double pr = s3[k] * s3[k], t = Y[i * Out + k];
                    sp += pr; st += t; spp += pr * pr; stt += t * t; spt += pr * t;
                }
                double cov = spt / c - sp / c * (st / c), vp = spp / c - sp / c * (sp / c), vt = stt / c - st / c * (st / c);
                Debug.Log($"NeuralCloud head {k}: mean ratio {sp / Math.Max(1e-9, st):F3}, correlation {cov / Math.Sqrt(Math.Max(1e-12, vp * vt)):F3}");
            }

            // Pack to the 160-vector layout the shader reads.
            var f = new float[640];
            for (int j = 0; j < H; j++) for (int m = 0; m < In; m++) f[16 * j + m] = th[W0 + j * In + m];
            for (int q = 0; q < 256; q++) f[256 + q] = th[W1 + q];
            for (int q = 0; q < 48; q++) f[512 + q] = th[W2 + q];
            for (int j = 0; j < H; j++) { f[560 + j] = th[B0 + j]; f[576 + j] = th[B1 + j]; }
            for (int k = 0; k < Out; k++) { f[592 + k] = th[B2 + k]; f[628 + k] = clamp[k]; }
            for (int m = 0; m < In; m++) { f[596 + m] = mean[m]; f[612 + m] = inv[m]; }
            f[636] = NeuralCloud.Sentinel;
            var bytes = new byte[2560];
            Buffer.BlockCopy(f, 0, bytes, 0, 2560);
            return bytes;
        }
    }
}
#endif

Scene wiring is three loads and one call: Resources.Load<Shader>("Shaders/NeuralCloud"), Resources.Load<Texture3D>("NeuralCloudDensity"), Resources.Load<TextAsset>("NeuralCloudWeights"), then NeuralCloud.Attach(shader, density, weights).

Traps

  • Descriptor mismatch is the silent killer. The network is only valid if CloudVolume.Descriptor and Shade() read the same numbers: same mips (uploaded from the CPU, never auto-generated), same radii, same zero-outside-box rule, same sign for the cosine. Any change to one side means retraining.
  • Material and density scale are baked in. _Extinction, the phase G and the albedo are not inputs. Changing them leaves the network answering confidently for a medium it never saw. Changing the cloud *shape* is allowed in principle (the descriptor is local), but a single-shape network generalises poorly: Grassi reports about 0.70 correlation on an unseen shape from single-shape weights against 0.86 when trained across 22 shapes.
  • Never transform the label. Labels are Monte Carlo estimates; fitting a cube root or log of noisy values biases the mean and cannot be undone afterwards (it cost Grassi half the light). The trainer above fits raw values and only weights the three heads.
  • ReLU and Leaky ReLU draw seams. A piecewise-flat network marched through becomes visible shell creases on the cloud. Squared ReLU removes them for one extra multiply.
  • Sky and ground labels are coin flips. Each path either escapes upward or it does not. At 8 paths the label noise is over half the signal (best achievable correlation about 0.79); 64 paths lifts the ceiling to about 0.98. Mean-brightness checks cannot see this, only correlation can.
  • Sample like a camera. Uniform samples spend the network on deep interior nobody sees. First-collision sampling (as in MakeSample) is what makes the bright visible shell accurate.
  • Uniform array length is fixed by the first upload. Always upload all 160 vectors, and keep the sentinel check so a missing or short upload falls back to single scatter instead of a white blob. Changing the layout needs an editor restart.
  • _MainLightColor is irradiance over pi. The sun head is trained per unit irradiance, hence the PI * in the shader. The forward peak of the phase function is large (about 6.5 per steradian at G = 0.85), so the result is HDR; keep tone mapping on.
  • Depth texture must be enabled on the URP asset or the depth clip reads garbage. Perspective cameras only.
  • No threads in the WebGL player. CloudVolume's constructor and the trainer use Parallel.For; both are editor-time only. The player loads baked assets.

Budgets

  • Per march step: 2 density fetches, then 12 descriptor fetches and about 560 multiply-adds for a lit sample. All 12 descriptor fetches are independent of each other, unlike a sequential march toward the sun.
  • Desktop GPU: _StepScale 1. Integrated or mobile: 1.5 to 2, or a 64-voxel volume at 6 m. Software GPUs (llvmpipe, SwiftShader): the runtime sets 3 so captures finish.
  • WebGL 2: every fetch is SAMPLE_TEXTURE3D_LOD, the loop bound is the constant MAX_STEPS, and 160 uniform vectors fit the GLES 3.0 minimum of 224. RHalf 3D textures filter linearly in WebGL 2.
  • Memory: 128 cubed RHalf with mips is about 4.8 MB; weights are 2,560 bytes.
  • Training time is dominated by the path tracer: roughly count * paths * bounces * 4 trilinear reads. Lower count to 40,000 and paths to 32 for a quick first pass, then rerun at full settings.
  • Today the matrix work runs as scalar shader arithmetic. Cooperative vectors (D3D12, Vulkan) and Slang would move it to tensor hardware, but Unity HLSL does not expose them.

Limits

One cloud in one axis-aligned box, no LOD, two-band sky (above and below the horizon), sun never below about 3 degrees in training. Looking straight into the sun is the weakest case because one narrow forward spike dominates; the known remedy is to compute the first bounce analytically (HG * exp(-tau)) and train the network only on the remainder.

Verification Checklist

  1. Run the trainer and read the three NeuralCloud head log lines. Expect the sun head's mean ratio within a few percent of 1.0 and correlation well above 0.8; sky and ground lower. A mean ratio near 1 with poor correlation means noisy labels (raise paths), not a small network.
  2. Toggle _UseNet at a fixed camera. The network version should be clearly brighter and whiter with the sun behind the camera, where single scatter is darkest.
  3. Sweep the sun through 0, 45, 90, 135, 180 degrees around the cloud and capture each. Brightness should stay stable across the sweep instead of collapsing front-lit; judge the sweep, never one screenshot.
  4. Zero the weights asset (or remove it) and confirm the fallback renders a plausible darker cloud rather than a white blob.
  5. Look for banding or shell creases at the silhouette: banding means the dither is missing, creases mean a flat-sided activation crept in.
  6. Place an opaque object in front of and inside the box and confirm the cloud sorts around it.

Official references

  • Charles Grassi (2026) — Neural Shaders, Explained With Clouds
  • Simon Kallweit et al. (SIGGRAPH Asia 2017) — Deep Scattering: Rendering Atmospheric Clouds with Radiance-Predicting Neural Networks
  • Magnus Wrenninge, Chris Kulla, Viktor Lundqvist (SIGGRAPH 2013) — Oz: The Great and Volumetric
  • Jan Novák et al. (Eurographics 2018 STAR) — Monte Carlo Methods for Volumetric Light Transport Simulation
  • NVIDIA — How to Get Started with Neural Shading for Your Game or Application
  • Jorge Jimenez (SIGGRAPH 2014) — Interleaved Gradient Noise

Open-source sources

Games built with this guide carry these credits, and the licence notices they ask for, in their third-party notices.

Who made it

This guide is by @maddmann.

More Unity 6 games

Games made with GameCrew on the same engine. No game has been built with this guide yet: these show what Unity 6 games here look like.

Fjordline — Leap from a granite wall under the midnight sun and carve one unbroken wingsuit line through Norway's most dramatic landscapes, from summit to sea, skimming close enough to touch the rock.

Fjordline

Leap from a granite wall under the midnight sun and carve one unbroken wingsuit line through Norway's most dramatic landscapes, from summit to sea, skimming close enough to touch the rock.

Saltwood Alley — Step up to the sunlit timber lanes of an old seaside arcade, feel the weight of turned maple in your palm, and bend real wrist-spin shots into tight vintage scoring cups.
Plays in VR

Saltwood Alley

Step up to the sunlit timber lanes of an old seaside arcade, feel the weight of turned maple in your palm, and bend real wrist-spin shots into tight vintage scoring cups.

More Unity 6 techniques

gameplay

Frame-Rate-Independent Procedural Springs, Squash-Stretch & Trauma Feel in Unity 6 →

Exact dt-invariant second-order critically/under-damped spring dampers, Squirrel Eiserloh T^2 rotational Perlin camera trauma, volume-preserving squash-and-stretch, and TestClock-safe hit-stop.

lighting

Atmospheric Height Fog, Sun Shafts & Rim-Readable Lighting in Unity 6 URP →

Three-point outdoor/interior URP lighting recipe combining directional sun + warm/cool fill, exponential height/distance fog, ACES/Neutral post-processing, and anti-darkness floors so captures never read black or washed out.

shaders

Cel-Shading, Shadow Ramps & Width-Compensated Outlines in Unity 6 URP →

Two-pass URP stylized cel shader combining main-light shadow-attenuated diffuse ramps, crisp specular/rim accents, and clip-space distance-compensated inverted-hull outlines.

physics

CharacterController Slope Projection & Floor Snap in Unity 6 →

Deterministic Unity 6 CharacterController locomotion with SphereCast ground projection, ramp stickiness, steep-slope slide, and coyote jumps.

Read via free MCP — or sign in to add techniques & beta test

Use /mcp/library free with no login to query guides, or connect via OAuth at /mcp to contribute technique guides and beta test cloud builds.

Connect via MCP