roamwright 0.4.0 → 0.20.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 (139) hide show
  1. package/CONTRIBUTING.md +3 -1
  2. package/README.md +11 -34
  3. package/geometry/bedding.js +141 -0
  4. package/geometry/builder-cells.js +42 -0
  5. package/geometry/builder-frame.js +47 -0
  6. package/geometry/builder.js +189 -177
  7. package/geometry/cell-mask.js +25 -0
  8. package/geometry/creased-sheet.js +34 -34
  9. package/geometry/ear.js +36 -36
  10. package/geometry/erosion.js +65 -42
  11. package/geometry/face-grid.js +65 -65
  12. package/geometry/foliage.js +10 -10
  13. package/geometry/hair-gathers.js +41 -41
  14. package/geometry/hair-locks.js +41 -41
  15. package/geometry/hair-patch.js +18 -18
  16. package/geometry/hair-shell.js +31 -31
  17. package/geometry/head-profile.js +15 -15
  18. package/geometry/head-shape.js +77 -77
  19. package/geometry/heightfield.js +27 -18
  20. package/geometry/index-parts.js +2 -2
  21. package/geometry/instance-visibility.js +12 -12
  22. package/geometry/instances.js +15 -15
  23. package/geometry/outline-grid.js +7 -7
  24. package/geometry/part-ranges.js +3 -3
  25. package/geometry/path-field.js +63 -33
  26. package/geometry/placement.js +52 -52
  27. package/geometry/point-buckets.js +50 -0
  28. package/geometry/primitives.js +63 -47
  29. package/geometry/sagging-tube.js +27 -27
  30. package/geometry/sampled-surface.js +109 -77
  31. package/geometry/scatter-grid.js +46 -6
  32. package/geometry/sculpt.js +93 -93
  33. package/geometry/shore-grid.js +77 -34
  34. package/geometry/strata-field.js +92 -92
  35. package/geometry/strata-tiles.js +91 -91
  36. package/geometry/stream.js +70 -48
  37. package/geometry/terrain-chunks.js +87 -82
  38. package/geometry/terrain-extension.js +6 -6
  39. package/index.js +5 -0
  40. package/math/cell-edge.js +16 -16
  41. package/math/cell-key.js +6 -0
  42. package/math/circle-clearances.js +19 -0
  43. package/math/cloth-textures.js +6 -6
  44. package/math/cloud-textures.js +20 -20
  45. package/math/color.js +14 -14
  46. package/math/curve.js +22 -22
  47. package/math/mountain-ranges.js +216 -165
  48. package/math/noise.js +101 -49
  49. package/math/particle-noise.js +28 -28
  50. package/math/periodic.js +5 -5
  51. package/math/random.js +24 -15
  52. package/math/rectangles.js +52 -0
  53. package/math/rock-texture.js +7 -7
  54. package/math/scalar.js +5 -5
  55. package/math/surface-textures.js +54 -54
  56. package/motion/arm-reach.js +24 -24
  57. package/motion/ballistic-arc.js +11 -0
  58. package/motion/biped-cycle.js +44 -0
  59. package/motion/biped-leg.js +37 -0
  60. package/motion/biped-stride.js +98 -122
  61. package/motion/contact-transition.js +33 -0
  62. package/motion/crowd-alarms.js +39 -39
  63. package/motion/crowd-routine.js +94 -65
  64. package/motion/daily-clock.js +9 -9
  65. package/motion/deck-surface.js +38 -0
  66. package/motion/ground-lookahead.js +5 -5
  67. package/motion/instance-sight.js +8 -8
  68. package/motion/player.js +36 -28
  69. package/motion/quadruped.js +155 -155
  70. package/motion/spaces.js +32 -32
  71. package/motion/weather.js +73 -24
  72. package/motion/wind.js +32 -13
  73. package/package.json +7 -3
  74. package/rendering/caster-motion.js +5 -5
  75. package/rendering/cell-lod.js +138 -82
  76. package/rendering/cloud-dome.js +28 -28
  77. package/rendering/cloud-field.js +2 -2
  78. package/rendering/compilation-schedule.js +68 -11
  79. package/rendering/contact-shadows.js +2 -2
  80. package/rendering/context.js +12 -0
  81. package/rendering/crowd-skinning.js +13 -13
  82. package/rendering/crust.js +18 -12
  83. package/rendering/daylight.js +3 -3
  84. package/rendering/detail-range.js +28 -0
  85. package/rendering/dispose-meshes.js +18 -0
  86. package/rendering/dof.js +9 -9
  87. package/rendering/eye-adapt.js +14 -14
  88. package/rendering/far-shadow.js +8 -8
  89. package/rendering/flocks.js +78 -78
  90. package/rendering/garment-material.js +17 -17
  91. package/rendering/glow-lines.js +13 -13
  92. package/rendering/hair-strands.js +20 -20
  93. package/rendering/height-probe.js +149 -19
  94. package/rendering/label-layout.js +46 -0
  95. package/rendering/label-range.js +38 -0
  96. package/rendering/light-budget.js +52 -52
  97. package/rendering/light-shafts.js +23 -23
  98. package/rendering/local-lights.js +15 -4
  99. package/rendering/material-lod.js +49 -49
  100. package/rendering/particle-emitters.js +90 -90
  101. package/rendering/particles.js +78 -67
  102. package/rendering/piece-batch.js +17 -6
  103. package/rendering/planar-reflection.js +38 -38
  104. package/rendering/post-shaders.js +17 -13
  105. package/rendering/post.js +71 -71
  106. package/rendering/rain-streaks.js +67 -0
  107. package/rendering/road-surface.js +11 -11
  108. package/rendering/sea-shaders.js +11 -11
  109. package/rendering/shader-warmup.js +29 -16
  110. package/rendering/shadow-alignment.js +4 -4
  111. package/rendering/shadow-depth.js +7 -7
  112. package/rendering/sky-occlusion.js +16 -16
  113. package/rendering/sky.js +16 -6
  114. package/rendering/stage-lights.js +6 -6
  115. package/rendering/static-point-shadow.js +3 -3
  116. package/rendering/still-casters.js +1 -1
  117. package/rendering/strata-material.js +10 -10
  118. package/rendering/stream-flow.js +10 -10
  119. package/rendering/taa.js +26 -26
  120. package/rendering/talus.js +15 -15
  121. package/rendering/terrain-rock.js +7 -7
  122. package/rendering/texture-fills.js +8 -8
  123. package/rendering/textures.js +28 -28
  124. package/rendering/wakes.js +24 -24
  125. package/rendering/water-material.js +36 -23
  126. package/rendering/world-matrices.js +38 -38
  127. package/runtime/diagnostic-log.js +2 -2
  128. package/runtime/first-use.js +33 -28
  129. package/runtime/frame-pacing.js +33 -0
  130. package/runtime/gpu-timing.js +7 -7
  131. package/runtime/grid-cache.js +1 -1
  132. package/runtime/grid-rows.js +44 -5
  133. package/runtime/hand-over.js +41 -23
  134. package/runtime/pool.js +58 -16
  135. package/runtime/quality-fit.js +1 -1
  136. package/runtime/search.js +22 -22
  137. package/runtime/spatial-audio.js +13 -13
  138. package/runtime/withdrawable-task.js +35 -0
  139. package/runtime/worker.js +7 -0
