@null3d/engine 0.0.0 → 0.1.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.
Files changed (311) hide show
  1. package/README.md +109 -0
  2. package/THIRD-PARTY-NOTICES.txt +0 -1
  3. package/dist/wasm/single/null3d.js +19 -6
  4. package/dist/wasm/single/null3d_bg.wasm +0 -0
  5. package/dist/wasm/threaded/null3d.js +19 -6
  6. package/dist/wasm/threaded/null3d_bg.wasm +0 -0
  7. package/docs/api/animation.md +23 -67
  8. package/docs/api/assets.md +42 -26
  9. package/docs/api/cameras.md +8 -6
  10. package/docs/api/controls.md +46 -44
  11. package/docs/api/debug.md +13 -8
  12. package/docs/api/engine.md +17 -11
  13. package/docs/api/feature-draws.md +3 -3
  14. package/docs/api/feature-effects.md +3 -3
  15. package/docs/api/feature-instances.md +2 -2
  16. package/docs/api/features.md +14 -15
  17. package/docs/api/geometry.md +56 -75
  18. package/docs/api/grass.md +1 -1
  19. package/docs/api/impostors.md +120 -9
  20. package/docs/api/input.md +4 -11
  21. package/docs/api/lights.md +14 -38
  22. package/docs/api/lines.md +8 -25
  23. package/docs/api/materials.md +69 -70
  24. package/docs/api/math.md +6 -7
  25. package/docs/api/objects.md +13 -13
  26. package/docs/api/particles.md +2 -14
  27. package/docs/api/points.md +3 -25
  28. package/docs/api/post.md +22 -23
  29. package/docs/api/quality.md +11 -6
  30. package/docs/api/raycast.md +13 -32
  31. package/docs/api/reference/animation.md +9 -9
  32. package/docs/api/reference/assets.md +18 -18
  33. package/docs/api/reference/cameras.md +5 -2
  34. package/docs/api/reference/controls.md +75 -23
  35. package/docs/api/reference/debug.md +23 -8
  36. package/docs/api/reference/engine.md +22 -10
  37. package/docs/api/reference/geometry.md +161 -82
  38. package/docs/api/reference/grass.md +1 -1
  39. package/docs/api/reference/impostors.md +92 -1
  40. package/docs/api/reference/input.md +3 -3
  41. package/docs/api/reference/lights.md +9 -9
  42. package/docs/api/reference/lines.md +7 -7
  43. package/docs/api/reference/materials.md +48 -48
  44. package/docs/api/reference/math.md +22 -22
  45. package/docs/api/reference/objects.md +9 -9
  46. package/docs/api/reference/points.md +4 -4
  47. package/docs/api/reference/post.md +18 -18
  48. package/docs/api/reference/quality.md +7 -3
  49. package/docs/api/reference/raycast.md +6 -6
  50. package/docs/api/reference/render.md +2 -2
  51. package/docs/api/reference/scene.md +29 -26
  52. package/docs/api/reference/sketch.md +4 -0
  53. package/docs/api/reference/sound.md +203 -0
  54. package/docs/api/reference/sprites.md +5 -5
  55. package/docs/api/reference/terrain.md +2 -1
  56. package/docs/api/reference/textures.md +4 -4
  57. package/docs/api/reference/ui.md +3 -3
  58. package/docs/api/reference/vertex-draws.md +3 -3
  59. package/docs/api/reference/water.md +77 -6
  60. package/docs/api/reference/wind.md +2 -2
  61. package/docs/api/render.md +12 -10
  62. package/docs/api/scene.md +40 -29
  63. package/docs/api/sketch.md +64 -3
  64. package/docs/api/sound.md +169 -0
  65. package/docs/api/splats.md +7 -0
  66. package/docs/api/sprites.md +4 -20
  67. package/docs/api/tasks.md +2 -2
  68. package/docs/api/terrain.md +2 -14
  69. package/docs/api/textures.md +9 -9
  70. package/docs/api/ui.md +3 -15
  71. package/docs/api/water.md +198 -15
  72. package/docs/api/wind.md +5 -5
  73. package/docs/cli/null3d.md +93 -18
  74. package/docs/concepts/architecture.md +10 -10
  75. package/docs/concepts/assets.md +2 -19
  76. package/docs/concepts/backends.md +7 -5
  77. package/docs/concepts/color-management.md +15 -26
  78. package/docs/concepts/culling.md +1 -1
  79. package/docs/concepts/instances.md +5 -5
  80. package/docs/concepts/large-worlds.md +1 -1
  81. package/docs/concepts/lighting.md +50 -55
  82. package/docs/concepts/lod.md +2 -15
  83. package/docs/concepts/materials.md +16 -16
  84. package/docs/concepts/post-processing.md +7 -29
  85. package/docs/concepts/quality-preset-tables.md +53 -50
  86. package/docs/concepts/quality-presets.md +56 -27
  87. package/docs/concepts/render-graph.md +19 -14
  88. package/docs/concepts/render-layers.md +3 -17
  89. package/docs/concepts/shadows.md +10 -28
  90. package/docs/concepts/static-dynamic.md +2 -2
  91. package/docs/cookbook/index.md +1 -1
  92. package/docs/data/threejs-mapping.json +136 -102
  93. package/docs/errors/E1214.md +3 -3
  94. package/docs/errors/E1307.md +23 -0
  95. package/docs/errors/E1420.md +3 -3
  96. package/docs/errors/index.md +3 -2
  97. package/docs/getting-started/cdn.md +17 -1
  98. package/docs/getting-started/first-scene.md +1 -1
  99. package/docs/getting-started/hosting.md +50 -9
  100. package/docs/getting-started/install.md +8 -7
  101. package/docs/getting-started/network-use.md +10 -2
  102. package/docs/getting-started/project-structure.md +15 -6
  103. package/docs/getting-started/third-party-notices.md +8 -6
  104. package/docs/guides/accessibility.md +1 -1
  105. package/docs/guides/add-ons.md +3 -2
  106. package/docs/guides/agents.md +16 -5
  107. package/docs/guides/assets-pipeline.md +13 -12
  108. package/docs/guides/audio.md +109 -124
  109. package/docs/guides/car-paint.md +1 -1
  110. package/docs/guides/content-pages.md +10 -6
  111. package/docs/guides/custom-passes.md +9 -8
  112. package/docs/guides/custom-shaders.md +6 -3
  113. package/docs/guides/debugging.md +78 -4
  114. package/docs/guides/deploying.md +105 -5
  115. package/docs/guides/deterministic-simulation.md +1 -1
  116. package/docs/guides/first-use-shaders.md +4 -4
  117. package/docs/guides/loading-screens.md +78 -33
  118. package/docs/guides/multiple-views.md +41 -2
  119. package/docs/guides/performance.md +6 -3
  120. package/docs/guides/phones.md +12 -1
  121. package/docs/guides/physics.md +1 -1
  122. package/docs/guides/screens.md +7 -5
  123. package/docs/guides/start-time.md +328 -0
  124. package/docs/guides/testing.md +23 -5
  125. package/docs/guides/ui-overlays.md +3 -3
  126. package/docs/index.md +12 -8
  127. package/docs/pages.md +26 -23
  128. package/docs/porting/react-three-fiber.md +228 -5
  129. package/docs/porting/threejs-loop-and-threads.md +220 -6
  130. package/docs/porting/threejs-mapping.md +86 -84
  131. package/docs/porting/threejs-materials.md +212 -5
  132. package/docs/porting/threejs-overview.md +218 -5
  133. package/docs/porting/threejs-postprocessing.md +2 -2
  134. package/docs/porting/threejs-shaders.md +298 -5
  135. package/docs/porting/threejs-unsupported.md +82 -6
  136. package/docs/porting/verification.md +181 -5
  137. package/docs/shaders/builtins.md +1 -1
  138. package/docs/shaders/library.md +63 -39
  139. package/docs/shaders/surface-functions.md +11 -10
  140. package/docs/shaders/wgsl-rules.md +1 -1
  141. package/lib/debug/channel.d.ts +103 -0
  142. package/lib/debug/channel.js +269 -0
  143. package/lib/debug/debug.d.ts +9 -7
  144. package/lib/debug/draw.d.ts +9 -0
  145. package/lib/debug/draw.js +49 -2
  146. package/lib/debug/inspector.d.ts +60 -0
  147. package/lib/debug/inspector.js +475 -0
  148. package/lib/debug/stats-panel.d.ts +1 -1
  149. package/lib/debug/stats.d.ts +2 -3
  150. package/lib/errors/codes.js +8 -2
  151. package/lib/errors/engine-error.js +25 -10
  152. package/lib/errors/fixes.d.ts +1 -0
  153. package/lib/errors/fixes.js +3 -2
  154. package/lib/generated/core.d.ts +1 -1
  155. package/lib/generated/core.js +1 -1
  156. package/lib/gpu/early-builds.d.ts +68 -0
  157. package/lib/gpu/early-builds.js +158 -0
  158. package/lib/gpu/pipeline-name.d.ts +6 -0
  159. package/lib/gpu/pipeline-name.js +23 -0
  160. package/lib/gpu/webgl2/backend.d.ts +63 -2
  161. package/lib/gpu/webgl2/backend.js +226 -8
  162. package/lib/gpu/webgl2/programs.d.ts +18 -0
  163. package/lib/gpu/webgl2/programs.js +4 -1
  164. package/lib/gpu/webgpu/backend.d.ts +89 -2
  165. package/lib/gpu/webgpu/backend.js +255 -8
  166. package/lib/gpu/webgpu/pipelines.d.ts +13 -0
  167. package/lib/gpu/webgpu/pipelines.js +15 -1
  168. package/lib/index.d.ts +6 -4
  169. package/lib/index.js +3 -2
  170. package/lib/math/color.d.ts +5 -5
  171. package/lib/math/color.js +5 -5
  172. package/lib/math/mat4.d.ts +6 -12
  173. package/lib/math/mat4.js +6 -12
  174. package/lib/math/namespaces/quat.d.ts +3 -3
  175. package/lib/math/namespaces/quat.js +3 -3
  176. package/lib/math/quat.d.ts +8 -12
  177. package/lib/math/quat.js +8 -12
  178. package/lib/math/random.d.ts +2 -3
  179. package/lib/math/random.js +2 -3
  180. package/lib/math/types.d.ts +4 -4
  181. package/lib/math/vec3.d.ts +3 -6
  182. package/lib/math/vec3.js +3 -6
  183. package/lib/page/capabilities.d.ts +7 -7
  184. package/lib/page/capabilities.js +39 -25
  185. package/lib/page/check-store.d.ts +14 -2
  186. package/lib/page/check-store.js +34 -11
  187. package/lib/page/engine.d.ts +103 -26
  188. package/lib/page/engine.js +420 -97
  189. package/lib/page/first-frame.d.ts +16 -0
  190. package/lib/page/first-frame.js +35 -0
  191. package/lib/page/frame-stats.d.ts +34 -1
  192. package/lib/page/frame-stats.js +15 -0
  193. package/lib/page/label-loop.d.ts +7 -3
  194. package/lib/page/label-loop.js +17 -10
  195. package/lib/page/labels.d.ts +3 -3
  196. package/lib/page/pipeline-store.d.ts +25 -0
  197. package/lib/page/pipeline-store.js +84 -0
  198. package/lib/page/start-marker.d.ts +4 -1
  199. package/lib/page/start-marker.js +5 -2
  200. package/lib/page/switches.d.ts +32 -2
  201. package/lib/page/switches.js +9 -1
  202. package/lib/quality/check.d.ts +24 -3
  203. package/lib/quality/check.js +21 -7
  204. package/lib/quality/chooser.d.ts +6 -0
  205. package/lib/quality/chooser.js +8 -0
  206. package/lib/quality/governor.d.ts +98 -6
  207. package/lib/quality/governor.js +250 -20
  208. package/lib/quality/preset-docs.d.ts +16 -1
  209. package/lib/quality/preset-docs.js +3 -0
  210. package/lib/quality/presets.d.ts +84 -7
  211. package/lib/quality/presets.js +94 -2
  212. package/lib/render/draw.d.ts +3 -2
  213. package/lib/render/draw.js +15 -5
  214. package/lib/render/load-draw.d.ts +7 -5
  215. package/lib/render/load-draw.js +7 -5
  216. package/lib/render/loss.d.ts +28 -10
  217. package/lib/render/loss.js +50 -22
  218. package/lib/render/recovery.d.ts +20 -0
  219. package/lib/render/recovery.js +44 -4
  220. package/lib/render/renderer.d.ts +85 -9
  221. package/lib/render/renderer.js +181 -42
  222. package/lib/render/scene-renderer.d.ts +19 -1
  223. package/lib/render/scene-renderer.js +25 -1
  224. package/lib/render/webgl2-renderers.js +8 -5
  225. package/lib/render/webgpu-renderers.js +5 -4
  226. package/lib/scene/animation.d.ts +28 -32
  227. package/lib/scene/animation.js +12 -15
  228. package/lib/scene/assets.d.ts +61 -86
  229. package/lib/scene/assets.js +103 -236
  230. package/lib/scene/background.d.ts +14 -18
  231. package/lib/scene/background.js +5 -2
  232. package/lib/scene/color.d.ts +3 -3
  233. package/lib/scene/downloads.d.ts +2 -0
  234. package/lib/scene/downloads.js +371 -0
  235. package/lib/scene/environment.d.ts +7 -7
  236. package/lib/scene/environment.js +1 -1
  237. package/lib/scene/fake-call-values.js +1 -1
  238. package/lib/scene/fog.d.ts +11 -4
  239. package/lib/scene/fog.js +8 -2
  240. package/lib/scene/frame-cameras.d.ts +19 -0
  241. package/lib/scene/frame-cameras.js +58 -0
  242. package/lib/scene/gltf.d.ts +32 -2
  243. package/lib/scene/gltf.js +78 -49
  244. package/lib/scene/grading.d.ts +2 -2
  245. package/lib/scene/grading.js +3 -3
  246. package/lib/scene/ktx2.d.ts +9 -1
  247. package/lib/scene/ktx2.js +3 -2
  248. package/lib/scene/level-rule.d.ts +120 -0
  249. package/lib/scene/level-rule.js +130 -0
  250. package/lib/scene/lines.d.ts +13 -17
  251. package/lib/scene/lines.js +3 -3
  252. package/lib/scene/lut.d.ts +1 -2
  253. package/lib/scene/lut.js +1 -2
  254. package/lib/scene/picks.d.ts +2 -2
  255. package/lib/scene/pointer-events.d.ts +4 -7
  256. package/lib/scene/post.d.ts +38 -43
  257. package/lib/scene/post.js +4 -1
  258. package/lib/scene/prefab.d.ts +7 -8
  259. package/lib/scene/prefab.js +7 -8
  260. package/lib/scene/property-animation.d.ts +1 -1
  261. package/lib/scene/property-animation.js +1 -1
  262. package/lib/scene/queries.d.ts +7 -13
  263. package/lib/scene/resources.d.ts +225 -254
  264. package/lib/scene/resources.js +179 -81
  265. package/lib/scene/scene.d.ts +149 -118
  266. package/lib/scene/scene.js +196 -98
  267. package/lib/scene/serial-loads.d.ts +29 -0
  268. package/lib/scene/serial-loads.js +68 -0
  269. package/lib/scene/shader-preloads.d.ts +34 -0
  270. package/lib/scene/shader-preloads.js +38 -0
  271. package/lib/scene/sprites.d.ts +14 -17
  272. package/lib/scene/sprites.js +5 -6
  273. package/lib/scene/textures.d.ts +11 -12
  274. package/lib/scene/textures.js +9 -10
  275. package/lib/scene/time-of-day.d.ts +3 -4
  276. package/lib/scene/time-of-day.js +2 -3
  277. package/lib/scene/vertex-draws.d.ts +5 -4
  278. package/lib/scene/vertex-draws.js +7 -5
  279. package/lib/shader-artifact.json +1 -0
  280. package/lib/shared/core.d.ts +5 -0
  281. package/lib/shared/core.js +1 -0
  282. package/lib/shared/import-once.d.ts +6 -0
  283. package/lib/shared/import-once.js +19 -0
  284. package/lib/shared/metrics.d.ts +38 -0
  285. package/lib/shared/metrics.js +62 -1
  286. package/lib/shared/run-task.js +7 -1
  287. package/lib/shared/task-pending.d.ts +12 -0
  288. package/lib/shared/task-pending.js +61 -1
  289. package/lib/shared/tasks.js +79 -32
  290. package/lib/shared/version.d.ts +17 -1
  291. package/lib/shared/version.js +19 -1
  292. package/lib/shared/wasm.d.ts +12 -4
  293. package/lib/shared/wasm.js +50 -27
  294. package/lib/shared/worker-start.d.ts +7 -0
  295. package/lib/shared/worker-start.js +27 -0
  296. package/lib/sketch/define-sketch.d.ts +35 -0
  297. package/lib/sketch/input.d.ts +2 -2
  298. package/lib/sketch/preset-check.d.ts +20 -6
  299. package/lib/sketch/preset-check.js +42 -17
  300. package/lib/sketch/quality.d.ts +69 -11
  301. package/lib/sketch/quality.js +54 -13
  302. package/lib/sketch/runner.d.ts +76 -9
  303. package/lib/sketch/runner.js +385 -52
  304. package/lib/sketch/ui.d.ts +5 -8
  305. package/lib/workers/probe-worker.d.ts +5 -0
  306. package/lib/workers/probe-worker.js +13 -4
  307. package/lib/workers/protocol.d.ts +61 -13
  308. package/lib/workers/protocol.js +4 -0
  309. package/lib/workers/render-worker.js +25 -4
  310. package/lib/workers/sketch-worker.js +104 -15
  311. package/package.json +2 -2
