roamwright 0.4.0 → 0.54.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (549) hide show
  1. package/.prettierrc.yaml +12 -0
  2. package/CONTRIBUTING.md +21 -14
  3. package/README.md +38 -42
  4. package/examples/animals.html +49 -0
  5. package/examples/animals.js +209 -0
  6. package/examples/crowds.html +50 -0
  7. package/examples/crowds.js +268 -0
  8. package/examples/effects.html +53 -0
  9. package/examples/effects.js +343 -0
  10. package/examples/figure-motion.html +55 -0
  11. package/examples/figure-motion.js +265 -0
  12. package/examples/figure.html +49 -0
  13. package/examples/figure.js +238 -0
  14. package/examples/fliers.html +53 -0
  15. package/examples/fliers.js +292 -0
  16. package/examples/fortification.html +54 -0
  17. package/examples/fortification.js +288 -0
  18. package/examples/house-kit.html +48 -0
  19. package/examples/house-kit.js +175 -0
  20. package/examples/index.html +26 -16
  21. package/examples/island.html +48 -0
  22. package/examples/island.js +134 -52
  23. package/examples/land.html +54 -0
  24. package/examples/land.js +392 -0
  25. package/examples/props-and-plants.html +53 -0
  26. package/examples/props-and-plants.js +275 -0
  27. package/examples/rooms.html +48 -0
  28. package/examples/rooms.js +242 -0
  29. package/examples/ships.html +51 -0
  30. package/examples/ships.js +235 -0
  31. package/examples/showcase.css +320 -0
  32. package/examples/small-world-land.js +151 -0
  33. package/examples/small-world-life.js +160 -0
  34. package/examples/small-world-town.js +127 -0
  35. package/examples/small-world.html +57 -0
  36. package/examples/small-world.js +226 -0
  37. package/examples/soundscape.html +138 -0
  38. package/examples/soundscape.js +467 -0
  39. package/examples/stage-kits.js +300 -0
  40. package/examples/stage.js +374 -0
  41. package/examples/towns.html +50 -0
  42. package/examples/towns.js +325 -0
  43. package/examples/viaduct-camera.js +8 -4
  44. package/examples/viaduct-landscape.js +28 -17
  45. package/examples/viaduct.html +45 -43
  46. package/examples/viaduct.js +68 -92
  47. package/geometry/animal-camel-body.js +410 -0
  48. package/geometry/animal-camel-head.js +118 -0
  49. package/geometry/animal-canine-body.js +361 -0
  50. package/geometry/animal-canine-breeds.js +316 -0
  51. package/geometry/animal-canine-head.js +337 -0
  52. package/geometry/animal-cattle-body.js +391 -0
  53. package/geometry/animal-cattle-coat.js +42 -0
  54. package/geometry/animal-cattle-head.js +152 -0
  55. package/geometry/animal-hen.js +248 -0
  56. package/geometry/animal-horse-body.js +446 -0
  57. package/geometry/animal-horse-bridle.js +171 -0
  58. package/geometry/animal-horse-coat.js +68 -0
  59. package/geometry/animal-horse-face.js +162 -0
  60. package/geometry/animal-horse-hair.js +304 -0
  61. package/geometry/animal-horse-head.js +133 -0
  62. package/geometry/animal-horse-tack.js +157 -0
  63. package/geometry/animal-options.js +59 -0
  64. package/geometry/animal-shapes.js +21 -0
  65. package/geometry/animal-skin.js +390 -0
  66. package/geometry/bedding.js +141 -0
  67. package/geometry/builder-cells.js +50 -0
  68. package/geometry/builder-frame.js +48 -0
  69. package/geometry/builder.js +200 -177
  70. package/geometry/card-emblem.js +437 -0
  71. package/geometry/catenary-canvas.js +396 -0
  72. package/geometry/cell-mask.js +25 -0
  73. package/geometry/cloth-folds.js +143 -0
  74. package/geometry/crawl-shapes.js +71 -0
  75. package/geometry/creased-sheet.js +40 -35
  76. package/geometry/crowd-dress.js +315 -0
  77. package/geometry/crowd-far.js +174 -0
  78. package/geometry/crowd-look.js +42 -0
  79. package/geometry/crowd-weld.js +218 -0
  80. package/geometry/ear.js +44 -39
  81. package/geometry/erosion.js +71 -45
  82. package/geometry/face-grid.js +85 -65
  83. package/geometry/field-map.js +59 -0
  84. package/geometry/figure-arms.js +339 -0
  85. package/geometry/figure-beard.js +250 -0
  86. package/geometry/figure-body.js +297 -0
  87. package/geometry/figure-bow.js +105 -0
  88. package/geometry/figure-cloak.js +189 -0
  89. package/geometry/figure-clothes.js +337 -0
  90. package/geometry/figure-face-grids.js +75 -0
  91. package/geometry/figure-gear.js +446 -0
  92. package/geometry/figure-hair-far.js +151 -0
  93. package/geometry/figure-hair-hangs.js +108 -0
  94. package/geometry/figure-hair-patch.js +66 -0
  95. package/geometry/figure-hair.js +320 -0
  96. package/geometry/figure-hands.js +321 -0
  97. package/geometry/figure-head-features.js +280 -0
  98. package/geometry/figure-head.js +375 -0
  99. package/geometry/figure-headwear.js +223 -0
  100. package/geometry/figure-legs.js +231 -0
  101. package/geometry/figure-limbs.js +39 -0
  102. package/geometry/figure-sculpt.js +82 -0
  103. package/geometry/figure-skin.js +97 -0
  104. package/geometry/figure-skirts.js +303 -0
  105. package/geometry/figure-trunk.js +411 -0
  106. package/geometry/flier-corvid-body.js +322 -0
  107. package/geometry/flier-corvid-wings.js +154 -0
  108. package/geometry/flier-long-body.js +195 -0
  109. package/geometry/flier-shapes.js +219 -0
  110. package/geometry/flier-soaring-bird.js +84 -0
  111. package/geometry/foliage.js +187 -14
  112. package/geometry/fort-city-walls.js +479 -0
  113. package/geometry/fort-gate-approach.js +233 -0
  114. package/geometry/fort-great-walls.js +280 -0
  115. package/geometry/fort-keep.js +297 -0
  116. package/geometry/fort-parts.js +261 -0
  117. package/geometry/fort-polyline.js +261 -0
  118. package/geometry/fort-portal.js +96 -0
  119. package/geometry/fort-ring-wall.js +267 -0
  120. package/geometry/fort-seawall.js +104 -0
  121. package/geometry/fort-terrace-gates.js +323 -0
  122. package/geometry/fort-terrace-plan.js +250 -0
  123. package/geometry/fort-terrace-wall.js +345 -0
  124. package/geometry/garment-tags.js +11 -3
  125. package/geometry/grid-gather.js +69 -0
  126. package/geometry/grid-sample.js +185 -0
  127. package/geometry/hair-gathers.js +57 -42
  128. package/geometry/hair-locks.js +42 -42
  129. package/geometry/hair-patch.js +24 -20
  130. package/geometry/hair-shell.js +43 -31
  131. package/geometry/head-presets.js +103 -0
  132. package/geometry/head-profile.js +26 -15
  133. package/geometry/head-shape.js +123 -95
  134. package/geometry/heightfield.js +50 -24
  135. package/geometry/horizon-angles.js +166 -0
  136. package/geometry/house-kit-body.js +195 -0
  137. package/geometry/house-kit-courtyard-parts.js +340 -0
  138. package/geometry/house-kit-courtyard-roof.js +223 -0
  139. package/geometry/house-kit-courtyard.js +409 -0
  140. package/geometry/house-kit-cut.js +29 -0
  141. package/geometry/house-kit-extras.js +192 -0
  142. package/geometry/house-kit-forms.js +298 -0
  143. package/geometry/house-kit-frame.js +74 -0
  144. package/geometry/house-kit-marks.js +93 -0
  145. package/geometry/house-kit-openings.js +193 -0
  146. package/geometry/house-kit-palette.js +54 -0
  147. package/geometry/house-kit-pool.js +71 -0
  148. package/geometry/house-kit-roofs.js +151 -0
  149. package/geometry/house-kit.js +202 -0
  150. package/geometry/index-parts.js +2 -2
  151. package/geometry/instance-visibility.js +12 -12
  152. package/geometry/instances.js +17 -17
  153. package/geometry/lamp-wash.js +65 -0
  154. package/geometry/land-clearings.js +83 -0
  155. package/geometry/land-ditches.js +290 -0
  156. package/geometry/land-dry-basin.js +327 -0
  157. package/geometry/land-dunes.js +150 -0
  158. package/geometry/land-earthworks.js +432 -0
  159. package/geometry/land-edge.js +292 -0
  160. package/geometry/land-mound-faces.js +349 -0
  161. package/geometry/land-near-relief.js +102 -0
  162. package/geometry/land-sheet.js +220 -0
  163. package/geometry/land-town-ground.js +256 -0
  164. package/geometry/land-waters.js +228 -0
  165. package/geometry/land-wildness.js +123 -0
  166. package/geometry/lathed-vessel.js +293 -0
  167. package/geometry/outline-grid.js +11 -10
  168. package/geometry/outline-segments.js +74 -0
  169. package/geometry/part-ranges.js +38 -3
  170. package/geometry/path-field.js +98 -34
  171. package/geometry/placement.js +52 -52
  172. package/geometry/planked-floor.js +149 -0
  173. package/geometry/plant-broadleaf.js +268 -0
  174. package/geometry/plant-shrub.js +198 -0
  175. package/geometry/plant-tints.js +80 -0
  176. package/geometry/plant-trees.js +453 -0
  177. package/geometry/plant-tussock.js +107 -0
  178. package/geometry/point-buckets.js +50 -0
  179. package/geometry/primitives.js +117 -59
  180. package/geometry/prop-battlefield.js +69 -0
  181. package/geometry/prop-camp.js +175 -0
  182. package/geometry/prop-door.js +26 -0
  183. package/geometry/prop-harbour.js +105 -0
  184. package/geometry/prop-haycock.js +60 -0
  185. package/geometry/prop-sacks.js +74 -0
  186. package/geometry/prop-sheaf.js +68 -0
  187. package/geometry/prop-street.js +69 -0
  188. package/geometry/prop-tents.js +396 -0
  189. package/geometry/prop-tombs.js +80 -0
  190. package/geometry/prop-trade.js +393 -0
  191. package/geometry/prop-vehicles.js +218 -0
  192. package/geometry/props.js +58 -0
  193. package/geometry/room-arcade.js +134 -0
  194. package/geometry/room-dome.js +188 -0
  195. package/geometry/room-flames.js +138 -0
  196. package/geometry/room-frame.js +106 -0
  197. package/geometry/room-furniture.js +260 -0
  198. package/geometry/room-hearth.js +98 -0
  199. package/geometry/room-kit.js +59 -0
  200. package/geometry/room-openings.js +142 -0
  201. package/geometry/room-stairs.js +180 -0
  202. package/geometry/room-surfaces.js +272 -0
  203. package/geometry/sagging-tube.js +27 -27
  204. package/geometry/sampled-surface.js +123 -77
  205. package/geometry/scatter-grid.js +49 -6
  206. package/geometry/sculpt.js +97 -93
  207. package/geometry/ship-fittings.js +350 -0
  208. package/geometry/ship-hull.js +460 -0
  209. package/geometry/ship-kit.js +208 -0
  210. package/geometry/ship-lines.js +69 -0
  211. package/geometry/ship-oars.js +150 -0
  212. package/geometry/ship-presets.js +131 -0
  213. package/geometry/ship-rig.js +374 -0
  214. package/geometry/ship-sails.js +148 -0
  215. package/geometry/shore-grid.js +81 -34
  216. package/geometry/strata-field.js +131 -98
  217. package/geometry/strata-tiles.js +108 -94
  218. package/geometry/stream.js +96 -59
  219. package/geometry/swept-tube.js +124 -0
  220. package/geometry/terrain-chunks.js +216 -123
  221. package/geometry/terrain-extension.js +29 -13
  222. package/geometry/town-courtyard-inn.js +272 -0
  223. package/geometry/town-ground.js +76 -0
  224. package/geometry/town-houses.js +343 -0
  225. package/geometry/town-lights.js +254 -0
  226. package/geometry/town-lots.js +172 -0
  227. package/geometry/town-plan.js +370 -0
  228. package/geometry/town-works.js +465 -0
  229. package/geometry/village-layout.js +181 -0
  230. package/geometry/village-yards.js +167 -0
  231. package/geometry/wall-runs.js +64 -0
  232. package/index.js +138 -2
  233. package/math/cell-edge.js +16 -16
  234. package/math/cell-key.js +6 -0
  235. package/math/circle-clearances.js +19 -0
  236. package/math/cloth-textures.js +6 -6
  237. package/math/cloud-textures.js +22 -26
  238. package/math/color.js +14 -14
  239. package/math/curve.js +26 -22
  240. package/math/lamp-texels.js +43 -0
  241. package/math/lit-share.js +22 -0
  242. package/math/mountain-ranges.js +379 -205
  243. package/math/noise.js +101 -49
  244. package/math/particle-noise.js +28 -28
  245. package/math/periodic.js +11 -5
  246. package/math/random.js +24 -15
  247. package/math/rectangles.js +58 -0
  248. package/math/rock-texture.js +22 -17
  249. package/math/scalar.js +5 -5
  250. package/math/surface-textures.js +74 -59
  251. package/math/wandering-path.js +40 -0
  252. package/math/ways.js +120 -0
  253. package/motion/action-dynamics.js +398 -0
  254. package/motion/animal-bearing.js +247 -0
  255. package/motion/animal-canine-bearing.js +178 -0
  256. package/motion/animal-canine-cast.js +131 -0
  257. package/motion/animal-cattle-cast.js +64 -0
  258. package/motion/animal-herd-cast.js +154 -0
  259. package/motion/animal-horse-still.js +161 -0
  260. package/motion/animal-troop-cast.js +43 -0
  261. package/motion/arm-reach.js +27 -26
  262. package/motion/ballistic-arc.js +191 -0
  263. package/motion/biped-cycle.js +46 -0
  264. package/motion/biped-leg.js +40 -0
  265. package/motion/biped-posture.js +459 -0
  266. package/motion/biped-stride.js +226 -140
  267. package/motion/boat-sailing.js +214 -0
  268. package/motion/contact-transition.js +32 -0
  269. package/motion/crowd-alarms.js +72 -42
  270. package/motion/crowd-attention.js +108 -0
  271. package/motion/crowd-beasts.js +203 -0
  272. package/motion/crowd-camp.js +295 -0
  273. package/motion/crowd-figure.js +100 -0
  274. package/motion/crowd-herd.js +86 -0
  275. package/motion/crowd-hold.js +130 -0
  276. package/motion/crowd-pose.js +296 -0
  277. package/motion/crowd-poses.js +481 -0
  278. package/motion/crowd-routine.js +126 -67
  279. package/motion/crowd-town.js +166 -0
  280. package/motion/crowd-water.js +143 -0
  281. package/motion/daily-clock.js +9 -9
  282. package/motion/deck-surface.js +40 -0
  283. package/motion/figure-acts.js +411 -0
  284. package/motion/figure-arms.js +437 -0
  285. package/motion/figure-blade-slide.js +149 -0
  286. package/motion/figure-body-place.js +180 -0
  287. package/motion/figure-bones.js +118 -0
  288. package/motion/figure-bow-draw.js +70 -0
  289. package/motion/figure-fingers.js +215 -0
  290. package/motion/figure-gaze.js +205 -0
  291. package/motion/figure-gestures.js +452 -0
  292. package/motion/figure-grip.js +134 -0
  293. package/motion/figure-head.js +287 -0
  294. package/motion/figure-legs.js +264 -0
  295. package/motion/figure-links.js +293 -0
  296. package/motion/figure-locomotion.js +391 -0
  297. package/motion/figure-mount-up.js +180 -0
  298. package/motion/figure-mount.js +201 -0
  299. package/motion/figure-pose-frame.js +375 -0
  300. package/motion/figure-pose-table.js +156 -0
  301. package/motion/figure-pose.js +343 -0
  302. package/motion/figure-seat.js +267 -0
  303. package/motion/figure-sway.js +125 -0
  304. package/motion/flier-corvid-pose.js +74 -0
  305. package/motion/flier-flight-air.js +122 -0
  306. package/motion/flier-flight-echelon.js +164 -0
  307. package/motion/flier-flight-roost.js +131 -0
  308. package/motion/flier-swarm-flight.js +252 -0
  309. package/motion/formation.js +193 -0
  310. package/motion/ground-lookahead.js +5 -5
  311. package/motion/instance-sight.js +15 -8
  312. package/motion/melee-contact.js +143 -0
  313. package/motion/moorings.js +48 -0
  314. package/motion/path-steering.js +358 -0
  315. package/motion/player.js +41 -32
  316. package/motion/quadruped.js +244 -168
  317. package/motion/spaces.js +90 -38
  318. package/motion/speech-cadence.js +304 -0
  319. package/motion/vessel-motion.js +57 -0
  320. package/motion/walk-grid.js +235 -0
  321. package/motion/weather.js +133 -26
  322. package/motion/wind.js +58 -13
  323. package/package.json +33 -6
  324. package/rendering/alpha-mips.js +340 -0
  325. package/rendering/animal-camel-figure.js +29 -0
  326. package/rendering/animal-canine-figure.js +59 -0
  327. package/rendering/animal-cattle-figure.js +36 -0
  328. package/rendering/animal-horse-figure.js +49 -0
  329. package/rendering/atmosphere.js +86 -0
  330. package/rendering/camera-track.js +156 -0
  331. package/rendering/cart-track.js +92 -0
  332. package/rendering/caster-motion.js +6 -5
  333. package/rendering/cell-lod-options.js +46 -0
  334. package/rendering/cell-lod.js +754 -113
  335. package/rendering/cloth-material.js +140 -0
  336. package/rendering/cloud-dome.js +30 -30
  337. package/rendering/cloud-field.js +2 -2
  338. package/rendering/compilation-schedule.js +79 -14
  339. package/rendering/contact-shadows.js +7 -4
  340. package/rendering/context.js +57 -6
  341. package/rendering/crowd-batches.js +420 -0
  342. package/rendering/crowd-herd.js +198 -0
  343. package/rendering/crowd-rig.js +132 -0
  344. package/rendering/crowd-skinning.js +62 -19
  345. package/rendering/crowd-update.js +419 -0
  346. package/rendering/crowd-visibility.js +107 -0
  347. package/rendering/crust.js +18 -12
  348. package/rendering/day-cycle-defaults.js +200 -0
  349. package/rendering/day-cycle.js +487 -0
  350. package/rendering/daylight.js +4 -6
  351. package/rendering/detail-range.js +29 -0
  352. package/rendering/dispose-meshes.js +18 -0
  353. package/rendering/dof.js +20 -13
  354. package/rendering/effects-frame.js +149 -0
  355. package/rendering/effects-water-rises.js +221 -0
  356. package/rendering/energy-stream.js +128 -0
  357. package/rendering/eye-adapt.js +14 -14
  358. package/rendering/facade-glass-material.js +105 -0
  359. package/rendering/far-shadow.js +89 -62
  360. package/rendering/field-surface.js +138 -0
  361. package/rendering/figure-shield.js +105 -0
  362. package/rendering/figure-skeleton.js +329 -0
  363. package/rendering/fire-light-watch.js +197 -0
  364. package/rendering/fire-pools.js +148 -0
  365. package/rendering/flame-sources.js +86 -0
  366. package/rendering/flier-bird-looks.js +97 -0
  367. package/rendering/flier-corvid-figure.js +67 -0
  368. package/rendering/flier-long-body-company.js +169 -0
  369. package/rendering/flier-swarm.js +186 -0
  370. package/rendering/flocks.js +82 -78
  371. package/rendering/garment-material.js +147 -51
  372. package/rendering/glow-lines.js +13 -13
  373. package/rendering/glsl-literal.js +19 -0
  374. package/rendering/ground-marks.js +316 -0
  375. package/rendering/hair-strands.js +45 -31
  376. package/rendering/height-haze.js +80 -33
  377. package/rendering/height-probe.js +164 -22
  378. package/rendering/house-kit-meshes.js +124 -0
  379. package/rendering/interior-bake.js +807 -0
  380. package/rendering/label-layout.js +56 -0
  381. package/rendering/label-range.js +41 -0
  382. package/rendering/lamp-light-map.js +159 -0
  383. package/rendering/lamp-maps.js +62 -0
  384. package/rendering/lamp-wash.js +51 -0
  385. package/rendering/light-budget.js +71 -55
  386. package/rendering/light-points.js +21 -5
  387. package/rendering/local-lights.js +39 -8
  388. package/rendering/material-lod.js +49 -50
  389. package/rendering/memory-estimate.js +84 -0
  390. package/rendering/moored-fleet.js +186 -0
  391. package/rendering/part-costs.js +104 -0
  392. package/rendering/particle-bursts.js +386 -0
  393. package/rendering/particle-emitters.js +135 -99
  394. package/rendering/particle-light-bursts.js +189 -0
  395. package/rendering/particles.js +212 -101
  396. package/rendering/pen-flocks.js +118 -0
  397. package/rendering/piece-batch.js +298 -11
  398. package/rendering/planar-reflection-options.js +159 -0
  399. package/rendering/planar-reflection.js +806 -103
  400. package/rendering/plant-cells.js +122 -0
  401. package/rendering/plant-reeds.js +113 -0
  402. package/rendering/plant-shade-trees.js +239 -0
  403. package/rendering/plant-tuft-patch.js +122 -0
  404. package/rendering/post-shaders.js +98 -31
  405. package/rendering/post.js +107 -87
  406. package/rendering/pressed-cover.js +135 -0
  407. package/rendering/prop-dig.js +136 -0
  408. package/rendering/rain-streaks.js +67 -0
  409. package/rendering/room-light.js +250 -0
  410. package/rendering/room-materials.js +78 -0
  411. package/rendering/room-space.js +111 -0
  412. package/rendering/scene-lights.js +106 -0
  413. package/rendering/sea-shaders.js +94 -37
  414. package/rendering/settlement-approach.js +226 -0
  415. package/rendering/settlement-dissolve.js +89 -0
  416. package/rendering/settlement-quarter-warm.js +55 -0
  417. package/rendering/settlement-quarter.js +477 -0
  418. package/rendering/settlement-switch.js +42 -0
  419. package/rendering/settlement-town.js +110 -0
  420. package/rendering/shader-warmup.js +101 -44
  421. package/rendering/shadow-alignment.js +4 -4
  422. package/rendering/shadow-depth.js +47 -25
  423. package/rendering/ship-meshes.js +150 -0
  424. package/rendering/shot-cuts.js +68 -0
  425. package/rendering/sky-occlusion.js +56 -29
  426. package/rendering/sky-pmrem.js +216 -0
  427. package/rendering/sky.js +126 -54
  428. package/rendering/smoke-shadows.js +201 -0
  429. package/rendering/stage-framing.js +182 -0
  430. package/rendering/stage-lights.js +46 -39
  431. package/rendering/stain-material.js +74 -0
  432. package/rendering/static-point-shadow.js +65 -26
  433. package/rendering/still-casters.js +77 -27
  434. package/rendering/strata-material.js +12 -12
  435. package/rendering/stream-flow.js +10 -10
  436. package/rendering/street-lamps.js +166 -0
  437. package/rendering/sunbeam-motes.js +670 -0
  438. package/rendering/surface-light.js +65 -6
  439. package/rendering/surface-material.js +306 -0
  440. package/rendering/surface-projection.js +32 -0
  441. package/rendering/surface-snippets.js +314 -0
  442. package/rendering/taa.js +75 -44
  443. package/rendering/talus.js +15 -15
  444. package/rendering/terrain-rock.js +7 -7
  445. package/rendering/texture-fills.js +8 -8
  446. package/rendering/textures.js +28 -28
  447. package/rendering/tree-impostor.js +929 -0
  448. package/rendering/vehicle-train.js +92 -0
  449. package/rendering/viewport.js +67 -4
  450. package/rendering/wakes.js +24 -24
  451. package/rendering/water-material.js +304 -103
  452. package/rendering/waypoint-beacons.js +191 -0
  453. package/rendering/world-matrices.js +38 -40
  454. package/ruff.toml +20 -0
  455. package/runtime/cue-cursor.js +21 -0
  456. package/runtime/device-quality.js +13 -2
  457. package/runtime/device.js +73 -0
  458. package/runtime/diagnostic-log.js +12 -4
  459. package/runtime/effect-sites.js +85 -0
  460. package/runtime/figure-orders.js +59 -0
  461. package/runtime/first-use.js +36 -28
  462. package/runtime/foley-script.js +124 -0
  463. package/runtime/foley-strides.js +333 -0
  464. package/runtime/frame-pacing.js +47 -0
  465. package/runtime/frame-yield.js +18 -0
  466. package/runtime/gpu-timing.js +15 -11
  467. package/runtime/grid-cache.js +16 -6
  468. package/runtime/grid-rows.js +44 -5
  469. package/runtime/hand-over.js +47 -24
  470. package/runtime/land-bake.js +78 -0
  471. package/runtime/lazy-sets.js +105 -0
  472. package/runtime/pool.js +73 -17
  473. package/runtime/quality-fit.js +60 -28
  474. package/runtime/region-pass-lay.js +40 -0
  475. package/runtime/region-pass.js +78 -0
  476. package/runtime/search.js +26 -22
  477. package/runtime/settlement-reach.js +42 -0
  478. package/runtime/sound-calls.js +113 -0
  479. package/runtime/sound-impacts.js +297 -0
  480. package/runtime/sound-voices.js +194 -0
  481. package/runtime/soundscape.js +282 -0
  482. package/runtime/spatial-audio.js +79 -30
  483. package/runtime/steady-frames.js +221 -0
  484. package/runtime/withdrawable-task.js +46 -0
  485. package/runtime/worker.js +7 -0
  486. package/scripts/app-parts.mjs +118 -0
  487. package/scripts/bake-revisions.mjs +81 -0
  488. package/scripts/browser-scripts.mjs +64 -0
  489. package/scripts/bundle.mjs +192 -0
  490. package/scripts/check-app.sh +26 -0
  491. package/scripts/eslint-config.mjs +119 -0
  492. package/scripts/format.sh +92 -0
  493. package/scripts/keep-builds.mjs +158 -0
  494. package/scripts/layers.mjs +112 -0
  495. package/scripts/lint.sh +49 -0
  496. package/scripts/module-graph.mjs +123 -0
  497. package/scripts/pre-commit.sh +38 -0
  498. package/scripts/serve.py +5 -3
  499. package/scripts/site.mjs +358 -0
  500. package/scripts/test-runner.sh +42 -0
  501. package/scripts/vendor.mjs +221 -0
  502. package/scripts/verify-publish.mjs +175 -0
  503. package/scripts/world.mk +59 -0
  504. package/tools/README.md +73 -0
  505. package/tools/contact-sheet.cjs +137 -0
  506. package/tools/cpu-profile.cjs +275 -0
  507. package/tools/cpu-profile.test.cjs +98 -0
  508. package/tools/first-draws.cjs +395 -0
  509. package/tools/flight-guard.cjs +482 -0
  510. package/tools/flight-guard.test.cjs +153 -0
  511. package/tools/flight-profile.cjs +145 -0
  512. package/tools/frame-bench.cjs +336 -0
  513. package/tools/frame-parts.cjs +365 -0
  514. package/tools/ios-sim.sh +145 -0
  515. package/tools/load-audit.cjs +201 -0
  516. package/tools/look-compare.cjs +304 -0
  517. package/tools/look-guard.cjs +407 -0
  518. package/tools/look-guard.test.cjs +93 -0
  519. package/tools/look-stats.cjs +185 -0
  520. package/tools/look-stats.test.cjs +71 -0
  521. package/tools/memory-audit.cjs +323 -0
  522. package/tools/page-driver.cjs +320 -0
  523. package/tools/page-driver.test.cjs +219 -0
  524. package/tools/program-census-report.cjs +191 -0
  525. package/tools/program-census.cjs +465 -0
  526. package/tools/program-census.test.cjs +332 -0
  527. package/tools/remote-runner.sh +265 -0
  528. package/tools/runners.test.cjs +59 -0
  529. package/tools/scene-audit-beat.cjs +344 -0
  530. package/tools/scene-audit-sheet.cjs +282 -0
  531. package/tools/scene-audit.cjs +471 -0
  532. package/tools/scene-audit.test.cjs +201 -0
  533. package/tools/scene-batch.cjs +219 -0
  534. package/tools/scene-bench.cjs +149 -0
  535. package/tools/scene-bench.test.cjs +33 -0
  536. package/tools/scene-run.cjs +443 -0
  537. package/tools/scene-run.test.cjs +94 -0
  538. package/tools/servers.sh +59 -0
  539. package/tools/shader-arrival.cjs +316 -0
  540. package/tools/shader-renewal.cjs +53 -0
  541. package/tools/shader-renewal.test.cjs +115 -0
  542. package/tools/speed-guard.cjs +258 -0
  543. package/tools/stills.cjs +492 -0
  544. package/tools/stills.test.cjs +49 -0
  545. package/tools/turns.sh +7 -0
  546. package/tools/yaml.cjs +158 -0
  547. package/examples/viaduct.css +0 -75
  548. package/rendering/light-shafts.js +0 -131
  549. package/rendering/road-surface.js +0 -63
