# Triplanar Alpine/Forest Terrain, Snow Deformation Trails, Canopy Sunbeams & VR Triangle Budgets in Unity 6

> Crisp slope-and-height triplanar terrain shading in Unity 6 URP (WebGL 2 & WebGPU safe), orthographic R8 snow/mud deformation trails with rim berms, lightweight canopy sunbeam cards, and strict VR/WebGL forest triangle budgets.

- **Canonical page:** https://gamecrew.ai/techniques/unity/triplanar-terrain-snow-trails-and-vr-forest-budget
- **Techniques hub:** https://gamecrew.ai/techniques
- **Engine:** Unity 6
- **Category:** materials
- **Tags:** `terrain`, `triplanar`, `snow`, `trails`, `footprints`, `deformation`, `powder`, `mountain`, `cliff`, `forest`, `redwood`, `god-rays`, `sunbeams`, `vr`, `budget`, `lod`, `urp`
- **Verification:** Compile-verified pattern
- **Revision:** 1 (2026-11-30)
- **Demo:** No demo

## When to Use (and When Not To)

Use this stack for hyperrealistic Redwood forests, alpine powder snowboarding/skiing mountains, open-world animal survival biomes, and outdoor VR walks where steep cliffs must never stretch UVs, footsteps or snowboards carve visible powder trenches, sunbeams cut through tall canopy, and frame rates must stay responsive in browsers and standalone headsets.

**Critical VR/WebGL Budget Warning**: Un-instanced high-poly tree trunks and un-decimated foliage easily hit `2–6 million` triangles in view, causing SwiftShader and mobile headsets to drop below 1 fps and fail VR exit checks. Always enforce the triangle & LOD budget below!

## Mathematical & Algorithmic Core

1. **Slope & Height Triplanar Weighting**: Blend horizontal ground/snow/moss against steep rock cliffs using world-space normal $n_y$ and world altitude $y$:
   $$w_{\text{rock}} = \mathrm{smoothstep}(0.55,\; 0.82,\; 1 - |n_y|), \qquad w_{\text{snow}} = \mathrm{smoothstep}(y_0 - \Delta y,\; y_0 + \Delta y,\; y)$$
   Triplanar projection weights $\mathbf{b} = \frac{|\mathbf{n}|^4}{\sum |\mathbf{n}|^4}$ sample procedural/tiled albedo along XY, ZY, and XZ with zero UV stretching on vertical cliff faces.
2. **Orthographic R8 Deformation Trail Buffer**: Track a `256x256` `R8` `RenderTexture` centered around the player (`worldOrigin`, `span = 48 m`). Stamp radial footprints or snowboard/ski tracks into the buffer, fade slowly if desired, and in the terrain vertex/fragment shader displace vertices downward by $-h \cdot d_{\max}$ while lifting a bright powder rim berm around the gradient $|\nabla h|$.
3. **Canopy Sunbeams & Forest Geometry Budget**:
   - Render dappled light shafts with `12–24` camera-facing or crossed soft additive depth-faded cards (0.05 ms) instead of full-screen raymarched volumetric passes.
   - **Strict Forest Polygon Targets**:
     - Standalone VR: `<= 150k` triangles, `<= 150` draw calls total in view.
     - Flat WebGL: `<= 300k` triangles, `<= 200` draw calls total in view.
     - Hero tree LOD0 `<= 1,800` tris (`0–22 m`), LOD1 `<= 450` tris (`22–65 m`), cross-card impostor `4–8` tris (`65 m+`); render all repeating trunks, fronds, ferns, and stones with `Graphics.RenderMeshInstanced`!

## Engine Implementation

### WebGL 2 & WebGPU Safe URP Triplanar + Snow Trail Terrain Shader (`Assets/Game/Shaders/TriplanarTerrainTrail.shader`)