@@ -75,8 +75,9 @@ scene.instantiate(ship);
75
75
  | Triangle order | Reordered for the GPU's vertex cache, and vertices in the order that triangles use them | The GPU shades fewer vertices and reads memory in order |
76
76
  | Positions | 16-bit integers in 16,384 steps across each mesh, with `KHR_mesh_quantization`, unless the mesh's extras keep them as floats | Half the size of floats. A mesh 100 m long gets steps of 6 mm |
77
77
  | Normals and tangents | 8-bit integers | A quarter of the size. Directions stay within about 1 degree |
78
- | Texture coordinates | 16-bit integers when every value lies from 0 to 1, else floats | Values past 1 would need a texture transform per material |
79
- | Vertex colors, joint weights | 8-bit integers | Weights still add up to one |
78
+ | Texture coordinates | 16-bit integers when every value of the mesh and its levels of detail lies from 0 to 1, else floats in all of them | Values past 1 would need a texture transform per material. A level draws only when its vertices are stored as the mesh's are |
79
+ | Vertex colors | 8-bit integers when every value of the mesh and its levels of detail lies from 0 to 1, else floats in all of them | A quarter of the size |
80
+ | Joint weights | 8-bit integers | Weights still add up to one |
80
81
  | Indices | 16 bits when a mesh has at most 65,535 vertices | Half the size |
