@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
@@ -1,15 +1,308 @@
1
1
  ---
2
2
  id: porting/threejs-shaders
3
3
  title: "Porting shaders: GLSL, onBeforeCompile and TSL"
4
- status: planned
4
+ status: experimental
5
5
  since: "0.3"
6
6
  summary: "GLSL to WGSL; three.js built-ins to engine built-ins; worked examples."
7
7
  ---
8
8
 
9
- <!-- null3d:placeholder -->
10
-
11
9
  # Porting shaders: GLSL, onBeforeCompile and TSL
12
10
 
13
- > Planned for roadmap step 0.3, first released in null3D 0.1.0. This page is a placeholder. No release has this feature yet, so the APIs it names do not exist. Coding agents must not use them.
11
+ > Roadmap step 0.3, first released in null3D 0.1.0. The API is experimental, so it can still change between versions.
12
+
13
+ ```mermaid
14
+ flowchart LR
15
+ glsl["ShaderMaterial<br/>GLSL"] --> pick{"What does<br/>the shader do?"}
16
+ obc["onBeforeCompile<br/>patch"] --> pick
17
+ tsl["TSL or<br/>node material"] --> pick
18
+ pick -- "changes a lit surface" --> surface["Surface function"]
19
+ pick -- "moves vertices" --> offset["vertexOffset"]
20
+ pick -- "replaces the lighting" --> full["Full shader"]
21
+ pick -- "full-screen pass" --> effect["post.addEffect"]
22
+ ```
23
+
24
+ null3D shaders are WGSL. The Vite plugin translates each one to GLSL for the WebGL2 path, so you write a shader once. A port reads what the three.js shader does, then writes the smallest null3D form that does the same.
25
+
26
+ A custom material takes its WGSL in one `wgsl` option, as a template literal tagged `/* wgsl */` or as a `.wgsl` import. The WGSL holds `fn surface`, `fn vertexOffset`, or both. It can also hold a full shader's `@vertex` and `@fragment` entry points. It declares its uniforms once, as `struct Uniforms`, and reads them from `material`. [Custom shaders](../guides/custom-shaders.md) covers the setup, and [Surface functions](../shaders/surface-functions.md) covers the contract.
27
+
28
+ ## Choose the target form
29
+
30
+ | The three.js shader | The null3D form |
31
+ | --- | --- |
32
+ | Changes the color, roughness, emission or alpha of a lit surface | A surface function |
33
+ | Moves vertices | `vertexOffset`, with a surface function where needed |
34
+ | Ignores the lights, such as a hologram or a fresnel glow | An unlit function, `fn unlit(input: SurfaceInput) -> vec4f`, which returns the color and the opacity with no lighting ([Unlit surfaces](../shaders/surface-functions.md#unlit-surfaces)) |
35
+ | Replaces three.js's lighting | A full shader with the `null3d::lighting` helpers |
36
+ | Is a full-screen pass | `post.addEffect`, or `render.addPass({ kind: 'fullscreen' })` when it writes a target of its own ([Porting post-processing](threejs-postprocessing.md)) |
37
+ | Draws into a texture for another material | A scene pass of `render.addPass` |
38
+
39
+ A surface function keeps instancing, skinning, shadows, fog and both GPU paths. A full shader keeps instancing and both GPU paths. It gets no lighting, shadows, fog, uniforms or standard values, so use one only when a surface function cannot give the look.
40
+
41
+ ## GLSL to WGSL
42
+
43
+ | GLSL | WGSL |
44
+ | --- | --- |
45
+ | `float`, `int`, `uint`, `bool` | `f32`, `i32`, `u32`, `bool` |
46
+ | `vec2`, `vec3`, `vec4` | `vec2f`, `vec3f`, `vec4f` |
47
+ | `ivec3`, `uvec3`, `bvec3` | `vec3i`, `vec3u`, `vec3<bool>` |
48
+ | `mat3`, `mat4` | `mat3x3f`, `mat4x4f` |
49
+ | `float x = 1.0;` | `var x = 1.0;`, or `let x = 1.0;` for a value that does not change |
50
+ | `const float K = 2.0;` at file scope | `const K = 2.0;` |
51
+ | `float f(float a) { ... }` | `fn f(a: f32) -> f32 { ... }` |
52
+ | `float a[4];` | `var a: array<f32, 4>;` |
53
+ | `float(i)`, `int(x)` | `f32(i)`, `i32(x)`. WGSL never converts types by itself. |
54
+ | `texture2D(t, uv)`, `texture(t, uv)` | `textureSample(t, tSampler, uv)` |
55
+ | `texture2DLod`, `textureLod` | `textureSampleLevel(t, tSampler, uv, lod)` |
56
+ | `texture(t, vec3(uv, layer))` on a `sampler2DArray` | `textureSample(t, tSampler, uv, i32(layer))` on a `texture_2d_array<f32>` |
57
+ | `texelFetch(t, ivec2(p), 0)` | `textureLoad(t, vec2i(p), 0)` |
58
+ | `mod(x, y)` | `x - y * floor(x / y)`. WGSL's `%` keeps the sign of `x`. |
59
+ | `atan(y, x)` | `atan2(y, x)` |
60
+ | `inversesqrt(x)` | `inverseSqrt(x)` |
61
+ | `dFdx`, `dFdy`, `fwidth` | `dpdx`, `dpdy`, `fwidth` |
62
+ | `lessThan(a, b)` | `a < b`, which gives a vector of bools |
63
+ | `mix`, `step`, `smoothstep`, `clamp`, `fract`, `pow`, `dot`, `cross`, `normalize`, `reflect` | The same names |
64
+ | `c ? a : b` | `select(b, a, c)`, with the false value first and the condition last |
65
+ | `v.xy = w;` | `v = vec3f(w, v.z);`. Only Chrome allows assignment to a swizzle. |
66
+ | `discard;` | `discard;` |
67
+ | `gl_FrontFacing` | `input.frontFacing` |
68
+ | `gl_FragCoord` | `input.fragCoord`, from the top left (see [Conventions](#conventions)) |
69
+ | `gl_InstanceID` | `input.instance`, the row in its batch |
70
+ | `gl_VertexID` | `@builtin(vertex_index)` in a full shader |
71
+ | `precision highp float;` | Delete it. |
72
+ | `#define NAME value` | `const NAME = value;` |
73
+ | `#ifdef`, `#if` | `if` on a `const`, which the compiler removes, or two materials |
74
+ | `#include <chunk>` | `#import null3d::...` from the [shader library](../shaders/library.md), or delete it |
75
+
76
+ A custom material samples 2D textures, declared as `var name: texture_2d<f32>;`, and texture arrays, declared as `var name: texture_2d_array<f32>;`. A GLSL `samplerCube` has no equivalent in a material. Sample an equirectangular 2D texture instead, or let the scene's environment light the surface.
77
+
78
+ ## Built-in values
79
+
80
+ The engine gives each surface function and vertex offset the values that three.js's `ShaderMaterial` adds. [Built-in values](../shaders/builtins.md) lists them all.
81
+
82
+ | three.js | null3D |
83
+ | --- | --- |
84
+ | The `position`, `normal`, `uv`, `uv1` and `color` attributes | `VertexInput.position`, `normal`, `uv`, `uv1` and `colors` in `vertexOffset`. `input.uv`, `input.uv1` and `input.vertexColor` in a surface function. |
85
+ | `modelMatrix` | `object.worldMatrix`, with its translation relative to the camera. `object.position` gives the origin in the world. |
86
+ | `viewMatrix`, `projectionMatrix` | `camera.view`, which holds the rotation only, and `camera.projection`, with reversed depth. `camera.viewProjection` is their product. |
87
+ | `cameraNear`, `cameraFar` | `camera.near`, `camera.far` |
88
+ | `cameraPosition` | `camera.position` |
89
+ | `modelViewMatrix * vec4(position, 1.0)` | Nothing: the engine places the vertices. A full shader calls `clip_position` from `null3d::mesh`. |
90
+ | `normalMatrix`, in view space | `input.normal` is already in world space. Multiply it by `camera.view` for view space. |
91
+ | Varyings such as `vWorldPosition`, `vViewDir` and `vNormal` | `input.worldPosition`, `input.viewDirection`, `input.normal` |
92
+ | `instanceMatrix`, `instanceColor` | The engine applies each row's transform. A batch made with `colors: true` multiplies each row's color into `input.vertexColor`. |
93
+ | An `InstancedBufferAttribute` such as a phase per instance | `object.values`, four floats per row from a batch made with `values: true` |
94
+ | A `time` uniform that the app updates | `frame.time` |
95
+ | The fog, tone mapping and color space chunks | Nothing: the engine adds fog after the surface function, and the final pass tone maps and encodes once. |
96
+ | The `<common>` and `<packing>` helpers | `null3d::math`, `null3d::depth` |
97
+ | The lighting chunks and light uniforms | The engine lights a surface function. A full shader imports `null3d::lighting`. |
98
+
99
+ The engine works relative to the camera, so positions stay precise far from the origin. That is why `object.worldMatrix` and `camera.view` hold no camera translation.
100
+
101
+ ## Conventions
102
+
103
+ - **Fragment coordinates.** `input.fragCoord` counts pixels from the top left, with y pointing down, on every GPU path. GLSL's `gl_FragCoord` starts at the bottom left. Replace `gl_FragCoord.y` with `frame.resolution.y - input.fragCoord.y`.
104
+ - **Screen coordinates in effects.** An effect's `input.uv` is (0, 0) at the top left. three.js's full-screen passes use a `vUv` that starts at the bottom left. Replace `vUv.y` with `1.0 - input.uv.y` where the direction matters.
105
+ - **Texture coordinates.** A texture loaded with `flipY: true` samples as three.js's `TextureLoader` does. glTF textures use `flipY: false` in both engines, so the shader's math stays the same.
106
+ - **Depth.** The engine uses reversed depth on both GPU paths: near is 1 and far is 0. Use `null3d::depth::linear_depth` and `null3d::depth::perspective_depth_to_view_z` in place of three.js's depth formulas.
107
+ - **Color.** A surface's colors are linear, and the final pass encodes sRGB once. A three.js `ShaderMaterial` without `<colorspace_fragment>` wrote sRGB values straight to the screen. Convert such constants with `null3d::color::srgb_to_linear`, or pass them as `'#rrggbb'` uniforms, which the engine converts.
108
+ - **Matrices.** Both engines store matrices by column, and `matrix * vector` keeps its order.
109
+
110
+ ## ShaderMaterial and RawShaderMaterial
111
+
112
+ 1. List the uniforms. Each becomes a field of `struct Uniforms`, with its first value in the `uniforms` option. A `sampler2D` uniform becomes `var name: texture_2d<f32>;` and an entry of the `textures` option, and a `sampler2DArray` becomes `var name: texture_2d_array<f32>;`. A material takes up to 6 textures, fixed when you create it.
113
+ 2. Replace each update such as `material.uniforms.uSpeed.value = 2` with `material.set({ speed: 2 })`. A name that `struct Uniforms` lacks fails the type check, and throws [E1216](../errors/E1216.md) when the sketch runs.
114
+ 3. Read the vertex shader. When it only places the vertices and passes varyings on, delete it. When it moves vertices, port that part as `vertexOffset`.
115
+ 4. Read the fragment shader. Map its varyings to the surface input, and its output to the surface's fields. A lit look goes to `baseColor`, `roughness` and `metalness`. An unlit look goes to the color that `fn unlit` returns, in place of `surface`. Transparency goes to `alpha`, or to the opacity that `fn unlit` returns, with the matching `alphaMode`.
116
+ 5. Set the options that were material flags. `transparent` becomes `alphaMode: 'blend'`, `side: DoubleSide` becomes `doubleSided: true`, and `AdditiveBlending` becomes `blending: 'additive'`.
117
+ 6. Compare parity images on WebGPU and WebGL2 ([Verifying a port](verification.md)).
118
+
119
+ A `RawShaderMaterial` adds nothing by itself, so every matrix and attribute is in its source. The same steps apply.
120
+
121
+ Uniforms take `f32`, `i32`, `u32`, `vec2f`, `vec3f` and `vec4f`, up to 32 numbers in all. Pass a matrix as `vec4f` rows. Rename a uniform called `color`, `roughness` or another standard value, because those names belong to the material.
122
+
123
+ ## onBeforeCompile patches
124
+
125
+ | What the patch does | The null3D form |
126
+ | --- | --- |
127
+ | Changes `transformed` after `#include <begin_vertex>` | `vertexOffset`, which returns the change: the new position minus the old |
128
+ | Changes `diffuseColor` after `<map_fragment>` or `<color_fragment>` | `s.baseColor` and `s.alpha` in a surface function |
129
+ | Changes `roughnessFactor` or `metalnessFactor` | `s.roughness`, `s.metalness` |
130
+ | Adds glow in `<emissivemap_fragment>` | `s.emissive` |
131
+ | Adds `discard`, for a dissolve or a cut-out | `alphaMode: 'mask'` and `s.alpha` |
132
+ | Adds a varying such as a world position | `input.worldPosition` |
133
+ | Replaces a lighting chunk | A full shader with `null3d::lighting` |
134
+ | Keeps `shader.uniforms` to update them later | `material.set({ ... })`, or `frame.time` for time |
135
+
136
+ Keep the original material's standard values on the new material. `materials.shader` takes every `materials.standard` option but the texture maps, and `defaultSurface()` starts from them. The original's maps become textures of the WGSL, which the surface function samples.
137
+
138
+ ## TSL and node materials
139
+
140
+ | TSL | WGSL in a surface function |
141
+ | --- | --- |
142
+ | `uniform(0.5)`, and `u.value = x` | `uniforms: { name: 0.5 }`, and `material.set({ name: x })` |
143
+ | `texture(map, uv())` | `textureSample(map, mapSampler, input.uv)`, with the texture in the `textures` option |
144
+ | `uv()`, `uv(1)` | `input.uv`, `input.uv1` |
145
+ | `modelWorldMatrix`, `cameraViewMatrix`, `cameraProjectionMatrix` | `object.worldMatrix`, `camera.view`, `camera.projection` |
146
+ | `positionGeometry`, `positionLocal` | `VertexInput.position` in `vertexOffset` |
147
+ | `positionWorld`, `normalWorld` | `input.worldPosition`, `input.normal` |
148
+ | `normalView` | `(camera.view * vec4f(input.normal, 0.0)).xyz` |
149
+ | `cameraPosition`, `time` | `camera.position`, `frame.time` |
150
+ | `vertexColor()`, `instanceIndex` | `input.vertexColor`, `input.instance` |
151
+ | `screenUV`, `screenCoordinate` | `input.fragCoord.xy / frame.resolution`, and `input.fragCoord.xy` |
152
+ | `add`, `sub`, `mul`, `div` | `+`, `-`, `*`, `/` |
153
+ | `oneMinus(x)`, `saturate(x)` | `1.0 - x`, `saturate(x)` |
154
+ | `mx_noise_float(p)` and other MaterialX noise | `null3d::noise::simplex3(p)` and `fbm3(p, octaves)`. The values differ, so tune them. |
155
+ | `Fn`, `If`, `Loop`, `.toVar()` | `fn`, `if`, `for`, `var` |
156
+ | `colorNode`, `opacityNode`, `roughnessNode`, `metalnessNode`, `normalNode`, `emissiveNode`, `aoNode` | `s.baseColor`, `s.alpha`, `s.roughness`, `s.metalness`, `s.normal`, `s.emissive`, `s.occlusion` |
157
+ | `positionNode` | `vertexOffset`, which returns `newPosition - input.position` |
158
+ | `fragmentNode` | An unlit function, `fn unlit`, which returns the color with no lighting |
159
+ | `outputNode` | A full shader, or a post effect for a post-processing `outputNode` |
160
+ | `mrtNode` | No equivalent |
161
+
162
+ On an `InstancedMesh`, three.js applies the instance matrix before `positionNode` runs, so `positionLocal` there holds the instanced vertex. In null3D, `input.position` is always the mesh's own vertex, and the engine applies the row's transform after `vertexOffset`. Write such a displacement from `input.position` and the row's own data.
163
+
164
+ ## Displacement
165
+
166
+ For three.js's `displacementMap`, use the standard material's own `displacementMap`, `displacementScale` and `displacementBias`. Shadows, the depth prepass and the culling bounds then follow the moved vertices.
167
+
168
+ Write a vertex offset for a height map that the standard material cannot take, such as one that moves along another direction:
169
+
170
+ ```ts
171
+ const ground = materials.shader({
172
+ color: '#7a8a5a', roughness: 0.9,
173
+ uniforms: { scale: 2.0, bias: 0.0 },
174
+ textures: { height: heightMap },
175
+ wgsl: /* wgsl */ `
176
+ struct Uniforms { scale: f32, bias: f32 }
177
+
178
+ var height: texture_2d<f32>;
179
+
180
+ fn vertexOffset(input: VertexInput) -> vec3f {
181
+ let h = textureSampleLevel(height, heightSampler, input.uv, 0.0).r;
182
+ return input.normal * (h * material.scale + material.bias);
183
+ }`,
184
+ });
185
+ groundMesh.setBounds([0, 1, 0], 60); // hold the highest moved point
186
+ ```
187
+
188
+ The vertex stage has no automatic mip level, so it uses `textureSampleLevel`. The engine does not recompute the normals after a vertex offset. Give `flatShading: true` to light the faces by their moved positions, or bend `s.normal` in the surface function.
189
+
190
+ ## Worked examples
191
+
192
+ ### A fresnel glow from a ShaderMaterial
193
+
194
+ ```glsl
195
+ // three.js vertex shader
196
+ varying vec3 vNormal; varying vec3 vViewDir;
197
+ void main() {
198
+ vec4 mv = modelViewMatrix * vec4(position, 1.0);
199
+ vNormal = normalize(normalMatrix * normal);
200
+ vViewDir = normalize(-mv.xyz);
201
+ gl_Position = projectionMatrix * mv;
202
+ }
203
+ // three.js fragment shader
204
+ uniform vec3 uColor; uniform float uPower;
205
+ varying vec3 vNormal; varying vec3 vViewDir;
206
+ void main() {
207
+ float f = pow(1.0 - max(dot(vNormal, vViewDir), 0.0), uPower);
208
+ gl_FragColor = vec4(uColor * f, f);
209
+ }
210
+ ```
211
+
212
+ ```ts
213
+ const glow = materials.shader({
214
+ alphaMode: 'blend', blending: 'additive', depthWrite: false,
215
+ uniforms: { glowColor: '#44aaff', power: 3 },
216
+ wgsl: /* wgsl */ `
217
+ struct Uniforms { glowColor: vec3f, power: f32 }
218
+
219
+ fn unlit(input: SurfaceInput) -> vec4f {
220
+ let f = pow(1.0 - max(dot(input.normal, input.viewDirection), 0.0), material.power);
221
+ return vec4f(material.glowColor * f, f);
222
+ }`,
223
+ });
224
+ ```
225
+
226
+ The original works in view space and the port in world space. The dot product is the same in both. The vertex shader goes, because it only placed the vertices and passed data on.
227
+
228
+ ### Wind sway from onBeforeCompile
229
+
230
+ ```js
231
+ // three.js
232
+ material.onBeforeCompile = (shader) => {
233
+ shader.uniforms.uTime = timeUniform;
234
+ shader.vertexShader = 'uniform float uTime;\n' + shader.vertexShader.replace(
235
+ '#include <begin_vertex>',
236
+ '#include <begin_vertex>\ntransformed.x += sin(uTime * 2.0 + position.y) * 0.1 * position.y;');
237
+ };
238
+ ```
239
+
240
+ ```ts
241
+ const foliage = materials.shader({
242
+ color: '#4f7a32', doubleSided: true,
243
+ uniforms: { strength: 0.1 },
244
+ wgsl: /* wgsl */ `
245
+ struct Uniforms { strength: f32 }
246
+
247
+ fn vertexOffset(input: VertexInput) -> vec3f {
248
+ let sway = sin(frame.time * 2.0 + input.position.y) * material.strength * input.position.y;
249
+ return vec3f(sway, 0.0, 0.0);
250
+ }`,
251
+ });
252
+ ```
253
+
254
+ ### A dissolve from TSL
255
+
256
+ ```js
257
+ // three.js TSL
258
+ const progress = uniform(0);
259
+ const n = texture(noiseTex, uv()).r;
260
+ material.opacityNode = step(progress, n);
261
+ material.emissiveNode = color(0xff6a00).mul(smoothstep(0.05, 0.0, n.sub(progress)).mul(4));
262
+ material.alphaTest = 0.5;
263
+ ```
264
+
265
+ ```ts
266
+ const dissolve = materials.shader({
267
+ alphaMode: 'mask', alphaCutoff: 0.5,
268
+ uniforms: { progress: 0, edgeColor: '#ff6a00' },
269
+ wgsl: /* wgsl */ `
270
+ #import null3d::noise::{fbm2}
271
+
272
+ struct Uniforms { progress: f32, edgeColor: vec3f }
273
+
274
+ fn surface(input: SurfaceInput) -> Surface {
275
+ var s = defaultSurface(input);
276
+ let n = fbm2(input.uv * 8.0, 4u) * 0.5 + 0.5;
277
+ s.alpha = step(material.progress, n);
278
+ let edge = 1.0 - smoothstep(0.0, 0.05, n - material.progress);
279
+ s.emissive = material.edgeColor * edge * 4.0;
280
+ return s;
281
+ }`,
282
+ });
283
+ ```
284
+
285
+ `opacityNode` becomes `s.alpha`, `emissiveNode` becomes `s.emissive`, and `alphaTest` becomes `alphaMode: 'mask'` with `alphaCutoff`. The port makes its noise with `null3d::noise` in place of a noise texture.
286
+
287
+ ## Pitfalls
288
+
289
+ - A `textureSample` inside a branch that differs between pixels breaks a WGSL rule that GLSL does not have. Chrome refuses such a shader. Sample before the branch, or use `textureSampleLevel`.
290
+ - `%` is not `mod`: negative inputs give other results.
291
+ - WGSL has no assignment to a swizzle in most browsers. Write the whole vector.
292
+ - Flip y for `gl_FragCoord` and for full-screen coordinates.
293
+ - Replace three.js's depth formulas with the `null3d::depth` helpers.
294
+ - Convert raw sRGB constants from a `ShaderMaterial` to linear.
295
+ - three.js's `normalMatrix` works in view space, and null3D's normals are in world space.
296
+ - WGSL does not mix `f32` and `i32` in arithmetic, so convert explicitly.
297
+ - A surface function shares its file with the engine's template. Rename GLSL helpers whose names clash with it, such as `frame`, `camera`, `object`, `material`, `shade` or `finish` ([WGSL rules](../shaders/wgsl-rules.md)).
298
+ - Test on WebGL2 with `?gpu=webgl2`. The translated GLSL can meet limits that the WGSL did not.
299
+
300
+ ## Related pages
14
301
 
15
- This page will cover: GLSL to WGSL; three.js built-ins to engine built-ins; worked examples.
302
+ - [Custom shaders](../guides/custom-shaders.md)
303
+ - [Surface functions](../shaders/surface-functions.md)
304
+ - [Built-in values](../shaders/builtins.md)
305
+ - [WGSL rules](../shaders/wgsl-rules.md)
306
+ - [The shader library](../shaders/library.md)
307
+ - [Porting materials and textures](threejs-materials.md)
308
+ - [Porting post-processing](threejs-postprocessing.md)
@@ -1,15 +1,91 @@
1
1
  ---
2
2
  id: porting/threejs-unsupported
3
3
  title: Unsupported three.js features
4
- status: planned
4
+ status: experimental
5
5
  since: "0.3"
6
- summary: "Features after 1.0 or out of scope, with workarounds."
6
+ summary: "three.js features with no null3D equivalent, with workarounds."
7
7
  ---
8
8
 
9
- <!-- null3d:placeholder -->
10
-
11
9
  # Unsupported three.js features
12
10
 
13
- > Planned for roadmap step 0.3, first released in null3D 0.1.0. This page is a placeholder. No release has this feature yet, so the APIs it names do not exist. Coding agents must not use them.
11
+ > Roadmap step 0.3, first released in null3D 0.1.0. The API is experimental, so it can still change between versions.
12
+
13
+ Most three.js features have a null3D equivalent, which the [three.js to null3D mapping](threejs-mapping.md) gives. This page lists the features that have none, and the parts of features that behave differently. Each entry gives the workaround.
14
+
15
+ Check this list before a port starts. When a feature is central to the app, such as an XR experience, keep the app in three.js. Never drop a feature without telling the app's owner.
16
+
17
+ Do not draw a three.js canvas over the null3D canvas to keep one effect. Two GPU contexts double the memory, and their frames fall out of step.
18
+
19
+ ## Rendering and output
20
+
21
+ | three.js | In null3D | Workaround |
22
+ | --- | --- | --- |
23
+ | WebXR: `renderer.xr`, `VRButton`, `ARButton` | null3D draws to a canvas on the page, with no XR session | Keep an XR app in three.js |
24
+ | `ArrayCamera` and `StereoCamera` | No stereo drawing | For split screens, give each view a camera and a rectangle of the canvas ([Multiple views](../guides/multiple-views.md)) |
25
+ | `BasicShadowMap` and `VSMShadowMap` | Shadows use percentage-closer filtering | The `shadowFilter` quality setting sets the filter size ([Shadows](../concepts/shadows.md)) |
26
+ | `light.shadow.camera` | The shadow cascades fit the camera's view | Tune `mapSize`, `cascades` and the bias |
27
+ | `side: BackSide` | Materials draw front faces, or both sides with `doubleSided: true` | Flip the geometry's winding |
28
+ | `material.envMap` on one material | One environment lights the whole scene | `scene.setEnvironment`, with `envIntensity` on each material ([Lighting](../concepts/lighting.md)) |
29
+ | A `CubeTexture` as a material's map | Materials do not sample cube maps | A cube map can be a background with `assets.loadCubemap`. For reflections, load an environment with `assets.loadEnvironment` |
30
+ | `AfterimagePass` | Effects cannot read the previous frame | No port |
31
+ | `TAARenderPass` with a moving camera | A still view blends jittered frames, but a moving view does not | Use MSAA or FXAA |
32
+ | `OITPass`'s `weightNode` | The weighted blending uses three.js's default weight | No change of weight |
33
+
34
+ ## Materials and shaders
35
+
36
+ | three.js | In null3D | Workaround |
37
+ | --- | --- | --- |
38
+ | `MeshToonMaterial` | Surface functions cannot read the scene's lights | Pass the light's direction as a uniform, step the light into bands, and return it as emissive. Or step each light in a lobe function, which reads the light's direction and its shadowed irradiance. The lobe adds to the base lighting, so set the base color to black and the roughness to 1. The engine calls no lobe for fill directional lights and area lights ([Porting materials and textures](threejs-materials.md)) |
39
+ | Standard maps on a `ShaderMaterial` | A custom material takes no standard maps, such as `map` or `normalMap` | Declare up to 6 textures in the WGSL, and pass them with the `textures` option ([Porting shaders](threejs-shaders.md)) |
40
+ | `onBeforeCompile` shader chunks | The engine has no shader chunks to patch | A surface function or a vertex offset function |
41
+ | `material.alphaMap` | No separate alpha map | Copy the map's green channel into the base color map's alpha |
42
+ | `PointsMaterial.alphaMap` | No alpha map on points | Put the alpha in the points' `map` |
43
+ | Clipping planes | No clipping planes | A surface function with `alphaMode: 'mask'`. Its shadow is cut at the plane too. For three.js's default, `clipShadows: false`, also declare `fn coverage` and return `1.0`, so the whole shadow stays |
44
+
45
+ ## Objects and scenes
46
+
47
+ | three.js | In null3D | Workaround |
48
+ | --- | --- | --- |
49
+ | `SkinnedMesh`, `Skeleton` and `Bone` built in code | Skeletons come from glTF files, and joints are not objects | Make the skeleton in a modeling tool and export glTF. Turn a joint from code with the animator's joint calls ([Animation](../api/animation.md)) |
50
+ | `object.userData` and subclasses of `Mesh` | Engine objects take no new properties | Your own `Map` or typed arrays, keyed by object or row |
51
+ | `onBeforeRender` and `onAfterRender` | No sketch code runs while the engine draws | `onUpdate` or `onLateUpdate`, or a declared pass |
52
+ | Shadows from lines, points and sprites | Lines, points and sprites cast no shadows and receive none | Use a mesh where a shadow matters |
53
+ | Particles lit by the scene's lights | Particles take no light and cast no shadows | Color the particles with their own curves ([Particles](../api/particles.md)) |
54
+ | `TextGeometry`, `FontLoader` and troika-three-text | null3D draws no text of its own | HTML labels with `ui.trackLabel` for text that follows an object, a texture for text on a surface, or a text mesh baked into glTF |
55
+ | Physics add-ons | null3D has no physics API | Run cannon-es or Rapier in the sketch worker ([Using a physics library](../guides/physics.md)) |
56
+ | Terrain collision | `@null3d/terrain` has no collision | Give the physics library its own height field |
57
+
58
+ ## Controls and helpers
59
+
60
+ | three.js | In null3D | Workaround |
61
+ | --- | --- | --- |
62
+ | `TrackballControls` and `ArcballControls` | No trackball or arcball controls | `createOrbitControls`, or your own rotation from `ctx.input` |
63
+ | Controls events: `change`, `start` and `end` | The controls send no events | `update(dt)` returns true when the camera moved |
64
+ | `PlaneHelper` and `PolarGridHelper` | No debug drawing for them | Draw the shape with `debug.arrow`, `debug.box` or lines |
65
+ | `MathUtils.smootherstep`, `pingpong`, `generateUUID` and the power of two helpers | No helpers of these names | Write them in a line each, or use `crypto.randomUUID()` |
66
+
67
+ ## Audio
68
+
69
+ | three.js | In null3D | Workaround |
70
+ | --- | --- | --- |
71
+ | `AudioLoader` | No loader | Name the file by its address. The page loads it once the user starts the sound ([Sound](../api/sound.md)) |
72
+ | `AudioAnalyser` | No analyser | Analyze the page's own Web Audio |
73
+
74
+ ## React Three Fiber and drei
75
+
76
+ | React Three Fiber or drei | In null3D | Workaround |
77
+ | --- | --- | --- |
78
+ | drei `<ContactShadows />` | No blurred shadow from above | `materials.shadowCatcher` shows the directional light's own shadow |
79
+ | `onPointerMissed` | No miss event | Set a flag in the click handlers, and treat a release without it as a miss |
80
+ | drei `<AdaptiveDpr>` with `performance.regress()` | The governor follows frame times, not camera movement | Remove the `regress()` calls |
81
+ | Pointer events on objects behind the closest one | Only the closest object and its parents get an event | `scene.raycastAll` finds the objects behind, nearest first |
82
+
83
+ [Porting React Three Fiber](react-three-fiber.md) covers the rest of a React Three Fiber port.
84
+
85
+ ## Related pages
14
86
 
15
- This page will cover: Features after 1.0 or out of scope, with workarounds.
87
+ - [Porting from three.js](threejs-overview.md)
88
+ - [three.js to null3D mapping](threejs-mapping.md)
89
+ - [Porting materials and textures](threejs-materials.md)
90
+ - [Porting shaders](threejs-shaders.md)
91
+ - [Verifying a port](verification.md)
@@ -1,15 +1,191 @@
1
1
  ---
2
2
  id: porting/verification
3
3
  title: Verifying a port
4
- status: planned
4
+ status: experimental
5
5
  since: "0.3"
6
6
  summary: "Parity images per camera view; performance comparison; the WebGL2 path; phones."
7
7
  ---
8
8
 
9
- <!-- null3d:placeholder -->
10
-
11
9
  # Verifying a port
12
10
 
13
- > Planned for roadmap step 0.3, first released in null3D 0.1.0. This page is a placeholder. No release has this feature yet, so the APIs it names do not exist. Coding agents must not use them.
11
+ > Roadmap step 0.3, first released in null3D 0.1.0. The API is experimental, so it can still change between versions.
12
+
13
+ ```mermaid
14
+ flowchart LR
15
+ views["Choose 3 to 8<br/>camera views"] --> baseline["Capture each view<br/>in the three.js app"]
16
+ baseline --> refs["Copy the images<br/>as references"]
17
+ refs --> test["bunx @null3d/cli test<br/>on each GPU path"]
18
+ test --> bench["Time both apps<br/>on the same device"]
19
+ bench --> report["Write down the<br/>accepted differences"]
20
+ ```
21
+
22
+ A port is done when each chosen camera view looks the same as the original within an agreed tolerance, on every GPU path. It must also run at least as fast as the original on the same device. This page shows how to check both with the command line tool.
23
+
24
+ ## Choose the views
25
+
26
+ Pick 3 to 8 camera views that together show every material, light, effect and kind of object in the app. Write each view down with its camera and its animation time:
27
+
28
+ ```json
29
+ {
30
+ "size": [800, 450],
31
+ "pixelRatio": 1,
32
+ "views": [
33
+ { "name": "overview", "position": [8, 6, 10], "target": [0, 1, 0], "fov": 50, "time": 0 },
34
+ { "name": "hero-closeup", "position": [1.2, 1.6, 2], "target": [0, 1.4, 0], "fov": 35, "time": 1.5 }
35
+ ]
36
+ }
37
+ ```
38
+
39
+ A fixed size and a pixel ratio of 1 make the two engines' images comparable.
40
+
41
+ ## Capture the three.js images
42
+
43
+ Make the original app give the same frame on every run first:
44
+
45
+ - Stop the damping and the auto-rotation of its controls.
46
+ - Set each animation mixer to the view's time with `mixer.setTime(time)`, and set each time uniform to the same value.
47
+ - Replace `Math.random` with a seeded generator while you capture, if the scene uses randomness.
48
+ - Keep anti-aliasing on in three.js, and start null3D with `createEngine({ antialias: 'msaa' })`. Both then draw 4 samples per pixel.
49
+ - Match the tone mapping. null3D tone maps with punchy AgX by default, which three.js lacks. An original with `NoToneMapping` needs `post.set({ toneMapping: 'none' })`.
50
+
51
+ Then add a short helper to the original app, and remove it after you capture:
52
+
53
+ ```js
54
+ // capture-baseline.js
55
+ export function captureBaseline(renderer, scene, camera, config, renderFn = () => renderer.render(scene, camera)) {
56
+ renderer.setPixelRatio(config.pixelRatio);
57
+ renderer.setSize(config.size[0], config.size[1], false);
58
+ const shots = {};
59
+ for (const v of config.views) {
60
+ camera.position.fromArray(v.position);
61
+ camera.lookAt(v.target[0], v.target[1], v.target[2]);
62
+ if (camera.isPerspectiveCamera && v.fov) camera.fov = v.fov;
63
+ camera.aspect = config.size[0] / config.size[1];
64
+ camera.updateProjectionMatrix();
65
+ renderFn(); // composer.render() for an app with post-processing
66
+ shots[v.name] = renderer.domElement.toDataURL('image/png');
67
+ }
68
+ return shots; // save each data URL as baseline/<name>.png
69
+ }
70
+ ```
71
+
72
+ With `WebGLRenderer`, a read of the canvas in the same task as the render works without `preserveDrawingBuffer`. With `WebGPURenderer`, call `await renderer.renderAsync(scene, camera)` first. Write the three.js version, the browser and the GPU down beside the images.
73
+
74
+ ## Compare the port with image tests
75
+
76
+ `bunx @null3d/cli test` compares images with references ([The `null3d` command](../cli/null3d.md#test)). Make each view an image test, with the three.js image as its reference:
77
+
78
+ 1. Let the sketch pose its camera from a view name in its module's address. In the setup, read `new URL(import.meta.url).searchParams.get('view')`, and set the camera from that view ([Testing your sketch](../guides/testing.md)).
79
+ 2. List one test for each view in `null3d.json`, with the view's time and the size of the three.js images:
80
+
81
+ ```json
82
+ {
83
+ "tests": [
84
+ { "name": "overview", "sketch": "sketch.ts?view=overview", "hold": 0, "size": "800x450" },
85
+ { "name": "hero-closeup", "sketch": "sketch.ts?view=hero-closeup", "hold": 1.5, "size": "800x450" }
86
+ ]
87
+ }
88
+ ```
89
+
90
+ 3. Copy each three.js image to `tests/references/<environment>/<tier>/<name>.png`, once for each tier: `webgpu`, `compat` and `webgl2`. The environment is `chrome-real-gpu` on your computer's GPU, and `chromium-swiftshader` with `CI=1`.
91
+ 4. Run `bunx @null3d/cli test`. For a view that fails, open its image and its `-diff.png` in `test-results/null3d/<environment>/<tier>/`.
92
+ 5. To find the object that differs, open the port's view with `?inspect` on the dev server. The panel lists the scene, and shows each object's transform and material values ([Debugging](../guides/debugging.md#the-in-page-inspector)).
93
+
94
+ A view passes when at most 0.1% of its pixels differ by more than 10% of the color range, as in three.js's own image tests. The pixels on anti-aliased edges never count.
95
+
96
+ Never run `bunx @null3d/cli test --update-references` in this setup. It replaces the three.js images with the port's own images.
97
+
98
+ A sketch test draws with the engine's default options. When your page passes options to `createEngine` that change the image, give the test a `page` in place of a `sketch`, such as `"page": "/?view=hero-closeup"`. To look at one view, `shot` draws it:
99
+
100
+ ```sh
101
+ bunx @null3d/cli shot --page '/?view=hero-closeup' --time 1.5 --size 800x450 --gpu webgl2 --out compare/hero-closeup.png
102
+ ```
103
+
104
+ ## Tolerances
105
+
106
+ | Scene content | Tolerance | Why |
107
+ | --- | --- | --- |
108
+ | Meshes, unlit and standard materials, lights, fog and tone mapping, without shadows or effects | Under 0.1% of pixels | The engine's own parity scenes stay under it on every GPU path. |
109
+ | The same with directional shadows | Under 0.5% of pixels | The shadow edges differ, because the two engines filter shadow maps in other ways. |
110
+ | Lambert, Phong or Toon materials | Review the diff image | Those materials become approximations ([Porting materials and textures](threejs-materials.md)). |
111
+ | Bloom, ambient occlusion and other effects | Review the diff image | The two engines build these effects in other ways. |
112
+ | Text and HTML labels | Compare in the browser | Labels are HTML on the page, and images leave them out. |
113
+
114
+ Some known differences need a tolerance of their own, or a matched setting:
115
+
116
+ - **Anti-aliased edges with tone mapping.** null3D averages an edge's samples before it tone maps them, and `WebGLRenderer` after. Where a very bright surface meets a dark one, the edge pixels differ. Compare such views with anti-aliasing off on both sides.
117
+ - **Fog in a wide view.** null3D measures the straight-line distance from the camera, and three.js the depth along the view. A wide view gets more fog at its corners. Compare the middle of the view, or review the corners.
118
+ - **The background.** null3D tone maps and exposes the background with the scene. `WebGLRenderer` clears to `scene.background` as it is. With an exposure other than 1, the two backgrounds differ.
119
+ - **Hemisphere lights.** three.js points the sky from the light's position toward the origin, and null3D along the light's +Y axis. Turn the null3D light to match a `HemisphereLight` that is not upright.
120
+
121
+ Write each accepted difference down, with its reason.
122
+
123
+ ## Compare performance
124
+
125
+ Measure both apps on the same device, browser, window size and pixel ratio, with the display at 60 Hz. Time a production build of each app: `bunx vite build`, then `bunx vite preview`. Never time null3D on the dev server. The dev server runs the engine's development checks in every frame, so the port looks slower than it ships.
126
+
127
+ `bunx @null3d/cli bench` makes a production build of the null3D app, and measures it ([The `null3d` command](../cli/null3d.md#bench)):
128
+
129
+ ```sh
130
+ bunx @null3d/cli bench --gpu webgpu,webgl2 --runs 5 --seconds 30 --size 800x450
131
+ ```
132
+
133
+ It warms up for 5 seconds by default, which leaves out the shader builds, and reports the medians and the spread of its runs.
134
+
135
+ | Measure | three.js | null3D |
136
+ | --- | --- | --- |
137
+ | Frame time at the 50th, 95th and 99th percentile | The intervals between frames that drew, counted as below | `intervalMs` from `engine.measure(seconds)`, or from `bench`, with `completedFps` beside it |
138
+ | CPU time per frame on the busiest thread | `performance.now()` around the update and the render | `cpuMs`, with each thread's phases in `threads` |
139
+ | Main thread time per frame | The same as above, because everything runs there | Close to zero |
140
+ | Memory | The browser's memory panel | `memory` from `engine.measure(seconds)` |
141
+ | Time to the first frame | From navigation to the first frame that drew | `load` from `engine.measure(seconds)` |
142
+ | Download size | The network panel, compressed | The same |
143
+
144
+ A `requestAnimationFrame` callback keeps firing while the GPU falls behind. `WebGPURenderer` can also return from a render with nothing drawn while its pipelines build. So count the three.js frames that drew and the frames that the GPU finished, and compare with the lower rate:
145
+
146
+ ```js
147
+ // three.js with WebGPURenderer's WebGPU backend
148
+ let drawn = 0;
149
+ let finished = 0;
150
+ renderer.setAnimationLoop(() => {
151
+ renderer.render(scene, camera);
152
+ if (renderer.info.render.drawCalls > 0) drawn++;
153
+ renderer.backend.device.queue.onSubmittedWorkDone().then(() => { finished++; });
154
+ });
155
+ ```
156
+
157
+ With `WebGLRenderer`, place a fence with `gl.fenceSync` after each render. Count the frame as finished when a later frame finds the fence signaled.
158
+
159
+ When the original app was not optimized, part of the gain comes from the rewrite, not from the engine. Say so when you report the figures.
160
+
161
+ ## The WebGL2 path
162
+
163
+ Many phones have no WebGPU, so they draw the port with WebGL2. Check every view on WebGL2 too:
164
+
165
+ - `bunx @null3d/cli test` draws each test on all three tiers unless a test lists its own `tiers`. `--gpu webgl2` runs that path alone.
166
+ - `?gpu=webgl2` in the page's address forces the path in a browser.
167
+ - `bunx @null3d/cli bench --gpu webgl2` times it.
168
+
169
+ The engine translates every shader for WebGL2. A translated shader can meet a limit that the WGSL did not, so a custom shader that passes on WebGPU can fail on WebGL2. [GPU tiers and backends](../concepts/backends.md) lists what each path gives.
170
+
171
+ ## Phones and tablets
172
+
173
+ A port that is faster on a computer is not always faster on a phone. Test on the devices that your users have:
174
+
175
+ - Serve the build over HTTPS on your local network, so that the device gets shared memory and WebGPU ([Hosting and cross-origin isolation](../getting-started/hosting.md#during-development)).
176
+ - Run each test for 10 minutes at least once. Phones slow down as they heat up.
177
+ - Compare at the quality preset that the engine picks on the device. A phone starts at Low and a tablet at Medium ([Quality presets](../concepts/quality-presets.md)).
178
+
179
+ [Phones and tablets](../guides/phones.md) says more about testing on a device.
180
+
181
+ ## Write down the result
182
+
183
+ Keep a short report beside the port. Give each device and browser, and the views that pass on each GPU path. Give the frame times of both apps, and each accepted difference with its reason. Add the commands that run the checks again, so that a later change can repeat them.
184
+
185
+ ## Related pages
14
186
 
15
- This page will cover: Parity images per camera view; performance comparison; the WebGL2 path; phones.
187
+ - [Testing your sketch](../guides/testing.md)
188
+ - [The `null3d` command](../cli/null3d.md)
189
+ - [Performance guide](../guides/performance.md)
190
+ - [Porting from three.js](threejs-overview.md)
191
+ - [Porting materials and textures](threejs-materials.md)
@@ -8,7 +8,7 @@ summary: "Camera, time, object and instance values available to custom shaders,
8
8
 
9
9
  # Built-in shader inputs
10
10
 
11
- > Roadmap step 0.1, first released in null3D 0.1.0. Step 0.2 adds the values of batch rows, the view and projection matrices, the camera's near and far planes, and the object's matrices and id. The API is experimental, so it can still change between versions. Light values are not built yet. Coding agents must not use them.
11
+ > Roadmap step 0.1, first released in null3D 0.1.0. The API is experimental, so it can still change between versions. The built-in values hold no light values. Pass a light's direction or color to a material as a uniform.
12
12
 
13
13
  A custom material's WGSL reads four built-in values besides its inputs: `frame`, `camera`, `object` and `material`. The engine fills them before it calls your functions, in the vertex offset and in the surface function alike. Read them anywhere in your WGSL, as global values. A [full shader](../guides/custom-shaders.md#full-shaders) imports `frame`, `camera` and `object` from `null3d::builtins`, and fills them with `fill_builtins`.
14
14