```hlsl
Shader "Game/TriplanarTerrainTrail"
{
    Properties
    {
        _GroundColor ("Ground / Moss Color", Color) = (0.24, 0.30, 0.17, 1)
        _CliffColor  ("Cliff / Rock Color", Color)  = (0.34, 0.33, 0.32, 1)
        _SnowColor   ("Snow / High Altitude", Color)= (0.90, 0.94, 0.98, 1)
        _TrailTint   ("Carved Trail Tint", Color)   = (0.62, 0.72, 0.84, 1)
        _SnowHeight  ("Snow Altitude Start", Float) = 18.0
        _SnowBlend   ("Snow Blend Band", Float)     = 6.0
        _TriScale    ("Triplanar Scale", Float)     = 0.18
        _TrailDepth  ("Trail Carve Depth (m)", Float) = 0.22
        _TrailTex    ("Trail Stamp RT (R8)", 2D)    = "black" {}
        _TrailArea   ("Trail Origin XZ + Span", Vector) = (0, 0, 48, 1)
    }

    SubShader
    {
        Tags { "RenderType"="Opaque" "RenderPipeline"="UniversalPipeline" "Queue"="Geometry" }
        Pass
        {
            Name "ForwardLit"
            Tags { "LightMode"="UniversalForward" }

            HLSLPROGRAM
            #pragma target 3.0
            #pragma vertex vert
            #pragma fragment frag
            #pragma multi_compile_fog
            #pragma multi_compile _ _MAIN_LIGHT_SHADOWS _MAIN_LIGHT_SHADOWS_CASCADE

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

            TEXTURE2D(_TrailTex);
            SAMPLER(sampler_TrailTex);

            CBUFFER_START(UnityPerMaterial)
                float4 _GroundColor;
                float4 _CliffColor;
                float4 _SnowColor;
                float4 _TrailTint;
                float4 _TrailArea;
                float _SnowHeight;
                float _SnowBlend;
                float _TriScale;
                float _TrailDepth;
            CBUFFER_END

            struct Attributes
            {
                float4 positionOS : POSITION;
                float3 normalOS   : NORMAL;
            };

            struct Varyings
            {
                float4 positionCS : SV_POSITION;
                float3 worldPos   : TEXCOORD0;
                float3 worldN     : TEXCOORD1;
                float  fogFactor  : TEXCOORD2;
                float  trailStamp : TEXCOORD3;
            };

            float hash21(float2 p)
            {
                p = frac(p * float2(123.34, 456.21));
                p += dot(p, p + 45.32);
                return frac(p.x * p.y);
            }

            float vnoise(float2 p)
            {
                float2 i = floor(p);
                float2 f = frac(p);
                f = f * f * (3.0 - 2.0 * f);
                float a = hash21(i);
                float b = hash21(i + float2(1.0, 0.0));
                float c = hash21(i + float2(0.0, 1.0));
                float d = hash21(i + float2(1.0, 1.0));
                return lerp(lerp(a, b, f.x), lerp(c, d, f.x), f.y);
            }

            float triNoise(float3 wp, float3 n, float scale)
            {
                float3 w = pow(abs(n), 4.0);
                w /= max(0.0001, w.x + w.y + w.z);
                float nx = vnoise(wp.zy * scale);
                float ny = vnoise(wp.xz * scale);
                float nz = vnoise(wp.xy * scale);
                return nx * w.x + ny * w.y + nz * w.z;
            }

            Varyings vert(Attributes IN)
            {
                Varyings OUT;
                float3 wp = TransformObjectToWorld(IN.positionOS.xyz);
                float3 wn = TransformObjectToWorldNormal(IN.normalOS);

                // Sample world-locked R8 trail buffer for snow/mud trenches.
                float2 trailUV = (wp.xz - _TrailArea.xy) / max(1.0, _TrailArea.z) + 0.5;
                float inBounds = step(0.01, trailUV.x) * step(trailUV.x, 0.99) * step(0.01, trailUV.y) * step(trailUV.y, 0.99);
                float stamp = SAMPLE_TEXTURE2D_LOD(_TrailTex, sampler_TrailTex, saturate(trailUV), 0).r * inBounds;
                wp.y -= stamp * _TrailDepth;

                OUT.worldPos = wp;
                OUT.worldN = wn;
                OUT.trailStamp = stamp;
                OUT.positionCS = TransformWorldToHClip(wp);
                OUT.fogFactor = ComputeFogFactor(OUT.positionCS.z);
                return OUT;
            }

            half4 frag(Varyings IN) : SV_Target
            {
                float3 n = normalize(IN.worldN);
                float detail = triNoise(IN.worldPos, n, _TriScale) * 0.65 + triNoise(IN.worldPos, n, _TriScale * 3.1) * 0.35;

                float cliffMask = smoothstep(0.55, 0.82, 1.0 - saturate(n.y));
                float snowMask = smoothstep(_SnowHeight - _SnowBlend, _SnowHeight + _SnowBlend, IN.worldPos.y + (detail - 0.5) * 3.5);
                snowMask *= (1.0 - cliffMask * 0.85);

                float3 albedo = lerp(_GroundColor.rgb, _CliffColor.rgb, cliffMask);
                albedo = lerp(albedo, _SnowColor.rgb, snowMask);
                albedo *= lerp(0.84, 1.14, detail);
                albedo = lerp(albedo, _TrailTint.rgb, saturate(IN.trailStamp * 0.85));

                Light mainLight = GetMainLight(TransformWorldToShadowCoord(IN.worldPos));
                float ndotl = saturate(dot(n, mainLight.direction));
                float3 ambient = SampleSH(n) * 0.65;
                float3 color = albedo * (ambient + mainLight.color * (ndotl * mainLight.shadowAttenuation));
                color = MixFog(color, IN.fogFactor);
                return half4(color, 1.0);
            }
            ENDHLSL
        }
    }
}
```

