wallhammer-web 0.0.0-stage → 0.4.1

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 (408) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +92 -2
  3. package/dist/base/data.d.ts +67 -0
  4. package/dist/base/data.js +10 -0
  5. package/dist/base/destructible.d.ts +167 -0
  6. package/dist/base/destructible.js +47 -0
  7. package/dist/base/env-slot.d.ts +101 -0
  8. package/dist/base/env-slot.js +8 -0
  9. package/dist/base/frames.d.ts +138 -0
  10. package/dist/base/frames.js +459 -0
  11. package/dist/base/index.d.ts +21 -0
  12. package/dist/base/index.js +11 -0
  13. package/dist/base/mat34.d.ts +46 -0
  14. package/dist/base/mat34.js +173 -0
  15. package/dist/base/material.d.ts +87 -0
  16. package/dist/base/material.js +6 -0
  17. package/dist/base/math.d.ts +27 -0
  18. package/dist/base/math.js +60 -0
  19. package/dist/base/progress.d.ts +38 -0
  20. package/dist/base/progress.js +81 -0
  21. package/dist/base/rig.d.ts +177 -0
  22. package/dist/base/rig.js +97 -0
  23. package/dist/base/trig.d.ts +29 -0
  24. package/dist/base/trig.js +169 -0
  25. package/dist/base/up.d.ts +26 -0
  26. package/dist/base/up.js +40 -0
  27. package/dist/base/view.d.ts +128 -0
  28. package/dist/base/view.js +136 -0
  29. package/dist/camera/camera.d.ts +99 -0
  30. package/dist/camera/camera.js +228 -0
  31. package/dist/camera/follow.d.ts +120 -0
  32. package/dist/camera/follow.js +320 -0
  33. package/dist/camera/free.d.ts +153 -0
  34. package/dist/camera/free.js +359 -0
  35. package/dist/camera/index.d.ts +10 -0
  36. package/dist/camera/index.js +6 -0
  37. package/dist/camera/orbit.d.ts +93 -0
  38. package/dist/camera/orbit.js +261 -0
  39. package/dist/camera/path.d.ts +48 -0
  40. package/dist/camera/path.js +179 -0
  41. package/dist/core/ballistic.d.ts +66 -0
  42. package/dist/core/ballistic.js +104 -0
  43. package/dist/core/bodies.d.ts +77 -0
  44. package/dist/core/bodies.js +125 -0
  45. package/dist/core/clock.d.ts +37 -0
  46. package/dist/core/clock.js +87 -0
  47. package/dist/core/cover-fade.d.ts +14 -0
  48. package/dist/core/cover-fade.js +38 -0
  49. package/dist/core/index.d.ts +13 -0
  50. package/dist/core/index.js +8 -0
  51. package/dist/core/kepler.d.ts +74 -0
  52. package/dist/core/kepler.js +108 -0
  53. package/dist/core/level-fade.d.ts +66 -0
  54. package/dist/core/level-fade.js +123 -0
  55. package/dist/core/palette.d.ts +15 -0
  56. package/dist/core/palette.js +47 -0
  57. package/dist/env/atmosphere.d.ts +129 -0
  58. package/dist/env/atmosphere.js +707 -0
  59. package/dist/env/cloud-field.d.ts +44 -0
  60. package/dist/env/cloud-field.js +111 -0
  61. package/dist/env/environment.d.ts +217 -0
  62. package/dist/env/environment.js +441 -0
  63. package/dist/env/frame-block.d.ts +29 -0
  64. package/dist/env/frame-block.js +152 -0
  65. package/dist/env/glsl.d.ts +35 -0
  66. package/dist/env/glsl.js +246 -0
  67. package/dist/env/index.d.ts +13 -0
  68. package/dist/env/index.js +9 -0
  69. package/dist/env/sky.d.ts +48 -0
  70. package/dist/env/sky.js +227 -0
  71. package/dist/env/sun.d.ts +31 -0
  72. package/dist/env/sun.js +42 -0
  73. package/dist/gen-arch/build.d.ts +17 -0
  74. package/dist/gen-arch/build.js +414 -0
  75. package/dist/gen-arch/damage/damaged.d.ts +44 -0
  76. package/dist/gen-arch/damage/damaged.js +1119 -0
  77. package/dist/gen-arch/damage/fall-material.d.ts +10 -0
  78. package/dist/gen-arch/damage/fall-material.js +47 -0
  79. package/dist/gen-arch/damage/fall.d.ts +78 -0
  80. package/dist/gen-arch/damage/fall.js +797 -0
  81. package/dist/gen-arch/damage/rubble.d.ts +22 -0
  82. package/dist/gen-arch/damage/rubble.js +188 -0
  83. package/dist/gen-arch/index.d.ts +25 -0
  84. package/dist/gen-arch/index.js +16 -0
  85. package/dist/gen-arch/interior/interior-plan.d.ts +114 -0
  86. package/dist/gen-arch/interior/interior-plan.js +615 -0
  87. package/dist/gen-arch/interior/interior.d.ts +97 -0
  88. package/dist/gen-arch/interior/interior.js +966 -0
  89. package/dist/gen-arch/structure/building-shader.d.ts +25 -0
  90. package/dist/gen-arch/structure/building-shader.js +946 -0
  91. package/dist/gen-arch/structure/buildings.d.ts +248 -0
  92. package/dist/gen-arch/structure/buildings.js +294 -0
  93. package/dist/gen-arch/structure/dims.d.ts +77 -0
  94. package/dist/gen-arch/structure/dims.js +39 -0
  95. package/dist/gen-arch/structure/distant.d.ts +62 -0
  96. package/dist/gen-arch/structure/distant.js +316 -0
  97. package/dist/gen-arch/structure/env-slots.d.ts +18 -0
  98. package/dist/gen-arch/structure/env-slots.js +47 -0
  99. package/dist/gen-arch/structure/facade.d.ts +193 -0
  100. package/dist/gen-arch/structure/facade.js +159 -0
  101. package/dist/gen-arch/structure/parts.d.ts +31 -0
  102. package/dist/gen-arch/structure/parts.js +69 -0
  103. package/dist/gen-arch/structure/roof.d.ts +76 -0
  104. package/dist/gen-arch/structure/roof.js +568 -0
  105. package/dist/gen-arch/structure/structure-material.d.ts +23 -0
  106. package/dist/gen-arch/structure/structure-material.js +55 -0
  107. package/dist/gen-arch/structure/writer.d.ts +94 -0
  108. package/dist/gen-arch/structure/writer.js +195 -0
  109. package/dist/gen-core/cell.d.ts +138 -0
  110. package/dist/gen-core/cell.js +150 -0
  111. package/dist/gen-core/cube-sphere.d.ts +57 -0
  112. package/dist/gen-core/cube-sphere.js +159 -0
  113. package/dist/gen-core/field.d.ts +55 -0
  114. package/dist/gen-core/field.js +154 -0
  115. package/dist/gen-core/geometry.d.ts +31 -0
  116. package/dist/gen-core/geometry.js +231 -0
  117. package/dist/gen-core/hash.d.ts +18 -0
  118. package/dist/gen-core/hash.js +58 -0
  119. package/dist/gen-core/height-field.d.ts +33 -0
  120. package/dist/gen-core/height-field.js +137 -0
  121. package/dist/gen-core/index.d.ts +22 -0
  122. package/dist/gen-core/index.js +17 -0
  123. package/dist/gen-core/instance-cells.d.ts +37 -0
  124. package/dist/gen-core/instance-cells.js +72 -0
  125. package/dist/gen-core/near-scatter.d.ts +56 -0
  126. package/dist/gen-core/near-scatter.js +120 -0
  127. package/dist/gen-core/noise.d.ts +23 -0
  128. package/dist/gen-core/noise.js +72 -0
  129. package/dist/gen-core/occupancy.d.ts +21 -0
  130. package/dist/gen-core/occupancy.js +104 -0
  131. package/dist/gen-core/sphere-patch.d.ts +138 -0
  132. package/dist/gen-core/sphere-patch.js +544 -0
  133. package/dist/gen-core/strip-surface.d.ts +34 -0
  134. package/dist/gen-core/strip-surface.js +246 -0
  135. package/dist/gen-core/strip.d.ts +102 -0
  136. package/dist/gen-core/strip.js +817 -0
  137. package/dist/gen-ground/env-slots.d.ts +48 -0
  138. package/dist/gen-ground/env-slots.js +78 -0
  139. package/dist/gen-ground/ground.d.ts +78 -0
  140. package/dist/gen-ground/ground.js +208 -0
  141. package/dist/gen-ground/index.d.ts +9 -0
  142. package/dist/gen-ground/index.js +7 -0
  143. package/dist/gen-ground/markings.d.ts +46 -0
  144. package/dist/gen-ground/markings.js +124 -0
  145. package/dist/gen-ground/materials.d.ts +18 -0
  146. package/dist/gen-ground/materials.js +22 -0
  147. package/dist/gen-ground/terrain-shader.d.ts +5 -0
  148. package/dist/gen-ground/terrain-shader.js +151 -0
  149. package/dist/gen-mesh/bare-shapes.d.ts +194 -0
  150. package/dist/gen-mesh/bare-shapes.js +596 -0
  151. package/dist/gen-mesh/bisect-surface.d.ts +47 -0
  152. package/dist/gen-mesh/bisect-surface.js +261 -0
  153. package/dist/gen-mesh/box.d.ts +18 -0
  154. package/dist/gen-mesh/box.js +2 -0
  155. package/dist/gen-mesh/cell-morph-mesh.d.ts +52 -0
  156. package/dist/gen-mesh/cell-morph-mesh.js +258 -0
  157. package/dist/gen-mesh/cell-surface-mesh.d.ts +32 -0
  158. package/dist/gen-mesh/cell-surface-mesh.js +140 -0
  159. package/dist/gen-mesh/chunk-mesh.d.ts +25 -0
  160. package/dist/gen-mesh/chunk-mesh.js +112 -0
  161. package/dist/gen-mesh/drape-mesh.d.ts +36 -0
  162. package/dist/gen-mesh/drape-mesh.js +98 -0
  163. package/dist/gen-mesh/height-field-mesh.d.ts +14 -0
  164. package/dist/gen-mesh/height-field-mesh.js +98 -0
  165. package/dist/gen-mesh/index.d.ts +26 -0
  166. package/dist/gen-mesh/index.js +15 -0
  167. package/dist/gen-mesh/line-mesh.d.ts +25 -0
  168. package/dist/gen-mesh/line-mesh.js +62 -0
  169. package/dist/gen-mesh/mesh-builder.d.ts +115 -0
  170. package/dist/gen-mesh/mesh-builder.js +315 -0
  171. package/dist/gen-mesh/packed-mesh.d.ts +53 -0
  172. package/dist/gen-mesh/packed-mesh.js +205 -0
  173. package/dist/gen-mesh/prism-mesh.d.ts +33 -0
  174. package/dist/gen-mesh/prism-mesh.js +176 -0
  175. package/dist/gen-mesh/rig-mesh.d.ts +9 -0
  176. package/dist/gen-mesh/rig-mesh.js +135 -0
  177. package/dist/gen-mesh/strip-mesh.d.ts +45 -0
  178. package/dist/gen-mesh/strip-mesh.js +258 -0
  179. package/dist/gen-plan/drain.d.ts +58 -0
  180. package/dist/gen-plan/drain.js +270 -0
  181. package/dist/gen-plan/grid.d.ts +37 -0
  182. package/dist/gen-plan/grid.js +182 -0
  183. package/dist/gen-plan/horizon.d.ts +50 -0
  184. package/dist/gen-plan/horizon.js +185 -0
  185. package/dist/gen-plan/index.d.ts +15 -0
  186. package/dist/gen-plan/index.js +13 -0
  187. package/dist/gen-plan/line-tiles.d.ts +35 -0
  188. package/dist/gen-plan/line-tiles.js +190 -0
  189. package/dist/gen-plan/lines.d.ts +31 -0
  190. package/dist/gen-plan/lines.js +183 -0
  191. package/dist/gen-plan/plots.d.ts +40 -0
  192. package/dist/gen-plan/plots.js +282 -0
  193. package/dist/gen-plan/route.d.ts +55 -0
  194. package/dist/gen-plan/route.js +297 -0
  195. package/dist/gen-plan/sites.d.ts +32 -0
  196. package/dist/gen-plan/sites.js +209 -0
  197. package/dist/gen-tex/code-stamp.d.ts +31 -0
  198. package/dist/gen-tex/code-stamp.js +137 -0
  199. package/dist/gen-tex/index.d.ts +7 -0
  200. package/dist/gen-tex/index.js +5 -0
  201. package/dist/gen-tex/light-horizon.d.ts +47 -0
  202. package/dist/gen-tex/light-horizon.js +180 -0
  203. package/dist/gen-tex/textures.d.ts +8 -0
  204. package/dist/gen-tex/textures.js +49 -0
  205. package/dist/gen-tex/value-textures.d.ts +46 -0
  206. package/dist/gen-tex/value-textures.js +102 -0
  207. package/dist/gen-vegetation/env-slots.d.ts +20 -0
  208. package/dist/gen-vegetation/env-slots.js +29 -0
  209. package/dist/gen-vegetation/index.d.ts +8 -0
  210. package/dist/gen-vegetation/index.js +7 -0
  211. package/dist/gen-vegetation/materials.d.ts +7 -0
  212. package/dist/gen-vegetation/materials.js +17 -0
  213. package/dist/gen-vegetation/planting.d.ts +170 -0
  214. package/dist/gen-vegetation/planting.js +363 -0
  215. package/dist/gen-vegetation/tree-shader.d.ts +23 -0
  216. package/dist/gen-vegetation/tree-shader.js +229 -0
  217. package/dist/gen-vegetation/trees.d.ts +59 -0
  218. package/dist/gen-vegetation/trees.js +329 -0
  219. package/dist/gpu/device.d.ts +286 -0
  220. package/dist/gpu/device.js +1157 -0
  221. package/dist/gpu/gl.d.ts +134 -0
  222. package/dist/gpu/gl.js +276 -0
  223. package/dist/gpu/index.d.ts +4 -0
  224. package/dist/gpu/index.js +3 -0
  225. package/dist/index.d.ts +11 -0
  226. package/dist/index.js +13 -0
  227. package/dist/motion/graph.d.ts +244 -0
  228. package/dist/motion/graph.js +739 -0
  229. package/dist/motion/index.d.ts +8 -0
  230. package/dist/motion/index.js +8 -0
  231. package/dist/motion/pose-ops.d.ts +30 -0
  232. package/dist/motion/pose-ops.js +232 -0
  233. package/dist/motion/reach.d.ts +45 -0
  234. package/dist/motion/reach.js +264 -0
  235. package/dist/motion/skeleton.d.ts +49 -0
  236. package/dist/motion/skeleton.js +99 -0
  237. package/dist/platform/byte-store.d.ts +21 -0
  238. package/dist/platform/byte-store.js +137 -0
  239. package/dist/platform/canvas.d.ts +29 -0
  240. package/dist/platform/canvas.js +76 -0
  241. package/dist/platform/context-loss.d.ts +8 -0
  242. package/dist/platform/context-loss.js +17 -0
  243. package/dist/platform/free-input.d.ts +51 -0
  244. package/dist/platform/free-input.js +100 -0
  245. package/dist/platform/index.d.ts +18 -0
  246. package/dist/platform/index.js +10 -0
  247. package/dist/platform/input.d.ts +48 -0
  248. package/dist/platform/input.js +117 -0
  249. package/dist/platform/keys.d.ts +12 -0
  250. package/dist/platform/keys.js +29 -0
  251. package/dist/platform/loop.d.ts +41 -0
  252. package/dist/platform/loop.js +84 -0
  253. package/dist/platform/walk-input.d.ts +74 -0
  254. package/dist/platform/walk-input.js +226 -0
  255. package/dist/platform/worker.d.ts +51 -0
  256. package/dist/platform/worker.js +170 -0
  257. package/dist/render/bone-instances.d.ts +24 -0
  258. package/dist/render/bone-instances.js +74 -0
  259. package/dist/render/cells.d.ts +70 -0
  260. package/dist/render/cells.js +144 -0
  261. package/dist/render/glsl.d.ts +66 -0
  262. package/dist/render/glsl.js +173 -0
  263. package/dist/render/index.d.ts +26 -0
  264. package/dist/render/index.js +16 -0
  265. package/dist/render/instance-sets.d.ts +97 -0
  266. package/dist/render/instance-sets.js +241 -0
  267. package/dist/render/near-instances.d.ts +75 -0
  268. package/dist/render/near-instances.js +219 -0
  269. package/dist/render/particles.d.ts +63 -0
  270. package/dist/render/particles.js +215 -0
  271. package/dist/render/pieces.d.ts +57 -0
  272. package/dist/render/pieces.js +151 -0
  273. package/dist/render/point-lights.d.ts +97 -0
  274. package/dist/render/point-lights.js +243 -0
  275. package/dist/render/renderer.d.ts +447 -0
  276. package/dist/render/renderer.js +1100 -0
  277. package/dist/render/rig.d.ts +74 -0
  278. package/dist/render/rig.js +576 -0
  279. package/dist/render/shadow-areas.d.ts +49 -0
  280. package/dist/render/shadow-areas.js +125 -0
  281. package/dist/render/shadow-glsl.d.ts +12 -0
  282. package/dist/render/shadow-glsl.js +146 -0
  283. package/dist/render/transient.d.ts +61 -0
  284. package/dist/render/transient.js +213 -0
  285. package/dist/render/value-glsl.d.ts +17 -0
  286. package/dist/render/value-glsl.js +208 -0
  287. package/dist/render/value-layers.d.ts +180 -0
  288. package/dist/render/value-layers.js +333 -0
  289. package/dist/runtime/atmosphere.d.ts +37 -0
  290. package/dist/runtime/atmosphere.js +304 -0
  291. package/dist/runtime/cloud-shell.d.ts +29 -0
  292. package/dist/runtime/cloud-shell.js +158 -0
  293. package/dist/runtime/engine.d.ts +155 -0
  294. package/dist/runtime/engine.js +305 -0
  295. package/dist/runtime/environment-link.d.ts +22 -0
  296. package/dist/runtime/environment-link.js +49 -0
  297. package/dist/runtime/index.d.ts +13 -0
  298. package/dist/runtime/index.js +12 -0
  299. package/dist/runtime/precipitation-glsl.d.ts +2 -0
  300. package/dist/runtime/precipitation-glsl.js +70 -0
  301. package/dist/runtime/precipitation.d.ts +11 -0
  302. package/dist/runtime/precipitation.js +78 -0
  303. package/dist/runtime/sky.d.ts +30 -0
  304. package/dist/runtime/sky.js +114 -0
  305. package/dist/runtime/streaming.d.ts +245 -0
  306. package/dist/runtime/streaming.js +602 -0
  307. package/dist/sim/agenda.d.ts +167 -0
  308. package/dist/sim/agenda.js +425 -0
  309. package/dist/sim/bytes.d.ts +34 -0
  310. package/dist/sim/bytes.js +125 -0
  311. package/dist/sim/destruction/apply.d.ts +59 -0
  312. package/dist/sim/destruction/apply.js +243 -0
  313. package/dist/sim/destruction/cell-states.d.ts +54 -0
  314. package/dist/sim/destruction/cell-states.js +198 -0
  315. package/dist/sim/destruction/index.d.ts +11 -0
  316. package/dist/sim/destruction/index.js +10 -0
  317. package/dist/sim/destruction/int-geometry.d.ts +17 -0
  318. package/dist/sim/destruction/int-geometry.js +131 -0
  319. package/dist/sim/destruction/pick.d.ts +13 -0
  320. package/dist/sim/destruction/pick.js +59 -0
  321. package/dist/sim/destruction/rubble.d.ts +8 -0
  322. package/dist/sim/destruction/rubble.js +159 -0
  323. package/dist/sim/destruction/state.d.ts +15 -0
  324. package/dist/sim/destruction/state.js +83 -0
  325. package/dist/sim/destruction/structure.d.ts +30 -0
  326. package/dist/sim/destruction/structure.js +139 -0
  327. package/dist/sim/events.d.ts +37 -0
  328. package/dist/sim/events.js +106 -0
  329. package/dist/sim/fixed.d.ts +21 -0
  330. package/dist/sim/fixed.js +64 -0
  331. package/dist/sim/flow-probe.d.ts +58 -0
  332. package/dist/sim/flow-probe.js +158 -0
  333. package/dist/sim/flow.d.ts +257 -0
  334. package/dist/sim/flow.js +967 -0
  335. package/dist/sim/index.d.ts +28 -0
  336. package/dist/sim/index.js +20 -0
  337. package/dist/sim/interlock.d.ts +47 -0
  338. package/dist/sim/interlock.js +252 -0
  339. package/dist/sim/movers.d.ts +228 -0
  340. package/dist/sim/movers.js +1083 -0
  341. package/dist/sim/nav.d.ts +72 -0
  342. package/dist/sim/nav.js +292 -0
  343. package/dist/sim/paths.d.ts +80 -0
  344. package/dist/sim/paths.js +197 -0
  345. package/dist/sim/regions.d.ts +87 -0
  346. package/dist/sim/regions.js +517 -0
  347. package/dist/sim/simulation.d.ts +114 -0
  348. package/dist/sim/simulation.js +291 -0
  349. package/dist/sim/states.d.ts +23 -0
  350. package/dist/sim/states.js +54 -0
  351. package/dist/sim/table.d.ts +49 -0
  352. package/dist/sim/table.js +126 -0
  353. package/dist/sim/zones.d.ts +11 -0
  354. package/dist/sim/zones.js +196 -0
  355. package/dist/tools/collision-lines.d.ts +12 -0
  356. package/dist/tools/collision-lines.js +50 -0
  357. package/dist/tools/data-view-glsl.d.ts +3 -0
  358. package/dist/tools/data-view-glsl.js +63 -0
  359. package/dist/tools/data-view-layers.d.ts +20 -0
  360. package/dist/tools/data-view-layers.js +60 -0
  361. package/dist/tools/debug-view.d.ts +30 -0
  362. package/dist/tools/debug-view.js +4 -0
  363. package/dist/tools/index.d.ts +10 -0
  364. package/dist/tools/index.js +7 -0
  365. package/dist/tools/mesh-checks.d.ts +67 -0
  366. package/dist/tools/mesh-checks.js +188 -0
  367. package/dist/tools/profile.d.ts +85 -0
  368. package/dist/tools/profile.js +173 -0
  369. package/dist/world/cell-cache.d.ts +32 -0
  370. package/dist/world/cell-cache.js +60 -0
  371. package/dist/world/cell-format.d.ts +25 -0
  372. package/dist/world/cell-format.js +232 -0
  373. package/dist/world/collide.d.ts +192 -0
  374. package/dist/world/collide.js +822 -0
  375. package/dist/world/index.d.ts +16 -0
  376. package/dist/world/index.js +12 -0
  377. package/dist/world/mesh-solids.d.ts +48 -0
  378. package/dist/world/mesh-solids.js +169 -0
  379. package/dist/world/pick.d.ts +34 -0
  380. package/dist/world/pick.js +177 -0
  381. package/dist/world/providers.d.ts +66 -0
  382. package/dist/world/providers.js +83 -0
  383. package/dist/world/sphere.d.ts +69 -0
  384. package/dist/world/sphere.js +271 -0
  385. package/dist/world/streaming.d.ts +288 -0
  386. package/dist/world/streaming.js +801 -0
  387. package/dist/world/walker.d.ts +145 -0
  388. package/dist/world/walker.js +502 -0
  389. package/docs/architecture.md +111 -0
  390. package/docs/cameras.md +302 -0
  391. package/docs/concepts.md +123 -0
  392. package/docs/destruction.md +127 -0
  393. package/docs/frames.md +199 -0
  394. package/docs/generators.md +575 -0
  395. package/docs/getting-started.md +123 -0
  396. package/docs/headless.md +50 -0
  397. package/docs/motion.md +160 -0
  398. package/docs/planet.md +152 -0
  399. package/docs/recipes.md +521 -0
  400. package/docs/reference.md +364 -0
  401. package/docs/rendering.md +823 -0
  402. package/docs/rigs.md +203 -0
  403. package/docs/simulation.md +235 -0
  404. package/docs/streaming.md +590 -0
  405. package/docs/system.md +166 -0
  406. package/docs/tools.md +175 -0
  407. package/docs/walking.md +262 -0
  408. package/package.json +131 -3