81
82
  | Buffers | Compressed with meshopt (`EXT_meshopt_compression`) | Smaller downloads. The engine decodes them on load, with no loss, and fetches the decoder only for such files |
82
83
 
@@ -95,11 +96,11 @@ The engine keeps each animation clip at one fixed rate of keys, so it never sear
95
96
  | Key times | One list of evenly spaced times per clip. The file's own spacing when every key lies on one grid of up to 30 keys a second, else 30 keys a second | The rate that the engine picks for the clip at load |
96
97
  | Rotations that change | One key per time, as 16-bit integers, compressed with meshopt's quaternion filter | A quarter of the size of floats. The engine keeps rotations in 16 bits as well |
97
98
  | Translations, scales and morph weights that change | One key per time, as 32-bit floats | glTF asks for floats. meshopt compresses them with no loss |
98
- | A track whose value never changes, or moves by under a millionth of its size | One key, at the clip's last time | The clip keeps its length, in null3D and in three.js. Exporters leave rounding noise of that size in tracks that do not move, and the engine counts such a track as constant in every file |
99
+ | A track whose value never changes, or moves by under a millionth of its size | One key, at the clip's last time | The clip keeps its length. Exporters leave rounding noise of that size in tracks that do not move, and the engine counts such a track as constant in every file |
99
100
  | Step tracks | Step tracks, with a key at each time | The engine steps at the same times |
100
101
  | Cubic spline tracks | Linear keys on the curve | The engine stores the same keys from the curve at load |
101
102
 
102
- The command drops no key and no track. A clip blends only where it has tracks, as in three.js, so a dropped track would change how the clip blends. Poses stay within the engine's tolerance of three.js. The KayKit Knight's skinning matrices differ by at most 7e-5, the same as from its source file.
103
+ The command drops no key and no track. A clip blends only where it has tracks, so a dropped track would change how the clip blends. Poses stay as accurate as the source file's: the KayKit Knight's skinning matrices from either file differ from three.js's by at most 7e-5.
103
104
 
104
105
  For the Knight and its 76 clips, the file's binary part falls from 838 KB to 405 KB after Brotli. On the engine's test page, its clips were ready in 8 ms on two job workers, against 16.5 ms for the source file.
105
106
 
@@ -191,7 +192,7 @@ A large mesh also gets pieces: `--lod` sorts each of its levels of 32,768 triang
191
192
 
192
193
  Over the 213 models of four Kenney city kits, `--lod` gives levels to 162. The 45 models of under 64 triangles get none, and so do six flat road pieces that cannot lose a quarter of their triangles.
193
194
 
194
- `assets.loadGltf` gives each mesh its levels. So every copy of the model and every instance batch of it picks its level in each frame, as [Levels of detail](../concepts/lod.md) explains. A skinned mesh draws its levels too, because the tool's levels name the mesh's own vertices and the skin moves them. three.js's `GLTFLoader` ignores `MSFT_lod`, and draws the full mesh.
195
+ `assets.loadGltf` gives each mesh its levels. So every copy of the model and every instance batch of it picks its level in each frame, as [Levels of detail](../concepts/lod.md) explains. A skinned mesh draws its levels too, because the tool's levels name the mesh's own vertices and the skin moves them. A glTF reader that ignores `MSFT_lod` draws the full mesh.
195
196
 
196
197
  ### Levels as separate downloads
197
198
 
@@ -351,7 +352,7 @@ FBX and MTL materials become glTF's metal-rough materials:
351
352
 
352
353
  Textures go into the file as PNG and JPEG images. TGA images become PNG. The command looks for each texture file where the model names it, then by its name in the model's folder. A missing file gets a note, and the material keeps its other maps.
353
354
 
354
- STL files hold facets with no other data. The command joins corners at the same place and leaves the facets' normals out, so glTF readers shade the faces flat, as the facets say. PLY and STL colors in bytes are sRGB, and the output stores them as linear values, as glTF requires. The engine does not draw glTF points yet, so a PLY point cloud loads with nothing to draw. three.js draws it.
355
+ STL files hold facets with no other data. The command joins corners at the same place and leaves the facets' normals out, so glTF readers shade the faces flat, as the facets say. PLY and STL colors in bytes are sRGB, and the output stores them as linear values, as glTF requires. The engine does not draw glTF points yet, so a PLY point cloud loads with nothing to draw.
355
356
 
356
357
  | Option | Effect | Without it |
357
358
  | --- | --- | --- |