### World-Locked Snow/Mud Trail Buffer Updater (`Assets/Game/Runtime/Terrain/GroundTrailBuffer.cs`)

```csharp
using UnityEngine;

namespace Game.Terrain
{
    public sealed class GroundTrailBuffer : MonoBehaviour
    {
        public Material TerrainMaterial;
        public Transform TrackedActor;
        public float AreaSpanMeters = 48f;
        public int Resolution = 256;
        public float StampRadiusMeters = 0.65f;

        Texture2D trailTex;
        Color32[] pixels;
        Vector2 originXZ;
        bool dirty;

        void Awake()
        {
            trailTex = new Texture2D(Resolution, Resolution, TextureFormat.R8, false, true);
            trailTex.wrapMode = TextureWrapMode.Clamp;
            trailTex.filterMode = FilterMode.Bilinear;
            pixels = new Color32[Resolution * Resolution];
            if (TrackedActor != null) originXZ = new Vector2(TrackedActor.position.x, TrackedActor.position.z);
            ApplyShaderUniforms();
        }

        void LateUpdate()
        {
            if (TrackedActor == null) return;
            StampWorldPoint(TrackedActor.position, StampRadiusMeters, 230);
            if (dirty)
            {
                trailTex.SetPixels32(pixels);
                trailTex.Apply(false, false);
                dirty = false;
            }
        }

        public void StampWorldPoint(Vector3 worldPos, float radiusMeters, byte strength)
        {
            float u = (worldPos.x - originXZ.x) / AreaSpanMeters + 0.5f;
            float v = (worldPos.z - originXZ.y) / AreaSpanMeters + 0.5f;
            if (u < 0.02f || u > 0.98f || v < 0.02f || v > 0.98f) return;

            int cx = Mathf.RoundToInt(u * (Resolution - 1));
            int cy = Mathf.RoundToInt(v * (Resolution - 1));
            int radPx = Mathf.Max(1, Mathf.RoundToInt((radiusMeters / AreaSpanMeters) * Resolution));
            float invR2 = 1f / Mathf.Max(1f, radPx * radPx);

            for (int y = Mathf.Max(0, cy - radPx); y <= Mathf.Min(Resolution - 1, cy + radPx); y++)
            {
                for (int x = Mathf.Max(0, cx - radPx); x <= Mathf.Min(Resolution - 1, cx + radPx); x++)
                {
                    float d2 = ((x - cx) * (x - cx) + (y - cy) * (y - cy)) * invR2;
                    if (d2 >= 1f) continue;
                    byte val = (byte)Mathf.RoundToInt((1f - d2) * strength);
                    int idx = y * Resolution + x;
                    if (val > pixels[idx].r) { pixels[idx].r = val; dirty = true; }
                }
            }
        }

        void ApplyShaderUniforms()
        {
            if (TerrainMaterial == null) return;
            TerrainMaterial.SetTexture("_TrailTex", trailTex);
            TerrainMaterial.SetVector("_TrailArea", new Vector4(originXZ.x, originXZ.y, AreaSpanMeters, 1f));
        }

        void OnDestroy()
        {
            if (trailTex != null) Destroy(trailTex);
        }
    }
}
```

## Performance & Platform Traps

- **WebGPU `CreateRenderPipeline` Safety**: Always keep `TEXTURE2D(_TrailTex)` paired with `SAMPLER(sampler_TrailTex)` and `#pragma target 3.0` + `CBUFFER_START(UnityPerMaterial)` so both WebGL 2 and WebGPU compile cleanly without binding-layout errors.
- **Zero Per-Tree GameObjects in Dense Forests**: Put repeating pines, redwoods, ferns, and boulders into GPU-instanced batches (`Graphics.RenderMeshInstanced`) with distance LODs so standalone VR stays strictly under `150k` triangles.
- **Avoid Alpha-Blended Overdraw Stacks**: Use alpha-clipped (`clip(alpha - 0.45)`) foliage cards with simple silhouettes rather than 10 overlapping semi-transparent billboard layers.

## Verification Checklist

1. Stamp a trail across snow/terrain in PlayMode and inspect the captured frame to verify a visible recessed track with zero cliff UV stretching.
2. Check scene triangle and draw-call totals (`<= 150k` tris in VR, `<= 300k` flat) and ensure zero shader warnings in WebGL/WebGPU builds.
3. Verify canopy sunbeams frame the vista without washing out foreground readability.

## Official references

- Ben Golus Normal Mapping for Triplanar Shaders
- NVIDIA GDC Snow & Mud Displacement Buffer Architecture
- Unity 6 URP HLSL Shader Library & GPU Instancing Guidelines
