depthview-mcp 0.1.0 → 0.5.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,137 @@
1
+ # Particles
2
+
3
+ ## Pick the technique by count and behaviour
4
+
5
+ | Technique | Count | Motion | Notes |
6
+ | ----------------------------------- | --------- | ------------------------------------------------------------ | ---------------------------------------------------------------------------------------------------------------------- |
7
+ | `Points` + shader | 1k–500k | Stateless: position is a function of time and a seed | Cheapest. Point size is capped by the GPU (often 64–256 px) and points are clipped when their centre leaves the screen |
8
+ | Camera-facing quads in one geometry | 1k–100k | Stateless | No size cap, can be stretched and rotated. What Depthview's `add_effect` builds |
9
+ | `InstancedMesh` | 100–50k | CPU per instance, or attribute-driven in the shader | Real geometry per particle (shards, leaves, coins), lit and shadowed |
10
+ | GPGPU (FBO ping-pong) | 16k–4M | Stateful simulation on the GPU: velocity, forces, collisions | Positions live in a float texture; a fragment shader advances them |
11
+ | WebGPU compute (TSL) | millions | Stateful | The clean way when WebGPU is the target |
12
+ | CPU arrays + `needsUpdate` | under ~5k | Anything | Simple; uploads the buffer every frame |
13
+
14
+ **Stateless first.** Most "magic dust", snow, rain, stars, embers and bokeh need no
15
+ simulation: `position = start + velocity * time`, wrapped with `fract` inside a box, plus
16
+ noise. No memory, no CPU, resumes perfectly after a pause, and it is deterministic for
17
+ screenshots. Simulate only when particles must react (to the pointer, to a shape, to each
18
+ other).
19
+
20
+ ## Live with Depthview
21
+
22
+ `add_effect kind:"particles"` with a preset (`dust`, `snow`, `embers`, `fireflies`, `rain`,
23
+ `stars`), then `set_effect` uniforms: `uSize` (scene units), `uSpeed`, `uDirection`,
24
+ `uTurbulence`, `uTwinkle`, `uStretch`, `uOpacity`, `uSoftness`, `uColor`, `uColor2`, and
25
+ `count`. The box they live in is the object's `scale`; move it with `position`.
26
+ `get_effect_code` writes the component. For anything the presets cannot do, write your own
27
+ vertex and fragment shader on `geometry: "sprites"` (attributes `position` = a random point
28
+ in the unit box, `dvCorner` = quad corner -1..1, `dvSeed` = four random numbers).
29
+
30
+ ## The stateless sprite shader, explained
31
+
32
+ ```glsl
33
+ attribute vec2 dvCorner; // which corner of the quad
34
+ attribute vec4 dvSeed; // four random numbers per particle
35
+ uniform float uTime, uSize, uSpeed;
36
+ uniform vec3 uDirection;
37
+ varying vec2 vUv;
38
+ varying float vFade;
39
+ void main() {
40
+ vec3 p = position + uDirection * uSpeed * uTime * (0.5 + dvSeed.x); // drift, each its own pace
41
+ p = fract(p + 0.5) - 0.5; // wrap inside the unit box
42
+ vec3 e = smoothstep(0.5, 0.4, abs(p));
43
+ vFade = e.x * e.y * e.z; // fade at the faces: no popping
44
+ vec4 mv = modelViewMatrix * vec4(p, 1.0);
45
+ mv.xy += dvCorner * uSize * 0.5; // billboard: offset in view space
46
+ gl_Position = projectionMatrix * mv;
47
+ vUv = dvCorner;
48
+ }
49
+ ```
50
+
51
+ With `Points` instead: `gl_PointSize = uSize * uPixelRatio * (uScale / -mv.z);` and
52
+ `gl_PointCoord` in the fragment shader. Multiply by the pixel ratio or the particles halve in
53
+ size on a 2× screen.
54
+
55
+ ## Making particles look good
56
+
57
+ - **Soft, not hard.** `alpha = 1.0 - smoothstep(0.0, 1.0, length(vUv))`, or a small texture.
58
+ A hard disc reads as confetti.
59
+ - **Vary everything by seed**: size (×0.25–1), speed, phase, brightness, colour between two
60
+ tones. Uniform particles look like a grid.
61
+ - **Few and deliberate beats many.** 300 well-placed dust motes in the light beam beat 30,000
62
+ filling the screen. Start low.
63
+ - **Additive blending** for light (sparks, dust in a beam, fireflies), with `depthWrite:
64
+ false`. It cannot darken: on a white page it disappears. Use normal blending for snow, ash,
65
+ smoke.
66
+ - **Depth**: far particles smaller and dimmer comes free with perspective; add fog by
67
+ fading with `-mv.z`. Blur the near ones (bigger, softer, lower alpha) for a bokeh look.
68
+ - **Soft particles** (no hard line where a sprite cuts through a floor): read the scene depth
69
+ texture and fade by the difference:
70
+ `alpha *= smoothstep(0.0, uSoftDistance, sceneDepthLinear - particleDepthLinear);`.
71
+ Needs a depth pre-pass or the composer's depth texture; skip it for small particles.
72
+ - **Motion blur for fast ones**: stretch the quad along its screen-space velocity (`uStretch`)
73
+ and lower alpha by the same factor. That is rain and sparks.
74
+ - **Size in world units**, so the effect survives a camera move; clamp a minimum of about one
75
+ pixel so far particles do not flicker (fade them instead).
76
+ - **HDR + bloom**: colours above 1 (`uColor * 4.0`) with bloom threshold 1 make embers glow
77
+ without making the whole scene hazy.
78
+
79
+ ## Sorting and transparency
80
+
81
+ - Additive particles need no sorting. `depthWrite: false`, `depthTest: true`.
82
+ - Alpha-blended particles drawn unsorted look wrong where they overlap. Options: keep them
83
+ low-alpha and soft (errors vanish); premultiplied alpha with a hash-dither
84
+ (`alphaHash`/`alphaToCoverage`) and `depthWrite: true`; sort on the CPU for small counts.
85
+ - Draw particles after opaque objects (they are, when `transparent: true`). Use `renderOrder`
86
+ between particle systems.
87
+ - `frustumCulled = false` on any system whose shader moves vertices: the bounding sphere does
88
+ not know.
89
+
90
+ ## GPGPU: the FBO simulation
91
+
92
+ For particles with state (igloo's shape-forming swarm, fluid-like flow, attraction to the
93
+ pointer).
94
+
95
+ 1. Two float render targets (`HalfFloatType` or `FloatType`, `NearestFilter`, no mipmaps), size
96
+ √N × √N. Each texel is one particle: rgb = position, a = life (a second pair for velocity
97
+ if needed).
98
+ 2. A full-screen fragment shader reads the previous state and writes the next:
99
+ `pos += vel * dt`. Swap the targets each frame (ping-pong).
100
+ 3. The draw geometry has one vertex per particle carrying its texel UV; the vertex shader
101
+ reads its position from the state texture (`texture2D(uPositions, aRef)`).
102
+
103
+ three ships `GPUComputationRenderer` (`three/addons/misc/GPUComputationRenderer.js`) for
104
+ steps 1–2. In R3F: drei `useFBO` plus `createPortal` for the simulation scene.
105
+
106
+ Forces worth knowing:
107
+
108
+ - **Curl noise**: the curl of a noise field is divergence-free, so particles swirl like smoke
109
+ and never bunch up or drain. `vel = curl(pos * frequency + time)`.
110
+ - **Attraction to a shape**: bake target positions into a texture (sample the mesh surface
111
+ with `MeshSurfaceSampler`, or a signed distance field as a 3D texture) and
112
+ `vel += (target - pos) * strength`. Morph between shapes by blending two target textures.
113
+ - **Pointer**: pass the pointer's world position; push with `normalize(d) / (1.0 + dot(d, d))`.
114
+ - **Respawn**: when life runs out, reset to the emitter with a hash of the texel UV and time.
115
+ - Use a fixed time step (clamp `dt` to 1/30) or the simulation explodes after a tab switch.
116
+ - iOS: float render targets need `EXT_color_buffer_half_float`; use `HalfFloatType`.
117
+
118
+ ## Instanced meshes as particles
119
+
120
+ `InstancedMesh(geometry, material, count)`; write matrices with `setMatrixAt` and set
121
+ `instanceMatrix.needsUpdate`. Better: leave matrices fixed and animate in the vertex shader
122
+ with an `InstancedBufferAttribute` seed, through `patch_shader`-style `onBeforeCompile`. Keeps
123
+ PBR lighting, costs one draw call. `instanceColor` for per-instance tint. Set
124
+ `mesh.count` lower on slow devices.
125
+
126
+ ## Trails and ribbons
127
+
128
+ A trail is a strip of quads following a path: keep the last N positions per trail (in a
129
+ texture for GPGPU), expand to width in the vertex shader perpendicular to the view. Libraries:
130
+ `three.meshline` / drei `<Trail>` for a few; a GPGPU history texture for thousands.
131
+
132
+ ## Budget
133
+
134
+ Overdraw is the cost, not vertex count: big soft sprites stacked near the camera are the
135
+ expensive case. Measure with `get_performance` before and after; if the frame time rises with
136
+ window size, it is fill rate: fewer or smaller sprites, or draw them into a half-resolution
137
+ target and composite. Phones: half the count, cap pixel ratio at 2.
@@ -0,0 +1,114 @@
1
+ # Performance
2
+
3
+ Measure first: `get_performance` (frame time, draw calls, triangles, passes),
4
+ `get_resources` (GPU memory), `get_lighting` (shadow passes). Change one thing, measure again,
5
+ report both numbers. Frame rate is capped by the screen: compare `frameMs.average`, not fps.
6
+
7
+ ## Budgets
8
+
9
+ | | Desktop | Phone |
10
+ | --------------------- | -------------------------------------- | ------------------------------ |
11
+ | Frame time | under 12 ms (leaves headroom at 60 Hz) | under 25 ms |
12
+ | Draw calls | under 150 | under 80 |
13
+ | Triangles on screen | under 1.5 M | under 400 k |
14
+ | Texture memory | under 400 MB | under 150 MB |
15
+ | Pixel ratio | min(device, 2) | min(device, 2), 1.5 when heavy |
16
+ | Full-screen passes | 4–6 | 2–3 |
17
+ | Shadow-casting lights | 1–2 | 1 or baked |
18
+ | First screen download | under 5 MB | under 3 MB |
19
+
20
+ ## Where the time goes, and the fix
21
+
22
+ **Too many draw calls** (each mesh × each material × each pass):
23
+
24
+ - Merge static meshes that share a material: `BufferGeometryUtils.mergeGeometries`, or in
25
+ Blender before export. `gltf-transform join`.
26
+ - Repeated objects: `InstancedMesh` (one call for thousands). Different geometries, one
27
+ material: `BatchedMesh` (r159+).
28
+ - Share materials: two materials with identical settings are two programs' worth of state
29
+ changes. `gltf-transform dedup`. Texture atlases so objects can share one.
30
+ - Every shadow light redraws the casters; every extra pass (transmission, reflection probe)
31
+ redraws the scene.
32
+
33
+ **Too many pixels** (fill rate: frame time grows with window size):
34
+
35
+ - Cap the pixel ratio at 2. A 3× phone at full ratio draws 2.25× the pixels of 2×.
36
+ - Overdraw: large transparent layers, particles near the camera, stacked full-screen quads.
37
+ - Expensive fragment shaders on large surfaces: transmission, clearcoat, many lights,
38
+ ray marching. Render heavy effects at half resolution.
39
+ - Post-processing: merge effects (pmndrs/postprocessing does), drop passes on phones.
40
+
41
+ **Too many triangles / vertices**: decimate (`gltf-transform simplify`, Meshopt), LODs (drei
42
+ `<Detailed>`), normal maps instead of geometry. Skinned and morphed meshes pay per vertex on
43
+ the CPU side of the GPU.
44
+
45
+ **CPU / JavaScript**:
46
+
47
+ - Allocation in the render loop (`new Vector3()` per frame) causes garbage-collection
48
+ stutter: hoist temporaries.
49
+ - `matrixWorld` updates for thousands of objects: `matrixAutoUpdate = false` on static ones.
50
+ - Raycasting against dense meshes every pointer move: `three-mesh-bvh`
51
+ (`geometry.computeBoundsTree()`), throttle to once a frame, raycast against proxies.
52
+ - React re-rendering every frame: see r3f.
53
+
54
+ **Memory and loading**:
55
+
56
+ - Textures dominate. PNG/JPEG decode to RGBA: 2048² = 16 MB + mips = 22 MB of GPU memory each.
57
+ **KTX2** (Basis ETC1S for colour, UASTC for normals) stays compressed on the GPU, 4–8×
58
+ smaller: `gltf-transform uastc` / `etc1s`, loaded with `KTX2Loader`.
59
+ - Resize to what the screen needs: `gltf-transform resize --width 1024`. A 4096² texture on
60
+ an object 300 px tall is waste (`audit_visuals` reports the opposite case).
61
+ - Geometry: Meshopt (`gltf-transform meshopt`) or Draco. Quantise attributes.
62
+ - Dispose what leaves the scene: `geometry.dispose()`, `material.dispose()`,
63
+ `texture.dispose()`, `renderTarget.dispose()`. three does not do it for you.
64
+
65
+ A one-line optimiser for any glTF:
66
+
67
+ ```bash
68
+ npx @gltf-transform/cli optimize in.glb out.glb --compress meshopt --texture-compress ktx2 --texture-size 2048
69
+ ```
70
+
71
+ ## Render only when needed
72
+
73
+ A scene that does not animate should not draw 60 times a second.
74
+
75
+ - three: draw on change (controls `change` event, scroll, resize), not in a permanent loop.
76
+ - R3F: `<Canvas frameloop="demand">` and `invalidate()` when something changes.
77
+ - Pause when off screen (IntersectionObserver) and when the tab is hidden.
78
+ - Shadows of a static scene: `renderer.shadowMap.autoUpdate = false`.
79
+
80
+ ## Adaptive quality
81
+
82
+ Decide from measured frame time, not from the user agent.
83
+
84
+ 1. Start at pixel ratio `min(devicePixelRatio, 2)`.
85
+ 2. Average the frame time over ~60 frames. Over budget: step down, in this order: shadow map
86
+ size, pixel ratio (to 1.5, then 1), depth of field, ambient occlusion, bloom, anti-aliasing
87
+ pass, particle count, volume steps.
88
+ 3. Under budget for a few seconds: step back up one level. Add hysteresis so it does not flap.
89
+
90
+ drei: `<PerformanceMonitor onDecline onIncline>` and `<AdaptiveDpr>`. Depthview's saved look
91
+ does these steps itself with `performance: { adaptive: true }`; `lighten_look` shows them live.
92
+ `detect-gpu` gives a starting tier before the first measurement.
93
+
94
+ ## Loading without hitches
95
+
96
+ - First-use stalls are shader compiles and texture uploads. Before the reveal:
97
+ `await renderer.compileAsync(scene, camera)` (uses `KHR_parallel_shader_compile`), then
98
+ `renderer.initTexture(texture)` for the big ones, or one render behind the loader.
99
+ - Keep the number of shader **variants** low: every different combination of material
100
+ features, light count, fog, shadow settings is another program to compile. A light toggled
101
+ on later recompiles every lit material: add it at intensity 0 from the start.
102
+ - Load in stages: first-screen assets, then the rest while idle. `LoadingManager` (or drei
103
+ `useProgress`) for a real progress number.
104
+ - Decode off the main thread: KTX2 and Draco loaders use workers; `ImageBitmapLoader` for
105
+ images.
106
+ - Code-split three and the scene from the page shell so the HTML paints first.
107
+
108
+ ## Finding the cost of one thing
109
+
110
+ `remove_object` it, `get_performance`, `reset_changes`. For a look feature:
111
+ `measure_look_cost`. For resolution: `set_viewport { pixelRatio }` and measure at 1 and 2: if
112
+ frame time doubles, the scene is fill-rate bound; if it barely moves, it is draw calls or CPU.
113
+ `passesOfOneFrame` in `get_performance` lists every `renderer.render()` of a frame with its
114
+ target size and cost: the pass that should not be there is usually visible at once.
@@ -0,0 +1,151 @@
1
+ # React Three Fiber
2
+
3
+ R3F is three.js with React managing the scene graph. Everything in the other guides applies;
4
+ this is what is specific to React.
5
+
6
+ ## The one rule
7
+
8
+ **React renders the structure. The frame loop moves it.** Anything that changes every frame
9
+ (time, scroll, pointer, physics) is written to refs inside `useFrame`, never to state.
10
+
11
+ ```tsx
12
+ function Spinner() {
13
+ const ref = useRef<THREE.Mesh>(null!);
14
+ useFrame((state, delta) => {
15
+ ref.current.rotation.y += delta; // mutate
16
+ ref.current.material.uniforms.uTime.value = state.clock.elapsedTime;
17
+ });
18
+ return <mesh ref={ref}>...</mesh>;
19
+ }
20
+ ```
21
+
22
+ Wrong, in order of how often it is seen:
23
+
24
+ - `setState` inside `useFrame`, `onPointerMove` or a scroll handler: React re-renders the
25
+ tree 60 times a second. Use a ref, or a store read with `getState()` (zustand) inside
26
+ `useFrame`.
27
+ - Creating objects during render: `<mesh position={new THREE.Vector3(1, 2, 3)}>`,
28
+ `args={[new THREE.BoxGeometry()]}`, an inline `uniforms={{ uTime: { value: 0 } }}`: a new
29
+ object every render, so the material or geometry is rebuilt. `useMemo` them, or use arrays
30
+ (`position={[1, 2, 3]}`).
31
+ - `new THREE.Vector3()` inside `useFrame`: allocate once outside the component.
32
+ - Mounting and unmounting to show and hide: it re-creates GPU resources and recompiles
33
+ shaders. Toggle `visible`, or keep it mounted and animate opacity/scale.
34
+ - Conditional lights (`{on && <pointLight />}`): changing the light count recompiles every
35
+ lit material. Keep the light, set `intensity={0}`.
36
+ - Reading `state.clock.elapsedTime` for motion that must be frame-rate independent: use
37
+ `delta` and damp: `THREE.MathUtils.damp(current, target, lambda, delta)` or maath `easing.damp3`.
38
+
39
+ ## Canvas set-up
40
+
41
+ ```tsx
42
+ <Canvas
43
+ dpr={[1, 2]} // pixel ratio between 1 and 2
44
+ gl={{ antialias: true, powerPreference: 'high-performance' }}
45
+ camera={{ fov: 35, near: 0.1, far: 100, position: [0, 1, 6] }}
46
+ shadows // PCF by default; "variance" for VSM
47
+ frameloop="always" // "demand" for scenes that only change on input
48
+ >
49
+ ```
50
+
51
+ - R3F sets sRGB output and ACES tone mapping by default. `flat` turns tone mapping off,
52
+ `linear` turns the sRGB output off (rarely what you want). When a postprocessing
53
+ `<EffectComposer>` does tone mapping, turn the renderer's off:
54
+ `gl={{ toneMapping: THREE.NoToneMapping }}` or the image is mapped twice.
55
+ - With an EffectComposer, `antialias: false` on the canvas and `multisampling={4}` on the
56
+ composer.
57
+ - A narrow field of view (25–40°) looks like a product photograph; 50–75° looks like a game.
58
+ - Keep `near`/`far` tight around the scene (depth precision: z-fighting).
59
+ - The canvas fills its parent: give the parent a size. Resizing is handled; do not call
60
+ `setSize` yourself.
61
+
62
+ ## drei, the parts worth knowing
63
+
64
+ | Need | drei |
65
+ | ------------------------------------------ | --------------------------------------------------------------------------------------------------------- |
66
+ | Lighting from an HDRI or built from shapes | `<Environment>` with `<Lightformer>` children; `preset` only for prototypes (it downloads from a CDN) |
67
+ | A product on a floor | `<ContactShadows>`, `<AccumulativeShadows>` + `<RandomizedLight>`, `<Stage>`, `<Center>`, `<Bounds>` |
68
+ | Models | `useGLTF` (+ `useGLTF.preload`), `gltfjsx` to turn a .glb into a component with named meshes |
69
+ | Textures | `useTexture`, `useKTX2`, `useVideoTexture` |
70
+ | Glass and special materials | `<MeshTransmissionMaterial>`, `<MeshReflectorMaterial>`, `<MeshDistortMaterial>`, `<MeshWobbleMaterial>` |
71
+ | Custom shader as a JSX element | `shaderMaterial()` + `extend()` |
72
+ | Scroll | `<ScrollControls>` + `useScroll()` (its own scroll container), or Lenis/GSAP driving a ref |
73
+ | Text | `<Text>` (troika SDF, crisp at any size), `<Text3D>` |
74
+ | HTML pinned to 3D | `<Html transform occlude>`: real DOM, so use it sparingly |
75
+ | Clouds, sparkles, stars | `<Cloud>` / `<Clouds>` (sprite stacks), `<Sparkles>`, `<Stars>`, `<Trail>` |
76
+ | Instancing | `<Instances>` / `<Instance>`, `<Merged>` |
77
+ | Performance | `<PerformanceMonitor>`, `<AdaptiveDpr>`, `<AdaptiveEvents>`, `<Detailed>` (LOD), `<Bvh>`, `<Preload all>` |
78
+ | Off-screen rendering | `useFBO`, `<RenderTexture>`, `<MeshPortalMaterial>` |
79
+ | Camera | `<PerspectiveCamera makeDefault>`, `<CameraControls>`, `<CameraShake>` |
80
+
81
+ `<Float>` for idle motion. `<Preload all />` compiles and uploads everything up front.
82
+
83
+ ## Loading and Suspense
84
+
85
+ - `useGLTF`, `useTexture` suspend. Wrap the scene in `<Suspense fallback={null}>` and show
86
+ progress with `useProgress()` in the DOM (not inside the canvas).
87
+ - Preload at module level (`useGLTF.preload(url)`) so loading starts with the bundle.
88
+ - A `<Suspense>` boundary per section lets the first screen appear before the rest loads.
89
+ - Loaded assets are cached by URL: the same model used twice is one geometry. To place it
90
+ twice, `scene.clone()` or `<Clone>`, or better `<Instances>`.
91
+
92
+ ## Scroll-driven camera
93
+
94
+ ```tsx
95
+ function Rig({ progress }: { progress: React.MutableRefObject<number> }) {
96
+ const smooth = useRef(0);
97
+ useFrame((state, delta) => {
98
+ smooth.current = THREE.MathUtils.damp(smooth.current, progress.current, 4, delta);
99
+ curve.getPointAt(smooth.current, state.camera.position);
100
+ lookCurve.getPointAt(smooth.current, target);
101
+ state.camera.lookAt(target);
102
+ });
103
+ return null;
104
+ }
105
+ ```
106
+
107
+ The scroll handler only writes `progress.current`. Depthview's `useCameraPath(path)` from
108
+ `depthview-r3f-bridge/camera-path` is this, driven by a `camera-path.json` you can edit in
109
+ the inspector (`edit_camera_path`, `save_camera_path`).
110
+
111
+ GSAP: animate plain objects or refs (`gsap.to(ref.current.position, {...})`), with
112
+ ScrollTrigger `scrub: 1` for smoothing. Never tween React state.
113
+
114
+ ## Post-processing
115
+
116
+ ```tsx
117
+ <EffectComposer multisampling={4} enableNormalPass={false}>
118
+ <N8AO aoRadius={0.5} intensity={1.5} />
119
+ <Bloom mipmapBlur luminanceThreshold={1} intensity={0.4} />
120
+ <ToneMapping mode={ToneMappingMode.AGX} />
121
+ <Vignette offset={0.3} darkness={0.5} />
122
+ <Noise opacity={0.04} premultiply />
123
+ </EffectComposer>
124
+ ```
125
+
126
+ `@react-three/postprocessing`. Effects are merged into as few passes as possible. Emissive
127
+ materials that should glow: `emissiveIntensity > 1` and `toneMapped={false}`.
128
+
129
+ ## Events and interaction
130
+
131
+ - Pointer events raycast the whole scene on every move. `<Bvh>` around heavy models, or
132
+ `raycast={() => null}` on meshes that never need events, or `<AdaptiveEvents>`.
133
+ - `e.stopPropagation()` so the nearest hit wins.
134
+ - Hover state changes the cursor and maybe a colour: that one `setState` is fine. Per-frame
135
+ follow-the-pointer motion is not: read `state.pointer` in `useFrame`.
136
+
137
+ ## Cleanup
138
+
139
+ R3F disposes geometries, materials and textures of unmounted JSX elements. It does **not**
140
+ dispose what you create by hand (`new THREE.WebGLRenderTarget`, textures made in effects):
141
+ dispose in the effect's cleanup. `dispose={null}` on shared assets you want to keep.
142
+
143
+ ## With Depthview
144
+
145
+ - Add `depthviewVite()` and `<DepthviewBridge />` (see the skill): objects then know their
146
+ file and line, and `apply_changes_to_code` writes literal props exactly.
147
+ - Name the meshes (`name="Coin"`): looks, surfaces and effects find objects by name.
148
+ - `get_effect_code` returns an effect as an R3F component ready to render inside `<Canvas>`.
149
+ - `patch_shader` returns `onBeforeCompile` source: put it on the material element
150
+ (`<meshStandardMaterial onBeforeCompile={...} customProgramCacheKey={() => 'key'} />`),
151
+ with the callback memoised.
@@ -0,0 +1,150 @@
1
+ # Rendering: from "three.js demo" to a photographic frame
2
+
3
+ ## Colour management (get this wrong and nothing else matters)
4
+
5
+ - **Output**: `renderer.outputColorSpace = THREE.SRGBColorSpace` (default since r152).
6
+ - **Colour textures** (base colour, emissive, sheen colour, specular colour):
7
+ `texture.colorSpace = THREE.SRGBColorSpace`.
8
+ - **Data textures** (normal, roughness, metalness, AO, displacement, alpha, any look-up table):
9
+ `THREE.NoColorSpace`. Marked sRGB, they bend: normals tilt, surfaces come out too rough.
10
+ - GLTFLoader sets these itself. A hand-made `TextureLoader().load()` does not: set it.
11
+ In R3F, `useTexture` on the `map` prop is converted for you; textures you pass to a
12
+ ShaderMaterial uniform are not.
13
+ - Colours written in a custom shader are **linear**. `new THREE.Color('#ff8800')` converts
14
+ from sRGB for you; a raw `vec3(1.0, 0.53, 0.0)` typed from a colour picker is wrong: convert
15
+ it (`pow(c, vec3(2.2))`) or pass it as a `THREE.Color` uniform.
16
+ - A ShaderMaterial must end its fragment shader with
17
+ `#include <tonemapping_fragment>` then `#include <colorspace_fragment>` (r154+; it was
18
+ `encodings_fragment` before), or it skips both and looks different from every other object.
19
+ - With post-processing, tone mapping and the sRGB conversion happen **once, at the end**
20
+ (`OutputPass` in three's EffectComposer; pmndrs/postprocessing does it itself). Tone mapping
21
+ on the renderer **and** in the composer is the classic washed-out double conversion.
22
+ Intermediate render targets: `HalfFloatType`, linear.
23
+
24
+ Symptoms: washed-out and pale = a colour texture read as linear, or sRGB applied twice. Dark
25
+ and contrasty = output not sRGB. `audit_visuals` reports both.
26
+
27
+ ## Tone mapping and exposure
28
+
29
+ A lit scene produces values above 1. Without tone mapping they clip to flat white.
30
+
31
+ | Mapping | Use it for |
32
+ | ----------------------- | -------------------------------------------------------------------- |
33
+ | `AgXToneMapping` | The natural default. Highlights roll off and desaturate like film. |
34
+ | `ACESFilmicToneMapping` | More contrast and saturation: the "cinematic" look. Shifts hues. |
35
+ | `NeutralToneMapping` | Product colours that must match the brand: keeps hue and saturation. |
36
+ | `NoToneMapping` | Unlit, baked or flat-design scenes where colours are already final. |
37
+
38
+ Set `toneMappingExposure` in steps of 0.1 after choosing. UI drawn in the same canvas and
39
+ baked textures that are already tone mapped: `material.toneMapped = false`.
40
+
41
+ ## Materials
42
+
43
+ `MeshStandardMaterial` is the floor; `MeshPhysicalMaterial` where one of its extras is needed
44
+ (each costs shader time: do not use it everywhere).
45
+
46
+ | Surface | Settings |
47
+ | ------------------ | --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
48
+ | Metal | `metalness: 1`, `roughness: 0.15–0.4`, colour is the metal's tint. Needs an environment or it is black. |
49
+ | Plastic | `metalness: 0`, `roughness: 0.3–0.6` |
50
+ | Car paint, lacquer | Physical: `clearcoat: 1`, `clearcoatRoughness: 0.03–0.1` |
51
+ | Glass | Physical: `transmission: 1`, `thickness`, `ior: 1.5`, `roughness: 0–0.1`. Costs an extra full-scene pass. For many glass objects fake it: env reflection + fresnel + low opacity. |
52
+ | Ice, frosted | Transmission with `roughness: 0.3–0.6`, `attenuationColor`, a normal map for cracks |
53
+ | Fabric, velvet | Physical: `sheen: 1`, `sheenRoughness`, `sheenColor` |
54
+ | Soap bubble, oil | Physical: `iridescence: 1` |
55
+ | Skin, wax, jade | No built-in subsurface: fake it with wrap lighting and a thickness map in a patched shader |
56
+
57
+ Rules: never `roughness: 0` (a perfect mirror reads as CG; 0.05 minimum). Never one flat
58
+ roughness on a hero object: add a roughness map or `set_surface detail`. `metalness` is 0 or
59
+ 1, in-between only where a map blends rust or dirt. A normal map does more for realism than
60
+ ten times the triangles.
61
+
62
+ ## Light
63
+
64
+ **Image-based lighting is most of realism.** `scene.environment` with a prefiltered HDR (drei
65
+ `<Environment>`, or `PMREMGenerator`). Metal and gloss show the environment, so _what is in
66
+ the HDRI is what the product looks like_: a studio HDRI with soft boxes gives long clean
67
+ highlights, a sunny outdoor one gives a hard hot spot. Depthview's `set_look world` builds a
68
+ studio from light boxes you can move; use it instead of hunting for an HDRI.
69
+
70
+ - `scene.environmentIntensity` (r163+) or `envMapIntensity` per material to balance it against
71
+ direct lights. `scene.environmentRotation` to turn the highlights.
72
+ - Direct lights add shape and shadows on top: one key `DirectionalLight` with shadows, maybe a
73
+ rim from behind. Three or four lights at most; each one is paid for per pixel.
74
+ - three.js light units are physical since r155 (`intensity` of a point light in candela,
75
+ `decay: 2`). Old tutorials with `intensity: 1` point lights look dark: that is why.
76
+ - `RectAreaLight` gives soft studio highlights on Standard/Physical only, with no shadows:
77
+ it needs `RectAreaLightUniformsLib.init()`.
78
+ - Background: a blurred environment (`scene.backgroundBlurriness`), a gradient, or the page
79
+ colour. Never the raw HDRI behind a product.
80
+
81
+ ## Shadows
82
+
83
+ Contact with the ground is what stops objects floating.
84
+
85
+ - `renderer.shadowMap.enabled = true`. The type defaults to `THREE.PCFShadowMap`; soften it with
86
+ `light.shadow.radius`. (`PCFSoftShadowMap` is deprecated since r186 and falls back to it.)
87
+ `VSMShadowMap` for wide soft shadows, with light-leak risk.
88
+ - **Fit the shadow camera to the casters.** A directional light's default box is 10 × 10
89
+ units: on a 1-unit product a 2048 map then has 5 mm texels and the shadow is mush.
90
+ `light.shadow.camera.left/right/top/bottom/near/far` tight around the scene, then
91
+ `updateProjectionMatrix()`. `get_lighting` measures this.
92
+ - `shadow.mapSize` 1024–2048. 4096 only for one hero light.
93
+ - Acne (stripes on lit surfaces): `shadow.normalBias = 0.02–0.05` first, then a small
94
+ negative `shadow.bias` (-0.0001 to -0.001). Peter-panning (shadow detached from the
95
+ object): the bias is too large.
96
+ - A static scene does not need a shadow pass every frame: `shadowMap.autoUpdate = false`, set
97
+ `needsUpdate = true` when something moved.
98
+ - Cheaper and softer for a product on a floor: drei `<ContactShadows>` (one top-down depth
99
+ render, blurred) or `<AccumulativeShadows>` (accumulates a path-traced-looking shadow over
100
+ frames, static scenes only). Or bake the shadow into the floor texture.
101
+ - Point-light shadows are six passes. Avoid.
102
+
103
+ ## Ambient occlusion
104
+
105
+ Darkening in creases and where objects meet. Baked AO (`aoMap`, needs a second UV set or
106
+ shared UVs) is free at run time and looks best. Screen-space: N8AO (`n8ao` package) is the
107
+ current good default, or three's `GTAOPass`. Radius about a tenth of the scene, intensity so
108
+ that you miss it when it is off but do not see it when it is on.
109
+
110
+ ## Post-processing, in order
111
+
112
+ Use `pmndrs/postprocessing` (`@react-three/postprocessing` in R3F): it merges effects into
113
+ one pass. Order:
114
+
115
+ 1. Render the scene into a **multisampled HalfFloat** target (`multisampling: 4`). The
116
+ canvas's own `antialias` does nothing once a composer is in use: turn it off.
117
+ 2. Ambient occlusion (needs depth; normal pass or reconstructed normals).
118
+ 3. Depth of field, if any: only for hero shots, focus on the subject, small bokeh.
119
+ 4. Bloom: `mipmapBlur: true`, `luminanceThreshold: 1` so only values brighter than white glow
120
+ (emissive with `emissiveIntensity > 1`, sun glints). Intensity 0.2–0.6. A threshold below 1
121
+ makes the whole image hazy.
122
+ 5. Tone mapping (here, not on the renderer).
123
+ 6. Colour grade: a 3D LUT or lift/gamma/gain; subtle chromatic aberration at the edges.
124
+ 7. Vignette (under 0.35), film grain (under 0.2 opacity). SMAA if not multisampling.
125
+
126
+ One `RenderPass`. Never two composers. Every pass at the drawing-buffer size:
127
+ `composer.setPixelRatio(renderer.getPixelRatio())`, `composer.setSize(w, h)` on resize: a
128
+ composer left at CSS-pixel size on a 2× screen is the usual cause of a pixelated site.
129
+
130
+ ## Anti-aliasing
131
+
132
+ | Situation | Use |
133
+ | -------------------------------------------- | ---------------------------------------------------------------------------- |
134
+ | No post-processing | `new WebGLRenderer({ antialias: true })` (MSAA 4×) |
135
+ | Post-processing | `samples: 4` on the composer target; or SMAA last |
136
+ | 1× desktop monitors, thin lines | Supersample: pixel ratio 1.5 there, MSAA on top |
137
+ | Foliage, fences, hair cards | `alphaToCoverage: true` with MSAA, not `alphaTest` alone |
138
+ | Shimmering highlights on normal-mapped metal | Raise roughness slightly; mipmaps on the normal map |
139
+ | Temporal shimmer everywhere | TAA (three's `TAARenderPass`, or TRAA with WebGPU) for stills and slow moves |
140
+
141
+ ## WebGPU and TSL (r170 and later)
142
+
143
+ `WebGPURenderer` (`three/webgpu`) with the node material system and TSL (three's shading
144
+ language, `three/tsl`) is where three.js is going: compute shaders, one shader source for
145
+ WebGPU and WebGL 2. Today: WebGL `WebGLRenderer` + GLSL is still what most award sites ship,
146
+ what the largest ecosystem (`postprocessing`, drei shaders) targets, and what **Depthview
147
+ inspects**. Choose WebGPU for compute-heavy work (millions of particles, fluid sims) and say
148
+ that Depthview's scene mode will not read it. ShaderMaterial, `onBeforeCompile` and
149
+ EffectComposer do not exist on WebGPURenderer: they become node materials, TSL and
150
+ `RenderPipeline` (named `PostProcessing` before). The `threejs` guide has what the manual says.