@@ -384,7 +385,7 @@ const brick = materials.standard({ metalnessRoughnessMap: orm, aoMap: orm });
384
385
 
385
386
  ## Normal maps from bump maps
386
387
 
387
- A bump map gives each texel a height. A normal map gives the slope that the heights make, which the GPU reads with no extra work. The engine draws bump maps too ([materials](../api/materials.md)), at three texture reads per pixel, and a normal map saves those. `assets normal-from-bump` makes one from a bump map, such as a three.js material's `bumpMap`:
388
+ A bump map gives each texel a height. A normal map gives the slope that the heights make, which the GPU reads with no extra work. The engine draws bump maps too ([materials](../api/materials.md)), at three texture reads per pixel, and a normal map saves those. The `assets normal-from-bump` command makes one from a bump map, such as a material's `bumpMap`:
388
389
 
389
390
  ```sh
390
391
  bunx @null3d/cli assets normal-from-bump textures/stone_bump.png textures/stone_normal.ktx2 --scale 2
@@ -392,13 +393,13 @@ bunx @null3d/cli assets normal-from-bump textures/stone_bump.png textures/stone_
392
393
 
393
394
  White stands high and black low. The height map is a PNG, JPEG or TGA image, read from its red channel. A 16-bit PNG keeps its full depth, so gentle slopes do not show steps. The normal map follows glTF: X to the right and Y up the image.
394
395
 
395
- `--scale` works as three.js's `bumpScale`. At 1, a slope of the whole height range per texel tilts the surface 45 degrees. three.js measures the slope per pixel of the screen, so its bumps look stronger when a texel covers less than a pixel. The normal map keeps the strength that three.js shows where one texel covers one pixel. Give the three.js material's `bumpScale` as `--scale`, and check the look up close.
396
+ `--scale` works as a material's `bumpScale`. At 1, a slope of the whole height range per texel tilts the surface 45 degrees. A bump map measures its slope per pixel of the screen, so its bumps look stronger when a texel covers less than a pixel. The normal map keeps the strength that the bump map shows where one texel covers one pixel. Give the material's `bumpScale` as `--scale`, and check the look up close.
396
397
 
397
398
  The map tiles: the texels at each edge take their neighbors from the opposite edge. `--clamp` stops that, for a map that does not tile.
398
399
 
399
400
  | Option | Effect | Without it |
400
401
  | --- | --- | --- |
401
- | `--scale <number>` | The strength of the slopes, as three.js's `bumpScale` | 1 |
402
+ | `--scale <number>` | The strength of the slopes, as a material's `bumpScale` | 1 |
402
403
  | `--clamp` | The edge texels take no neighbors from the opposite edge | The map tiles |
403
404
  | `--max-texture-size <pixels>` | The largest side of a `.ktx2` texture: a power of two up to 2048 | 2048 |
404
405
 
@@ -438,11 +439,11 @@ The output is one KTX2 file:
438
439
 
439
440
  Both formats filter on every GPU the engine supports. `rgb9e5ufloat` stores three 9-bit values with one shared exponent, in half the memory of `rgba16float`. In tests, the two formats differed by under a tenth of a step of 255 after tone mapping. Both hold light up to about 65,000, and the command clamps brighter texels, such as the middle of an unclipped sun.
440
441
 
441
- three.js prefilters an HDR file in the browser on every visit, with `PMREMGenerator`. The command does it once, before you publish. Your page then downloads the filtered file and does no work before it draws. The same file gives the same bytes on every computer.
442
+ The command filters the image once, before you publish. Your page then downloads the filtered file and does no work before it draws. The same file gives the same bytes on every computer.
442
443
 
443
444
  `assets.loadEnvironment` also takes the HDR file itself, for maps that change, such as files that users upload. A worker reads the file, and the GPU filters it at load with this command's steps, so the two maps match. [Assets](../api/assets.md#environments) gives what it reads and costs.
444
445
 
445
- `--builtin room` writes the room that three.js's `RoomEnvironment` builds: a white room with six boxes, six glowing panels and one point light. It blurs the room by 0.04 radians first, as three.js's examples do with `fromScene(room, 0.04)`. The engine makes the same room on the GPU when `assets.builtinEnvironment('room')` asks for it, so its package ships no file. The engine's tests compare its map with this command's.
446
+ `--builtin room` writes the engine's built-in room: a white room with six boxes, six glowing panels and one point light. It blurs the room by 0.04 radians first, which softens the edges of the panels' reflections. The engine makes the same room on the GPU when `assets.builtinEnvironment('room')` asks for it, so its package ships no file. The engine's tests compare its map with this command's.
446
447
 
447
448
  A sketch loads the file with `assets.loadEnvironment`, and lights the scene with it through `scene.setEnvironment`:
448
449
 
@@ -481,7 +482,7 @@ The preview serves HTTPS by default. A secure origin is what makes WebGPU, and s
481
482
 
482
483
  The empty variable makes a full set, because the recording reads every word that the pages ask for. Without it, the build narrows to the list that a recorded run wrote.
483
484
 
484
- The recorder writes `examples/shader-permutations.txt`, and `bun run examples:build` reads it. The recorder runs from a checkout of this repository, because it drives a browser through the repository's own page list and browser launcher. A project outside the repository runs it from such a checkout and names its pages with one `--page <path>` for each, instead of `--pages demos`.
485
+ The recorder writes `examples/shader-permutations.txt`, and `bun run examples:build` reads it. Its `--page-root` names the address that the pages sit under. Use `/` for a preview of the built site, or `/examples/` for this repository's own dev server. A demo that draws more in a state its controls cannot reach enters that state through the recorder's own query. The island's pages record with its highest walker count. The recorder runs from a checkout of this repository, because it drives a browser through the repository's own page list and browser launcher. A project outside the repository runs it from such a checkout and names its pages with one `--page <path>` for each, instead of `--pages demos`.
485
486
 
486
487
  A game page that starts its engine on a click needs `--live` pages and `--click <selector>`, such as `--click "#play"`. A production build of the engine folder ignores the URL switches. Record against a development build of that folder (`vite build --mode development`). The [deterministic simulation guide](deterministic-simulation.md#a-production-build-of-a-games-engine-files) gives the full sequence.
487
488
 
@@ -1,163 +1,148 @@
1
1
  ---
2
2
  id: guides/audio
3
- title: Audio with Web Audio
3
+ title: Sound in a scene
4
4
  status: experimental
5
5
  since: "0.1"
6
- summary: "Why audio stays on the page; sending positions from the sketch."
6
+ summary: "Sound that follows the scene with @null3d/sound: beds whose level the scene sets, sources at places, groups of many sources, and events."
7
7
  ---
8
8
 
9
- # Audio with Web Audio
9
+ # Sound in a scene
10
10
 
11
11
  > Roadmap step 0.1, first released in null3D 0.1.0. The API is experimental, so it can still change between versions.
12
12
 
13
13
  ```mermaid
14
14
  flowchart LR