@@ -0,0 +1,823 @@
1
+ # Rendering
2
+
3
+ The renderer lives in `wallhammer-web/render`. It draws a list of layers through four passes, owns the shadow map and compiles materials. The GPU itself is hidden in `wallhammer-web/gpu` (`Device`).
4
+
5
+ ## Passes
6
+
7
+ | Pass | When | What |
8
+ | --- | --- | --- |
9
+ | `shadow` | Only when the shadow map must be refitted (see [Shadows](#shadows)). | Depth from the light. Programs read the light matrix as `u_lightRender`. |
10
+ | `color` | Every frame in the normal mode. | The image. |
11
+ | `data` | Every frame when `renderer.mode = 'data'`. | Flat data colours (the data view). Falls back to the `color` program when a material has no `data` program. `overlay` is skipped in this mode. |
12
+ | `overlay` | After `color`. | Things drawn on top. |
13
+
14
+ `ctx.pass` tells a layer which pass is running.
15
+
16
+ ## Layers
17
+
18
+ A layer implements `Layer`:
19
+
20
+ ```ts
21
+ import type { CullVolume, View } from 'wallhammer-web/base';
22
+ import type { DrawContext, Layer } from 'wallhammer-web/render';
23
+
24
+ class CountingLayer implements Layer {
25
+ draw(ctx: DrawContext): void {
26
+ if (ctx.pass !== 'color') return;
27
+ // ctx.device draws; ctx.count(triangles) records a draw call in the frame statistics.
28
+ ctx.count(0);
29
+ }
30
+ // Optional. Called only when the shadow map is refitted: first with the light's volume, then with the view's.
31
+ cull(volume: CullVolume, purpose: 'shadow' | 'view', view: View): number {
32
+ return 0;
33
+ }
34
+ // Optional. True makes the renderer refit and cull again this frame (for example after something was added).
35
+ cullStale(): boolean {
36
+ return false;
37
+ }
38
+ }
39
+ ```
40
+
41
+ A layer may also have `prepare(device, view)`. The renderer calls it once per frame that draws the scene, after the Frame block of the frame is uploaded and before the first pass. It is the place to fill a target of the layer's own: `device.colorTarget(width, height, count, format)` makes a target of `count` colour textures (`'rgba8'` or `'rgba16f'`; `null` where the graphics card cannot draw into the format), and `device.fill(target, program, uniforms?)` draws one triangle over all of it. `fill` changes the viewport and the draw state, so it belongs between passes, not inside `draw`.
42
+
43
+ Layers draw in the order they were added (`renderer.add`, or `engine.add`, which keeps the precipitation layer last). The pass base state is set before each layer and restored after it.
44
+
45
+ Ready-made layers (which one: a single mesh → `MeshLayer`; many meshes with their own boxes → `PieceLayer`; a few thousand instances → `InstancedLayer`; many thousands of instances over a large area → `InstanceCellLayer`):
46
+
47
+ - **`MeshLayer`**: one material, one mesh, uniforms, textures and an optional `bind` hook. Passes default to every pass the material has a program for. Textures bind to units 1, 2, … in order. Unit 0 (`SHADOW_MAP_UNIT`) holds the shadow map.
48
+ - **`PieceLayer`**: a `MeshLayer` with a list of pieces (`{ mesh, min, max }`) instead of one mesh. Each piece is culled by its axis-aligned box: against the light's volume for the shadow pass and against the view's volume for the others. Material, uniforms and textures are set once per pass, then each kept piece is one draw. `add` and `remove` mark the layer stale, so the next frame refits and culls again. `drawn` is the number of pieces in the last colour pass; `bytes` sums the pieces' GPU buffers. Use it for a scene built in separately generated tiles or chunks. Culling writes into arrays that grow only on `add`, so it allocates nothing. `order: 'front-to-back'` sorts the kept pieces by the depth of their box centre along the view when culling (default `'added'`, the order of `add`); `lights` gives each piece its own list of point lights (see [Point lights](#point-lights)).
49
+ - **`InstanceSetLayer`**, **`ParticleLayer`**: one mesh with a matrix per instance, and looping particles. See [Point lights, particles and instance sets](#point-lights-particles-and-instance-sets).
50
+ - **`InstanceCellLayer`**: instances split into cells by `splitInstanceCells` (`gen-core`). `addGroup(lods, cells, layout, uniforms?)` uploads one shape: each level of detail once, each (cell, tier) as an instance buffer, and a shared mesh per (cell, tier, level). On a refit each cell is culled as one box and picks its level of detail and thinning tier by its distance from the eye (`detail: CellDetail`, see `cellDetail`). Nothing is rewritten on the GPU afterwards. The shadow pass draws level 0. An orthographic view has no eye, so all cells use one distance from `orthoDistance(view)` (by default the distance at which a 45° perspective view of about 1100 pixels would show the same pixel size). `group.uniforms` is set before that group's draws.
51
+ - **`InstancedLayer`**: batches of instances with per-instance culling and levels of detail. Each instance is culled as an upright segment (`bounds.position`, `bounds.height`) widened by `bounds.radius`. Culling copies the kept instances into the GPU buffer. The shadow pass uses level 0; the colour pass asks `levelOfDetail()`.
52
+ - **`TransientLayer`**: batches of pieces on closed-form tracks driven by the clock in `u_time.x`, plus dust puffs. Nothing is integrated per frame, so pausing or scrubbing the clock shows the same pose. While a batch moves, the shadow map is redrawn every frame. Used for falling pieces ([Destruction](destruction.md)).
53
+
54
+ <!-- check: wrap -->
55
+ ```ts
56
+ import type { InstanceData, MeshData } from 'wallhammer-web/base';
57
+ import { splitInstanceCells } from 'wallhammer-web/gen-core';
58
+ import { InstanceCellLayer, InstancedLayer, MeshLayer, PieceLayer } from 'wallhammer-web/render';
59
+ import type { Material, Renderer } from 'wallhammer-web/render';
60
+ declare const renderer: Renderer;
61
+ declare const material: Material;
62
+ declare const instancedMaterial: Material;
63
+ declare const ground: MeshData;
64
+ declare const shape: MeshData;
65
+ declare const shapeFar: MeshData;
66
+ declare const stones: InstanceData;
67
+ declare const tiles: { mesh: MeshData; min: [number, number, number]; max: [number, number, number] }[];
68
+
69
+ // One mesh with a uniform.
70
+ renderer.add(new MeshLayer({ material, mesh: renderer.createMesh(ground, material), uniforms: { u_albedo: { vec3: [0.6, 0.6, 0.5] } } }));
71
+
72
+ // Instances: base point at float 0, reach 1.5 m, 4 m tall.
73
+ const layer = new InstancedLayer(renderer.device, { material: instancedMaterial, bounds: { position: 0, radius: 1.5, height: 4 } });
74
+ const instances = renderer.createInstances(stones);
75
+ layer.batches = [{ lods: [renderer.createMesh(shape, instancedMaterial, instances)], instances, all: stones.data, uniforms: {} }];
76
+ renderer.add(layer);
77
+
78
+ // Tiles, each culled by its box. Pieces can arrive later (from workers); the next frame culls them in.
79
+ const tileLayer = new PieceLayer({ material });
80
+ for (const t of tiles) tileLayer.add({ mesh: renderer.createMesh(t.mesh, material), min: t.min, max: t.max });
81
+ renderer.add(tileLayer);
82
+
83
+ // Many instances over a large area: 256 m cells, the fine shape up to 150 m, thinned tiers from 600 m and 1500 m.
84
+ const bounds = { position: 0, radius: 1.5, height: 4 };
85
+ const cells = splitInstanceCells(stones.data, { stride: stones.layout.stride / 4, bounds, cellM: 256 });
86
+ const cellLayer = new InstanceCellLayer(renderer.device, { material: instancedMaterial, detail: { lodSteps: [150], tierSteps: [600, 1500] } });
87
+ cellLayer.addGroup([shapeFar, shape], cells, stones.layout);
88
+ renderer.add(cellLayer);
89
+ ```
90
+
91
+ ## Value layers
92
+
93
+ Three layers show numbers over a scene through a colour ramp. The engine does not know what the numbers mean: the caller gives values, a range and a ramp, and draws the legend itself.
94
+
95
+ - **`RasterValueLayer`**: a grid of values on a sheet over the ground. The sheet (`drapeTiles` over the height field) only carries the surface; which cell a fragment shows follows from its world position, so the grid and the sheet need not match in size or density. With `smooth` (default) values blend between cell centres, cells without a value take no part and the sheet ends half-way to them. With `lookup: { cells, rows }` a cell does not hold a value but names a table row (row + 1, 0 = nothing): areas of any outline, rasterised once, coloured from a table per time step, with a darkened border between rows.
96
+ - **`PointValueLayer`**: discs that face the view, one per point (x, y, z, radius in metres), coloured by a value per point; one instanced draw call. `sizeByValue` (0–1) lets the disc area follow the value, `minRadiusPx` keeps far points visible. By default the discs lie over the whole image; `depthTest: true` hides them behind nearer surfaces.
97
+ - **`ShapeValueLayer`**: prisms (`prismMesh`) tinted by the value of the table row each of them carries. Blended over what is already drawn, with depth and a polygon offset. Rows without a value are not drawn unless `neutral` gives them a colour.
98
+
99
+ What they share:
100
+
101
+ - **Values are 16-bit words** (`quantizeValues`): 0 means "no value", 1–65535 span `min`–`max` linearly. One `Uint16Array` per time step: one word per grid cell (row by row, row 0 first), per point, or per table row.
102
+ - **Time steps.** `show(a)` shows one step, `show(a, b, mix)` blends two; where only one of the two has a value it fades in or out. A step is recognised by its array, so walking through steps uploads one small texture per new step and showing a loaded one costs nothing. Keep one array per step and pass the same arrays again.
103
+ - **Style.** `setStyle({ opacity, range })`; `range` is the part of the value range the ramp spans (default `[0, 1]`), for a legend that zooms into the data. `setRamp` replaces the ramp of a raster layer.
104
+ - **Passes and order.** They draw in the `color` and `data` passes, never in the shadow pass, without light or haze, so a colour can be read against the legend. Register them after the layers they should lie on. Nothing of them exists until a layer is constructed, and `dispose()` frees its meshes and textures (take the layer out of the renderer yourself).
105
+ - **Coordinates.** The sheet, the points, the prisms and the corner of a grid are in the coordinates the renderer draws in. A scene drawn relative to a moving origin (`worldOrigin`) has to give them relative to that origin and build them again when it moves.
106
+
107
+ <!-- check: wrap -->
108
+ ```ts
109
+ import { HeightField } from 'wallhammer-web/gen-core';
110
+ import { drapeEvery, drapeTiles, prismMesh } from 'wallhammer-web/gen-mesh';
111
+ import { VALUE_RAMPS, colorRamp, quantizeValues } from 'wallhammer-web/gen-tex';
112
+ import { PointValueLayer, RasterValueLayer, ShapeValueLayer } from 'wallhammer-web/render';
113
+ import type { Renderer } from 'wallhammer-web/render';
114
+ declare const renderer: Renderer;
115
+ declare const field: HeightField;
116
+ // Two time steps of a 60 × 40 grid of 25 m cells; NaN marks cells without a value.
117
+ declare const morning: Float32Array;
118
+ declare const noon: Float32Array;
119
+
120
+ const [min, max] = [5, 35];
121
+ const steps = [quantizeValues(morning, min, max), quantizeValues(noon, min, max)];
122
+ const grid = { x0: 0, z0: 0, cellX: 25, cellZ: 25, cols: 60, rows: 40 };
123
+ const raster = new RasterValueLayer(renderer, { grid, ramp: colorRamp(VALUE_RAMPS.heat), opacity: 0.75 });
124
+ const rect = { x0: 0, z0: 0, x1: 1500, z1: 1000 };
125
+ raster.addTiles(drapeTiles(field, { rect, every: drapeEvery(field, 400_000, rect) }));
126
+ raster.show(steps[0]!, steps[1]!, 0.5); // half-way between the two steps
127
+ renderer.add(raster);
128
+
129
+ // Three points: x, y, z, radius. Table row i belongs to point i.
130
+ const points = new PointValueLayer(renderer, { points: Float32Array.of(100, 210, 80, 6, 400, 214, 300, 6, 900, 209, 650, 9), ramp: colorRamp(VALUE_RAMPS.viridis), sizeByValue: 0.8 });
131
+ points.show(quantizeValues([12, NaN, 40], 0, 50)); // the second point has no value and is not drawn
132
+ renderer.add(points);
133
+
134
+ // Two prisms tinted by rows 0 and 1 of a table; the ramp has six flat bands.
135
+ const shapes = new ShapeValueLayer(renderer, { rows: 2, ramp: colorRamp(VALUE_RAMPS.blues, 6) });
136
+ shapes.addShapes(
137
+ prismMesh(
138
+ [
139
+ { ring: [10, 10, 30, 10, 30, 25, 10, 25], minY: 200, maxY: 212, ref: 0 },
140
+ { ring: [50, 10, 70, 10, 60, 30], minY: 200, maxY: 207, ref: 1 },
141
+ ],
142
+ { growM: 0.25 },
143
+ ),
144
+ );
145
+ shapes.show(quantizeValues([3.5, 9], 0, 10));
146
+ renderer.add(shapes);
147
+
148
+ // Later: take a layer out and free what it holds.
149
+ renderer.remove(raster);
150
+ raster.dispose();
151
+ ```
152
+
153
+ A shader of your own can read the same words: `VALUE_GLSL` (put it right after `#include <header>`) has `valueWord`, `tableCell`, `valueOf`, `blendSteps`, `rampPosition` and `rampCoord`.
154
+
155
+ ## Materials
156
+
157
+ A material is data (`MaterialDesc` in `base`) and is compiled by `renderer.material(desc)`:
158
+
159
+ - `attribs`: fixed attribute locations. The mesh layout and every program of the material share them.
160
+ - `passes`: GLSL (`{ vs, fs }`) per pass, or `'depth'` for the shared shadow programs (`DEPTH_VS`, `DEPTH_FS`). A material with instanced or displaced vertices needs its own shadow program; `'depth'` only transforms `a_pos`.
161
+ - `state`: extra draw state per pass (`DrawState`: depth test and function, depth write, face culling, blending, alpha to coverage, polygon offset). The device applies only what changes.
162
+ - Face culling: `cull: 'none' | 'back' | 'front'` (type `CullMode`). The older `cullBack` (true: `'back'`, false: `'none'`) keeps working; when one state object has both, `cull` wins. The pass base state is `'back'`. The device switches `CULL_FACE` and `cullFace` only when they change. `'front'` draws only the back faces, for example an inflated copy of a mesh drawn behind it as a silhouette.
163
+
164
+ Uniforms are tagged values (`UniformValue`): `{ int }`, `{ float }`, `{ vec2 }`, `{ vec3 }`, `{ vec4 }`, `{ ivec4 }`, `{ mat4 }`.
165
+
166
+ ## Shader includes
167
+
168
+ A line `#include <name>` is replaced by a registered snippet. Rules:
169
+
170
+ - The line must hold only the include and must end with a newline. The regex is `^#include <name>\n`.
171
+ - Includes do not nest. A snippet's own `#include` lines are not resolved. So list them yourself, in dependency order.
172
+ - An unknown name throws when the material is compiled.
173
+
174
+ Built-in and engine-registered includes:
175
+
176
+ | Include | Registered by | Provides |
177
+ | --- | --- | --- |
178
+ | `header` | renderer | `#version 300 es`, precision, the `Frame` block, the `Palette` block (`u_palette[64]`). Also `localUp`, `localHeight`, `localFrame` (see [Local up](#local-up)) and the pixel size helpers `detailVisible`, `metresPerPixelAt`, `detailVisibleAt` (`PIXEL_SIZE_GLSL`), so a material without `<noise>` can fade detail by its size on screen. In the logarithmic depth mode a fragment shader also gets its depth output here (see [Depth modes](#depth-modes)). |
179
+ | `noise` | renderer | `hashU`, `hash1/2/3`, `vnoise`, `vnoise3`. It still contains the pixel size helpers, behind the guard `WH_PIXEL_SIZE`, so including it after the header defines nothing twice. |
180
+ | `shadow` | `EnvironmentLink` | The sun visibility alone, without colours of light: `u_shadowMap`, `cloudLight`, `sunVisibility(worldPos, n, offsetTexels)`, `sunVisibilityBaked(…, baked)`, and the sharp variants `sunVisibilitySharp(worldPos, n, offsetTexels)` and `sunVisibilityBakedSharp(…, baked)`: one depth compare at the centre of the shadow map texel, no filter, so the edge is a hard step (stepped light, toon shading). Guarded by `WH_SHADOW_QUERY`: `<lighting>` contains the same text, so a material may include both, in either order. Needs `<noise>` before it (for `cloudLight`). |
181
+ | `lighting` | `EnvironmentLink` | `u_shadowMap`, `cloudLight`, `sunVisibility(worldPos, n, offsetTexels)`, `sunVisibilityBaked(worldPos, n, offsetTexels, baked)` (see [Shadow modes](#shadow-modes)), `lightOn(n, sun, ao)`, `lightOnAt(worldPos, n, sun, ao)` (see [Local up](#local-up)), `applyFog(display, worldPos)`, `toDisplay(c)`. Needs `<noise>` first. |
182
+ | `sky` | `EnvironmentLink` (stand-ins) or the sky slot | `skyToEye`, `skyColorDir`, `aerialPerspective`. Without the sky slot, stand-ins (no haze, fog colour as sky) keep the same material working. |
183
+ | `atmosphere` | `EnvironmentLink` (stand-in) or the atmosphere slot | `atmosphereAir(worldPos, through)` for the vertex shader and `atmosphereApply(display, worldPos, air, through)` for the fragment shader; `atmosphereApply(display, worldPos)` integrates in the fragment shader instead. With the slot it also defines `WH_ATMOSPHERE` and provides `atmosphereLight(worldPos, n, sun, ao)`, `atmosphereSun(worldPos)` and `atmosphereSky(dir, through, ground)`. Without it `atmosphereApply` returns its input and `atmosphereAir` gives no air. See [The atmosphere](#the-atmosphere). |
184
+ | `point-lights` | `PointLightSet` | The `PointLights` block, `u_lightListA`/`B` and `pointLights(world, normal, wrap)`. Needs `u_time`. See [Point lights](#point-lights). |
185
+ | slot name | `EnvironmentLink` | The `glsl` of each environment slot that has one. |
186
+
187
+ The usual order is `header`, `noise`, `lighting`, `sky`, then slot includes. Register your own with `renderer.includes.set(name, glsl)` before compiling the material.
188
+
189
+ ## The Frame block
190
+
191
+ Members of `Frame`, in order: `u_viewProj`, `u_lightViewProj`, `u_sunDir` (w = used share of the shadow map), the `afterLight` slot members, `u_view`, `u_camRight` (w = pixel growth), `u_camUp` (w = logarithmic depth scale, 0 unless the depth mode is logarithmic), `u_camForward` (w = reference depth), the `afterView` slot members.
192
+
193
+ Engine members (from `ENV_CORE_SLOT`):
194
+
195
+ - after light: `u_sunColor`, `u_ambient`, `u_skyFill`, `u_bounce`, `u_warmTint`;
196
+ - after view: `u_time` (x animation time in seconds, y hour of day), `u_wind`, `u_gust`, `u_cloud`, `u_cloudEdge`, `u_weather` (x snow, y wetness, z fog, w precipitation), `u_fogColor`, `u_snow`, `u_fogShape`.
197
+
198
+ With a shadow mode other than `'single'` the block ends with the members of the shadow areas (`u_shadowArea[n]`, `u_shadowPart[n]`, `u_shadowReach[n]`, `u_shadowFocus`, `u_shadowRight`, `u_shadowUp`, `u_shadowHorizon`, `u_shadowHorizonY`) and the header defines `WH_SHADOW_AREAS` as their number. Materials do not read them; `sunVisibility` does.
199
+
200
+ Free lanes: `u_time.zw` and `u_wind.zw`. `gen-arch`'s window light uses `u_time.zw`; `gen-vegetation`'s sway uses `u_wind.zw`. Read the generated block (`assembleFrameBlock(slots).glsl`) when in doubt.
201
+
202
+ ## Environment slots
203
+
204
+ The environment is generic. A slot (`EnvSlot` in `base`) turns it into what content needs:
205
+
206
+ - `params`: plain, mutable parameters.
207
+ - `compute(env, params)`: a pure function of `FrameEnvironment`.
208
+ - `fields`: the vec4 members it declares, or lanes of an existing member, filled by `lanes(values)`.
209
+ - `glsl`: optional, registered as the include `<name>`.
210
+ - `shadowKey(values)`: optional part of the shadow cache key.
211
+
212
+ `assembleFrameBlock(slots)` puts `ENV_CORE_SLOT` first and sorts members by `order` within their region. The engine uses multiples of 10. It throws on a duplicate slot name or a lane filled twice. The block is fixed when the engine is created, so pass every slot to `createEngine({ slots })`. `engine.link.value(slot)` returns a slot's values for the last frame. [Recipes](recipes.md#add-an-environment-slot) has a full slot.
213
+
214
+ ### Cloud cover by place
215
+
216
+ `weather.cloudCover` is one number for the whole world. Under radial up (see [Local up](#local-up)) `cloudFieldSlot(field)` (in `env`) makes the cover vary by place instead: a profile of 8 covers by `|dot(up, axis)|` (linear between, `zonal[0]` where up is across the axis, `zonal[7]` along it), plus value-noise patches of `patchSizeM` that move the cover by up to `patchAmount`, bent by one more lookup (`patchWarp`) and shifted by `patchOffset` (the app drifts it with its time). The field is fixed in one frame; `axis` and the up the shader reads are in that frame. The slot has no include of its own: when the frame block holds a slot named `CLOUD_FIELD_SLOT`, the environment link registers `lightingGlsl({ cloudField: true })` as `lighting`, whose `cloudLight` then reads the cover at the point and gives the share of the sun there. The frame's light stays dimmed by the global `weather.cloudCover`, so the shader divides by that dimming (`u_cloudFieldLight.y`); a shader that takes the sun from `sunVisibility` and wants the field's shade multiplies by it. Without the slot `LIGHTING` is the include, unchanged.
217
+
218
+ `cloudFieldCover(field, up, radiusM)` and `cloudFieldSun(cover, noise, darkness)` are the same functions on the CPU: an app asks them for the weather under the eye. Every cover 0 (`active` 0) means full sun without a lookup.
219
+
220
+ `CloudShellLayer` (in `runtime`) draws the clouds themselves as a shell `heightM` above a sphere (`center`, `baseRadiusM`, render space) with the same field, so the clouds sit over their shadows. `toField` (3 × 3, row-major) turns render directions into the field's frame, `light` is the direction to the sun, `opacity` 0 draws nothing. It throws without the slot. Add it before transparent layers that should be drawn over it.
221
+
222
+ <!-- check: wrap -->
223
+ ```ts
224
+ import { PerspectiveOrbitRig, definePalette } from 'wallhammer-web';
225
+ import { cloudFieldSlot } from 'wallhammer-web/env';
226
+ import { CloudShellLayer, createEngine } from 'wallhammer-web/runtime';
227
+ declare const canvas: HTMLCanvasElement;
228
+
229
+ const slot = cloudFieldSlot({ axis: [0, 1, 0], zonal: [0.6, 0.5, 0.3, 0.3, 0.4, 0.5, 0.5, 0.3], patchAmount: 0.4, patchSizeM: 45_000, patchWarp: 0.6, patchOffset: [0, 0, 0], darkness: 0.3 });
230
+ const engine = createEngine({ canvas, view: new PerspectiveOrbitRig(), palette: definePalette({ ground: '#4d4335' }), background: [0.6, 0.7, 0.8], slots: [slot] });
231
+ const shell = new CloudShellLayer(engine.renderer, engine.link);
232
+ shell.baseRadiusM = 600_000;
233
+ shell.center = [0, -600_000, 0];
234
+ engine.add(shell);
235
+ // Each frame: drift the patches with the time of the app.
236
+ slot.params.patchOffset = [0, 0, 3 * engine.env.time.time];
237
+ ```
238
+
239
+ ## The environment
240
+
241
+ `Environment` (in `env`) holds:
242
+
243
+ - `mode`: `'studio'` (default, fixed light), `'day'` (sun from `site`, date and hour) or `'fixed'` (a light given directly, see below).
244
+ - Two clocks. `time` drives wind, clouds and transient pieces; it plays by default (`animate: true`). `day` is the hour; it wraps at 24 and is **paused** by default. Default hour 13.
245
+ - `weather` (`cloudCover`, `precipitation`, `precipitationKind`, `snowCover`, `wetness`, `fog`, all 0..1), `wind`, `clouds`, `fogLayer`, `site`.
246
+
247
+ ### A fixed light
248
+
249
+ `env.setFixedLight(toLight, light?)` switches to `mode: 'fixed'`: the sun stands in the world direction `toLight`
250
+ (toward the light, need not be unit, normalised each frame; the sun's height is its angle over the horizontal plane) and the colours and
251
+ strengths are the ones given, not derived from a sun position. `light` (type `FixedLight` without `toLight`) may set
252
+ `sun`, `ambient`, `skyFill`, `bounce`, `warmTint` (RGB), `exposure` and `backdrop`; what it leaves out keeps its value.
253
+ Call it again at any time to move or recolour the light (a new direction refits the shadow map as any sun movement
254
+ does). `EnvironmentConfig.fixed` gives the starting values (`DEFAULT_FIXED`); the day clock is paused in this mode.
255
+ Sky colour and fog are the day values of the weather. `'studio'` and `'day'` are unchanged.
256
+
257
+ <!-- check: wrap -->
258
+ ```ts
259
+ import { Environment } from 'wallhammer-web/env';
260
+
261
+ const env = new Environment({ fixed: { exposure: 1.1 } });
262
+ env.setFixedLight([-0.4, 0.8, 0.3], { sun: [1.0, 0.95, 0.85], ambient: [0.30, 0.32, 0.38] });
263
+ env.setFixedLight([0.6, 0.5, -0.2]); // later: only the direction
264
+ console.log(env.mode, env.fixed.exposure);
265
+ ```
266
+
267
+ ## Shadows
268
+
269
+ The shadow map is refitted only when the view key, the light direction or `renderer.shadowKeyExtra` change. A static frame is one pass. Consequences:
270
+
271
+ - `Layer.cull` runs only on a refit. A layer whose visible set changes for another reason must make the renderer refit: return true from `cullStale()` (as `PieceLayer` and `InstanceCellLayer` do after an add), or call `renderer.invalidateShadows()`.
272
+ - Animation time is not part of the key. Something that moves and casts a shadow must refresh the map itself. `TransientLayer` does this while its batches move.
273
+
274
+ Options: `shadowMapSize` (default 4096), `shadowSoftnessM` (default 0.9), `shadowDistanceM` (perspective only, default the whole scene).
275
+
276
+ ### Moving casters
277
+
278
+ A layer whose casters move says so: `shadowCasters: 'dynamic'` and `shadowDirty()`, which the renderer asks once per frame and which returns true when what the layer casts changed since it was last drawn into the shadow map. Nobody calls `invalidateShadows()` for it. Without such a layer nothing below happens and the frame is what it was.
279
+
280
+ In the mode `'single'`, with at least one dynamic layer:
281
+
282
+ - A second depth target of the same size, made with the first dynamic layer, keeps only the static casters (every layer without `shadowCasters: 'dynamic'`). It is drawn on a refit only: when the view key, the light direction or `shadowKeyExtra` change, a static layer's `cullStale()` is true, `invalidateShadows()` is called, or the first dynamic layer comes or the last one goes.
283
+ - In a frame where it was drawn, or where a dynamic layer's `shadowDirty()` (or `cullStale()`) is true, its depth is copied into the map that is sampled (`Device.copyDepth`, a depth blit of the used square) and only the dynamic layers are drawn over it. Around that draw each dynamic layer's `cull` is called with the light's volume of the fitted map (`'shadow'`) and then with the view's (`'view'`), as at a refit; static layers are not culled again.
284
+ - A frame where nothing moved draws no shadow pass, as before. `FrameStats.shadowTriangles` and `shadowDrawCalls` count everything drawn into the map in the frame; `dynamicShadowTriangles` and `dynamicShadowDrawCalls` the dynamic part of it.
285
+ - Set `shadowCasters` before the layer is added and leave it; a layer that changes it is not followed until the next refit.
286
+
287
+ The modes `'snapped'` and `'cascades'` keep no static map: a dynamic layer's `shadowDirty()` redraws all their areas, as `invalidateShadows()` does. That is correct but costs the whole scene in every such frame.
288
+
289
+ The mode `'single'` still refits (and draws the static casters again) in every frame in which the view changes, for instance while the camera turns.
290
+
291
+ ### Shadow modes
292
+
293
+ `RendererOptions.shadows.mode` chooses how the shadow map is laid out. The default is `'single'`: the map above, fitted to what the view sees, and nothing in this section applies. The mode is fixed when the renderer is created (it changes the program header); `renderer.shadowMode` tells it.
294
+
295
+ | Mode | The map | For |
296
+ | --- | --- | --- |
297
+ | `'single'` | One map fitted to the view, drawn anew whenever the view changes. | Small scenes. |
298
+ | `'snapped'` | One map over a square of the light's plane around the centre of the view, fixed to the world's texel grid. Kept between frames; a pan draws only the border it uncovers. | Views from above over a large scene. |
299
+ | `'cascades'` | Two to four maps around the eye in the quarters of the one shadow texture, each reaching farther and coarser, blended into each other. | Perspective views that see far. |
300
+
301
+ <!-- check: wrap -->
302
+ ```ts
303
+ import { PerspectiveOrbitRig, definePalette } from 'wallhammer-web';
304
+ import { createEngine } from 'wallhammer-web/runtime';
305
+
306
+ const engine = createEngine({
307
+ canvas: document.querySelector<HTMLCanvasElement>('canvas')!,
308
+ view: new PerspectiveOrbitRig(),
309
+ palette: definePalette({ ground: '#4d4335' }),
310
+ background: [0.6, 0.7, 0.8],
311
+ renderer: { shadowMapSize: 4096, shadows: { mode: 'cascades', cascades: 4, firstReachM: 48, reachM: 3000 } },
312
+ });
313
+ console.log(engine.renderer.shadowMode, engine.renderer.lastStats.shadowUpdates);
314
+ ```
315
+
316
+ How the two new modes work:
317
+
318
+ - **Areas on a block grid.** Each map holds an area: a square of the light's plane, 16 blocks along its edge, placed on a grid of blocks counted from the world origin (`worldOrigin` is taken into account). A texel therefore never moves against the world, and a shadow edge does not shimmer when the view moves. An area follows its focus in whole blocks, and only when the focus has left its middle block by a quarter of a block; it always covers 7 blocks around the focus.
319
+ - **The cache.** An area is drawn anew only when the light direction (compared to 4 decimals; the light's plane is laid by the direction rounded the same way, so a light that drifts by less keeps the map and its lookup in step), `shadowKeyExtra` or the scene's depth range change, when `invalidateShadows()` is called or a layer's `cullStale()` returns true. Otherwise a frame draws no shadow pass at all. `FrameStats.shadowUpdates` counts the parts of the map drawn in a frame.
320
+ - **`'snapped'`** addresses its one map around the edges (a texel's place is its world texel number modulo the map size), so a step keeps every texel it still covers and draws only the uncovered strips, each with the casters the light's volume over that strip selects. The block size follows the scale of the view on a ladder of √2 steps, from the size the softness asks for up to a reach of `reachM` (default 2048 m); a change of step draws the map once.
321
+ - **`'cascades'`** centres every area on the eye (on the centre of the view for an orthographic one). Reaches grow in equal ratios from `firstReachM` (default 48) to `reachM` (default `shadowDistanceM`, else 4000). An area that steps is drawn whole, the far ones rarely. The lookup takes the finest area whose reach holds the point and blends into the next over the outer 15 % of the reach, so there is no seam.
322
+ - **The light may stand straight above.** The areas use a light frame that is defined for every direction.
323
+ - **Beyond the reach** the lookup returns the far term: `baked` of `sunVisibilityBaked(worldPos, n, offsetTexels, baked)` (what the material knows itself, for example an occlusion value baked per vertex or per tile; 1 = lit; `sunVisibility` passes 1) times the scene's light horizon when `renderer.shadowHorizon` is set. The last area blends into it over the outer 25 % of its reach, so shadows do not end with a jump. In the `'single'` mode `sunVisibilityBaked` returns `baked` outside the map and the usual lookup inside.
324
+ - **The light horizon** is a coarse texture over the scene's x–z extent: per texel the height below which a point is hidden from the light. A texel with code 0 hides nothing, whatever the height of the point. `lightHorizon` and `horizonTexture` in `gen-tex` make it from a `SurfaceRaster` of surface heights (see [Generators](generators.md)); it belongs to one light direction, so make a new one when the light has moved. It is sampled through `u_shadowHorizonMap` on the fixed texture unit `SHADOW_HORIZON_UNIT`, which the device sets in every program (`Device.fixSampler`); layers need not know about it.
325
+
326
+ <!-- check: wrap -->
327
+ ```ts
328
+ import { SurfaceRaster, horizonTexture, lightHorizon } from 'wallhammer-web/gen-tex';
329
+ import type { Renderer } from 'wallhammer-web/render';
330
+
331
+ declare const renderer: Renderer;
332
+ declare const surfaceAt: (x: number, z: number) => number;
333
+
334
+ // 8 m cells over a 4 km square whose corner is the world origin; one outline raised to 30 m above the surface.
335
+ const surface = new SurfaceRaster(500, 500, 8, surfaceAt);
336
+ surface.raisePolygon([[100, 100, 160, 100, 160, 140, 100, 140]], surfaceAt(130, 120) + 30);
337
+ const packed = horizonTexture(lightHorizon(surface, renderer.lightDirection), surface);
338
+ renderer.shadowHorizon = {
339
+ texture: renderer.device.createTexture(packed.texture),
340
+ originX: 0,
341
+ originZ: 0,
342
+ sizeX: surface.cols * surface.step,
343
+ sizeZ: surface.rows * surface.step,
344
+ baseY: packed.baseY,
345
+ rangeM: packed.rangeM,
346
+ };
347
+ ```
348
+
349
+ Limits: in the new modes `u_lightViewProj` is the projection of the first area only (read shadows through `sunVisibility`); the horizon assumes that up is +y; `Layer.cull` for the shadow pass gets a box volume per drawn part instead of one volume per frame; the shadow texture of `'snapped'` repeats, so a program that samples `u_shadowMap` itself must wrap its coordinates as `whShadowArea` does.
350
+
351
+ ## Depth modes
352
+
353
+ `RendererOptions.depth` chooses how the main passes (`color`, `data`, `overlay`) store depth. The default is `'standard'` and changes nothing. The shadow pass always stores standard depth.
354
+
355
+ | Mode | Depth buffer | What it gives | Cost |
356
+ | --- | --- | --- | --- |
357
+ | `'standard'` | The canvas's own. | A perspective view holds a far : near ratio of a few thousand (the rigs use at most 2000). | None. |
358
+ | `'reversed'` | 32-bit float, 1 at the near plane, 0 at infinity (`EXT_clip_control`). | About the same relative precision at every distance: 1 m and 1,000 km in one view. No far plane. | An offscreen target and one copy per frame. |
359
+ | `'logarithmic'` | 32-bit float, the fragment shader writes `log2(1 + distance)`. | The same range. The fallback when `'reversed'` is asked for and the browser lacks `EXT_clip_control`. | The same, and no early depth test (roughly 10 % more fragment work). |
360
+
361
+ `renderer.depthMode` is the mode in effect after the fallback. `depthNearM` (default 0.1, also a field of the renderer) is the near plane of a perspective view in the two new modes; the far : near rule of the rig does not apply there.
362
+
363
+ <!-- check: wrap -->
364
+ ```ts
365
+ import { PerspectiveOrbitRig, definePalette } from 'wallhammer-web';
366
+ import { createEngine } from 'wallhammer-web/runtime';
367
+
368
+ const engine = createEngine({
369
+ canvas: document.querySelector<HTMLCanvasElement>('canvas')!,
370
+ view: new PerspectiveOrbitRig(),
371
+ palette: definePalette({ ground: '#4d4335' }),
372
+ background: [0.6, 0.7, 0.8],
373
+ renderer: { depth: 'reversed', depthNearM: 0.1 },
374
+ });
375
+ console.log(engine.renderer.depthMode); // 'reversed', or 'logarithmic' without EXT_clip_control
376
+ ```
377
+
378
+ By hand (see [Without `createEngine`](#without-createengine)): `new Device(createContext(canvas, mode))`, then `new Renderer(device, { depth: mode, … })`. The context has to know the mode, because a canvas for the two new modes is created without its own depth buffer and antialiasing.
379
+
380
+ How it works, and what a material has to do (nothing):
381
+
382
+ - **The device owns the convention of the bound target.** `DrawState` keeps one meaning in every mode: `depthFunc: 'less'` passes what is nearer, a positive `polygonOffset` pushes away from the viewer, `device.clear` clears depth to the farthest value. With reversed depth the device turns these into "greater", a negated offset and a clear to 0, and switches the clip range to 0…w for the main target and back to −w…w for a depth target.
383
+ - **The renderer builds the matrix.** In the two new modes a perspective `u_viewProj` comes from `depthViewProj` (module `base`): the rig's axes, field of view and eye with the renderer's own depth row. A rig needs no code per mode; `View.viewProj` is used as it is only in the standard mode and for orthographic views.
384
+ - **A canvas cannot have a float depth buffer.** In the two new modes the device draws into its own multisampled target (`device.target(null)` binds it) and `device.present()`, called by the renderer at the end of a frame, copies the result to the canvas.
385
+ - **Logarithmic depth is added to fragment shaders by `renderer.resolve`.** A fragment shader of the main target that starts with `#include <header>` gets its `main` renamed and a new `main` that calls it and then writes `gl_FragDepth` from `gl_FragCoord.w`. No varying is needed, so vertex shaders stay as they are. The polygon offset of the draw state reaches such a shader as a uniform, set by the device before each draw.
386
+ - `u_camUp.w` carries the logarithmic scale (0 in the other modes). The header defines `WH_DEPTH_REVERSED` or `WH_DEPTH_LOGARITHMIC` for a shader that reads depth values of the main target itself.
387
+
388
+ Rules for code that goes around the usual path:
389
+
390
+ - A program built with `device.program` for the main target must get its fragment source through `renderer.resolve(src)` and its shadow or bake sources through `renderer.resolve(src, 'other')`. A source that never mentions `gl_Position` counts as a fragment shader.
391
+ - A fragment shader with its own `#version` line instead of `<header>` is not wrapped. In the logarithmic mode use it only for draws with the depth test off.
392
+ - A vertex shader that writes clip coordinates directly must not assume that z = 1 is far. Draw such things with the depth test off (as the sky and the precipitation layers do), or put hidden vertices outside the clip volume on x or y.
393
+ - Bind the main target only with `device.target(null)`, and read pixels of the frame only after `renderer.render` has returned.
394
+
395
+ ## Local up
396
+
397
+ By default up is +y everywhere, and everything that needs up says so in its shader. `RendererOptions.radialUp` (off by default) makes up point away from one point instead, for a world on a sphere:
398
+
399
+ <!-- check: wrap -->
400
+ ```ts
401
+ import type { Device } from 'wallhammer-web/gpu';
402
+ import { Renderer } from 'wallhammer-web/render';
403
+ import type { RendererOptions } from 'wallhammer-web/render';
404
+ import { SphereWorld } from 'wallhammer-web/world';
405
+ declare const device: Device;
406
+ declare const options: RendererOptions;
407
+
408
+ const shape = new SphereWorld(100_000);
409
+ // `shape.radial` is { center, radiusM }: the centre in world metres (doubles) and the radius of the base surface.
410
+ const renderer = new Renderer(device, { ...options, radialUp: shape.radial });
411
+ renderer.upCenter(); // the centre relative to the render origin, or null when up is +y
412
+ ```
413
+
414
+ Every program header then defines `WH_LOCAL_UP`, and the Frame block ends with `vec4 u_upCenter` (xyz the centre in render space, w the radius). Three functions exist in every shader, with or without the option:
415
+
416
+ | Function | Up is +y (default) | With `radialUp` |
417
+ | --- | --- | --- |
418
+ | `localUp(p)` | `vec3(0, 1, 0)` | unit vector from the centre to `p` |
419
+ | `localHeight(p)` | `p.y` | distance from the centre minus the radius |
420
+ | `localFrame(p)` | identity | the world's axes turned by the shortest rotation that takes +y to up; the middle column is up |
421
+
422
+ Write a new shader with these instead of `.y` and `vec3(0, 1, 0)` and it works on both kinds of world: an upright object is `base + localFrame(base) * (a_pos * scale)`, the share of sky a normal sees is `dot(n, localUp(p))`. On the CPU the same frame is `upFrame(radialUpAt(center, p))` (module `base`); `toFramePlane(frame, dir)` gives a world direction as the (x, z) pair of that frame, and `radialHeight` is the height.
423
+
424
+ What follows the option in the engine:
425
+
426
+ - **`lighting` include.** `lightOn(n, sun, ao)` takes the sky and bounce light by the up of the point last given to `sunVisibility`, `sunVisibilityBaked` or `cloudLight`; `lightOnAt(worldPos, n, sun, ao)` names the point. Where up turns away from the sun the direct light and the sky light fade out (the night side). Cloud shadows are read from a field on the sphere. `applyFog` takes the fog layer as heights above the base surface (`env.fogLayer = { bottomY: 0, topY: 1500 }` is then 0–1500 m above the sphere).
427
+ - **Rigs.** `RigLayer` stands every rig along the up of its position, turns its heading in the local horizon and culls it there.
428
+ - **Instances.** `InstancedLayerOptions.upCenter` (pass `() => renderer.upCenter()`) culls instance boxes that extend along the local up; `cullInstances` takes the same centre as its sixth argument. The streamed world culls by cell boxes and needs nothing.
429
+ - **Slots of `gen-ground` and `gen-vegetation`.** `snowOn` settles snow by the local up; the plant shader stands plants along the up of their base and sways them in the local horizon.
430
+ - **Precipitation.** `PrecipitationLayer` lets rain and snow fall along the up under the eye (towards `renderer.upCenter()`), with the wind across it.
431
+ - **Cloud cover by place.** See [Cloud cover by place](#cloud-cover-by-place).
432
+
433
+ Not adapted: the shadow modes `'snapped'` and `'cascades'` and the light horizon (they assume ground along y), the `sky` include and the sky layer, `InstanceCellLayer`, `PieceLayer`, `TransientLayer` and the value layers, the shaders of `gen-arch`, and the joint pattern of the rig finish `'tiles'` (a grid in render-space xz). The environment computes one sun direction for a site whose up is +y. `localFrame` has no shortest rotation exactly opposite +y: where up is within a quarter of a degree of −y (cosine under −0.99999, a disc of 450 m radius on a sphere of 100 km) the frame is the world turned by half a turn about x, so objects there stand along −y exactly, and headings jump at the rim of that disc.
434
+
435
+ ## Levels of detail with a fade
436
+
437
+ `LevelFade` (`core`) picks a level from one number, for example screen pixels per metre: level 0 is the finest, level k + 1 takes over once the value drops below `below[k]`. A dead band around every threshold (`hysteresis`, a share of it) keeps the level from flickering, and a change moves a continuous `position` to the new level over `seconds`. The class has no clock: pass the time since the last frame to `update`. `limit` holds the position at a finer level while a coarser one is not ready yet.
438
+
439
+ The transition is drawn as a screen-door fade (`FADE_GLSL`): while the position is between two levels both are drawn, and every fragment belongs to exactly one of them by a fixed screen pattern. Nothing is blended, so the passes, the depth buffer and the draw order stay as they are. `withFade(desc)` adds the fade to every pass of a material that has its own program (a pass drawn with `'depth'` stays whole; to fade it as well, write the pass out as `{ vs: DEPTH_VS, fs: DEPTH_FS }` from `render` before wrapping); the uniform is `u_fade`, and a layer that never sets it is drawn whole.
440
+
441
+ ```ts
442
+ import { LevelFade, withFade } from 'wallhammer-web/core';
443
+ import type { MaterialDesc, MeshData, View } from 'wallhammer-web/base';
444
+ import { MeshLayer } from 'wallhammer-web/render';
445
+ import type { Renderer } from 'wallhammer-web/render';
446
+
447
+ declare const renderer: Renderer;
448
+ declare const fineDesc: MaterialDesc;
449
+ declare const coarseDesc: MaterialDesc;
450
+ declare const fineMesh: MeshData;
451
+ declare const coarseMesh: MeshData;
452
+ declare const requestFrame: () => void;
453
+
454
+ const fineMaterial = renderer.material(withFade(fineDesc));
455
+ const coarseMaterial = renderer.material(withFade(coarseDesc));
456
+ const layers = [
457
+ new MeshLayer({ material: fineMaterial, mesh: renderer.createMesh(fineMesh, fineMaterial) }),
458
+ new MeshLayer({ material: coarseMaterial, mesh: renderer.createMesh(coarseMesh, coarseMaterial) }),
459
+ ];
460
+ for (const layer of layers) renderer.add(layer);
461
+ const passes = layers.map((layer) => layer.passes);
462
+
463
+ // The coarse level takes over below half a screen pixel per metre.
464
+ const levels = new LevelFade({ below: [0.5], hysteresis: 0.15, seconds: 0.35 });
465
+ let last = 0;
466
+ renderer.beforeFrame.push((view: View) => {
467
+ const now = performance.now();
468
+ // A transition starts with the frame that asks for it: time the page stood still before does not count.
469
+ const dt = levels.moving ? Math.min(0.1, (now - last) / 1000) : 0;
470
+ last = now;
471
+ const before = levels.position;
472
+ const more = levels.update(1 / view.metresPerPixel, dt);
473
+ layers.forEach((layer, level) => {
474
+ layer.passes = levels.shown(level) ? passes[level]! : new Set();
475
+ layer.uniforms = { ...layer.uniforms, ...levels.uniforms(level) };
476
+ });
477
+ // The shadow pass fades too, and the shadow map is drawn anew only when asked.
478
+ if (levels.position !== before) renderer.invalidateShadows();
479
+ if (more) requestFrame();
480
+ });
481
+ ```
482
+
483
+ A level may span several entries: `levels.shown(0, 1)` and `levels.fade(0, 1)` are for something drawn on levels 0 and 1 alike. Neighbouring spans get complementary patterns.
484
+
485
+ ## Point lights, particles and instance sets
486
+
487
+ Three things a lit, animated scene needs besides the sun: many small lights, looping particles, and meshes that move
488
+ in their own way. Each is plain data owned by the app; the engine selects, packs and draws it without allocating in
489
+ the frame. Static meshes for such a scene are best cut into chunks first (`chunkMeshes` in `gen-mesh`) and drawn by a
490
+ `PieceLayer`, one draw per visible chunk.
491
+
492
+ <!-- check: wrap -->
493
+ ```ts
494
+ import type { MaterialDesc, MeshData } from 'wallhammer-web/base';
495
+ import { chunkMeshes } from 'wallhammer-web/gen-mesh';
496
+ import { InstanceSetLayer, ParticleLayer, PieceLayer, PointLightSet, instanceSet, pushInstance } from 'wallhammer-web/render';
497
+ import type { Renderer } from 'wallhammer-web/render';
498
+ declare const renderer: Renderer;
499
+ declare const staticMeshes: MeshData[];
500
+ declare const partMesh: MeshData;
501
+ declare const solidDesc: MaterialDesc; // includes <point-lights>
502
+ declare const instancedDesc: MaterialDesc; // also INSTANCE_SET_GLSL and instanceSetAttribs
503
+ declare const eye: [number, number, number];
504
+
505
+ // Lights first: the set registers the include the materials need.
506
+ const lights = new PointLightSet(renderer, { max: 32 });
507
+ lights.add({ position: [4, 3, -2], color: [1, 0.7, 0.4], radius: 9, intensity: 1, flicker: 0.15, group: 1 });
508
+
509
+ const solid = renderer.material(solidDesc);
510
+ const statics = new PieceLayer({ material: solid, order: 'front-to-back', lights, name: 'statics' });
511
+ for (const c of chunkMeshes(staticMeshes, { cellM: 56, padM: 0.5 })) statics.add({ mesh: renderer.createMesh(c.data, solid), min: c.min, max: c.max });
512
+
513
+ const moving = new InstanceSetLayer(renderer, { material: renderer.material(instancedDesc), lights, name: 'moving' });
514
+ const set = instanceSet(partMesh, 64);
515
+ moving.add(set);
516
+ pushInstance(set, [1, 0, 0, 0, 1, 0, 0, 0, 1, 2, 0, 5], 0.8, 0.6, 0.4, 0);
517
+
518
+ const particles = new ParticleLayer(renderer, [
519
+ { position: [0, 2, 0], count: 40, life: 6, size: [0.6, 2.4], rise: 0.8, spread: [0.3, 0.15], colorStart: [0.5, 0.5, 0.5, 0.5], colorEnd: [0.6, 0.6, 0.6, 0] },
520
+ ]);
521
+ renderer.add(statics);
522
+ renderer.add(moving);
523
+ renderer.add(particles);
524
+
525
+ // Every frame, before rendering:
526
+ lights.gains[1] = 0.8; // fade group 1
527
+ lights.update(eye[0], eye[1], eye[2]);
528
+ ```
529
+
530
+ ### Point lights
531
+
532
+ `PointLightSet` holds `PointLight` records (`position`, `color`, `radius` where the light reaches zero, `intensity`,
533
+ `flicker` 0–1, `group`). The owner may change any field or the gain of a group (`gains[group]`, default 1) at any time.
534
+ `update(x, y, z)` once per frame selects at most `max` lights (default 32) for the eye at that point: brighter than
535
+ `threshold` after gains, nearer and larger first. It packs them into the uniform block `PointLights` (binding
536
+ `POINT_LIGHTS_BINDING`) and uploads it once. The set registers the include `<point-lights>` when it is made, so make it
537
+ before compiling the materials that use it; a material that includes it without a set fails to compile.
538
+
539
+ The include gives `pointLights(world, normal, wrap)`: the summed light at a point, with `wrap` > 0 letting it reach round
540
+ the terminator (0 is plain Lambert). It reads `u_time` of the Frame block for the flicker, whose phase follows the
541
+ light, not its slot. Multiply the result into the albedo as you do the sun.
542
+
543
+ The cost per pixel does not grow with the number of lights. A draw names at most `POINT_LIGHTS_PER_DRAW` (8) of the
544
+ selected lights in the uniforms `u_lightListA` and `u_lightListB`, and the shader visits only those. `PieceLayer` with
545
+ `lights` fills the list per piece from the lights whose sphere reaches the piece's box (`bindFor(program, box)`), in
546
+ order of importance; a piece out of every light's reach visits none. A piece that more than 8 lights reach gets the
547
+ whole selection rather than lose some of them (the cost per pixel is then bounded by `max`; `crowdedDraws` counts such
548
+ draws since the last `update`, so smaller pieces can be chosen where it is high). A draw that sets no list sees the whole selection
549
+ (`bindAll`, also the state of a fresh program), which `InstanceSetLayer` uses, since its sets spread over the scene;
550
+ `bindNone` turns them off for a draw. A scene without a `PointLightSet` pays nothing.
551
+
552
+ ### Particles
553
+
554
+ `ParticleLayer(renderer, sources, { budget?, name? })` draws looping `ParticleSource`s: a birth disc (`position`,
555
+ `spread[0]`), `count` particles alive at once born one after the other over `life` seconds, size from `size[0]` to
556
+ `size[1]`, upward speed `rise`, horizontal spread speed `spread[1]`, `gravity`, the share of the wind `wind` (default 1),
557
+ colour and opacity from `colorStart` to `colorEnd`. `blend` is `'blend'` (alpha over the scene) or `'add'` (light added),
558
+ `shape` is `'soft'` (a lit noise puff, turned per particle) or `'core'` (a bright core with a flicker). Opacity is
559
+ multiplied by `gains[group]` (four groups, default 1), so a group can be faded at run time.
560
+
561
+ The whole life of a particle is computed in the vertex shader from `u_time.x`: nothing is simulated, pausing the clock
562
+ freezes the particles and scrubbing it shows the same picture. The instance buffers are written once, by the
563
+ constructor or by `setSources`. The budget (default 4096) is shared by all sources in order; `counts.dropped` tells how
564
+ many particles did not fit. The layer draws in the colour pass only, at most two draws (blended first, then added), with
565
+ the depth test and no depth write: add it after the opaque layers. The materials read `u_time`, `u_wind`, `u_warmTint`
566
+ and the `lighting` include of the environment.
567
+
568
+ `TransientLayer` dust stays separate: its puffs are one-shot events at absolute clock times that come and go with
569
+ batches of falling pieces, while particle sources loop with no start or end.
570
+
571
+ ### Instance sets
572
+
573
+ An `InstanceSet` (`instanceSet(mesh, capacity, { name?, castShadow?, visible? })`) is one mesh in its own coordinates
574
+ and `capacity` records of `INSTANCE_SET_FLOATS` (16) floats: a 3 × 4 matrix as four columns (the linear part column by
575
+ column, then the translation) and four free numbers (typically a tint and one more value). The owner writes records with
576
+ `writeInstance(set, i, m, a, b, c, d)` or appends with `pushInstance`, sets `count`, and sets `dirty` after a change.
577
+ `InstanceSetLayer` uploads the dirty sets at the start of the next frame (a `Renderer.beforeFrame` hook; `dispose()`
578
+ removes it) over the set's own array, and draws each visible set with one instanced draw, in the shadow pass too when it
579
+ casts shadows.
580
+
581
+ The material's vertex shader adds `INSTANCE_SET_GLSL`, which declares the attributes `i_m0`, `i_m1`, `i_m2`, `i_extra`
582
+ and gives `instanceLinear()`, `instancePoint(p)` and `instanceNormal(n)`; `instanceSetAttribs(first)` gives their
583
+ locations after the mesh's own attributes.
584
+
585
+ The layer is a dynamic shadow caster: `shadowCasters` is `'dynamic'` and `shadowDirty()` is true when a set that casts
586
+ shadows was uploaded, added, removed, shown or hidden since the layer was last drawn into the shadow map. The renderer
587
+ then draws only the dynamic layers over the kept static shadow map; the app never calls `invalidateShadows` for it.
588
+ A layer whose material has no shadow pass, or whose sets never cast shadows, never reports `shadowDirty()`, so it
589
+ costs no shadow redraw.
590
+
591
+ One set may be added to several layers of one renderer, for example one material for the surface and another (with
592
+ `cull: 'front'`) for an outline. The layers share the set's GPU instance buffer: whichever layer uploads first writes
593
+ the records once and clears `dirty`, the others only take the new count. Each layer keeps its own vertex binding of the
594
+ mesh, because each material has its own attribute locations. The buffer is deleted when the last layer removes the set.
595
+
596
+ The layer does not cull, but `cull` returns the records of its visible sets, so `FrameStats.instancesVisible` counts
597
+ them.
598
+
599
+ <!-- check: wrap -->
600
+ ```ts
601
+ import type { MeshData } from 'wallhammer-web/base';
602
+ import { InstanceSetLayer, instanceSet } from 'wallhammer-web/render';
603
+ import type { Material, Renderer } from 'wallhammer-web/render';
604
+ declare const renderer: Renderer;
605
+ declare const surface: Material;
606
+ declare const outline: Material;
607
+ declare const shape: MeshData;
608
+
609
+ const set = instanceSet(shape, 64, { name: 'props' });
610
+ const fill = new InstanceSetLayer(renderer, { material: surface });
611
+ const edge = new InstanceSetLayer(renderer, { material: outline, passes: ['color'], state: { color: { cull: 'front' } } });
612
+ fill.add(set);
613
+ edge.add(set); // the same records, uploaded once
614
+ renderer.add(fill);
615
+ renderer.add(edge);
616
+ ```
617
+
618
+ ## Instances near the viewer
619
+
620
+ `NearInstanceLayer` (`render/near-instances.ts`) draws the records of `nearScatter`
621
+ ([Instances near the viewer](generators.md#instances-near-the-viewer)) round the eye.
622
+
623
+ <!-- check: wrap -->
624
+ ```ts
625
+ import type { MaterialDesc, MeshData, Vec3 } from 'wallhammer-web/base';
626
+ import type { Device } from 'wallhammer-web/gpu';
627
+ import { NearInstanceLayer } from 'wallhammer-web/render';
628
+ import type { Renderer } from 'wallhammer-web/render';
629
+ declare const engine: { device: Device };
630
+ declare const renderer: Renderer;
631
+ declare const MY_MATERIAL: MaterialDesc;
632
+ declare const unitShape: MeshData;
633
+ declare const key: string;
634
+ declare const anchor: Vec3, radiusM: number, data: Float32Array;
635
+ declare const dir: Vec3, strength: number, timeS: number, eye: Vec3, gain: number;
636
+
637
+ const layer = new NearInstanceLayer(engine.device, {
638
+ material: renderer.material(MY_MATERIAL), // its vertex shader includes NEAR_INSTANCE_GLSL
639
+ kinds: [{ mesh: unitShape, fade: { reachM: 60, band: 0.6, softM: 9 }, maxInstances: 44_000, bendM: 0.4 }],
640
+ origin: () => renderer.worldOrigin,
641
+ });
642
+ renderer.add(layer);
643
+ layer.put(key, 0, { anchor, radiusM, data }); // one kind of one set; null removes it
644
+ // every frame:
645
+ layer.wind = { dir, strength, timeS };
646
+ layer.view(eye, [gain]);
647
+ ```
648
+
649
+ - A set is one kind of the records of one square, relative to its anchor, a world point in doubles. The layer keeps
650
+ what it is given and drops nothing by itself.
651
+ - `view` rebuilds the buffers only when the eye has moved more than `stepM` (default 2 m), a set came or went, or a
652
+ gain changed by more than 0.01. A rebuild takes the sets nearest first and from each the prefix that can still be
653
+ seen from the nearest point of its sphere, moved to one anchor of the layer (the eye of the rebuild) so the numbers
654
+ on the GPU stay small. A full buffer leaves the rest out and counts it in `stats.clipped`: the hard ceiling.
655
+ - The exact fade runs per instance in the vertex shader, so a rebuild changes no pixel. A gain below 1 shortens the
656
+ reach of its kind.
657
+ - The bend in the wind follows two waves fixed to the world (9 m and 3.5 m long): the layer computes the phase of its
658
+ anchor per wave in doubles, the shader adds the part of the instance. Time is wrapped to 20π s, in which both
659
+ speeds make whole turns. `wind.waves = 0` keeps only the steady lean (for a jump of the time).
660
+ - One draw per kind with records, colour pass only, no shadow pass. With every gain 0 nothing is uploaded or drawn.
661
+
662
+ `NEAR_INSTANCE_GLSL` declares `i_base`, `i_shape`, `i_color` and the uniforms the layer sets, and gives `nearBase()`,
663
+ `nearScale()`, `nearAxes(base)` (upright along `localFrame`, turned about up) and `nearPoint(unitPos)`, the vertex in
664
+ render space. The unit shape stands on y = 0 and reaches y = 1; width scales x and z, height y.
665
+
666
+ ## The sky
667
+
668
+ `createEngine({ sky: true })` or `sky: { hazeDistanceM, cloudHeightM, … }` adds the sky slot and `SkyLayer` as the first layer. Perspective views only. The sky draws a gradient, a sun glow, sun and moon discs, stars and clouds. The clouds use the same field as the cloud shadows (`CLOUD_OCTAVES`), so they agree. Materials end with `aerialPerspective(display, worldPos)` to fade into the sky.
669
+
670
+ **Behind the scene.** As the first layer the sky computes every pixel of the screen, and the scene then draws over most of them. `engine.moveSkyBefore(layer)` sets `SkyLayer.behindScene` and moves the sky to just before `layer` (null: after every layer added so far). It then draws at the far end of the depth range with the depth test on and without writing depth, so only the samples nothing has covered get the sky, and each of them the colour it got before. The image is the same as long as every layer drawn before the sky is opaque (writes depth where it draws); give it the first layer that blends or does not write depth (water, glass, particles). In the logarithmic depth mode the sky's fragment shader keeps the pipeline's depth of the far end, so a surface that the logarithm puts at exactly depth 1 (beyond the scene's far end) is covered by the sky. Off by default.
671
+
672
+ <!-- check: wrap -->
673
+ ```ts
674
+ import type { Engine } from 'wallhammer-web/runtime';
675
+ import type { Layer } from 'wallhammer-web/render';
676
+
677
+ declare const engine: Engine;
678
+ declare const water: Layer; // the first layer that blends
679
+ engine.moveSkyBefore(water);
680
+ ```
681
+
682
+ ## The atmosphere
683
+
684
+ `createEngine({ atmosphere: true })`, or `atmosphere: { … }` with its params, adds air as a shell round a sphere: the atmosphere slot in the Frame block and `AtmosphereLayer` as the first layer. Off by default; the sky above stays what it was and is still the choice for a flat map. Use one or the other. Perspective views only.
685
+
686
+ The sphere is the renderer's [`radialUp`](#local-up) sphere, and its radius must be the slot's `radiusM`. Without `radialUp` the ground is the plane `groundY` and the air curves away from it as on a sphere of `radiusM`. The air itself (`AtmosphereMedium`: molecules, particles, an absorbing layer, the albedo of the ground) defaults to that of the Earth; `atmosphereFor(radiusM, heightM)` gives the same air fitted to another sphere, with the same light straight down.
687
+
688
+ <!-- check: wrap -->
689
+ ```ts
690
+ import type { Vec3 } from 'wallhammer-web/base';
691
+ import { atmosphereFor, sphereSunDirection } from 'wallhammer-web/env';
692
+ import { createEngine } from 'wallhammer-web/runtime';
693
+ import type { EngineOptions, EngineView } from 'wallhammer-web/runtime';
694
+
695
+ declare const options: EngineOptions<EngineView>; // canvas, view, palette, background, renderer: { radialUp }
696
+ declare const upAtEye: () => Vec3; // unit up at the place of the eye
697
+
698
+ const engine = createEngine({ ...options, atmosphere: { ...atmosphereFor(100_000, 30_000), exposure: 30 } });
699
+ // The sun over a turning sphere, and the light of the frame for the place under the eye.
700
+ engine.renderer.beforeFrame.unshift(() => {
701
+ engine.env.observer = { up: upAtEye(), sunDir: sphereSunDirection(172, engine.env.day.time) };
702
+ });
703
+ ```
704
+
705
+ How it works:
706
+
707
+ - **Tables.** Three small tables are computed on the CPU when the slot is made, from the medium alone (pure, no files; in the order of a tenth of a second on the calling thread, once): how much sunlight passes the air from a point toward the sun, the light scattered more than once, and the sky's light on a level surface. They are stored in one 160 × 32 RGBA8 texture (`atmosphereTables`, `ATMOSPHERE_TABLE_LAYOUT`), which the layer keeps on texture unit 14 (`ATMOSPHERE_TABLE_UNIT`, sampler `u_atmTables`) for every layer drawn after it. The tables do not depend on the sun or the eye, so nothing is baked again while they move.
708
+ - **The sky** is the integral of the scattered light along a view ray (`atmosphereSky`, `skySteps` steps), from wherever the eye is: on the ground, in flight, above the air. There is one code path, so the way up has no seam: from orbit the same integral gives the rim of the shell round the sphere, and the shadow of the sphere in its own air gives the line between day and night. The pixels do not integrate it themselves. Before the passes of a frame the layer fills the **sky table** on the graphics card (`Layer.prepare`; 64 × 128 texels, `ATMOSPHERE_SKY_TABLE`, three 16-bit float textures, program `ATMOSPHERE_TABLE_FS`) with that integral for directions over the whole sky of the eye, and every pixel reads it. The table is filled again only in a frame whose environment or eye differs from the last one.
709
+ - Columns follow the cosine of the angle round the eye's up between the direction and the sun. Rows are in two halves that never blend into each other, so the horizon stays a line: the lower half holds the directions that end on the ground sphere, the upper half the others, up to straight up, or up to the rim of the shell for an eye above the air. Both halves are spaced by the square root of the angle from the horizon, where the light changes fastest.
710
+ - The light of particles is stored before its phase value and the pixel multiplies that in, so the glow round the sun stays sharp. The sun's disc and the stars are worked out per pixel as before, behind the share of light the table says passes.
711
+ - **Materials** take the air between the eye and the surface at their vertices and apply it in the fragment shader: `v_air = atmosphereAir(worldPos, v_airThrough)` in the vertex shader (`airSteps` steps per vertex, two `vec3` varyings), and `atmosphereApply(display, v_world, v_air, v_airThrough)` at the end of the fragment shader, after `toDisplay` and `applyFog`. Both values change slowly over a surface, so this suits any mesh whose triangles are small against the distance over which the air changes (streamed terrain, objects). A material with very large triangles calls `atmosphereApply(display, worldPos)` instead, which integrates per fragment. A material that is also used without the slot needs no branch for this: the stand-ins give no air and return the input.
712
+ - **Reference quality.** `params.reference = true` (may change at any time) makes every pixel integrate its own ray again: the sky per pixel, and `atmosphereApply` with the vertex values per fragment. It costs many times more and is there to compare the picture against. The layer also falls back to it for the sky where the graphics card cannot draw into 16-bit float textures.
713
+ - **Light on surfaces.** `atmosphereLight(worldPos, n, sun, ao)` stands in the place of `lightOnAt`: the sun through the air above the point (white high up, red through a long way of air, none behind the sphere), the sky's light there, and `nightLight`. It is computed for the point, not for the eye, so the far side of a sphere is dark while the eye stands in daylight. `atmosphereSun(worldPos)` is the colour of the direct sun alone, e.g. for a glint.
714
+ - **The sun.** The slot takes the direction to the sun from the environment (`sunDir` of the frame). For a world with one up that is the site's sun. For a sphere set `Environment.observer` every frame (default `null`): the sun then stands in the given world direction, and the values of the frame that follow its height (light colours, exposure, the direction of the shadow map, the swap to the moon) are computed for the place with the given up.
715
+
716
+ <!-- check: skip -->
717
+ ```ts
718
+ #include <header>
719
+ #include <noise>
720
+ #include <lighting>
721
+ #include <atmosphere>
722
+ // …
723
+ float sun = sunVisibility(v_world, n, 1.2);
724
+ #ifdef WH_ATMOSPHERE
725
+ vec3 lit = albedo * atmosphereLight(v_world, n, sun, 1.0);
726
+ #else
727
+ vec3 lit = albedo * u_warmTint.rgb * lightOnAt(v_world, n, sun, 1.0);
728
+ #endif
729
+ // v_air and v_airThrough come from the vertex shader: v_air = atmosphereAir(v_world, v_airThrough);
730
+ o_color = vec4(atmosphereApply(applyFog(toDisplay(lit), v_world), v_world, v_air, v_airThrough), 1.0);
731
+ ```
732
+
733
+ Params that may change at any time (`engine.atmosphere.slot.params`): `exposure` (scattered light to screen colour, `1 − exp(−light × exposure)`), `sunLight`, `skyLightGain`, `nightLight`, `sunDiscRad`, `stars`, `groundY`, `reference`. The medium and the step counts `skySteps` and `airSteps` are read once, when the slot is made. Without `createEngine`: pass `atmosphereSlot(params)` to `assembleFrameBlock` and to the `EnvironmentLink`, then add `new AtmosphereLayer(renderer, slot)` first.
734
+
735
+ Limits: the atmosphere draws no clouds and no moon, and the weather does not change it (`applyFog` still does). The tables hold 8 bits per channel behind a square root. A pixel of the sky costs three reads of the sky table, and a fragment of a material that takes the air at its vertices costs nothing more than the two varyings; the steps (three table reads each) are paid per texel of the sky table (`skySteps`) and per vertex (`airSteps`). In the reference quality, and for `atmosphereApply(display, worldPos)`, they are paid per pixel. Across one triangle the air is interpolated, so a triangle that spans a long way of air (a single quad to the horizon) shows it only roughly: such a material integrates per fragment. The sky table follows the sun by 64 columns: the shadow line of the sphere in the sky at dusk is as sharp as that allows. Shadows still come from the one shadow map round the eye.
736
+
737
+ ## Resolution and antialiasing
738
+
739
+ `createEngine({ maxPixelRatio })` caps the canvas's pixels per CSS pixel (default none: the device's own ratio, as before). With a cap below the device's ratio the image is drawn at fewer pixels and the browser scales the canvas up to its CSS size; the view's `dpr` is the ratio in effect, so input and pixel sizes stay right. Without the engine pass the same cap to `observeCanvasSize` and `syncCanvasSize` (`canvasPixelRatio(max)` gives the ratio).
740
+
741
+ `renderer: { samples }` chooses the samples per pixel of the main target: 0, 2 or 4 (`Device.setMainSamples`; the engine also creates the context to match, by hand use `createContext(canvas, depth, samples)`). Default unchanged: the canvas's own antialiasing in the standard depth mode, 4 samples in the reversed and logarithmic modes. In the standard mode 0 and 4 keep drawing into the canvas (made without or with antialiasing); 2 draws into the device's offscreen target with a 32-bit float depth buffer and copies it to the canvas in `present`, as the other depth modes do, because a canvas cannot be asked for a sample count. `Device.mainSamples()` reports the count in effect.
742
+
743
+ <!-- check: wrap -->
744
+ ```ts
745
+ import { createEngine } from 'wallhammer-web/runtime';
746
+ import type { EngineOptions, EngineView } from 'wallhammer-web/runtime';
747
+
748
+ declare const options: EngineOptions<EngineView>;
749
+ const engine = createEngine({ ...options, maxPixelRatio: 1.5, renderer: { ...options.renderer, samples: 2 } });
750
+ console.log(engine.view.dpr, engine.device.mainSamples());
751
+ ```
752
+
753
+ ## Allocation-free frames
754
+
755
+ A frame of a still scene allocates nothing in the renderer: the Frame block is written in place, the shadow key is compared as numbers and the view key, and the renderer hands its own scratch to the view (`View.axes(out)`, `View.cornerRays(out)`, `View.viewProj(…, out)`, `depthViewProj(…, out)`). These `out` arguments are optional: a rig that ignores them still works and allocates as before. `PerspectiveOrbitRig` and `SteppedOrthoRig` honour them and build `key()` only when a number in it changed; `FreeRig` takes `eye(out)` only (its up comes from the world shape). `SkyLayer` and the frame loop allocate nothing per frame either. Still allocating per frame: the returned `FrameStats` object, the environment (`Environment.frame` and the slots' `pack`), and a refit (the light fit and the view's cull volume).
756
+
757
+ ## Statistics and benchmarks
758
+
759
+ `renderer.render(view)` returns `FrameStats` (triangles, draw calls, shadow triangles and calls, CPU ms, instances visible). `renderer.lastStats` keeps the last one. `renderer.benchmark(view, n)` renders `n` frames synchronously and returns ms per frame. It flushes after each frame, as presenting a frame would: without that, Chrome's Metal backend merged the frames of a still view (no shadow pass, so no render target switch between them) into one long render pass, and a whole-town view measured 15–21 ms instead of about 4 ms.
760
+
761
+ **Frame profile.** `profileFrame(renderer, view)` from `tools` measures what the frame costs on the graphics card at hand and what every layer adds to it, in the colour and in the shadow pass (see [Tools](tools.md#frame-profile)). It uses two hooks of the renderer that are idle in normal use: `Layer.name` (optional, shown in the profile) and `Renderer.probe` (`RenderProbe`: `draws(layer, pass)` may leave a layer out of a pass or of `prepare`, `drawn(layer, pass, triangles, calls)` reports what it counted). With `probe` null the renderer does exactly what it did before.
762
+
763
+ **GPU memory.** `device.memory()` returns the bytes the device has allocated and not deleted: `buffers` (vertex, index, instance, uniform), `textures` (uploads and bakes, mipmaps included), `targets` (the shadow map) and `total`. Every `Mesh` carries `bytes` (its own buffers; 0 for a mesh from `shareMesh`). The canvas's drawing buffer is not counted.
764
+
765
+ ## Without `createEngine`
766
+
767
+ The same parts by hand. Use this when you need a non-standard loop.
768
+
769
+ <!-- check: wrap -->
770
+ ```ts
771
+ import { Device, Environment, SteppedOrthoRig, createContext, definePalette } from 'wallhammer-web';
772
+ import { Renderer } from 'wallhammer-web/render';
773
+ import { assembleFrameBlock } from 'wallhammer-web/env';
774
+ import { EnvironmentLink } from 'wallhammer-web/runtime';
775
+
776
+ const palette = definePalette({ background: '#6795b1', ground: '#4d4335' });
777
+ const canvas = document.querySelector<HTMLCanvasElement>('canvas')!;
778
+ const device = new Device(createContext(canvas));
779
+ const block = assembleFrameBlock([]); // environment slots go here
780
+ const renderer = new Renderer(device, { palette: palette.data(), frameSlots: block });
781
+ const env = new Environment({ mode: 'day' });
782
+ const link = new EnvironmentLink(renderer, env, { background: palette.color('background'), block });
783
+ renderer.bounds = { min: [0, 0, 0], max: [500, 80, 500] };
784
+
785
+ const view = new SteppedOrthoRig({ yawDeg: 22.5, pitchDegByZoom: [35, 45], pxPerMeterByZoom: [1, 4] });
786
+ view.bounds = { minX: 0, maxX: 500, minZ: 0, maxZ: 500 };
787
+ renderer.render(view);
788
+ ```
789
+
790
+ The link registers itself in `renderer.beforeFrame`, so each `render` computes the environment first. You still size the canvas and the view yourself (`syncCanvasSize` or `observeCanvasSize` in `platform`), run the clocks and own the loop. `src/runtime/engine.ts` shows the exact calls.
791
+
792
+ ## Loss of the graphics context
793
+
794
+ A browser may take the WebGL context of a canvas away at any time (a driver reset, too many contexts, a tab put to sleep) and hand a fresh, empty one back later. Every program, buffer and texture of the old context is then void. By default the engine does nothing about it. With `contextRecovery: true` in `createEngine` it restores the picture without a reload:
795
+
796
+ - `Device.retainUploads` is set, so the device keeps what every mesh, instance buffer, texture and bake was made from. These are references to the arrays the caller uploaded, not copies; the price is that uploaded data stays in memory for as long as its GPU object lives.
797
+ - `watchContextLoss` (module `platform`) answers the browser's "lost" event so that a restore happens at all, and reports the restore.
798
+ - While the context is lost, `Device.lost` is true and `Renderer.render` returns without drawing. Uploads made in that time get handles that are filled in on the restore.
799
+ - On the restore, `Device.contextRestored()` puts the context state back and makes everything again in place: the same `Program`, `Mesh`, `InstanceBuffer` and `Texture` objects are valid again, including bytes written into mesh vertices with `writeBuffer`. Then the `onRestored` listeners run; the renderer uses one to draw its shadow maps again. The engine draws a frame.
800
+
801
+ <!-- check: wrap -->
802
+ ```ts
803
+ import { createEngine } from 'wallhammer-web/runtime';
804
+ import type { EngineOptions, EngineView } from 'wallhammer-web/runtime';
805
+
806
+ declare const options: EngineOptions<EngineView>;
807
+ const engine = createEngine({ ...options, contextRecovery: true });
808
+
809
+ // For a test: take the context away as a driver reset would, and ask for it back.
810
+ if (engine.device.loseContext()) setTimeout(() => engine.device.restoreContext(), 500);
811
+ ```
812
+
813
+ Without `createEngine` the same takes three lines: set `device.retainUploads = true` before the first upload, call `watchContextLoss(canvas, { restored })`, and in `restored` call `device.contextRestored()` and draw a frame. A device without `retainUploads` still restores its programs, uniform blocks and depth targets; whoever owns meshes and textures then makes them again in an `onRestored` listener (`StreamedWorld` does: it uploads its cells again from their CPU data, see `reupload()`).
814
+
815
+ What is not restored: anything drawn into a texture outside a bake, and GPU objects made with the low-level helpers (`createBuffer`, `createTexture` of `gpu`) instead of the device.
816
+
817
+ ## Known weak spots
818
+
819
+ - Includes are a plain text replace without nesting or include guards.
820
+ - Depth modes: the shadow map keeps 24-bit standard depth in every mode. With logarithmic depth a multisampled pixel has one depth for all its samples, so the line where two surfaces cut through each other is not antialiased (outlines are).
821
+ - The shadow map does not follow animation time. Moving shadow casters other than `TransientLayer` batches need `invalidateShadows()`, or `shadowCasters: 'dynamic'` with `shadowDirty()` (see [Moving casters](#moving-casters)).
822
+ - The data view (`tools`) uses fixed texture units 2–4 next to `MeshLayer`'s units starting at 1.
823
+ - The atmosphere keeps its tables on texture unit 14 for the whole colour pass (unit 15 is the light horizon's). A layer that binds more than thirteen textures of its own would take the unit over. While it draws the sky the layer also uses units 1 to 3 for the sky table and leaves them empty.