package/CONTRIBUTING.md CHANGED
@@ -23,7 +23,9 @@ npm run test:package
23
23
 
24
24
  CI runs the first three checks with Three.js 0.170.0 and 0.187.0. To try the older peer locally, run `npm install --no-save --package-lock=false three@0.170.0` and repeat the checks. Run `npm ci` to restore the locked dependencies.
25
25
 
26
- After both compatibility jobs pass on `main`, the same workflow deploys the [live examples](https://enestaylan.github.io/roamwright/) from this repository. The site serves the locked Three.js build alongside the example modules.
26
+ Run `npm run docs` to generate the API reference in `build/docs/`. Preview it with `python3 -m http.server --directory build/docs`. TypeDoc reads the public JavaScript modules and their source comments. Document caller-visible behavior, units and return values next to the declarations.
27
+
28
+ After both compatibility jobs pass on `main`, the same workflow generates and deploys the [API reference](https://enestaylan.github.io/roamwright/docs/) alongside the [live examples](https://enestaylan.github.io/roamwright/) from this repository. The site serves the locked Three.js build alongside the example modules.
27
29
 
28
30
  ## Prepare a pull request
29
31
 
package/README.md CHANGED
@@ -3,11 +3,11 @@
3
3
  [![npm version](https://img.shields.io/npm/v/roamwright)](https://www.npmjs.com/package/roamwright)
4
4
  [![Compatibility tests](https://github.com/enestaylan/roamwright/actions/workflows/test.yml/badge.svg?branch=main)](https://github.com/enestaylan/roamwright/actions/workflows/test.yml)
5
5
 
6
- Roamwright is a procedural worldbuilding engine built on top of Three.js. It gives you reusable systems for turning a 3D scene into a world you can explore. You define the landscape once and use the same terrain to shape riverbanks, place scenery and guide characters over uneven ground. First-person walking and flight, crowd animation, weather and day–night lighting can all be used in your own Three.js scene.
6
+ **Roamwright is a procedural worldbuilding engine for Three.js.** Start with a seed and a height field. Use that same ground to carve a river valley, plant trees along its banks and place the piers of a bridge. Add weather and daylight, give characters routes through the landscape, and explore the world on foot or in flight.
7
7
 
8
8
  ![A red passenger train on a stone viaduct above a winding alpine river, with conifers on the banks and snow on the peaks](https://raw.githubusercontent.com/enestaylan/roamwright/main/docs/alpine-viaduct.jpg)
9
9
 
10
- **Alpine viaduct.** One height field shapes the riverbed and snowy ridges and determines where the conifers take root. Eight copies of an arch profile form the viaduct. The stonework, rails and overhead wires share one mesh. The four-car electric train moves as a separate mesh. Choose Valley, Trackside or Riverbank and select **Run train** to watch it cross. [Explore the example source](examples/viaduct.js).
10
+ **[Alpine viaduct](https://enestaylan.github.io/roamwright/examples/viaduct.html).** One height field shapes the riverbed and snowy ridges and determines where the conifers take root. Eight copies of an arch profile form the viaduct. The stonework, rails and overhead wires share one mesh. The four-car electric train moves as a separate mesh. Choose Valley, Trackside or Riverbank and select **Run train** to watch it cross. [Explore the example source](examples/viaduct.js).
11
11
 
12
12
  ## Building an explorable world
13
13
 
@@ -72,39 +72,16 @@ renderer.render(scene, camera);
72
72
 
73
73
  ## Modules
74
74
 
75
- Import any module from `roamwright/<folder>/<name>.js`. Each area below names its main modules first. Its other modules are listed after them. See each module’s source for its parameters, and the [tests](test) and browser fixtures for complete setups.
75
+ Import modules by path, for example `roamwright/geometry/builder.js`. Browse the [API reference](https://enestaylan.github.io/roamwright/docs/) for signatures, usage notes and source links.
76
76
 
77
- | Area | Main modules | Also includes |
78
- | --- | --- | --- |
79
- | Foundations | `math/noise.js`, `math/random.js`, `math/curve.js` and `math/color.js` provide seeded noise, resumable random streams, spline samples and colour conversion. They also run in workers. | `math/scalar.js`, `math/cell-edge.js`, `math/periodic.js` |
80
- | Geometry | `geometry/builder.js` and `geometry/primitives.js` merge primitives into typed buffers or a Three.js mesh. `geometry/sculpt.js` builds lofted, skinned shapes. `geometry/instances.js` and `rendering/piece-batch.js` draw repeated or changing pieces. | `geometry/sampled-surface.js`, `geometry/placement.js`, `geometry/creased-sheet.js`, `geometry/sagging-tube.js`, `rendering/cell-lod.js` |
81
- | Terrain | `geometry/terrain-chunks.js` refines a height grid in mesh batches. `geometry/heightfield.js` samples and refines it, `math/mountain-ranges.js` raises relief and `geometry/strata-field.js` plans rock outcrops. | `geometry/terrain-extension.js`, `geometry/erosion.js`, `geometry/strata-tiles.js`, `geometry/scatter-grid.js`, `geometry/outline-grid.js`, `geometry/path-field.js`, `math/rock-texture.js`, `rendering/terrain-rock.js`, `rendering/strata-material.js`, `rendering/talus.js`, `rendering/road-surface.js` |
82
- | Water | `rendering/water-material.js` shades lakes, streams and rivers. `geometry/stream.js` builds stream ribbons and `geometry/shore-grid.js` measures distance to shorelines. | `rendering/sea-shaders.js`, `rendering/wakes.js`, `rendering/stream-flow.js`, `rendering/rain-rings.js`, `rendering/planar-reflection.js` |
83
- | Sky and weather | `rendering/sky.js` combines `rendering/cloud-field.js` and `rendering/cloud-dome.js` into a volumetric cloud sky ([fixture](test/atmosphere.js)). `motion/weather.js` and `motion/wind.js` drive rain, dust, squalls and gusts. | `math/cloud-textures.js`, `rendering/daylight.js`, `rendering/height-haze.js`, `rendering/particles.js`, `math/particle-noise.js`, `rendering/particle-emitters.js`, `rendering/flocks.js` |
84
- | Characters | `geometry/head-shape.js` builds parametric heads, `geometry/hair-shell.js` hair and `rendering/garment-material.js` cloth, plate and mail ([fixture](test/garment-material.js)). `motion/biped-stride.js` and `motion/quadruped.js` animate gaits, and `rendering/crowd-skinning.js` draws instanced skinned crowds. | `geometry/ear.js`, `geometry/face-grid.js`, `geometry/head-profile.js`, `geometry/hair-locks.js`, `geometry/hair-gathers.js`, `geometry/hair-patch.js`, `geometry/hair-tags.js`, `geometry/garment-tags.js`, `math/cloth-textures.js`, `rendering/hair-strands.js`, `motion/arm-reach.js`, `motion/crowd-alarms.js`, `motion/crowd-routine.js` |
85
- | Surfaces | `rendering/surface-projection.js` projects textures in metres onto standard materials and `rendering/surface-light.js` adds wetness and backlighting ([fixture](test/projected-surface.js)). `math/surface-textures.js` fills seeded, tileable masonry, plaster, roof tile, rock, plank, foliage, ground, road, brick and ice textures, in a worker if wanted. | `rendering/interior-mapping.js`, `rendering/crust.js`, `rendering/low-light.js`, `rendering/material-lod.js`, `rendering/textures.js`, `rendering/texture-fills.js` |
86
- | Lights and shadows | `rendering/far-shadow.js` pairs near and far directional shadows, `rendering/static-point-shadow.js` caches point-light shadows and `rendering/sky-occlusion.js` darkens covered areas. | `rendering/shadow-depth.js`, `rendering/shadow-alignment.js`, `rendering/local-lights.js`, `rendering/caster-motion.js`, `rendering/still-casters.js`, `rendering/contact-shadows.js`, `rendering/light-points.js`, `rendering/light-shafts.js`, `rendering/glow-lines.js`, `rendering/glow-shell.js`, `rendering/light-budget.js`, `rendering/stage-lights.js` |
87
- | Rendering pipeline | `rendering/context.js` sets up WebGL2, a scene and a camera. `rendering/post.js` and `rendering/taa.js` compose HDR passes and temporal antialiasing, and `rendering/shader-warmup.js` compiles programs ahead of use. | `rendering/dof.js`, `rendering/post-shaders.js`, `rendering/eye-adapt.js`, `rendering/viewport.js`, `rendering/world-matrices.js`, `rendering/compilation-schedule.js`, `rendering/height-probe.js` |
88
- | Player and world | `motion/spaces.js` and `motion/player.js` move a first-person controller over terrain, decks and colliders. | `motion/instance-sight.js`, `motion/daily-clock.js`, `runtime/spatial-audio.js` |
89
- | Runtime | `runtime/pool.js` and `runtime/worker.js` run named jobs on module workers. `runtime/quality-fit.js` adapts quality to measured GPU time. | `runtime/device-quality.js`, `runtime/quality-store.js`, `runtime/gpu-timing.js`, `runtime/first-use.js`, `runtime/hand-over.js`, `runtime/seen.js`, `runtime/frame-yield.js`, `runtime/grid-cache.js`, `runtime/grid-rows.js`, `runtime/events.js`, `runtime/diagnostic-log.js`, `runtime/module-preload.js`, `runtime/search.js` |
90
-
91
- For triangle lists, `indexParts` from `geometry/index-parts.js` reuses vertices whose complete attribute records are byte-identical and preserves the original triangle order. Run it where the arrays are built.
92
-
93
- Use `shapeParts`, `addShape` and `partsGeometry` from `geometry/foliage.js` to assemble immutable, indexed plant models with per-vertex tints and leaf flags. `partitionInstances(arrays, cellSize)` from `geometry/instances.js` groups transforms and colours into horizontal cells for camera and shadow culling. For opaque instances with independently owned matrix and colour attributes, `createInstanceVisibility(mesh)` from `geometry/instance-visibility.js` returns a function to show or hide a logical ID. The mesh submits only its visible prefix. Instance order and shader `gl_InstanceID` can change.
94
-
95
- For pieces that change material, `batch.materialView(material)` creates a child mesh that shares the GPU buffers. Assign pieces with `batch.setView(id, mesh)` and return them to the original material with `batch.setView(id)`. Configure the batch layers and shadow flags before creating the view. Treat the child transform and visibility as batch-managed.
96
-
97
- Use `createFrameBudget` from `runtime/frame-budget.js` for optional synchronous work shared by multiple systems. Call `begin(rafTimestamp)` once per frame. Register each small step once with `task(fn)`. Its wrapper preserves the receiver and arguments and returns true after running the step, or false when the caller should retry it. Keep worker jobs concurrent and apply ready results in application order. The budget accounts for elapsed work, reserves time before presentation, and reduces the next allowance after a missed frame. After `maxWaitMs`, the longest-waiting producer can advance one step even on a busy frame. An individual step runs to completion, so divide expensive work at safe boundaries. Before the first frame, steps run immediately.
98
-
99
- `createGroundLookahead` from `motion/ground-lookahead.js` predicts a horizontal position from samples in seconds, with a capped lead and a reset after jumps or pauses. `joinParts` from `geometry/part-ranges.js` assembles attribute buffers from ordered position ranges.
100
-
101
- Pass a `revisions` object mapping grid names to input-version strings to `createGridCache` to reuse compatible grids across builds. Saving a grid retires its previous revision. Names without a revision bypass storage. The existing `build` string versions the whole cache when `revisions` is omitted.
102
-
103
- Pass an optional world-space `initialPosition` to `terrainChunks` to create the terrain at its first viewing distance. Subsequent updates follow the camera.
104
-
105
- For elevated viewpoints, pass the eye height and an optional positive distance scale as the last arguments to `createCellLod().update(cells, x, z, distance, detail, density, y, scale)`. Set `cy` on each cell to its centre elevation. Detail follows the eye in three dimensions while visibility follows ground distance.
106
-
107
- For geometry generated off the main thread, call `builder.parts(true)` in the worker and `geometryOf(parts)` on the page.
77
+ | Area | Main modules |
78
+ | --- | --- |
79
+ | Seeded generation | `math/noise.js`, `math/random.js` |
80
+ | Geometry and terrain | `geometry/builder.js`, `geometry/heightfield.js`, `geometry/terrain-chunks.js` |
81
+ | Static geometry assembly | `geometry/builder-frame.js`, `geometry/builder-cells.js` |
82
+ | Rendering | `rendering/context.js`, `rendering/sky.js`, `rendering/water-material.js` |
83
+ | Movement | `motion/player.js`, `motion/biped-stride.js` |
84
+ | Background jobs | `runtime/pool.js`, `runtime/worker.js`, `runtime/grid-rows.js` |
108
85
 
109
86
  ## Contributing and license
110
87
 
@@ -0,0 +1,141 @@
1
+ import { creasedSheet } from './creased-sheet.js';
2
+ import { sampleSurface } from './sampled-surface.js';
3
+ import { dim } from '../math/color.js';
4
+ import { sstep, TAU } from '../math/scalar.js';
5
+
6
+ // A stuffed linen case, from the underside through the welt to the crown.
7
+ // The pillow's filling banks up around the hollow. The straw tick has a broad, level top under the cover.
8
+ const PILLOW = [
9
+ [0, 0],
10
+ [0.78, 0.02],
11
+ [0.94, 0.29],
12
+ [1, 0.43],
13
+ [1.02, 0.46],
14
+ [0.99, 0.5],
15
+ [0.88, 0.78],
16
+ [0.64, 1],
17
+ [0.36, 0.94],
18
+ [0.17, 0.74],
19
+ [0, 0.66],
20
+ ];
21
+ const TICK = [
22
+ [0, 0],
23
+ [0.93, 0],
24
+ [0.99, 0.2],
25
+ [1, 0.68],
26
+ [0.98, 0.91],
27
+ [0.91, 1],
28
+ [0, 1],
29
+ ];
30
+
31
+ /** Append a seamed cushion above its base centre. Dimensions are in metres, yaw is in radians and tone is linear RGB. */
32
+ function linenCase(cloth, x, y, z, width, height, length, tone, yaw = 0, profile = PILLOW) {
33
+ const pillow = profile === PILLOW,
34
+ rows = [],
35
+ colors = [],
36
+ sin = Math.sin(yaw),
37
+ cos = Math.cos(yaw);
38
+ for (const [radius, level] of profile) {
39
+ const row = [],
40
+ shades = [];
41
+ for (let i = 0; i < 32; i++) {
42
+ const angle = (i * TAU) / 32,
43
+ cosAngle = Math.cos(angle),
44
+ sinAngle = Math.sin(angle);
45
+ // Rounded corners with a little more filling at the four ears of a pillowcase.
46
+ const power = pillow ? 4 : 10;
47
+ const r = radius / Math.pow(Math.abs(cosAngle) ** power + Math.abs(sinAngle) ** power, 1 / power);
48
+ const u = (cosAngle * r * width) / 2,
49
+ v = (sinAngle * r * length) / 2;
50
+ const tuck = pillow ? Math.sin(2 * angle + 0.15) ** 2 * radius ** 3 : 0;
51
+ row.push([x + cos * u + sin * v, y + height * (level + 0.12 * tuck), z - sin * u + cos * v]);
52
+ shades.push(dim(tone, pillow && level === 0.43 ? 0.65 : 1 - 0.07 * tuck));
53
+ }
54
+ rows.push(row);
55
+ colors.push(shades);
56
+ }
57
+ creasedSheet(cloth, rows, colors, { wrap: true, inside: true });
58
+ }
59
+
60
+ /**
61
+ * Append a mattress, cover and pillows to a geometry builder. The centre (x, y, z)
62
+ * is the top of the mattress. The mattress extends down by `tick` and the cover
63
+ * hangs by `drop`. Dimensions are in metres, colours are linear RGB and yaw is in radians.
64
+ */
65
+ function bedLinen(cloth, x, y, z, { width, length, tick, cover, drop, coverTone, linen, ticking, pillows = 1, yaw = 0 }) {
66
+ const cos = Math.cos(yaw),
67
+ sin = Math.sin(yaw),
68
+ point = (u, h, v) => [x + cos * u + sin * v, y + h, z - sin * u + cos * v];
69
+ linenCase(cloth, x, y - tick, z, width, tick - 0.008, length, ticking, yaw, TICK);
70
+
71
+ // The last two strips at each side and at the foot turn down over the tick. Folds widen towards the free hem.
72
+ sampleSurface(
73
+ cloth,
74
+ 24,
75
+ 18,
76
+ (u, v) => {
77
+ const across = (2 * u - 1) * 1.2,
78
+ along = v * 1.125,
79
+ side = Math.max(0, (Math.abs(across) - 1) * 5),
80
+ foot = Math.max(0, (along - 1) * 8),
81
+ hang = Math.max(side, foot),
82
+ lateral = Math.max(-1, Math.min(1, across)),
83
+ longitudinal = Math.min(1, along),
84
+ edge = sstep(0.54, 1, Math.abs(across)),
85
+ toe = sstep(0.72, 1, along),
86
+ fold = Math.sin(along * 23 + 1.6 * lateral + 0.72 * Math.sin(along * 9)),
87
+ fan = Math.cos(across * 16 + 1.1 * Math.sin(across * 8) + 1.5 * foot),
88
+ turned = Math.max(0, 1 - Math.abs(along - 0.125) * 13);
89
+ return point(
90
+ (lateral * width) / 2 + Math.sign(across) * side * (0.05 + drop * (0.17 + 0.16 * fold)),
91
+ -drop * hang * (1 - 0.13 * fold * side - 0.12 * fan * foot) + 0.021 * (edge * (1 + fold) + toe * (1 + fan)) + 0.028 * turned,
92
+ length / 2 -
93
+ cover * (1 - longitudinal) +
94
+ 0.023 * Math.sin(3 * across + 0.8) * (1 - longitudinal) +
95
+ foot * (0.045 + drop * (0.15 + 0.15 * fan)),
96
+ );
97
+ },
98
+ (u, v) => dim(coverTone, v < 0.112 ? 1.22 : v < 0.166 ? 0.86 : 1),
99
+ );
100
+
101
+ const pillowZ = -length / 2 + length * 0.173;
102
+ for (let i = 0; i < pillows; i++) {
103
+ const px = ((i + 0.5) / pillows - 0.5) * width,
104
+ [cx, cy, cz] = point(px, -0.01, pillowZ);
105
+ linenCase(
106
+ cloth,
107
+ cx,
108
+ cy,
109
+ cz,
110
+ width * (pillows === 1 ? 0.79 : 0.46),
111
+ (width / pillows) * 0.21,
112
+ length * 0.218,
113
+ linen,
114
+ yaw + (i === 0 ? -0.045 : 0.07),
115
+ );
116
+ }
117
+ }
118
+
119
+ /** Append a two-sided cloth canopy between side rails at height y. Width and length are in metres. */
120
+ function bedCanopy(cloth, x, y, z, width, length, silk) {
121
+ const fall = (u, v) => Math.sin(Math.PI * u) * (0.12 * v + Math.sin(Math.PI * v) * (0.15 + 0.018 * Math.cos(4 * Math.PI * v)));
122
+ sampleSurface(cloth, 16, 12, (u, v) => [x + (u - 0.5) * width, y - fall(u, v), (v - 0.5) * length + z], silk, { back: dim(silk, 0.85) });
123
+ sampleSurface(
124
+ cloth,
125
+ 32,
126
+ 4,
127
+ (u, v) => {
128
+ const span = Math.sin(Math.PI * u),
129
+ gathers = Math.cos(u * TAU * 7);
130
+ return [
131
+ x + (u - 0.5) * width,
132
+ y - fall(u, 1) - v * (0.11 + 0.17 * span + 0.019 * gathers),
133
+ z + length / 2 + v * (0.016 + 0.023 * gathers) * span,
134
+ ];
135
+ },
136
+ (u, v) => dim(silk, v > 0.75 ? 1.22 : 0.96),
137
+ { back: dim(silk, 0.78) },
138
+ );
139
+ }
140
+
141
+ export { bedLinen, linenCase, bedCanopy };
@@ -0,0 +1,42 @@
1
+ import { sphereOf } from './builder.js';
2
+
3
+ // Set builder.pb = [] before adding unindexed, unskinned geometry. Partition whole
4
+ // parts by their x-z bounds centres, separating parts smaller than smallSize on every
5
+ // axis. Preserve first-encounter order within each cell and among the cells.
6
+ // The result owns compact position, normal, colour and optional scalar tag arrays.
7
+ export function cutBuilderCells(builder, cellSize, smallSize = 0) {
8
+ if (!Number.isFinite(cellSize) || cellSize <= 0) throw new RangeError('Cell size must be positive and finite');
9
+ if (!builder.pb || builder.indexed || builder.sk) throw new TypeError('Expected marked, unindexed static geometry');
10
+ const starts = builder.pb,
11
+ bounds = builder.bounds,
12
+ cells = new Map(); // key -> { small, runs: [from, to, ...], numbers }
13
+ for (let partIndex = 0; partIndex < starts.length; partIndex++) {
14
+ const start = starts[partIndex],
15
+ end = partIndex + 1 < starts.length ? starts[partIndex + 1] : builder.count;
16
+ if (end <= start) continue;
17
+ const boundsOffset = partIndex * 6,
18
+ small = Math.max(bounds[boundsOffset + 1] - bounds[boundsOffset], bounds[boundsOffset + 3] - bounds[boundsOffset + 2], bounds[boundsOffset + 5] - bounds[boundsOffset + 4]) < smallSize,
19
+ key =
20
+ Math.floor((bounds[boundsOffset] + bounds[boundsOffset + 1]) / 2 / cellSize) + ':' + Math.floor((bounds[boundsOffset + 4] + bounds[boundsOffset + 5]) / 2 / cellSize) + (small ? 's' : '');
21
+ let cell = cells.get(key);
22
+ if (!cell) cells.set(key, (cell = { small, runs: [], numbers: 0 }));
23
+ cell.runs.push(start, end);
24
+ cell.numbers += end - start;
25
+ }
26
+ const { positions, normalBytes, colourBytes, tg } = builder;
27
+ return [...cells.values()].map(({ small, runs, numbers }) => {
28
+ const parts = { position: new Float32Array(numbers), normal: new Int8Array(numbers), color: new Uint8Array(numbers) };
29
+ if (tg) parts.aTag = new Float32Array(numbers / 3);
30
+ let at = 0;
31
+ for (let runOffset = 0; runOffset < runs.length; runOffset += 2) {
32
+ const from = runs[runOffset],
33
+ to = runs[runOffset + 1];
34
+ parts.position.set(positions.subarray(from, to), at);
35
+ parts.normal.set(normalBytes.subarray(from, to), at);
36
+ parts.color.set(colourBytes.subarray(from, to), at);
37
+ if (tg) for (let i = from / 3, k = at / 3; i < to / 3; i++) parts.aTag[k++] = tg[i];
38
+ at += to - from;
39
+ }
40
+ return { small, parts, sphere: sphereOf(parts.position) };
41
+ });
42
+ }
@@ -0,0 +1,47 @@
1
+ import { Matrix4 } from 'three';
2
+ import { TRS } from './primitives.js';
3
+
4
+ // Builders can share the stable matrix reference. Stack entries are reused on subsequent pushes.
5
+ export function createBuilderFrame() {
6
+ const matrix = new Matrix4(), stack = [];
7
+ let depth = 0;
8
+ function push(local) {
9
+ (stack[depth] ??= new Matrix4()).copy(matrix);
10
+ depth++;
11
+ matrix.multiply(local);
12
+ }
13
+ function pop() {
14
+ if (!depth) throw new RangeError('Builder frame stack is empty');
15
+ matrix.copy(stack[--depth]);
16
+ }
17
+ return { matrix, push, pop };
18
+ }
19
+
20
+ const FACE_NORMAL = [
21
+ [0, 0, 1],
22
+ [0, 0, -1],
23
+ [1, 0, 0],
24
+ [-1, 0, 0],
25
+ ].map(Object.freeze);
26
+ const FACE_RY = [0, Math.PI, Math.PI / 2, -Math.PI / 2];
27
+ // Number faces +Z, -Z, +X, -X. Dimensions and offsets are in world units.
28
+ // put(builder, shape, color, along, height, outward, sx, sy, sz, roll, pitch) adds geometry.
29
+ // put.point(along, height, outward) and the read-only put.normal describe the same face.
30
+ export function boxFacePlacer(face, halfWidth, halfDepth, offsetX = 0, offsetZ = 0) {
31
+ const faceYaw = FACE_RY[face],
32
+ normal = FACE_NORMAL[face],
33
+ nx = normal[0],
34
+ nz = normal[2],
35
+ wallX = offsetX + nx * halfWidth,
36
+ wallZ = offsetZ + nz * halfDepth;
37
+ const xAt = (u, out) => wallX + nz * u + nx * out;
38
+ const zAt = (u, out) => wallZ - nx * u + nz * out;
39
+ const put = (builder, geometry, color, u, y, out, sx, sy, sz, roll = 0, pitch = 0) =>
40
+ builder.add(geometry, color, TRS(xAt(u, out), y, zAt(u, out), sx, sy, sz, faceYaw, pitch, roll));
41
+ put.point = (u, y, out) => [xAt(u, out), y, zAt(u, out)];
42
+ put.normal = normal;
43
+ put.face = face;
44
+ put.halfWidth = halfWidth;
45
+ put.halfDepth = halfDepth;
46
+ return put;
47
+ }