15
- sketch["Sketch worker<br/>writes positions<br/>in each frame"] -- "a shared array,<br/>sent once" --> page["Page's main thread<br/>moves the listener<br/>and the sounds"]
16
- sketch -- "one message<br/>for each event" --> page
17
- page --> audio["Web Audio<br/>plays the sounds"]
15
+ scene["The sketch<br/>knows the scene"] -- "level, place, rate<br/>and tone of each sound" --> sound["@null3d/sound"]
16
+ sound --> bed["Beds:<br/>sea, wind, rain"]
17
+ sound --> spot["Sources at places:<br/>a waterfall"]
18
+ sound --> group["Groups:<br/>the cars of a street"]
19
+ sound --> shot["Events:<br/>thunder, a bounce"]
18
20
  ```
19
21
 
20
- null3D has no audio API of its own. Use the browser's Web Audio API on the page. This page shows how the sketch tells the page where the sounds are.
22
+ A scene sounds right when its sounds follow what the camera sees. The sea grows louder as the camera nears the shore, and a passing car's engine moves from one ear to the other. The sketch knows all of that, so the sketch drives the sound. [Sound (@null3d/sound)](../api/sound.md) plays it on the page with the browser's audio, and this guide shows the four kinds of sound a scene needs.
21
23
 
22
- ## Why audio stays on the page
24
+ ## Set up the sound
23
25
 
24
- A worker cannot create an `AudioContext`: the browser offers Web Audio on the page's main thread only. So the page plays the sound, and the sketch tells it where each sound is. The browser mixes the sound on a thread of its own, so the page's audio code has little to do. It moves the listener and the sounds to where the sketch put them.
25
-
26
- The sketch tells the page two kinds of facts, in two ways:
27
-
28
- | Fact | How it travels | Examples |
29
- | --- | --- | --- |
30
- | Positions that change in each frame | A shared array, which the sketch sends once | The camera, the engine of a moving car |
31
- | Events | One message for each event | A footstep or an explosion |
32
-
33
- ## The sketch: write positions into a shared array
34
-
35
- This sketch flies a drone in a circle in front of the camera. In each frame it writes the camera's position and direction, and the drone's position, into an array that the page also reads. Once per lap, it asks the page for a chime at the drone.
26
+ The sketch makes the sounds with `createSound`, and the page connects with `connectSound`. Call `update` once a frame, in `onLateUpdate`.
36
27
 
37
28
  ```ts
38
29
  // sketch.ts