@@ -16,8 +16,10 @@ export function createGpuTiming(renderer) {
16
16
  const _pixel = new Uint8Array(4);
17
17
  const cardBlocks = () => blocks;
18
18
  // Resolves once the card has drawn everything handed to it before this call, with when that was seen (performance.now()),
19
- // whether it was already so the first time it was asked (the card was not behind), and whether the wait was given up.
20
- function cardDone() {
19
+ // whether it was already so the first time it was asked (the card was not behind), and whether the wait was given up:
20
+ // after `giveUpMs` (400 ms unless asked). A caller that must not go on with work still queued on the card (a world shown
21
+ // while the driver is still building what start-up handed it) asks for a longer wait.
22
+ function cardDone(giveUpMs = GIVE_UP_MS) {
21
23
  const gl = renderer.getContext();
22
24
  if (blocks) {
23
25
  gl.readPixels(0, 0, 1, 1, gl.RGBA, gl.UNSIGNED_BYTE, _pixel);
@@ -33,7 +35,7 @@ export function createGpuTiming(renderer) {
33
35
  const at = performance.now(),
34
36
  status = gl.clientWaitSync(fence, 0, 0),
35
37
  waiting = status === gl.TIMEOUT_EXPIRED;
36
- if (waiting && at - since < GIVE_UP_MS) {
38
+ if (waiting && at - since < giveUpMs) {
37
39
  asked++;
38
40
  // A queued GPU frame can take tens of milliseconds. Leave the page thread
39
41
  // free between observations. The channel resets nested timer clamping.
@@ -41,7 +43,9 @@ export function createGpuTiming(renderer) {
41
43
  return;
42
44
  }
43
45
  gl.deleteSync(fence);
44
- if (waiting && !globalThis.document?.hidden) blocks = true; // not passed in all that time on a page that is being shown: fences do not work here
46
+ // not passed in the usual time on a page that is being shown: fences do not work here (a longer wait asked for may
47
+ // simply have been given more than that to draw)
48
+ if (waiting && giveUpMs <= GIVE_UP_MS && !globalThis.document?.hidden) blocks = true;
45
49
  resolve({ at, prompt: asked === 0, gaveUp: waiting || status === gl.WAIT_FAILED });
46
50
  };
47
51
  nextTask(ask);
@@ -53,24 +57,24 @@ export function createGpuTiming(renderer) {
53
57
  // when no measurement can begin (no such query here, or the last one has not been answered yet); cardWork() gives the last
54
58
  // answer in milliseconds, or null if there has been none.
55
59
  let timer; // the extension, once asked for (null where there is none)
56
- let asked = null, // the query waiting for its answer
60
+ let pendingQuery = null, // the query waiting for its answer
57
61
  work = null;
58
62
  function timeCard() {
59
63
  const gl = renderer.getContext();
60
64
  if (timer === undefined) timer = gl.getExtension('EXT_disjoint_timer_query_webgl2');
61
65
  if (!timer) return null;
62
- if (asked) {
63
- if (!gl.getQueryParameter(asked, gl.QUERY_RESULT_AVAILABLE)) return null;
64
- if (!gl.getParameter(timer.GPU_DISJOINT_EXT)) work = gl.getQueryParameter(asked, gl.QUERY_RESULT) / NANOSECONDS_IN_MS;
65
- gl.deleteQuery(asked);
66
- asked = null;
66
+ if (pendingQuery) {
67
+ if (!gl.getQueryParameter(pendingQuery, gl.QUERY_RESULT_AVAILABLE)) return null;
68
+ if (!gl.getParameter(timer.GPU_DISJOINT_EXT)) work = gl.getQueryParameter(pendingQuery, gl.QUERY_RESULT) / NANOSECONDS_IN_MS;
69
+ gl.deleteQuery(pendingQuery);
70
+ pendingQuery = null;
67
71
  }
68
72
  const query = gl.createQuery();
69
73
  if (!query) return null;
70
74
  gl.beginQuery(timer.TIME_ELAPSED_EXT, query);
71
75
  return () => {
72
76
  gl.endQuery(timer.TIME_ELAPSED_EXT);
73
- asked = query;
77
+ pendingQuery = query;
74
78
  };
75
79
  }
76
80
  const cardWork = () => work;
@@ -1,8 +1,8 @@
1
1
  // Persist typed grid arrays in IndexedDB. A synchronous hint lets a consumer
2
2
  // start computing immediately on a cold visit. A missing hint is always safe.
3
3
  export function createGridCache({ database, store, build, revisions, hintPrefix }) {
4
- const revisionOf = name => revisions ? Object.hasOwn(revisions, name) && revisions[name] : build;
5
- const recordKey = (name, revision) => revisions ? [name, revision] : revision + ' ' + name;
4
+ const revisionOf = name => (revisions ? Object.hasOwn(revisions, name) && revisions[name] : build);
5
+ const recordKey = (name, revision) => (revisions ? [name, revision] : revision + ' ' + name);
6
6
 
7
7
  function obsolete(key, name, revision) {
8
8
  if (!revisions) return !String(key).startsWith(build + ' ');
@@ -16,7 +16,10 @@ export function createGridCache({ database, store, build, revisions, hintPrefix
16
16
  const request = indexedDB.open(database, 1);
17
17
  let blocked = false;
18
18
  request.onupgradeneeded = () => request.result.createObjectStore(store);
19
- request.onblocked = () => { blocked = true; resolve(null); };
19
+ request.onblocked = () => {
20
+ blocked = true;
21
+ resolve(null);
22
+ };
20
23
  request.onerror = () => resolve(null);
21
24
  request.onsuccess = () => {
22
25
  if (blocked) request.result.close();
@@ -48,9 +51,16 @@ export function createGridCache({ database, store, build, revisions, hintPrefix
48
51
  request.onsuccess = () => resolve(request.result);
49
52
  request.onerror = () => reject(request.error);
50
53
  });
51
- if (!Array.isArray(kept) || kept.length !== arrays.length ||
52
- !kept.every((a,i) => ArrayBuffer.isView(a) && a.constructor === arrays[i].constructor && a.length === arrays[i].length)) return false;
53
- arrays.forEach((array,i) => array.set(kept[i]));
54
+ if (
55
+ !Array.isArray(kept) ||
56
+ kept.length !== arrays.length ||
57
+ !kept.every(
58
+ (cachedArray, i) =>
59
+ ArrayBuffer.isView(cachedArray) && cachedArray.constructor === arrays[i].constructor && cachedArray.length === arrays[i].length,
60
+ )
61
+ )
62
+ return false;
63
+ arrays.forEach((array, i) => array.set(kept[i]));
54
64
  return true;
55
65
  } catch {
56
66
  return false;
@@ -1,9 +1,48 @@
1
1
  // Rows of baked grids, cut out to be sent from a worker and put back in their place on the page. A grid is a typed array of
2
2
  // `rows` rows, with any number of values to a row (a height, three of a normal, four of a cover).
3
3
 
4
- // Copy the half-open row interval [j0, j1) from each grid.
5
- const cutRows = (grids, rows, j0, j1) => grids.map(grid => grid.slice((j0 * grid.length) / rows, (j1 * grid.length) / rows));
6
- // Puts what cutRows cut back into grids of the same shapes, from row j0 on.
7
- const pasteRows = (grids, rows, j0, cut) => grids.forEach((grid, i) => grid.set(cut[i], (j0 * grid.length) / rows));
4
+ // Copy the half-open row interval [startRow, endRow) from each grid.
5
+ const cutRows = (grids, rows, startRow, endRow) =>
6
+ grids.map(grid => grid.slice((startRow * grid.length) / rows, (endRow * grid.length) / rows));
7
+ // Puts what cutRows cut back into grids of the same shapes, starting at startRow.
8
+ const pasteRows = (grids, rows, startRow, bandData) => grids.forEach((grid, i) => grid.set(bandData[i], (startRow * grid.length) / rows));
8
9
 
9
- export { cutRows, pasteRows };
10
+ function checkBandSize(size) {
11
+ if (!Number.isSafeInteger(size) || size <= 0) throw new RangeError('Band size must be a positive integer');
12
+ }
13
+
14
+ // Bake a grid locally with one yield after each synchronous band, including the tail.
15
+ async function bakeRowBands(rows, bandSize, bake, yieldTurn) {
16
+ checkBandSize(bandSize);
17
+ if (!Number.isSafeInteger(rows) || rows < 0) throw new RangeError('Invalid row count');
18
+ for (let from = 0; from < rows; from += bandSize) {
19
+ bake(from, Math.min(rows, from + bandSize));
20
+ await yieldTurn();
21
+ }
22
+ }
23
+
24
+ /**
25
+ * Fill the half-open interval [from, to) in typed destination grids of equal row count.
26
+ * request(start, end) returns one cutRows result or a promise for it. Requests are
27
+ * submitted synchronously in row order. Completed cuts are installed and released
28
+ * immediately. Rejection waits for all outstanding writes before returning ownership.
29
+ */
30
+ async function fillRowBands(grids, rows, bandSize, request, from = 0, to = rows) {
31
+ checkBandSize(bandSize);
32
+ if (!Number.isSafeInteger(rows) || !Number.isSafeInteger(from) || !Number.isSafeInteger(to) || from < 0 || to < from || to > rows)
33
+ throw new RangeError('Invalid row interval');
34
+ const pending = [];
35
+ async function fill(start, end) {
36
+ const bandData = await request(start, end);
37
+ pasteRows(grids, rows, start, bandData);
38
+ }
39
+ for (let start = from; start < to; start += bandSize) pending.push(fill(start, Math.min(start + bandSize, to)));
40
+ try {
41
+ await Promise.all(pending);
42
+ } catch (error) {
43
+ await Promise.allSettled(pending);
44
+ throw error;
45
+ }
46
+ }
47
+
48
+ export { bakeRowBands, cutRows, fillRowBands, pasteRows };
@@ -22,6 +22,8 @@ export function createHandOver({ painted, frameShare }) {
22
22
  handed += bytes;
23
23
  };
24
24
  const frameFull = () => handed >= frameShare();
25
+ // The bytes this frame's share still has room for: what a piece sent in parts may write now (PieceBatch.stepUpload)
26
+ const shareLeft = () => Math.max(0, frameShare() - handed);
25
27
  // A browser can paint without rendering a scene while loading.
26
28
  async function nextShare() {
27
29
  const was = drawn;
@@ -29,31 +31,39 @@ export function createHandOver({ painted, frameShare }) {
29
31
  if (drawn === was) handed = 0;
30
32
  }
31
33
 
32
- const heldBytes = geometry => Object.values(geometry.attributes).reduce((sum, a) => sum + (a.array?.byteLength ?? 0), 0);
33
- const letsGo = geometry => Object.values(geometry.attributes).some(a => Object.hasOwn(a, 'onUploadCallback'));
34
+ const heldBytes = geometry => Object.values(geometry.attributes).reduce((sum, attribute) => sum + (attribute.array?.byteLength ?? 0), 0);
35
+ const letsGo = geometry => Object.values(geometry.attributes).some(attribute => Object.hasOwn(attribute, 'onUploadCallback'));
34
36
 
35
- function handToCard(roots) {
37
+ function handToCard(roots, signal) {
38
+ const turn = handing.then(() => handOver(roots, signal));
39
+ handing = turn.catch(() => {});
40
+ return turn;
41
+ }
42
+ async function handOver(roots, signal) {
43
+ signal?.throwIfAborted();
36
44
  const found = new Map();
37
45
  for (const root of roots)
38
46
  root.traverse(o => {
39
47
  if (o.isMesh && !o.isSkinnedMesh && !inHand.has(o.geometry) && heldBytes(o.geometry) && letsGo(o.geometry))
40
48
  found.set(o.geometry, [...(found.get(o.geometry) ?? []), o]);
41
49
  });
42
- const turn = handing.then(() => handOver(found));
43
- handing = turn.catch(() => {});
44
- return turn;
45
- }
46
- async function handOver(found) {
47
- let batch = [];
50
+
51
+ const batch = [];
52
+ const restoreBatch = () => {
53
+ restore(batch);
54
+ batch.length = 0;
55
+ };
48
56
  const flush = async () => {
57
+ signal?.addEventListener('abort', restoreBatch, { once: true });
49
58
  try {
50
59
  await nextShare();
51
60
  } finally {
52
- restore(batch);
53
- batch = [];
61
+ signal?.removeEventListener('abort', restoreBatch);
62
+ restoreBatch();
54
63
  }
55
64
  };
56
65
  for (const [geometry, meshes] of found) {
66
+ signal?.throwIfAborted();
57
67
  if (inHand.has(geometry)) continue;
58
68
  inHand.add(geometry);
59
69
  const range = { ...geometry.drawRange },
@@ -64,7 +74,7 @@ export function createHandOver({ painted, frameShare }) {
64
74
  m.frustumCulled = false;
65
75
  }
66
76
  // The first render uploads everything queued before the render loop started.
67
- if (!drawn) {
77
+ if (!drawn && !signal) {
68
78
  beforeFirst.push([geometry, meshes, range, was]);
69
79
  continue;
70
80
  }
@@ -73,6 +83,7 @@ export function createHandOver({ painted, frameShare }) {
73
83
  if (frameFull()) await flush();
74
84
  }
75
85
  if (batch.length) await flush();
86
+ signal?.throwIfAborted();
76
87
  }
77
88
  function restore(handedOver) {
78
89
  for (const [geometry, meshes, range, was] of handedOver) {
@@ -82,21 +93,33 @@ export function createHandOver({ painted, frameShare }) {
82
93
  }
83
94
  }
84
95
 
85
- async function paced(steps) {
86
- let step;
87
- while (!(step = steps.next()).done) {
88
- countHanded(step.value);
89
- if (frameFull()) await nextShare();
96
+ async function paced(steps, signal) {
97
+ try {
98
+ while (true) {
99
+ signal?.throwIfAborted();
100
+ const step = steps.next();
101
+ if (step.done) return step.value;
102
+ countHanded(step.value);
103
+ if (frameFull()) await nextShare();
104
+ }
105
+ } catch (error) {
106
+ steps.return?.();
107
+ throw error;
90
108
  }
91
- return step.value;
92
109
  }
93
- function drain(steps) {
94
- let step;
95
- do step = steps.next();
96
- while (!step.done);
97
- return step.value;
110
+ function drain(steps, signal) {
111
+ try {
112
+ while (true) {
113
+ signal?.throwIfAborted();
114
+ const step = steps.next();
115
+ if (step.done) return step.value;
116
+ }
117
+ } catch (error) {
118
+ steps.return?.();
119
+ throw error;
120
+ }
98
121
  }
99
122
 
100
123
  const anyFrameDrawn = () => drawn > 0;
101
- return { anyFrameDrawn, countHanded, drain, frameDrawn, frameFull, handToCard, heldBytes, paced };
124
+ return { anyFrameDrawn, countHanded, drain, frameDrawn, frameFull, handToCard, heldBytes, paced, shareLeft };
102
125
  }
@@ -0,0 +1,78 @@
1
+ /**
2
+ * Baking a land's ground on every core. A bake is rows of arithmetic over noise, each row worked out from the land's
3
+ * layout alone: the rows are handed to a pool's workers a band at a time, whichever worker is free taking the next, and
4
+ * each band is put in its place as it comes back (`grid-rows.js`). The numbers are the same to the last bit whoever
5
+ * works them out, so where there are no workers, or one fails, the page bakes the rows itself, a few between two
6
+ * frames. Whole-grid stages that follow the rows (rain's wear, horizon angles) go to one worker the same way, and the
7
+ * finished grids are kept between visits (`grid-cache.js`).
8
+ *
9
+ * A world writes its lands' stages with these; its worker entries answer the jobs with `cutRows`.
10
+ * @module
11
+ */
12
+
13
+ import { bakeRowBands, fillRowBands } from './grid-rows.js';
14
+
15
+ /**
16
+ * @typedef {object} LandBake
17
+ * @property {(rows: number, bake: (startRow: number, endRow: number) => void) => Promise<void>} rowsOnPage - Bakes every row on
18
+ * the page's own thread, `pageRows` between two frames.
19
+ * @property {(job: string, input: object, rows: number, grids: ArrayLike<number>[], from?: number, to?: number) => Promise<boolean>} rowsOnPool -
20
+ * Bakes rows [from, to) of `grids` on the pool: each band is asked for as job `job` with `{ ...input, j0, j1 }` and must come
21
+ * back as `cutRows` of those grids. Resolves false, with the grids to be baked again, where there is no pool or a job was refused.
22
+ * @property {(job: string, input: object, rows: number, grids: ArrayLike<number>[], bake: (startRow: number, endRow: number) => void) => Promise<void>} rows -
23
+ * Every row on the pool, or on the page if the pool could not.
24
+ * @property {(job: string, input: object) => void} tell - Tells every worker something the rows asked for next are worked out
25
+ * from. A worker that fails shows in those rows.
26
+ * @property {<T>(job: string, input: object, here: () => T) => Promise<T>} stage - A whole-grid stage on one worker, or `here()` on
27
+ * the page where there is no pool or the job was refused.
28
+ * @property {(name: string, arrays: () => ArrayLike<number>[], bake: () => Promise<void>) => Promise<boolean>} kept - Fills
29
+ * `arrays()` from what an earlier visit kept under `name`, or bakes them and keeps them; resolves whether they were taken as kept.
30
+ */
31
+
32
+ /**
33
+ * Make the runner of a world's ground bakes.
34
+ * @param {object} options
35
+ * @param {{ pooled: () => boolean, run: (job: string, input: object) => Promise<any>, runOnEach: (job: string, input: object) => Promise<any> }} options.pool -
36
+ * The world's worker pool (`createPool`).
37
+ * @param {() => Promise<void>} options.yieldFrame - Resolves on the page's next frame.
38
+ * @param {{ hasKept: (name: string) => boolean, takeKept: (name: string, arrays: ArrayLike<number>[]) => Promise<boolean>, keep: (name: string, arrays: ArrayLike<number>[]) => void }} [options.cache] -
39
+ * Where finished grids are kept between visits (`createGridCache`); needed by `kept` only.
40
+ * @param {number} [options.band=16] - Rows to a job: small enough that the workers end together, though some rows are quicker than others.
41
+ * @param {number} [options.pageRows=64] - Rows baked between two frames on the page's own thread.
42
+ * @returns {LandBake}
43
+ */
44
+ export function createLandBake({ pool, yieldFrame, cache, band = 16, pageRows = 64 }) {
45
+ const rowsOnPage = (rows, bake) => bakeRowBands(rows, pageRows, bake, yieldFrame);
46
+
47
+ async function rowsOnPool(job, input, rows, grids, from = 0, to = rows) {
48
+ if (!pool.pooled()) return false;
49
+ try {
50
+ await fillRowBands(grids, rows, band, (j0, j1) => pool.run(job, { ...input, j0, j1 }), from, to);
51
+ return true;
52
+ } catch {
53
+ return false; // the pool already logged the refused job
54
+ }
55
+ }
56
+
57
+ async function rows(job, input, count, grids, bake) {
58
+ if (!(await rowsOnPool(job, input, count, grids))) await rowsOnPage(count, bake);
59
+ }
60
+
61
+ function tell(job, input) {
62
+ if (pool.pooled()) pool.runOnEach(job, input).catch(() => {});
63
+ }
64
+
65
+ async function stage(job, input, here) {
66
+ const done = pool.pooled() ? await pool.run(job, input).catch(() => null) : null;
67
+ return done ?? here();
68
+ }
69
+
70
+ async function kept(name, arrays, bake) {
71
+ if (cache.hasKept(name) && (await cache.takeKept(name, arrays()))) return true;
72
+ await bake();
73
+ cache.keep(name, arrays());
74
+ return false;
75
+ }
76
+
77
+ return { rowsOnPage, rowsOnPool, rows, tell, stage, kept };
78
+ }
@@ -0,0 +1,105 @@
1
+ import { nextFrame } from './frame-yield.js';
2
+
3
+ /**
4
+ * A breather for one long piece of building: `await breathe()` between its parts gives a frame back to the page whenever more
5
+ * than `budgetMs` of building has run since the last, so what is built while a world is being drawn is built over several
6
+ * frames, never in one long one. While `behindBar()` is true (nothing is drawn yet: a loading bar stands) it gives nothing
7
+ * back, so loading is no longer for it.
8
+ *
9
+ * @param {object} [options]
10
+ * @param {number} [options.budgetMs=6] Milliseconds of building between two frames.
11
+ * @param {() => boolean} [options.behindBar] Whether no world is drawn yet.
12
+ * @param {() => Promise<void>} [options.yieldFrame] Waits for the next frame.
13
+ * @param {() => number} [options.clock] Milliseconds.
14
+ * @returns {() => Promise<void>}
15
+ */
16
+ export function createBreather({ budgetMs = 6, behindBar = () => false, yieldFrame = nextFrame, clock = () => performance.now() } = {}) {
17
+ let since = clock();
18
+ return async () => {
19
+ if (behindBar() || clock() - since < budgetMs) return;
20
+ await yieldFrame();
21
+ since = clock();
22
+ };
23
+ }
24
+
25
+ /**
26
+ * Sets that are declared when a land is built and raised only when first needed: what a staged scene needs standing at its
27
+ * place (a camp, a ruin, a tower), or anything else too dear to build for a visitor who never goes there. A set is declared with
28
+ * its place and reach and a `load()` that fetches its builder; it is raised the first time someone asks for it (`raise`) or
29
+ * comes within its reach (`raiseNearest`, one at a time, nearest first: two builders in the same frames would each take their
30
+ * share of it). The sets it `needs` are raised before it, their builders fetched beside its own.
31
+ *
32
+ * @param {object} options
33
+ * @param {(id: string, builder: any) => Promise<void>} options.build Builds a fetched set where it stands and resolves when it
34
+ * does; `builder` is what the set's `load()` resolved to.
35
+ * @param {(id: string) => void} [options.unfetched] Told when a set's builder, or a needed set's, could not be fetched (and the
36
+ * asker was not another set): the set is asked for again the next time someone raises it.
37
+ * @returns {{ declare: Function, fetch: (id: string) => void, raise: (id: string, quiet?: boolean) => Promise<boolean>,
38
+ * raiseWithin: (x: number, z: number) => Promise<boolean[]>, raiseNearest: (x: number, z: number) => void,
39
+ * stands: (id: string) => boolean, declared: () => { id: string, x: number, z: number, range: number }[] }}
40
+ * `declare(id, { x, z, range, load, needs })`; `fetch` starts a set's fetch (and its needs') without raising it, so that a
41
+ * fetch and a fade overlap; `raise` resolves true once the set stands (at once if it stood already or was never declared), false
42
+ * if it could not be fetched, and rejects if its builder failed; `raiseWithin` raises every set whose reach holds (x, z);
43
+ * `stands(id)`: it stands, or is no set here; `declared()`: those not yet raised.
44
+ */
45
+ export function createLazySets({ build, unfetched: tellUnfetched = () => {} }) {
46
+ const sets = new Map(), // id -> { x, z, range, load, needs, part }; a set leaves the map when it is raised
47
+ rising = new Map(), // id -> the promise of a set being raised, until it stands
48
+ unfetched = new Map(); // id -> a set whose builder could not be fetched: raised again only when someone asks
49
+
50
+ function declare(id, { x, z, range, load, needs = [] }) {
51
+ sets.set(id, { x, z, range, load, needs, part: null });
52
+ }
53
+ function fetch(id) {
54
+ const set = sets.get(id) ?? unfetched.get(id);
55
+ if (!set) return;
56
+ for (const need of set.needs) fetch(need);
57
+ if (!set.part) (set.part = set.load()).catch(() => {}); // a failure is raise's to tell
58
+ }
59
+ function raise(id, quiet = false) {
60
+ const set = sets.get(id) ?? unfetched.get(id);
61
+ if (set && !rising.has(id)) {
62
+ fetch(id);
63
+ unfetched.delete(id);
64
+ const notFetched = () => {
65
+ set.part = null; // asked again the next time
66
+ unfetched.set(id, set);
67
+ if (!quiet) tellUnfetched(id);
68
+ return false;
69
+ };
70
+ const raised = Promise.all(set.needs.map(need => raise(need, true))).then(stood =>
71
+ stood.every(Boolean) ? set.part.then(builder => build(id, builder).then(() => true), notFetched) : notFetched(),
72
+ );
73
+ rising.set(id, raised);
74
+ raised.then(
75
+ () => {
76
+ sets.delete(id); // a second asker waits for the same build until it stands
77
+ rising.delete(id);
78
+ },
79
+ () => {}, // a builder that fails is the caller's to report
80
+ );
81
+ }
82
+ return rising.get(id) ?? Promise.resolve(true);
83
+ }
84
+ const stands = id => !sets.has(id) && !rising.has(id) && !unfetched.has(id);
85
+ function raiseWithin(x, z) {
86
+ const due = [...sets].filter(([, set]) => Math.hypot(set.x - x, set.z - z) < set.range).map(([id]) => id);
87
+ return Promise.all(due.map(id => raise(id)));
88
+ }
89
+ function raiseNearest(x, z) {
90
+ if (rising.size) return;
91
+ let near = null,
92
+ least = Infinity;
93
+ for (const [id, set] of sets) {
94
+ const d = Math.hypot(set.x - x, set.z - z);
95
+ if (d < set.range && d < least) {
96
+ least = d;
97
+ near = id;
98
+ }
99
+ }
100
+ if (near) raise(near);
101
+ }
102
+ const declared = () => [...sets].map(([id, { x, z, range }]) => ({ id, x, z, range }));
103
+
104
+ return { declare, fetch, raise, raiseWithin, raiseNearest, stands, declared };
105
+ }
package/runtime/pool.js CHANGED
@@ -1,12 +1,40 @@
1
+ /**
2
+ * Schedule jobs across workers, prepare per-worker data and release idle workers.
3
+ * @module
4
+ */
5
+
6
+ /** The pool can use every logical processor the browser exposes beyond its main thread. */
7
+ export function workerCapacity(cores = globalThis.navigator?.hardwareConcurrency) {
8
+ return Number.isFinite(cores) ? Math.max(1, Math.floor(cores) - 1) : 1;
9
+ }
10
+
1
11
  /**
2
12
  * Route weighted jobs to FIFO workers. Each worker receives { job, input } and
3
13
  * replies in order with { result } or { error }. Supply prestarted workers to
4
- * adopt them immediately, and a synchronous factory to restart after idle.
14
+ * adopt them immediately. Supply startWorkers for a fixed pool, or createWorker
15
+ * for a pool that grows with concurrent work up to maxWorkers. A broadcast
16
+ * initializes every worker, so later jobs see the state it set.
17
+ * @param {object} [options] - Worker factories and scheduling settings.
18
+ * @param {() => Worker} [options.createWorker] - Synchronously create one worker when demand grows.
19
+ * @param {() => Worker[]} [options.startWorkers] - Start the fixed pool on first use.
20
+ * @param {Worker[]} [options.initialWorkers] - Adopt already running workers.
21
+ * @param {number} [options.maxWorkers] - Upper bound for an elastic pool.
22
+ * @param {number} [options.idleMs] - Milliseconds before idle workers terminate.
23
+ * @param {(message: string) => void} [options.warn] - Receive worker startup and job failure messages.
5
24
  */
6
- export function createPool({ startWorkers, initialWorkers, idleMs = 4000, warn = message => console.warn(message) } = {}) {
25
+ export function createPool({
26
+ startWorkers,
27
+ createWorker,
28
+ initialWorkers,
29
+ maxWorkers = workerCapacity(),
30
+ idleMs = 4000,
31
+ warn = message => console.warn(message),
32
+ } = {}) {
7
33
  const slots = [];
8
34
  const preparations = new Map();
9
- let broken = typeof startWorkers !== 'function',
35
+ const elastic = typeof createWorker === 'function';
36
+ let capacity = Number.isFinite(maxWorkers) ? Math.max(1, Math.floor(maxWorkers)) : 1;
37
+ let broken = !elastic && typeof startWorkers !== 'function',
10
38
  idle = 0,
11
39
  held = 0;
12
40
 
@@ -29,14 +57,24 @@ export function createPool({ startWorkers, initialWorkers, idleMs = 4000, warn =
29
57
  rest();
30
58
  for (const task of waiting) task.refuse(new Error('pool: ' + reason));
31
59
  }
32
- function adopt(workers) {
33
- for (const worker of workers) {
34
- const slot = { worker, tasks: [], holds: new Set() };
35
- worker.onmessage = ({ data }) => finish(slot, data);
36
- worker.onerror = event => giveUp(event.message || 'a worker could not start');
37
- worker.onmessageerror = () => giveUp('an answer could not be read');
38
- slots.push(slot);
60
+ function attach(worker) {
61
+ const slot = { worker, tasks: [], holds: new Set() };
62
+ worker.onmessage = ({ data }) => finish(slot, data);
63
+ worker.onerror = event => giveUp(event.message || 'a worker could not start');
64
+ worker.onmessageerror = () => giveUp('an answer could not be read');
65
+ slots.push(slot);
66
+ }
67
+ function grow() {
68
+ if (!elastic || broken || slots.length >= capacity) return;
69
+ try {
70
+ attach(createWorker());
71
+ } catch (error) {
72
+ if (!slots.length) giveUp(error.message);
73
+ else capacity = slots.length; // A browser resource limit can be lower than its hardware count.
39
74
  }
75
+ }
76
+ function adopt(workers) {
77
+ for (const worker of workers) attach(worker);
40
78
  if (!workers.length || workers.some(worker => worker.failed)) giveUp('the workers could not start');
41
79
  else restWhenIdle();
42
80
  }
@@ -89,7 +127,8 @@ export function createPool({ startWorkers, initialWorkers, idleMs = 4000, warn =
89
127
  function awake() {
90
128
  if (!broken && !slots.length) {
91
129
  try {
92
- adopt(startWorkers());
130
+ if (elastic) grow();
131
+ else adopt(startWorkers());
93
132
  } catch (error) {
94
133
  giveUp(error.message);
95
134
  }
@@ -101,14 +140,25 @@ export function createPool({ startWorkers, initialWorkers, idleMs = 4000, warn =
101
140
  const unheard = () => {};
102
141
  const load = slot => slot.tasks.reduce((sum, task) => sum + task.cost, 0);
103
142
  // Costs include both running and queued jobs. Dispatch immediately, even when the main thread is busy.
104
- const leastBusy = list => list.reduce((a, b) => (load(b) < load(a) ? b : a));
143
+ const leastBusy = list => list.reduce((leastLoaded, candidate) => (load(candidate) < load(leastLoaded) ? candidate : leastLoaded));
105
144
  // Register the input to send once per worker before a job that names this preparation.
106
145
  function prepare(name, input, cost = 1) {
107
146
  preparations.set(name, { input, cost });
108
147
  for (const slot of slots) slot.holds.delete(name);
109
148
  }
149
+ /**
150
+ * Register a shared input on first demand. The factory runs once per pool and name,
151
+ * only when workers are available. A later prepare() can replace the registered input.
152
+ * @param {string} name - Preparation job needed by dependent jobs.
153
+ * @param {Function} inputOf - Synchronous factory for the worker input.
154
+ * @param {number} [cost] - Relative cost of installing it on one worker.
155
+ */
156
+ function prepareOnce(name, inputOf, cost = 1) {
157
+ if (pooled() && !preparations.has(name)) prepare(name, inputOf(), cost);
158
+ }
110
159
  function run(job, input, transfer = [], needs = null, cost = 1) {
111
160
  if (!awake().length) return noWorkers();
161
+ if (elastic && slots.every(slot => slot.tasks.length)) grow();
112
162
  let least = leastBusy(slots);
113
163
  if (needs && !least.holds.has(needs)) {
114
164
  const holding = slots.filter(slot => slot.holds.has(needs)),
@@ -129,9 +179,11 @@ export function createPool({ startWorkers, initialWorkers, idleMs = 4000, warn =
129
179
  function spread(name, count) {
130
180
  const preparation = preparations.get(name);
131
181
  if (!preparation) return;
132
- const others = awake().filter(slot => !slot.holds.has(name)),
182
+ if (!awake().length) return;
183
+ while (elastic && slots.length < Math.min(count, capacity)) grow();
184
+ const others = slots.filter(slot => !slot.holds.has(name)),
133
185
  more = Math.min(count, slots.length) - (slots.length - others.length);
134
- for (const slot of others.sort((a, b) => load(a) - load(b)).slice(0, Math.max(0, more))) {
186
+ for (const slot of others.sort((firstSlot, secondSlot) => load(firstSlot) - load(secondSlot)).slice(0, Math.max(0, more))) {
135
187
  slot.holds.add(name);
136
188
  send(slot, name, preparation.input, [], preparation.cost, null, name).catch(unheard);
137
189
  }
@@ -144,10 +196,14 @@ export function createPool({ startWorkers, initialWorkers, idleMs = 4000, warn =
144
196
  slot.holds.add(job);
145
197
  }
146
198
  }
147
- function runOnEach(job, input) {
148
- if (!awake().length) return noWorkers();
199
+ /** Broadcast a job to every worker. Set `activeOnly` to reach existing workers without creating more. */
200
+ function runOnEach(job, input, { activeOnly = false } = {}) {
201
+ if (!activeOnly) {
202
+ if (!awake().length) return noWorkers();
203
+ while (elastic && slots.length < capacity) grow();
204
+ }
149
205
  return Promise.all(slots.map(slot => send(slot, job, input, [])));
150
206
  }
151
207
  if (!broken && initialWorkers) adopt(initialWorkers);
152
- return { keepAwake, pooled, poolSize, prepare, ready, run, runOnEach, runOrHere, spread };
208
+ return { keepAwake, pooled, poolSize, prepare, prepareOnce, ready, run, runOnEach, runOrHere, spread };
153
209
  }