# Photorealistic PBR Interior Lighting, Reflection Probes, Shadow Budgets & WebGPU URP Shader Safety in Unity 6

> Credible realistic PBR interior materials and lighting in Unity 6 URP without exceeding browser light/shadow budgets, plus strict HLSL shader rules that eliminate WebGPU CreateRenderPipeline validation errors in browser builds.

- **Canonical page:** https://gamecrew.ai/techniques/unity/pbr-interior-lighting-and-webgpu-urp-safety
- **Techniques hub:** https://gamecrew.ai/techniques
- **Engine:** Unity 6
- **Category:** lighting
- **Tags:** `pbr`, `lighting`, `interior`, `reflection-probe`, `shadows`, `light-budget`, `webgpu`, `webgl`, `urp`, `shader`, `createrenderpipeline`, `wood`, `metal`, `vr`
- **Verification:** Compile-verified pattern
- **Revision:** 1 (2026-11-30)
- **Demo:** No demo

## When to Use (and When Not To)

Use this guide whenever building realistic wood/brass/stone interiors (arcades, bowling/skee-ball alleys, workshops, labs, museums, lodges, Backrooms) or authoring custom URP shaders targeting Unity 6 WebGL 2 and WebGPU browser builds.

Poor interior PBR almost always comes from two causes: zero environment reflections (making brass, lacquered wood, and glass look muddy flat plastic) or too many realtime shadow-casting lights (blowing WebGL/VR frame budgets or breaking shader variants).

## Mathematical & Algorithmic Core

1. **PBR Metal/Dielectric Calibration & Specular Micro-Detail**:
   - **Dielectrics** (wood, plaster, tile, fabric): `metallic = 0.0`, albedo luminance strictly inside `[0.04, 0.85]` linear (never pure `#000000` or `#FFFFFF`), roughness driven by subtle procedural grain (`smoothness = 0.35–0.75` for varnished timber).
   - **Metals** (brass rails, brushed steel, copper trim): `metallic = 0.88–1.0`, colored specular albedo (warm brass `#D4AF5A`, brushed aluminum `#C8CDD2`), `smoothness = 0.65–0.88`.
2. **Reflection Probes & Tri-Band Interior Lighting Budget**:
   - Place **one** baked/on-start `ReflectionProbe` (`resolution = 128`, `boxProjection = true`, `refreshMode = ViaScripting`) per room so lacquered wood and brass catch authentic room highlights and skylights!
   - Budget realtime lights strictly: **1** directional or key spot light with `LightShadows.Soft`, plus at most **2–4** non-shadow fill `PointLight`/`SpotLight` accents (`shadows = LightShadows.None`) + warm emissive practical fixtures (lamps, ceiling tubes, scoreboard bulbs) + `RenderSettings.ambientMode = AmbientMode.Trilight` (sky/equator/ground bounce).
3. **WebGPU `CreateRenderPipeline` URP Shader Checklist**:
   Browser WebGPU validates every vertex/fragment binding strictly (unlike forgiving desktop drivers). Prevent `CreateRenderPipeline` validation failures in custom URP shaders by following ALL five rules:
   - Always declare `#pragma target 3.0` (avoid exotic geometry/tessellation stages).
   - Pair every `TEXTURE2D(_Name)` with its own `SAMPLER(sampler_Name)` and sample via `SAMPLE_TEXTURE2D(_Name, sampler_Name, uv)` (never reuse mismatched samplers or legacy `tex2D` inside `HLSLPROGRAM`).
   - Keep all material scalar/color uniforms inside `CBUFFER_START(UnityPerMaterial) ... CBUFFER_END` and match types identically between vertex and fragment stages.
   - Include a matching `ShadowCaster` pass (or use `Universal Render Pipeline/Lit` with procedural `Texture2D` albedo/normal/roughness maps) when objects cast shadows.
   - Never output uninitialized struct fields from `vert()` or leave `SV_Target` alpha NaN/Inf.

## Engine Implementation

### Interior Lighting, Box-Projected Reflection Probe & Light Budget Manager (`Assets/Game/Runtime/Lighting/InteriorPbrRig.cs`)