39
- import { defineSketch, quat, vec3 } from '@null3d/engine';
40
-
41
- const AHEAD = [0, 0, -1]; // a camera looks down its own -Z axis
42
- const UP = [0, 1, 0];
43
-
44
- export default defineSketch(({ scene, geometry, materials, page, time }) => {
45
- const camera = scene.createPerspectiveCamera({ fov: 60, position: [0, 2, 8], target: [0, 1, 0] });
46
- scene.setActiveCamera(camera);
47
- scene.createDirectionalLight({ direction: [-1, -2, -1], intensity: 3 });
48
- scene.createAmbientLight({ intensity: 0.4 });
49
- const drone = scene.createMesh({
50
- mesh: geometry.sphere({ radius: 0.3 }),
51
- material: materials.standard({ color: '#e8554e' }),
52
- dynamic: true,
53
- });
54
-
55
- // 12 numbers for the page: the listener's position, forward and up, then the drone's position.
56
- const bytes = 12 * Float32Array.BYTES_PER_ELEMENT;
57
- const positions = new Float32Array(
58
- crossOriginIsolated ? new SharedArrayBuffer(bytes) : new ArrayBuffer(bytes),
59
- );
60
- const listener = positions.subarray(0, 3);
61
- const forward = positions.subarray(3, 6);
62
- const up = positions.subarray(6, 9);
63
- const source = positions.subarray(9, 12);
64
- page.post('audio', positions); // sent once, in the setup
65
-
66
- const turn = quat.create();
67
- let laps = 0;
30
+ import { defineSketch } from '@null3d/engine';
31
+ import { createSound } from '@null3d/sound';
32
+
33
+ export default defineSketch((ctx) => {
34
+ const camera = ctx.scene.createPerspectiveCamera({ position: [0, 2, 10], target: [0, 1, 0] });
35
+ ctx.scene.setActiveCamera(camera);
36
+ const sound = createSound(ctx, { listener: camera });
37
+ // ... the sounds below ...
68
38
  return {
69
- onUpdate() {
70
- const angle = time.now * 0.8;
71
- drone.setPosition(Math.cos(angle) * 4, 1, Math.sin(angle) * 4);
72
- drone.getPosition(source);
73
- camera.getPosition(listener);
74
- camera.getRotation(turn);
75
- vec3.transformQuat(forward, AHEAD, turn);
76
- vec3.transformQuat(up, UP, turn);
77
-
78
- if (angle / (Math.PI * 2) >= laps + 1) {
79
- laps++;
80
- page.post('chime', [source[0], source[1], source[2]]); // one message for each event
81
- }
39
+ onLateUpdate() {
40
+ sound.update();
82
41
  },
83
42
  };
84
43
  });
85
44
  ```
86
45
 
87
- - In the threaded build, the page is cross-origin isolated, and the array lives in a `SharedArrayBuffer`. The page and the sketch worker then read and write the same memory, and no message travels in each frame.
88
- - In the single-threaded build, the sketch runs on the page's thread, and messages are not copied. So a plain `ArrayBuffer` reaches the page as the same array. [Messages between sketch and page](../api/page.md) explains both builds.
89
- - The `subarray` views are made once, in the setup. `onUpdate` writes through them and allocates nothing.
90
- - `getPosition` and `getRotation` give values relative to the parent. This camera has no parent. For a camera under a parent, use `getWorldPosition` and `getWorldQuaternion`, which give the world transform of the last frame.
46
+ ```ts
47
+ // page.ts: the sound starts on the user's first click, tap or key.
48
+ import { connectSound } from '@null3d/sound/page';
49
+ const sound = connectSound(engine, { startOnInput: true });
50
+ ```
51
+
52
+ A sound button suits a page that people browse. Call `sound.start()` from its click handler, and `sound.setMuted` to mute it after that.
91
53
 
92
- ## The page: move the listener and the sounds
54
+ ## Beds whose level the scene sets
93
55
 
94
- The page receives the array in the `onSketchMessage` option of `createEngine`, which hears the sketch's messages from the start of its setup. In each display frame, it moves the listener and the drone's hum.
56
+ A bed is a sound that fills the space, such as the sea, wind or rain. Its level comes from a measure of the scene where the camera stands. That might be the distance to the shore, the trees around the camera, or the wind's speed. Make it with no `near` and no `far`, and set its level in each frame.
95
57
 
96
58
  ```ts
97
- // page.ts
98
- import { createEngine } from '@null3d/engine';
99
-
100
- let positions: Float32Array | undefined; // the sketch's array
101
- let audio: AudioContext | undefined;
102
- let hum: PannerNode | undefined; // follows the drone
103
-
104
- // Browsers play sound only after the user interacts with the page.
105
- addEventListener('pointerdown', () => {
106
- audio = new AudioContext();
107
- hum = new PannerNode(audio, { panningModel: 'HRTF', refDistance: 2 });
108
- hum.connect(audio.destination);
109
- const motor = new OscillatorNode(audio, { type: 'sawtooth', frequency: 110 });
110
- motor.connect(new GainNode(audio, { gain: 0.1 })).connect(hum);
111
- motor.start();
112
- }, { once: true });
113
-
114
- /** Plays a short tone at a point in the scene. */
115
- function chime([x, y, z]: number[]) {
116
- if (!audio) return;
117
- const panner = new PannerNode(audio, { panningModel: 'HRTF', positionX: x, positionY: y, positionZ: z });
118
- panner.connect(audio.destination);
119
- const tone = new OscillatorNode(audio, { frequency: 880 });
120
- tone.connect(panner);
121
- tone.start();
122
- tone.stop(audio.currentTime + 0.2);
123
- }
59
+ const wind = sound.loop({ file: '/sounds/wind.mp3', positional: false });
60
+ const at = new Float64Array(3);
61
+ const air = new Float32Array(3);
62
+ // In onUpdate: louder and brighter as the wind blows harder and the camera climbs.
63
+ camera.getWorldPosition(at);
64
+ windField.sample(at[0], at[1], at[2], air);
65
+ const speed = Math.hypot(air[0], air[2]);
66
+ const height = Math.min(1, Math.max(0, (at[1] - groundHeight(at[0], at[2])) / 60));
67
+ wind.setLevel(Math.min(1, speed / 10) * (0.4 + 0.6 * height));
68
+ wind.setTone(0.4 + 0.6 * Math.min(1, speed / 12));
69
+ ```
124
70
 
125
- await createEngine({
126
- canvas: document.querySelector('canvas')!,
127
- sketch: new URL('./sketch.ts', import.meta.url),
128
- onSketchMessage(name, data) {
129
- if (name === 'audio') positions = data as Float32Array;
130
- if (name === 'chime') chime(data as number[]);
131
- },
132
- });
71
+ A bed that comes from one side can still have a place. The sea is louder toward the water. So place it out to sea from the camera, along the way the shore faces, and keep it positional. Its level still comes from the sketch.
72
+
73
+ ## Sources at places
74
+
75
+ A source at a place falls off with distance by itself. Give it `near`, the distance within which it plays at its full level, and `far`, where it has faded out. A waterfall heard across a valley might take `near: 6` and `far: 200`. With `far`, the sound also loses its highs with distance, as real sounds do.
76
+
77
+ Choose `far` as the distance at which a listener would stop hearing the thing, and `near` as the distance at which it is as loud as it gets. The ranges differ by kind:
78
+
79
+ | The source | `near` | `far` |
80
+ | --- | --- | --- |
81
+ | A stream, a fountain or water over stones | 3 | 50 |
82
+ | A bird or a voice nearby | 2 | 60 |
83
+ | A car or a van beside its road | 5 | 120 |
84
+ | A bus or a lorry | 8 | 200 |
85
+ | A crowd or a street of people | 5 | 150 |
86
+ | A waterfall, which is loud and carries | 5 | 400 |
87
+ | The breakers along a beach | 30 | 400 |
88
+ | The open sea heard from shore | 40 | 300 |
89
+ | Thunder, heard across a city | 100 | 4000 |
90
+
91
+ A source whose `far` reaches a kilometre is heard from the whole map, and a scene's opening view roars when nothing stands near it.
133
92
 
134
- // Once per display frame, move the listener and the hum to where the sketch put them.
135
- function follow() {
136
- const p = positions;
137
- if (p && audio && hum) {
138
- audio.listener.setPosition(p[0], p[1], p[2]);
139
- audio.listener.setOrientation(p[3], p[4], p[5], p[6], p[7], p[8]);
140
- hum.positionX.value = p[9];
141
- hum.positionY.value = p[10];
142
- hum.positionZ.value = p[11];
143
- }
144
- requestAnimationFrame(follow);
93
+ ```ts
94
+ const fall = sound.loop({ file: '/sounds/waterfall.mp3', near: 6, far: 200 });
95
+ fall.setPosition(lip[0], lip[1] - drop, lip[2]);
96
+ ```
97
+
98
+ A long source, such as a stream, has a place that moves with the camera: the nearest point of its course. Work that point out in each frame and move the source there.
99
+
100
+ ## Groups of many sources
101
+
102
+ A street of cars, a swarm of bees or the traffic of a city has more sources than a browser can mix. A group plays one file from each member, and gives a few voices to the loudest members where the listener stands. A voice that moves to another member fades out first.
103
+
104
+ ```ts
105
+ const cars = sound.group({ file: '/sounds/car.mp3', count: 40, voices: 6, near: 4, far: 150 });
106
+ // In onUpdate: each car's place, and its engine's pitch from its speed.
107
+ for (let i = 0; i < 40; i++) {
108
+ cars.setPosition(i, x[i], y[i], z[i]);
109
+ cars.setRate(i, 0.8 + speed[i] / 30);
145
110
  }
146
- requestAnimationFrame(follow);
147
111
  ```
148
112
 
149
- - The browser does not let a page start sound before the user clicks, taps or presses a key. So the page makes its `AudioContext` on the first press.
150
- - Firefox has no `positionX` on the listener, so the example uses `setPosition` and `setOrientation`, which every browser has. `PannerNode` has `positionX` in every browser.
151
- - The page reads the array at any moment, so it can read some numbers from one frame and some from the next. That difference is too small to hear.
152
- - The oscillators stand in for recorded sounds. For a recorded sound, decode the file once with `decodeAudioData`. Then play it through an `AudioBufferSourceNode` for each event.
113
+ A sketch that keeps its places in one array of three numbers each copies them in one call: `cars.positions.set(places)`. A member whose level is 0, such as a parked car, takes no voice.
114
+
115
+ ## Events
116
+
117
+ A shot plays its file once for each event, such as thunder, a door or a bounce. A physics library's contact events suit it ([Using a physics library](physics.md)).
118
+
119
+ ```ts
120
+ const bounce = sound.shot({ file: '/sounds/bounce.mp3', voices: 4, near: 2, far: 60 });
121
+ // In the contact handler: a harder hit is louder.
122
+ bounce.play(x, y, z, Math.min(1, impact / 8));
123
+ ```
124
+
125
+ ## A mix that works
126
+
127
+ - Normalize the files to one loudness, so a level of 1 means the same for each. The sample loops are normalized to -20 LUFS.
128
+ - Keep beds below the sources that tell a story. The sea at 0.6 and a passing car at 1 lets the car stand out.
129
+ - Tie a sound to the motion that makes it. Rustling leaves follow the wind's speed and the trees near the camera, and an engine's rate follows its car's speed.
130
+ - Tie a bed's level to the scene. A level that follows the distance to the shore never jumps when the camera cuts.
131
+ - Give every source a reach that matches what makes it. Waves are heard near water, and an engine near its own car. A bed that carries a thousand meters makes an opening view over open water roar. A scene's first frame is the test: where nothing makes a sound, the mix is silent.
132
+ - Never write a level as a step. Move it along a curve that passes through its neighbors, so a car that stops fades through silence rather than cutting off at a threshold. Let the frame's own time smooth what the scene writes.
133
+ - Count the voices of a group. They add as power, so three points at full level sound about five decibels louder than a loop's one file. Give a group's points a lower level than a loop's.
134
+ - Write massed ambience as one loop scaled by density, such as a wood's leaves from the canopy around the camera. One source for each of fifty trees adds up in a way no listener calls rustling. A density that levels off cannot pile up.
135
+ - Check the mix at fixed camera places, not by ear alone: the opening pose, the shore, a town square and the climb. The opening should be silent, and each place should lead with the sound its view shows. No level should move faster between frames than a listener would expect.
136
+
137
+ ## How the sound reaches the speakers
153
138
 
154
- ## Pauses and hidden pages
139
+ The browser offers its audio on the page's main thread only, and the sketch runs in a worker. The add-on bridges the two with a table that the page shares. The sketch writes each sound's values there, and a mixer on the browser's audio thread reads them and drives each voice. Where the page shares its memory with its workers, no message travels in a frame. The page's thread then does no work while the sounds play. When the engine pauses or the page is hidden, the sketch's frames stop, and the sound fades out with them.
155
140
 
156
- `engine.setPaused(true)` stops the sketch's frames, but not the sound. Call `audio.suspend()` beside it, and `audio.resume()` when the engine resumes. The browser stops the engine's frames while the page is hidden, and Web Audio keeps playing then too. To mute a hidden page, suspend the context in a `visibilitychange` handler.
141
+ The page can still play its own sounds with Web Audio, such as music or the clicks of its buttons. Such sounds belong to the page, so they need no add-on.
157
142
 
158
143
  ## Related pages
159
144
 
160
- - [Messages between sketch and page](../api/page.md): `page.post`, `onSketchMessage` and the single-threaded build.
145
+ - [Sound (@null3d/sound)](../api/sound.md): every call, the distances, the voices and the costs.
146
+ - [Messages between sketch and page](../api/page.md): messages for events that the page shows.
161
147
  - [Using a physics library](physics.md): events from a physics world, such as a bounce.
162
- - [Objects and transforms](../api/objects.md): `getPosition`, `getRotation` and their world forms.
163
- - [Hosting and cross-origin isolation](../getting-started/hosting.md): when a page gets shared memory.
148
+ - [Hosting and cross-origin isolation](../getting-started/hosting.md): when a page shares its memory.
@@ -117,5 +117,5 @@ plain metallic paint.
117
117
  - [Surface functions](../shaders/surface-functions.md): the surface record that the paint returns.
118
118
  - [A material's own lobe](../shaders/surface-functions.md#a-materials-own-lobe): the hook that the
119
119
  glints use.
120
- - [The Showroom demo](https://github.com/null3d-engine/null3d/tree/main/examples/coat-and-sheen): a
120
+ - [The Showroom to street demo](https://github.com/null3d-engine/null3d/tree/main/examples/showroom): a
121
121
  car that uses the paint.
@@ -64,8 +64,8 @@ Decide how long a visitor waits for the scene, and count it from the moment the
64
64
  - Keep the waiting state short. Largest Contentful Paint, the time until the largest content appears, should come within 2.5 seconds. Measure your own cold load on a slow connection before you pick a deadline.
65
65
  - Never hide the page's text while the scene loads. Where a rule must hide content, put it inside `@media (scripting: enabled)`, so a page without JavaScript still shows everything.
66
66
  - Show no loading indicator for the first half second or so. A fast load then never flashes one.
67
- - Never let a progress value move back. Keep the largest value shown so far.
68
- - Reveal the canvas only when `engine.firstFrame` resolves. Before that, it shows nothing.
67
+ - Within a phase, never let a progress value move back. Keep the largest value shown so far in that phase. When a new phase starts, name it beside its number ([Loading screens](loading-screens.md#show-progress-on-the-page)).
68
+ - Reveal the canvas only when `engine.firstFrame` resolves. Before that, it shows nothing. It rejects when drawing stops before the first frame, and the page then keeps its poster.
69
69
  - Chromium browsers report `navigator.connection.saveData`. When it is true, go straight to the late state.
70
70
 
71
71
  ```ts
@@ -75,8 +75,12 @@ const root = document.documentElement;
75
75
  setTimeout(() => {
76
76
  if (!root.classList.contains('ready')) root.classList.add('late');
77
77
  }, Math.max(0, DEADLINE_MS - performance.now()));
78
- await engine.firstFrame;
79
- root.classList.add('ready'); // CSS fades the canvas in over the poster
78
+ try {
79
+ await engine.firstFrame;
80
+ root.classList.add('ready'); // CSS fades the canvas in over the poster
81
+ } catch {
82
+ // Drawing stopped before the first frame: the onFailure handler above keeps the poster.
83
+ }
80
84
  ```
81
85
 
82
86
  For a game, the late state has no page content to show. There it changes the message, and opens the menus and settings that do not need the scene.
@@ -174,7 +178,7 @@ return {
174
178
  | Views of a single-page app | The running engine | `engine.detach()` and `engine.attach(element)`: [Architecture](../concepts/architecture.md) |
175
179
  | Back and forward | The browser's back/forward cache | Listen for `pagehide`, never `unload`, and do not send `Cache-Control: no-store` on the page |
176
180
 
177
- Browsers decide whether they can keep a page with a running engine in the back/forward cache. Build the page so that a full reload works too. [Caches between visits](../getting-started/hosting.md#caches-between-visits) shows every cache that a repeat visit uses.
181
+ Browsers decide whether they can keep a page with a running engine in the back/forward cache. Build the page so that a full reload works too. On phones and tablets the engine gives its GPU back while the page sits in that cache. It builds the scene's GPU objects again when the page shows ([When the GPU goes away](../concepts/backends.md#when-the-gpu-goes-away)). [Caches between visits](../getting-started/hosting.md#caches-between-visits) shows every cache that a repeat visit uses.
178
182
 
179
183
  A sketch that generates data, such as a terrain or a scatter of objects, can keep it in the engine's cache of derived data. The call `assets.cache(name, version)` gives the sketch a namespace of it ([Caching](../api/assets.md#the-cache-of-derived-data)). Follow these rules:
180
184
 
@@ -218,7 +222,7 @@ else {
218
222
  write(String(Date.now()));
219
223
  addEventListener('pagehide', () => write(null));
220
224
  // ... createEngine, then:
221
- await engine.firstFrame;
225
+ await engine.firstFrame.catch(() => {}); // a start that failed cleanly is no crash
222
226
  setTimeout(() => write(null), 5000);
223
227
  }
224
228
  ```
@@ -71,8 +71,9 @@ The effect can also call these functions:
71
71
  | --- | --- |
72
72
  | `effectColor(uv: vec2f) -> vec4f` | The image's color at `uv`, read with a linear filter. Places outside the image read its edge. |
73
73
  | `effectPixel(pixel: vec2i) -> vec4f` | The color of one pixel, counted from the top left. A pixel outside the image reads the nearest one inside. |
74
+ | `effectBloom(uv: vec2f) -> vec3f` | The glow at `uv` of the bloom chain's level that the effect's `bloomLevel` names, as linear HDR color. A level that the chain does not draw reads black ([Custom effects](../api/post.md#custom-effects)). |
74
75
  | `effectDepth(uv: vec2f) -> f32` | The scene's depth at `uv`: 1 at the camera's near plane, 0 at its far plane, and 0 where nothing drew. |
75
- | `effectViewPosition(uv: vec2f) -> vec3f` | The position of the surface at `uv` in view space. Its z is negative in front of the camera, as in three.js. |
76
+ | `effectViewPosition(uv: vec2f) -> vec3f` | The position of the surface at `uv` in view space. Its z is negative in front of the camera. |
76
77
  | `effectDistance(uv: vec2f) -> f32` | How far in front of the camera the surface at `uv` lies, in world units. |
77
78
  | `effectInputSize() -> vec2f` | The image's size in pixels. In an effect it equals `input.size`; a [full-screen pass](#full-screen-passes) of another size needs it. |
78
79
  | `effectPassUv(uv: vec2f) -> vec2f` | The coordinates in a render pass's texture of the image's place `uv`. A pass texture holds its bottom row first, so `v` turns around. |
@@ -233,7 +234,7 @@ A debug view, such as `debug.view('normals')`, turns effects off while it draws.
233
234
  A custom tone curve replaces the built-in curves (`'agx-punchy'`, the default, and `'agx'`, `'aces'`, `'neutral'` and `'none'`). Its WGSL declares one function, and `post.set` takes it as `toneMapping`:
234
235
 
235
236
  ```ts
236
- // Reinhard's curve, as three.js's ReinhardToneMapping draws it.
237
+ // Reinhard's tone curve.
237
238
  const reinhard = /* wgsl */ `
238
239
  fn toneCurve(color: vec3f) -> vec3f {
239
240
  return color / (vec3f(1.0) + color);
@@ -252,7 +253,7 @@ post.set({ toneMapping: 'aces' });
252
253
 
253
254
  ## Render to a texture
254
255
 
255
- A scene pass draws the scene from a camera of your own into a texture, as three.js's `WebGLRenderTarget` with `renderer.setRenderTarget` does. `textures.fromPass` gives the texture to any material or sprite.
256
+ A scene pass draws the scene from a camera of your own into a texture. `textures.fromPass` gives the texture to any material or sprite.
256
257
 
257
258
  ```mermaid
258
259
  flowchart LR
@@ -308,7 +309,7 @@ In [hold mode](testing.md#hold-mode) every pass draws in every frame, whatever i
308
309
 
309
310
  ### What a scene pass draws
310
311
 
311
- A scene pass draws with the scene's materials, the sun and its shadows where the camera's shadow cascades reach. It draws the ambient and hemisphere lights, the environment's light and the fog. It also draws the point and spot lights that its camera sees. It draws the scene's background behind them, the sky included, as a three.js render target shows `scene.background`. With a `clearColor` the texture clears to that color and shows no background, which suits a minimap. A pass draws no ambient occlusion: three.js draws it as a post pass over the canvas, so its render targets have none either.
312
+ A scene pass draws with the scene's materials, the sun and its shadows where the camera's shadow cascades reach. It draws the ambient and hemisphere lights, the environment's light and the fog. It also draws the point and spot lights that its camera sees. It draws the scene's background behind them, the sky included. With a `clearColor` the texture clears to that color and shows no background, which suits a minimap. A pass draws no ambient occlusion.
312
313
 
313
314
  A point or spot light casts its shadow in a pass when the camera's view gives it a shadow. The engine gives shadows only to the lights that the camera sees. So a light that only the pass sees lights the pass without a shadow. Reflection passes draw these lights the same way. A pass that sees a point or spot light keeps its own list of lights, as the camera's view does. The list takes under 1 MB of memory. A pass that sees none keeps no list.
314
315
 
@@ -316,7 +317,7 @@ The texture holds linear color after the exposure, so a material that shows it g
316
317
 
317
318
  ## Reflections
318
319
 
319
- A reflection pass draws the camera's view mirrored across a plane into a texture, as three.js's `Reflector` add-on does. Everything below the plane is clipped. A custom material reads the texture where its surface shows on the screen, so water and polished floors reflect what stands on them. [Render graph API](../api/render.md#reflection-passes) lists the options, and [Surface functions](../shaders/surface-functions.md#reflections) the WGSL side.
320
+ A reflection pass draws the camera's view mirrored across a plane into a texture. Everything below the plane is clipped. A custom material reads the texture where its surface shows on the screen, so water and polished floors reflect what stands on them. [Render graph API](../api/render.md#reflection-passes) lists the options, and [Surface functions](../shaders/surface-functions.md#reflections) the WGSL side.
320
321
 
321
322
  ```ts
322
323
  const pass = render.addPass({ kind: 'reflection', writes: 'water', plane: { point: [0, 0, 0] } });
@@ -326,7 +327,7 @@ const water = materials.shader({ wgsl: waterWgsl, textures: { mirror: textures.f
326
327
  - The pass follows the active camera. The quality preset sets its size: half the render size each way on Medium and High.
327
328
  - The surface function puts the pass's color in the surface's `reflection`. The engine's lighting then weighs it with the material's Fresnel, so water reflects little straight down and much at a low angle.
328
329
  - `scale: 1` gives a sharp mirror. `every: 2` draws the reflection in every other frame, for a camera that moves slowly.
329
- - A reflection draws the scene's background, the sun's light and shadows, and the point and spot lights that it sees. It draws no ambient occlusion, as three.js's render targets draw none.
330
+ - A reflection draws the scene's background, the sun's light and shadows, and the point and spot lights that it sees. It draws no ambient occlusion.
330
331
 
331
332
  ### A water recipe
332
333
 
@@ -417,7 +418,7 @@ surface.setRotationEuler(-Math.PI / 2, 0, 0);
417
418
  - `ripple` sets how far the waves tilt the normal. The tilt bends the reflection and the sun's highlights.
418
419
  - The foam hides the reflection where it lies, through the reflection's share in `a`.
419
420
  - The water is opaque, so the bed does not show through it. The shallow tint stands in for the bed's color.
420
- - Without a height map of the bed, a blended sheet reads the depth of the opaque scene behind it with `sceneInputs: ['sceneDepth']`. The water's depth along the view ray is the gap between the sheet and the geometry behind the pixel. Convert the pixel's own depth to a distance with the camera's range in `engine_frame.camera_range`, then subtract it from `sceneDistance(uv)`. Fade the water's alpha to zero over the last centimeters of the gap. The water then thins and foams against the bank, so its shore ends softly. Such a sheet takes up to seven textures of its own, so this recipe's mirror and a foam map join it. [Materials](../api/materials.md#the-scene-behind-a-surface) shows the options.
421
+ - Without a height map of the bed, a blended sheet reads the depth of the opaque scene behind it with `sceneInputs: ['sceneDepth']`. The water's depth along the view ray is the gap between the sheet and the geometry behind the pixel. Convert the pixel's own depth to a distance with the camera's range in `engine_frame.camera_range`, then subtract it from `sceneDistance(uv)`. Fade the water's alpha to zero over the last centimeters of the gap. The water then thins and foams against the bank, so its shore ends softly. Such a sheet takes up to 6 textures of its own, as every custom material does. So this recipe's mirror and a foam map join it. [Materials](../api/materials.md#the-scene-behind-a-surface) shows the options.
421
422
 
422
423
  - Waves that move the surface's vertices need `setBounds`, as [Culling](../concepts/culling.md) explains. The reflection's plane stays flat, which suits small waves.
423
424
 
@@ -466,7 +467,7 @@ A pass that names no input image is placed before the camera's passes. A chain o
466
467
 
467
468
  ### A soft outline glow
468
469
 
469
- three.js's `OutlinePass` draws a soft glow around outlined objects. null3D's outline draws a crisp line ([Outlines](../api/post.md#outlines)), and a full-screen pass and an effect draw the glow. `@null3d/three-compat`'s `createOutlinePass` builds this shape, with three.js's glow, pulse and blur settings ([three.js compatibility](../api/three-compat.md)); the recipe below shows what it does.
470
+ The built-in outline draws a crisp line ([Outlines](../api/post.md#outlines)). A full-screen pass and an effect add a soft glow around it. The `@null3d/three-compat` add-on builds this shape with `createOutlinePass`, which takes settings for the glow, a pulse and the blur ([its API page](../api/three-compat.md)). The recipe below shows what it does.
470
471
 
471
472
  ```ts
472
473
  const glowFromMask = /* wgsl */ `
@@ -8,7 +8,7 @@ summary: "WGSL in sketch code; shader errors; surface functions; full shaders; u
8
8
 
9
9
  # Custom shaders
10
10
 
11
- > Roadmap step 0.1, first released in null3D 0.1.0. Step 0.2 adds typed uniforms, textures and hot reload. The API is experimental, so it can still change between versions. Custom materials with surface functions, vertex offsets, uniforms, textures and full shaders are built, and so is hot reload on the dev server.
11
+ > Roadmap step 0.1, first released in null3D 0.1.0. The API is experimental, so it can still change between versions. Custom materials with surface functions, vertex offsets, uniforms, textures and full shaders are built, and so is hot reload on the dev server.
12
12
 
13
13
  ```mermaid
14
14
  flowchart LR
@@ -136,10 +136,13 @@ The plugin puts the compiled shader where the literal was. Your code therefore r
136
136
 
137
137
  ## What the plugin compiles
138
138
 
139
- The plugin compiles two kinds of WGSL:
139
+ The plugin compiles these kinds of WGSL:
140
140
 
141
- - WGSL without entry points that declares `fn surface`, `fn vertexOffset` or both is a custom material's WGSL. The plugin builds it into the standard material's shader, once for each of that shader's variants.
141
+ - WGSL without entry points that declares `fn surface`, `fn vertexOffset`, `fn lobe`, `fn coverage` or `fn unlit` is a custom material's WGSL. The plugin builds it into the standard material's shader, once for each of that shader's variants.
142
+ - WGSL without entry points that declares `fn effect` or `fn toneCurve` is a [custom effect or tone curve](custom-passes.md#custom-effects). The plugin builds it into every variant of its template.
143
+ - WGSL without entry points that declares `fn skyLayer` is a [sky layer](../api/scene.md#sky-layers). The plugin builds it into the engine's sky-layer template.
142
144
  - WGSL whose `@vertex` entry point takes an `InstanceIn` is a [full shader](#full-shaders) of a custom material. The plugin builds it for WebGPU, and for WebGL2 with and without multi-draw.
145
+ - WGSL whose `@vertex` entry point takes the vertex and instance indices and no mesh attribute is a draw shader. A [vertex draw](../api/vertex-draws.md) draws it from a vertex count.
143
146
  - Other WGSL with entry points is a whole shader. It has one `@vertex` entry point and one or more `@fragment` entry points. Each `@fragment` entry point makes one render pipeline, named after it, with the `@vertex` entry point. A shader with only `@compute` entry points builds for WebGPU alone, because WebGL2 has no compute shaders.
144
147
 
145
148
  WGSL that is neither stops the build with an error that says how to fix it.