```csharp
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.Rendering;

namespace Game.Lighting
{
    /// <summary>
    /// Sets up realistic tri-light interior ambience, one box-projected ReflectionProbe rendered once at startup,
    /// and enforces a WebGL/VR-safe shadow-casting light budget.
    /// </summary>
    public sealed class InteriorPbrRig : MonoBehaviour
    {
        [Header("Room Bounds for Box-Projected Reflections")]
        public Vector3 ProbeCenterOffset = new Vector3(0f, 2.2f, 0f);
        public Vector3 RoomSize = new Vector3(16f, 6f, 20f);
        public int ProbeResolution = 128;

        [Header("Tri-Light Interior Bounce")]
        public Color SkyBounce = new Color(0.55f, 0.58f, 0.64f);
        public Color WallBounce = new Color(0.36f, 0.31f, 0.25f);
        public Color FloorBounce = new Color(0.18f, 0.14f, 0.11f);

        [Header("Shadow Light Budget")]
        public int MaxShadowCasters = 1;
        public int MaxActiveNonShadowLights = 4;
        public Transform FocusTarget;

        ReflectionProbe probe;
        readonly List<Light> managedLights = new List<Light>();

        void Start()
        {
            ConfigureAmbience();
            BuildReflectionProbe();
            EnforceLightBudget();
        }

        void ConfigureAmbience()
        {
            RenderSettings.ambientMode = AmbientMode.Trilight;
            RenderSettings.ambientSkyColor = SkyBounce;
            RenderSettings.ambientEquatorColor = WallBounce;
            RenderSettings.ambientGroundColor = FloorBounce;
            RenderSettings.reflectionIntensity = 1.0f;
        }

        void BuildReflectionProbe()
        {
            var go = new GameObject("InteriorReflectionProbe");
            go.transform.SetParent(transform, false);
            go.transform.localPosition = ProbeCenterOffset;

            probe = go.AddComponent<ReflectionProbe>();
            probe.mode = ReflectionProbeMode.Realtime;
            probe.refreshMode = ReflectionProbeRefreshMode.ViaScripting;
            probe.timeSlicingMode = ReflectionProbeTimeSlicingMode.NoTimeSlicing;
            probe.resolution = Mathf.Clamp(ProbeResolution, 64, 256);
            probe.boxProjection = true;
            probe.size = RoomSize;
            probe.nearClipPlane = 0.25f;
            probe.farClipPlane = Mathf.Max(RoomSize.x, RoomSize.z) * 1.5f;
            probe.hdr = false; // LDR cubemap avoids WebGL2/WebGPU half-float render-target edge cases
            probe.RenderProbe();
        }

        /// <summary>Keeps only the highest-priority key light casting shadows so WebGL/VR stays fast.</summary>
        public void EnforceLightBudget()
        {
            managedLights.Clear();
            Light[] all = FindObjectsByType<Light>(FindObjectsSortMode.None);
            int shadowCount = 0;

            // Keep directional key light first, then closest point/spot lights.
            System.Array.Sort(all, (a, b) =>
            {
                if (a.type == LightType.Directional && b.type != LightType.Directional) return -1;
                if (b.type == LightType.Directional && a.type != LightType.Directional) return 1;
                if (FocusTarget == null) return 0;
                float da = (a.transform.position - FocusTarget.position).sqrMagnitude;
                float db = (b.transform.position - FocusTarget.position).sqrMagnitude;
                return da.CompareTo(db);
            });

            int localCount = 0;
            for (int i = 0; i < all.Length; i++)
            {
                Light l = all[i];
                if (l.shadows != LightShadows.None)
                {
                    if (shadowCount < MaxShadowCasters)
                        shadowCount++;
                    else
                        l.shadows = LightShadows.None;
                }
                if (l.type != LightType.Directional)
                {
                    localCount++;
                    l.enabled = localCount <= MaxActiveNonShadowLights;
                }
                managedLights.Add(l);
            }
        }

        /// <summary>Creates a procedural lacquered-wood or brushed-metal URP Lit material with normal/smoothness micro-variation.</summary>
        public static Material CreateCalibratedPbrMaterial(string label, Color baseColor, float metallic, float smoothness, float grainContrast = 0.08f)
        {
            Shader lit = Shader.Find("Universal Render Pipeline/Lit") ?? Shader.Find("Standard");
            var mat = new Material(lit) { name = label };
            const int size = 128;
            var tex = new Texture2D(size, size, TextureFormat.RGBA32, true);
            tex.wrapMode = TextureWrapMode.Repeat;
            var px = new Color32[size * size];
            for (int y = 0; y < size; y++)
            {
                float band = Mathf.Sin(y * 0.28f) * 0.5f + Mathf.Sin(y * 0.73f) * 0.5f;
                for (int x = 0; x < size; x++)
                {
                    float fine = Mathf.PerlinNoise(x * 0.14f, y * 0.04f) - 0.5f;
                    float m = 1f + (band * 0.4f + fine) * grainContrast;
                    Color c = new Color(
                        Mathf.Clamp01(baseColor.r * m),
                        Mathf.Clamp01(baseColor.g * m),
                        Mathf.Clamp01(baseColor.b * m),
                        1f);
                    px[y * size + x] = c;
                }
            }
            tex.SetPixels32(px);
            tex.Apply(true, false);
            mat.SetTexture("_BaseMap", tex);
            mat.SetColor("_BaseColor", Color.white);
            mat.SetFloat("_Metallic", Mathf.Clamp01(metallic));
            mat.SetFloat("_Smoothness", Mathf.Clamp01(smoothness));
            return mat;
        }
    }
}
```

## Performance & Platform Traps

- **Render `ReflectionProbe` Once, Not Every Frame**: `ReflectionProbeRefreshMode.EveryFrame` renders 6 extra scene cameras per frame and destroys WebGL/VR frame rate. Use `ViaScripting` and call `probe.RenderProbe()` once after room geometry finishes spawning.
- **Avoid `hdr = true` Probes in WebGL 2**: Some software and mobile GPUs reject float cubemap render targets during headless verification; `probe.hdr = false` works universally while giving rich specular highlights on brass and wood.
- **Use `Universal Render Pipeline/Lit` Before Writing Custom Shaders**: Procedural `Texture2D` albedo + normal + roughness maps on URP Lit pass WebGL 2 and WebGPU `CreateRenderPipeline` validation 100% of the time with automatic shadow/fog/probe support.

## Verification Checklist

1. Inspect browser boot logs to confirm zero `CreateRenderPipeline` or shader compile warnings.
2. Verify active shadow-casting lights stay `<= 1` (`<= 2` max on flat desktop) and check `Captures/*.png` for crisp specular highlights on metal/wood surfaces.
3. In VR scenes, verify the probe captures once at startup without raising per-frame draw calls.

## Official references

- Sebastien Lagarde & Charles de Rousiers Moving Frostbite to PBR (SIGGRAPH)
- Unity 6 URP Forward Rendering Light Limits & WebGPU Shader Compatibility Docs
