@threenative/terrain 0.1.9 → 0.1.12

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 (243) hide show
  1. package/README.md +40 -59
  2. package/THIRD_PARTY_NOTICES.md +2 -1
  3. package/dist/bake-DJ5cxg0C.d.ts +82 -0
  4. package/dist/editor/index.d.ts +4 -4
  5. package/dist/editor/index.js +130 -128
  6. package/dist/editor/server.d.ts +2 -2
  7. package/dist/editor/server.js +38 -35
  8. package/dist/editor/worker.d.ts +1 -1
  9. package/dist/editor/worker.js +101 -101
  10. package/dist/export.d.ts +1 -1
  11. package/dist/index.d.ts +156 -273
  12. package/dist/index.js +562 -378
  13. package/dist/kit-world.d.ts +107 -0
  14. package/dist/kit-world.js +5134 -0
  15. package/dist/kit.d.ts +21 -4
  16. package/dist/kit.js +337 -223
  17. package/dist/mcp/cook-child.js +1963 -1543
  18. package/dist/mcp/server.js +716 -429
  19. package/dist/prop-package-Dwz0EWoB.d.ts +141 -0
  20. package/dist/{server-B5RdvEAC.d.ts → server-LnFwY8sr.d.ts} +1 -1
  21. package/dist/starter.d.ts +1142 -7
  22. package/dist/starter.js +2102 -120
  23. package/dist/{terrain-CAEaW0mQ.d.ts → terrain-DYCyAOCJ.d.ts} +1 -1
  24. package/dist/three.d.ts +1 -1
  25. package/dist/three.js +1 -1
  26. package/dist/{types-BpH00qsx.d.ts → types-kpI0C4hW.d.ts} +1 -1
  27. package/dist/{world-package-B8QgHjAQ.d.ts → world-package-DqJC3-Nn.d.ts} +2 -2
  28. package/docs/authoring/editor.md +73 -0
  29. package/docs/authoring/new-environment.md +97 -0
  30. package/docs/authoring/recipes.md +97 -0
  31. package/docs/authoring/world-export.md +66 -0
  32. package/package.json +24 -8
  33. package/starter/alpine/README.md +22 -12
  34. package/starter/alpine/bake.mjs +14 -1
  35. package/starter/alpine/biome.data.json +187 -25
  36. package/starter/alpine/heightmap.r16 +0 -0
  37. package/starter/alpine/playerRig.ts +89 -0
  38. package/starter/alpine/recipe.json +169 -15
  39. package/starter/alpine/render/bakedFile.ts +17 -0
  40. package/starter/alpine/render/benchmark.ts +77 -0
  41. package/starter/alpine/render/biomeData.ts +14 -0
  42. package/starter/alpine/render/biomes.ts +687 -0
  43. package/starter/alpine/render/ground/cover.ts +565 -0
  44. package/starter/alpine/render/ground/horizon.ts +219 -0
  45. package/starter/alpine/render/ground/palette.d.ts +1 -0
  46. package/starter/alpine/render/ground/palette.js +11 -0
  47. package/starter/alpine/render/ground/scatter.ts +104 -0
  48. package/starter/alpine/render/ground/terrain.ts +1860 -0
  49. package/starter/alpine/render/kitAssets.ts +28 -0
  50. package/starter/alpine/render/loading.ts +354 -0
  51. package/starter/alpine/render/lookKnobs.ts +37 -0
  52. package/starter/alpine/render/orbitCamera.ts +155 -0
  53. package/starter/alpine/render/props/farForest.ts +94 -0
  54. package/starter/alpine/render/props/pack.ts +1114 -0
  55. package/starter/alpine/render/props/prepared.ts +225 -0
  56. package/starter/alpine/render/props/propMaterials.ts +1239 -0
  57. package/starter/alpine/render/props/propProgress.ts +2 -0
  58. package/starter/alpine/render/props/propWorld.ts +105 -0
  59. package/starter/alpine/render/props/props.ts +633 -0
  60. package/starter/alpine/render/props/spruce.ts +440 -0
  61. package/starter/alpine/render/sky/atmosphere.ts +329 -0
  62. package/starter/alpine/render/sky/sky.ts +382 -0
  63. package/starter/alpine/render/texturePreparation.ts +135 -0
  64. package/starter/alpine/render/water/river.ts +1132 -0
  65. package/starter/alpine/render/worldNames.ts +6 -0
  66. package/starter/alpine/scene.ts +715 -0
  67. package/starter/alpine/sceneProps.ts +561 -0
  68. package/starter/alpine/sceneState.ts +33 -0
  69. package/starter/alpine/world/terrainAssets.ts +145 -0
  70. package/starter/alpine/world/walkBand.ts +47 -0
  71. package/starter/alpine/world/water.ts +74 -0
  72. package/starter/alpine/worlds.ts +13 -0
  73. package/starter/arbor/wind.ts +84 -0
  74. package/starter/coastal/README.md +26 -25
  75. package/starter/coastal/assets.json +10 -0
  76. package/starter/coastal/bake.mjs +14 -1
  77. package/starter/coastal/biome.data.json +18 -3
  78. package/starter/coastal/playerRig.ts +89 -0
  79. package/starter/coastal/recipe.json +220 -18
  80. package/starter/coastal/render/bakedFile.ts +17 -0
  81. package/starter/coastal/render/benchmark.ts +81 -0
  82. package/starter/coastal/render/biomeData.ts +14 -0
  83. package/starter/coastal/render/biomes.ts +678 -0
  84. package/starter/coastal/render/ground/cover.ts +565 -0
  85. package/starter/coastal/render/ground/horizon.ts +219 -0
  86. package/starter/coastal/render/ground/palette.d.ts +1 -0
  87. package/starter/coastal/render/ground/palette.js +11 -0
  88. package/starter/coastal/render/ground/scatter.ts +104 -0
  89. package/starter/coastal/render/ground/terrain.ts +1829 -0
  90. package/starter/coastal/render/kitAssets.ts +28 -0
  91. package/starter/coastal/render/loading.ts +354 -0
  92. package/starter/coastal/render/lookKnobs.ts +37 -0
  93. package/starter/coastal/render/orbitCamera.ts +155 -0
  94. package/starter/coastal/render/props/farForest.ts +94 -0
  95. package/starter/coastal/render/props/pack.ts +1109 -0
  96. package/starter/coastal/render/props/prepared.ts +225 -0
  97. package/starter/coastal/render/props/propMaterials.ts +1239 -0
  98. package/starter/coastal/render/props/propProgress.ts +2 -0
  99. package/starter/coastal/render/props/propWorld.ts +105 -0
  100. package/starter/coastal/render/props/props.ts +633 -0
  101. package/starter/coastal/render/props/spruce.ts +440 -0
  102. package/starter/coastal/render/sky/atmosphere.ts +329 -0
  103. package/starter/coastal/render/sky/sky.ts +382 -0
  104. package/starter/coastal/render/texturePreparation.ts +135 -0
  105. package/starter/coastal/render/water/ocean.ts +284 -0
  106. package/starter/coastal/render/water/river.ts +1132 -0
  107. package/starter/coastal/render/worldNames.ts +6 -0
  108. package/starter/coastal/scene.ts +740 -0
  109. package/starter/coastal/sceneProps.ts +559 -0
  110. package/starter/coastal/sceneState.ts +33 -0
  111. package/starter/coastal/world/terrainAssets.ts +151 -0
  112. package/starter/coastal/world/walkBand.ts +47 -0
  113. package/starter/coastal/world/water.ts +74 -0
  114. package/starter/coastal/worlds.ts +13 -0
  115. package/starter/desert/README.md +51 -23
  116. package/starter/desert/bake-flora.mjs +142 -0
  117. package/starter/desert/bake-rocks.mjs +291 -0
  118. package/starter/desert/bake.mjs +14 -1
  119. package/starter/desert/biome.data.json +24 -12
  120. package/starter/desert/playerRig.ts +89 -0
  121. package/starter/desert/recipe.json +63 -16
  122. package/starter/desert/render/bakedFile.ts +17 -0
  123. package/starter/desert/render/benchmark.ts +79 -0
  124. package/starter/desert/render/biomeData.ts +14 -0
  125. package/starter/desert/render/biomes.ts +660 -0
  126. package/starter/desert/render/ground/cover.ts +565 -0
  127. package/starter/desert/render/ground/debris.ts +136 -0
  128. package/starter/desert/render/ground/horizon.ts +219 -0
  129. package/starter/desert/render/ground/palette.d.ts +1 -0
  130. package/starter/desert/render/ground/palette.js +11 -0
  131. package/starter/desert/render/ground/scatter.ts +104 -0
  132. package/starter/desert/render/ground/terrain.ts +1854 -0
  133. package/starter/desert/render/kitAssets.ts +28 -0
  134. package/starter/desert/render/loading.ts +354 -0
  135. package/starter/desert/render/lookKnobs.ts +37 -0
  136. package/starter/desert/render/orbitCamera.ts +155 -0
  137. package/starter/desert/render/props/farForest.ts +96 -0
  138. package/starter/desert/render/props/formations.ts +630 -0
  139. package/starter/desert/render/props/pack.ts +1195 -0
  140. package/starter/desert/render/props/prepared.ts +225 -0
  141. package/starter/desert/render/props/propMaterials.ts +1255 -0
  142. package/starter/desert/render/props/propProgress.ts +2 -0
  143. package/starter/desert/render/props/propWorld.ts +105 -0
  144. package/starter/desert/render/props/props.ts +624 -0
  145. package/starter/desert/render/props/spruce.ts +440 -0
  146. package/starter/desert/render/sand.ts +581 -0
  147. package/starter/desert/render/sky/atmosphere.ts +329 -0
  148. package/starter/desert/render/sky/sky.ts +382 -0
  149. package/starter/desert/render/texturePreparation.ts +135 -0
  150. package/starter/desert/render/water/river.ts +1132 -0
  151. package/starter/desert/render/worldNames.ts +6 -0
  152. package/starter/desert/scene.ts +748 -0
  153. package/starter/desert/sceneProps.ts +562 -0
  154. package/starter/desert/sceneState.ts +33 -0
  155. package/starter/desert/world/terrainAssets.ts +162 -0
  156. package/starter/desert/world/walkBand.ts +47 -0
  157. package/starter/desert/world/water.ts +74 -0
  158. package/starter/desert/worlds.ts +13 -0
  159. package/starter/forest/README.md +59 -116
  160. package/starter/forest/assets.json +14 -14
  161. package/starter/forest/bake.mjs +26 -4
  162. package/starter/forest/playerRig.ts +89 -0
  163. package/starter/forest/recipe.json +233 -43
  164. package/starter/forest/render/bakedFile.ts +17 -0
  165. package/starter/forest/render/benchmark.ts +77 -0
  166. package/starter/forest/render/biomeData.ts +14 -0
  167. package/starter/forest/render/biomes.ts +637 -0
  168. package/starter/forest/render/ground/cover.ts +565 -0
  169. package/starter/forest/render/ground/horizon.ts +219 -0
  170. package/starter/forest/render/ground/palette.d.ts +1 -0
  171. package/starter/forest/render/ground/palette.js +11 -0
  172. package/starter/forest/render/ground/scatter.ts +104 -0
  173. package/starter/forest/render/ground/terrain.ts +1796 -0
  174. package/starter/forest/render/kitAssets.ts +28 -0
  175. package/starter/forest/render/loading.ts +354 -0
  176. package/starter/forest/render/lookKnobs.ts +37 -0
  177. package/starter/forest/render/orbitCamera.ts +155 -0
  178. package/starter/forest/render/props/farForest.ts +94 -0
  179. package/starter/forest/render/props/pack.ts +1078 -0
  180. package/starter/forest/render/props/prepared.ts +226 -0
  181. package/starter/forest/render/props/propMaterials.ts +1247 -0
  182. package/starter/forest/render/props/propProgress.ts +2 -0
  183. package/starter/forest/render/props/propWorld.ts +105 -0
  184. package/starter/forest/render/props/props.ts +624 -0
  185. package/starter/forest/render/props/spruce.ts +440 -0
  186. package/starter/forest/render/sky/atmosphere.ts +329 -0
  187. package/starter/forest/render/sky/sky.ts +382 -0
  188. package/starter/forest/render/texturePreparation.ts +135 -0
  189. package/starter/forest/render/water/river.ts +1132 -0
  190. package/starter/forest/render/worldNames.ts +6 -0
  191. package/starter/forest/scene.ts +715 -0
  192. package/starter/forest/sceneProps.ts +559 -0
  193. package/starter/forest/sceneState.ts +33 -0
  194. package/starter/forest/surface.json +2 -2
  195. package/starter/forest/world/terrainAssets.ts +158 -0
  196. package/starter/forest/world/walkBand.ts +47 -0
  197. package/starter/forest/world/water.ts +74 -0
  198. package/starter/forest/worlds.ts +13 -0
  199. package/starter/tundra/README.md +35 -14
  200. package/starter/tundra/bake.mjs +14 -1
  201. package/starter/tundra/biome.data.json +6 -6
  202. package/starter/tundra/playerRig.ts +89 -0
  203. package/starter/tundra/recipe.json +111 -110
  204. package/starter/tundra/render/bakedFile.ts +17 -0
  205. package/starter/tundra/render/benchmark.ts +79 -0
  206. package/starter/tundra/render/biomeData.ts +14 -0
  207. package/starter/tundra/render/biomes.ts +714 -0
  208. package/starter/tundra/render/ground/cover.ts +565 -0
  209. package/starter/tundra/render/ground/horizon.ts +219 -0
  210. package/starter/tundra/render/ground/palette.d.ts +1 -0
  211. package/starter/tundra/render/ground/palette.js +11 -0
  212. package/starter/tundra/render/ground/scatter.ts +104 -0
  213. package/starter/tundra/render/ground/terrain.ts +1874 -0
  214. package/starter/tundra/render/kitAssets.ts +28 -0
  215. package/starter/tundra/render/loading.ts +354 -0
  216. package/starter/tundra/render/lookKnobs.ts +37 -0
  217. package/starter/tundra/render/orbitCamera.ts +155 -0
  218. package/starter/tundra/render/props/farForest.ts +96 -0
  219. package/starter/tundra/render/props/pack.ts +1088 -0
  220. package/starter/tundra/render/props/prepared.ts +225 -0
  221. package/starter/tundra/render/props/propMaterials.ts +1247 -0
  222. package/starter/tundra/render/props/propProgress.ts +2 -0
  223. package/starter/tundra/render/props/propWorld.ts +105 -0
  224. package/starter/tundra/render/props/props.ts +624 -0
  225. package/starter/tundra/render/props/spruce.ts +440 -0
  226. package/starter/tundra/render/sky/atmosphere.ts +329 -0
  227. package/starter/tundra/render/sky/sky.ts +382 -0
  228. package/starter/tundra/render/texturePreparation.ts +135 -0
  229. package/starter/tundra/render/water/river.ts +1132 -0
  230. package/starter/tundra/render/worldNames.ts +6 -0
  231. package/starter/tundra/scene.ts +715 -0
  232. package/starter/tundra/sceneProps.ts +559 -0
  233. package/starter/tundra/sceneState.ts +33 -0
  234. package/starter/tundra/world/terrainAssets.ts +159 -0
  235. package/starter/tundra/world/walkBand.ts +47 -0
  236. package/starter/tundra/world/water.ts +74 -0
  237. package/starter/tundra/worlds.ts +13 -0
  238. package/starter-assets.json +4 -4
  239. package/starter-credits.json +901 -15
  240. package/AGENT_GUIDE.md +0 -209
  241. package/starter/forest/sky.ts +0 -38
  242. package/starter/forest/water.ts +0 -257
  243. package/starter/forest/world.ts +0 -182
@@ -0,0 +1,624 @@
1
+ // The starter props of the Temperate world: three seeded spruce variants, three boulders, grass
2
+ // clumps and poppy patches. `propWorld.ts` hands their draws to `WorldCells`.
3
+ //
4
+ // What lives here and what does not:
5
+ //
6
+ // - The shapes, their variants, their materials and their placement rule are all this file's. They
7
+ // are the picture, and the picture is the game's (AGENTS rule 3).
8
+ // - The pose's own steps (snap, burial, footprint, base ring) are the package's `prop-pose`; this
9
+ // file supplies the forest's `GROUND_RULES` rows and `propWorld.ts` delegates LOD to WorldCells.
10
+ import { staticLowestY } from "@threenative/core/world";
11
+ import type { IPlacement, IPlacementOverride } from "@threenative/terrain";
12
+ import {
13
+ type IPropGroundRules,
14
+ type IPropInstance,
15
+ type IPropPoseOverride,
16
+ type PropGroundQuery,
17
+ preparePose as preparePoseIn,
18
+ preparePropTransform as preparePropTransformIn,
19
+ propKey as propKeyIn,
20
+ } from "@threenative/terrain/starter";
21
+ import {
22
+ type BufferGeometry,
23
+ DoubleSide,
24
+ type Material,
25
+ MeshStandardMaterial,
26
+ Vector3,
27
+ } from "three";
28
+ import { WILDFLOWER, boulder, fernClump, grassClump, poppyCluster } from "../ground/cover.js";
29
+ import { FAR_FOREST_LAYER } from "./farForest.js";
30
+ import { SPRUCE, spruceFarCrown, spruceVariants } from "./spruce.js";
31
+
32
+ /** Which cell of the needle atlas the poppy petals sample. */
33
+ const POPPY_PETAL = { u0: 0.5, v0: 0, u1: 1, v1: 0.5 };
34
+
35
+ /** How many variants of each prop the starter builds, and the seed they are built from. */
36
+ export const VARIANTS = {
37
+ boulder: 3,
38
+ bush: 2,
39
+ fern: 3,
40
+ grass: 4,
41
+ /** The open meadow's dense base layer (`meadowCover`). */
42
+ meadow: 2,
43
+ poppy: 4,
44
+ /** The open meadow's white and violet wildflowers (`meadowCover`). */
45
+ bloom: 4,
46
+ sapling: 3,
47
+ scrub: 3,
48
+ spruce: 5,
49
+ litter: 2,
50
+ seed: 0x9e3779b9,
51
+ } as const;
52
+
53
+ /**
54
+ * Metres at which a prepared prop steps down one detail level.
55
+ *
56
+ * `near` is 60, not the 22 the prepared pine was cut against: the only banded variants in the world
57
+ * are the pack canopy's, and a twelve-metre pine at sixty metres is about eighty pixels tall in a
58
+ * 1080-line frame — the same picture as its far level — while at twenty-two metres it is seven hundred
59
+ * pixels tall and the swap is not a distance LOD at all, it is a visible substitution.
60
+ */
61
+
62
+ /**
63
+ * The assets whose draws skip the shadow pass.
64
+ *
65
+ * Seedlings and shrubs, and the reason is the cost rather than the look: a pine's shadow is a shape
66
+ * on the meadow, and the shadow of a knee-high plant under a pine is already inside it. Wildwood's
67
+ * `LAYERS` marks the same three layers `castShadows: false`, and its numbers agree.
68
+ */
69
+ export const DRAW_REACH: Record<string, number> = {
70
+ grass: 112,
71
+ /** The vista meadow's base layer: `meadowCover` thins it with distance itself, so it is not faded. */
72
+ meadow: 230,
73
+ scrub: 110,
74
+ fern: 105,
75
+ poppy: 65,
76
+ bloom: 65,
77
+ sapling: 160,
78
+ bush: 120,
79
+ litter: 16,
80
+ /** Fallen boughs and logs: metres long, so they read from across a clearing. */
81
+ deadfall: 110,
82
+ boulder: 170,
83
+ riverrock: 100,
84
+ /** River-bed cobbles: a 0.2 m stone under water is sub-pixel well before 45 m. */
85
+ pebble: 45,
86
+ scree: 190,
87
+ cliff: 300,
88
+ mountain: 650,
89
+ volcanic: 400,
90
+ reveal: 260,
91
+ };
92
+ /**
93
+ * Variants whose own reach is shorter than their asset's.
94
+ *
95
+ * Empty on measurement: cutting the three low mats' reach bought nothing once the band stopped
96
+ * rebuilding every third frame, and it cost the far meadow its grass. A variant named here draws
97
+ * less far.
98
+ */
99
+ export const VARIANT_REACH: Record<string, number> = {};
100
+ export const NO_SHADOW_ASSETS = new Set([
101
+ "sapling",
102
+ "scrub",
103
+ "grass",
104
+ "meadow",
105
+ "fern",
106
+ "poppy",
107
+ "bloom",
108
+ "litter",
109
+ "pebble",
110
+ ]);
111
+ /** The species whose cover thins out with distance instead of switching off at a fixed reach. */
112
+ export const FADED_ASSETS = new Set(["grass", "scrub", "fern"]);
113
+
114
+ /** One drawable piece of a prop: its geometry, and the role that decides its material. */
115
+ /** The share of a boulder's height that sits below the ground. */
116
+ const BOULDER_BURIAL = 0.32;
117
+
118
+ export type PropRole =
119
+ | "bark"
120
+ | "crown"
121
+ | "fern"
122
+ | "grass"
123
+ | "impostor"
124
+ | "needles"
125
+ | "petal"
126
+ | "pine"
127
+ | "stem"
128
+ | "stone";
129
+
130
+ /**
131
+ * Metres at which a prepared prop steps down one detail level, and the slack that keeps a
132
+ * camera walking the boundary from stepping it up and down again.
133
+ *
134
+ * The bands are the game's, because the triangle budget behind them is the game's: a prop is drawn
135
+ * from its full prepared detail inside `near`, from the mid level past it, and from the far
136
+ * engine impostor past that. The dither transition is a fifth of the band rather than a fixed number of
137
+ * metres, so the same slack works for a two-metre rock, a fourteen-metre spruce and a
138
+ * twenty-two-metre pine.
139
+ */
140
+ export const LOD_BANDS = { far: 150, hysteresis: 0.2, mid: 80, near: 22 } as const;
141
+
142
+ /**
143
+ * Species that step to their second and third prepared level nearer than `LOD_BANDS.mid` and `far`.
144
+ *
145
+ * A spruce 105 m out stands about 110 px tall on a 900 px frame, and from 80 m to 150 m it drew its
146
+ * 10.7k-triangle middle level: two triangles a pixel, on every tree of the far bank. It takes the
147
+ * level it already draws past `far` from 105 m. A grass tuft is under 25 px tall past 30 m and
148
+ * under 10 px past 60 m, and it drew every blade to the end of its 112 m reach.
149
+ * Forest, RTX 2080, 1600x900, four interleaved pairs against `?lodSteps=off`: main-pass triangles
150
+ * fell from 21.2 M to 17.5 M at the player pose and from 36.4 M to 29.0 M at the overview, and the
151
+ * GPU frame by a median 8% at the overview (the frame is bound by pixels, not triangles).
152
+ */
153
+ export const LOD_STEPS: Record<string, readonly [number, number]> = {
154
+ fern: [30, 60],
155
+ grass: [30, 60],
156
+ spruce: [LOD_BANDS.mid, 105],
157
+ };
158
+
159
+ /** The metres at which `asset` steps to its second and third prepared level. */
160
+ export function lodSteps(asset: string): readonly [number, number] {
161
+ return LOD_STEPS[asset] ?? [LOD_BANDS.mid, LOD_BANDS.far];
162
+ }
163
+
164
+ /**
165
+ * The draw reach a placement's variant gives it, shortened by its seeded fade for `FADED_ASSETS`.
166
+ *
167
+ * `variantIndex` counts the placements the bake drew before this one on the same variant, so the
168
+ * fade is a stable number per blade: the bake writes the reach it computes into the package, and the
169
+ * load path counts live placements on from there.
170
+ */
171
+ export function streamedReach(placement: IPlacement, variantIndex: number): number {
172
+ const variant = `${placement.asset}:${variantFor(placement, placement.asset)}`;
173
+ const reach = VARIANT_REACH[variant] ?? DRAW_REACH[placement.asset] ?? Number.POSITIVE_INFINITY;
174
+ if (!FADED_ASSETS.has(placement.asset)) return reach;
175
+ const seed = (Math.imul(variantIndex + 1, 2654435761) >>> 0) / 4294967296;
176
+ return 28 + (reach - 28) * (1 - Math.sqrt(seed));
177
+ }
178
+
179
+ /**
180
+ * The streamed world a placement draws in: the far forest alone, or its reach and shadow policy.
181
+ *
182
+ * The bake writes one container per name, and the load path keeps or drops a container by kind, so
183
+ * `?farForest=` and `?meadow=` answer the same question at load that they answered at compile.
184
+ */
185
+ export function streamedBucket(placement: IPlacement, reach: number): string {
186
+ if (placement.layer === FAR_FOREST_LAYER) return "far:false";
187
+ return `${reach === Number.POSITIVE_INFINITY ? "horizon" : "local"}:${!NO_SHADOW_ASSETS.has(placement.asset)}`;
188
+ }
189
+
190
+ /**
191
+ * The terminal gate a spruce variant switches to the engine's whole-asset impostor at.
192
+ *
193
+ * A scaled tree's gate divides by its scale, so the minimum scale of its variant is what keeps the
194
+ * gate beyond the last authored level. A gate inside that step pops the whole tree at a distance the
195
+ * player can see it.
196
+ */
197
+ export function impostorDistanceForScale(minScale: number, lastLodDistance: number): number {
198
+ if (!Number.isFinite(minScale) || minScale === 0)
199
+ throw new Error("Spruce terminal distance requires a positive finite placement scale.");
200
+ return Math.max(LOD_BANDS.far / Math.abs(minScale), lastLodDistance * (1 + Number.EPSILON));
201
+ }
202
+
203
+ /**
204
+ * The scale each streamed spruce variant's terminal gate divides by: the smallest one it draws.
205
+ *
206
+ * The gate divides by a variant's minimum scale, so the minimum is taken over the placements that
207
+ * actually draw it — every spruce the far forest does not own, keyed by the variant that draws it.
208
+ * One bucket's minimum, or a far tree's, puts a gate inside a step the player sees pop.
209
+ */
210
+ export function spruceGateScales(
211
+ drawn: Iterable<{ readonly placement: IPlacement; readonly scale: number }>,
212
+ ): Map<string, number> {
213
+ const gates = new Map<string, number>();
214
+ for (const { placement, scale } of drawn) {
215
+ if (placement.asset !== "spruce" || placement.layer === FAR_FOREST_LAYER) continue;
216
+ const variant = `${placement.asset}:${variantFor(placement, placement.asset)}`;
217
+ gates.set(variant, Math.min(gates.get(variant) ?? Number.POSITIVE_INFINITY, Math.abs(scale)));
218
+ }
219
+ return gates;
220
+ }
221
+
222
+ export interface IPropPart {
223
+ readonly geometry: BufferGeometry;
224
+ /**
225
+ * The surface this part draws with, when it is not one of the starter's.
226
+ *
227
+ * The CC0 prepared art and every procedural prop are re-dressed in the starter's own surfaces, so
228
+ * a role decides them. A licensed pack species brings its own atlas and its own UVs and is not
229
+ * re-dressed (`src/render/props/pack.ts`), so it carries the material it was authored with, and this
230
+ * field is how the batch knows to leave that draw alone when the lit surfaces arrive.
231
+ */
232
+ readonly material?: Material;
233
+ /** Which detail level this part is. `0` is the full one; a variant with only it never steps. */
234
+ readonly level?: number;
235
+ readonly role: PropRole;
236
+ /** Which variant of the prop this part belongs to; parts of one variant always agree. */
237
+ readonly variant: number;
238
+ }
239
+
240
+ /**
241
+ * Build every variant of every prop, once, as flat parts.
242
+ *
243
+ * Building the whole set up front is what makes placement cheap and what keeps the draw count
244
+ * bounded: three spruce variants times two parts is six draws for every tree in the world, not one
245
+ * per tree. The caller decides which variant each placement gets.
246
+ *
247
+ * A `prepared` map replaces the variants it names: indices 0 and 1 of the spruce are the two
248
+ * prepared CC0 firs and index 2 is the procedural one, so both sets are live at once and the
249
+ * procedural tree stays a variant rather than becoming dead code. The indices it does not name
250
+ * are still built, which is what the editor's own scene gets when it has no prepared art.
251
+ */
252
+ export function buildPropVariants(
253
+ prepared?: ReadonlyMap<string, IPropPart[]>,
254
+ fallbackSaplingHeight?: number,
255
+ ): Map<string, IPropPart[]> {
256
+ if (
257
+ fallbackSaplingHeight !== undefined &&
258
+ (!Number.isFinite(fallbackSaplingHeight) || fallbackSaplingHeight <= 0)
259
+ )
260
+ throw new Error("Fallback sapling height must be positive and finite");
261
+ const variants = new Map<string, IPropPart[]>();
262
+ // Every index the layout knows about, so a prepared variant replaces the procedural one at the
263
+ // same index rather than being appended: the placement hash is what picks a variant, and it
264
+ // picks an index, so index 0 has to mean the pine on the machine that has the pine and the
265
+ // procedural spruce on the machine that does not. The saplings' own variants come off the end of
266
+ // the same seeded set, so a seedling and a tree are the same species at two sizes rather than two
267
+ // unrelated shapes.
268
+ const spruces = spruceVariants(PROP_COUNTS.spruce, VARIANTS.seed, SPRUCE.standBareTrunk);
269
+ const youngs = spruceVariants(PROP_COUNTS.sapling, VARIANTS.seed ^ 0x51ed3a7f);
270
+ for (let index = 0; index < PROP_COUNTS.spruce; index += 1) {
271
+ const ready = prepared?.get(`spruce:${index}`);
272
+ if (ready) {
273
+ variants.set(`spruce:${index}`, [...ready]);
274
+ continue;
275
+ }
276
+ const spruce = spruces[index];
277
+ if (spruce === undefined) continue;
278
+ variants.set(`spruce:${index}`, [
279
+ { geometry: spruce.trunk, role: "bark", variant: index },
280
+ // Each variant leans on a different needle card, so three spruce silhouettes are three
281
+ // textures rather than one texture at three sizes.
282
+ { geometry: spruce.crown, role: "crown", variant: index },
283
+ { geometry: spruce.trunk.clone(), role: "bark", variant: index, level: 1 },
284
+ { geometry: spruceFarCrown(spruce.crown), role: "crown", variant: index, level: 1 },
285
+ ]);
286
+ }
287
+ for (let i = 0; i < PROP_COUNTS.boulder; i += 1) {
288
+ const ready = prepared?.get(`boulder:${i}`);
289
+ if (ready) {
290
+ variants.set(`boulder:${i}`, [...ready]);
291
+ continue;
292
+ }
293
+ variants.set(`boulder:${i}`, [
294
+ {
295
+ geometry: boulder((VARIANTS.seed ^ (i * 0x85ebca6b)) >>> 0),
296
+ role: "stone",
297
+ variant: i,
298
+ },
299
+ ]);
300
+ }
301
+ for (let i = 0; i < VARIANTS.fern; i += 1)
302
+ variants.set(
303
+ `fern:${i}`,
304
+ prepared?.get(`fern:${i}`) ?? [
305
+ { geometry: fernClump((VARIANTS.seed ^ (i * 0x165667b1)) >>> 0), role: "fern", variant: i },
306
+ ],
307
+ );
308
+ // The young generation and the two undergrowth niches, all three with the starter's own geometry
309
+ // standing in: a machine with no licensed pack grows a small spruce, a fern-sized shrub and a
310
+ // grass clump. That is a thinner wood, and it is never a broken one — which is the whole point of
311
+ // the licensed art being optional rather than required.
312
+ for (let i = 0; i < PROP_COUNTS.sapling; i += 1) {
313
+ const ready = prepared?.get(`sapling:${i}`);
314
+ if (ready) {
315
+ variants.set(`sapling:${i}`, [...ready]);
316
+ continue;
317
+ }
318
+ const young = youngs[i];
319
+ if (young === undefined) continue;
320
+ if (fallbackSaplingHeight !== undefined) {
321
+ young.trunk.computeBoundingBox();
322
+ young.crown.computeBoundingBox();
323
+ const height = Math.max(
324
+ young.trunk.boundingBox?.max.y ?? 0,
325
+ young.crown.boundingBox?.max.y ?? 0,
326
+ );
327
+ if (!(height > 0)) throw new Error("Procedural sapling has no measurable height");
328
+ const scale = fallbackSaplingHeight / height;
329
+ young.trunk.scale(scale, scale, scale);
330
+ young.crown.scale(scale, scale, scale);
331
+ }
332
+ variants.set(`sapling:${i}`, [
333
+ { geometry: young.trunk, role: "bark", variant: i },
334
+ { geometry: young.crown, role: "crown", variant: i },
335
+ { geometry: young.trunk.clone(), role: "bark", variant: i, level: 1 },
336
+ { geometry: spruceFarCrown(young.crown), role: "crown", variant: i, level: 1 },
337
+ ]);
338
+ }
339
+ for (let i = 0; i < PROP_COUNTS.bush; i += 1) {
340
+ const ready = prepared?.get(`bush:${i}`);
341
+ if (ready) {
342
+ variants.set(`bush:${i}`, [...ready]);
343
+ continue;
344
+ }
345
+ variants.set(`bush:${i}`, [
346
+ { geometry: fernClump((VARIANTS.seed ^ (i * 0x27d4eb2f)) >>> 0), role: "fern", variant: i },
347
+ ]);
348
+ }
349
+ for (let i = 0; i < PROP_COUNTS.scrub; i += 1) {
350
+ const ready = prepared?.get(`scrub:${i}`);
351
+ if (ready) {
352
+ variants.set(`scrub:${i}`, [...ready]);
353
+ continue;
354
+ }
355
+ variants.set(`scrub:${i}`, [
356
+ {
357
+ geometry: grassClump((VARIANTS.seed ^ (i * 0x165667b1)) >>> 0, i),
358
+ role: "grass",
359
+ variant: i,
360
+ },
361
+ ]);
362
+ }
363
+ for (const [asset, i] of [
364
+ ...Array.from({ length: VARIANTS.grass }, (_, i) => ["grass", i] as const),
365
+ ...Array.from({ length: VARIANTS.meadow }, (_, i) => ["meadow", i] as const),
366
+ ]) {
367
+ const ready = prepared?.get(`${asset}:${i}`);
368
+ // Imported grass draws as imported: a darkened procedural clump under each photographed tuft
369
+ // read as a black star at every root.
370
+ variants.set(
371
+ `${asset}:${i}`,
372
+ ready ?? [
373
+ {
374
+ geometry: grassClump((VARIANTS.seed ^ (i * 0xc2b2ae35)) >>> 0, i),
375
+ role: "grass",
376
+ variant: i,
377
+ },
378
+ ],
379
+ );
380
+ }
381
+ for (const [asset, i] of [
382
+ ...Array.from({ length: VARIANTS.poppy }, (_, i) => ["poppy", i] as const),
383
+ ...Array.from({ length: VARIANTS.bloom }, (_, i) => ["bloom", i] as const),
384
+ ]) {
385
+ const ready = prepared?.get(`${asset}:${i}`);
386
+ if (ready) {
387
+ variants.set(`${asset}:${i}`, [...ready]);
388
+ continue;
389
+ }
390
+ const cluster = poppyCluster((VARIANTS.seed ^ (i * 0x27d4eb2f)) >>> 0, POPPY_PETAL, WILDFLOWER);
391
+ variants.set(`${asset}:${i}`, [
392
+ { geometry: cluster.stems, role: "stem", variant: i },
393
+ { geometry: cluster.petals, role: "petal", variant: i },
394
+ ]);
395
+ }
396
+ for (let i = 0; i < VARIANTS.litter; i += 1) {
397
+ const ready = prepared?.get(`litter:${i}`);
398
+ if (ready) {
399
+ variants.set(`litter:${i}`, [...ready]);
400
+ continue;
401
+ }
402
+ // Needle litter has no procedural model, and an empty part list throws away the whole prop
403
+ // build: a machine without the licensed pack then draws no vegetation at all, because the
404
+ // floor of the wood was the one layer with nothing behind it. A flattened clump stands in.
405
+ const twig = grassClump((VARIANTS.seed ^ (i * 0x9e3779b1)) >>> 0);
406
+ twig.scale(1.7, 0.22, 1.7);
407
+ variants.set(`litter:${i}`, [{ geometry: twig, role: "grass", variant: i }]);
408
+ }
409
+ for (const asset of [
410
+ "riverrock",
411
+ "scree",
412
+ "cliff",
413
+ "mountain",
414
+ "volcanic",
415
+ "reveal",
416
+ "pebble",
417
+ "deadfall",
418
+ ])
419
+ for (
420
+ let variant = 0;
421
+ variant < (PROP_COUNTS[asset as keyof typeof PROP_COUNTS] ?? 1);
422
+ variant++
423
+ ) {
424
+ const ready = prepared?.get(`${asset}:${variant}`);
425
+ if (ready) {
426
+ variants.set(`${asset}:${variant}`, ready);
427
+ continue;
428
+ }
429
+ const fallback = boulder(
430
+ asset === "pebble"
431
+ ? (VARIANTS.seed ^ ((variant + 7) * 0x85ebca6b)) >>> 0
432
+ : VARIANTS.seed ^ variant,
433
+ );
434
+ // Without the licensed pack a fallen log is a long low lump of the same generator.
435
+ if (asset === "deadfall") fallback.scale(1.5, 0.22, 0.3);
436
+ if (["mountain", "volcanic", "reveal"].includes(asset)) {
437
+ if (asset === "mountain") fallback.scale(0.65, 1.45, 1.8);
438
+ fallback.computeBoundingBox();
439
+ const size = fallback.boundingBox?.getSize(new Vector3());
440
+ const scale =
441
+ (asset === "mountain" ? 24 : asset === "volcanic" ? 10 : 5) /
442
+ Math.max(size?.x ?? 1, size?.y ?? 1, size?.z ?? 1);
443
+ fallback.scale(scale, scale, scale);
444
+ }
445
+ variants.set(`${asset}:${variant}`, [{ geometry: fallback, role: "stone", variant }]);
446
+ }
447
+ return variants;
448
+ }
449
+
450
+ /**
451
+ * The prop names this starter knows, and how many variants each has.
452
+ *
453
+ * A prepared variant is counted whether or not its model loaded: the count is the starter's
454
+ * layout, and a game with no prepared art still hashes into the same five boulders.
455
+ */
456
+ const PROP_COUNTS = {
457
+ ...VARIANTS,
458
+ riverrock: 1,
459
+ /** River-bed cobbles: the boulder generator, three seeds. */
460
+ pebble: 3,
461
+ scree: 1,
462
+ cliff: 1,
463
+ mountain: 2,
464
+ volcanic: 4,
465
+ reveal: 2,
466
+ /** Three fallen bough groups and one log. */
467
+ deadfall: 4,
468
+ };
469
+
470
+ export const PROP_ASSETS: Record<string, number> = Object.fromEntries(
471
+ Object.entries(PROP_COUNTS).filter(([name]) => name !== "seed"),
472
+ );
473
+
474
+ /** Exact lowest world Y of a static geometry under `matrix`: core `staticLowestY`. */
475
+ export const lowestY = staticLowestY;
476
+
477
+ /**
478
+ * The forest's own ground rules: which assets bury, which flat footprints sink, which crag rims are
479
+ * measured. The pose steps are the package's; these rows are the picture's.
480
+ */
481
+ export const GROUND_RULES: IPropGroundRules = {
482
+ burial: (placement) => {
483
+ if (
484
+ ![
485
+ "boulder",
486
+ "riverrock",
487
+ "pebble",
488
+ "scree",
489
+ "cliff",
490
+ "mountain",
491
+ "volcanic",
492
+ "reveal",
493
+ ].includes(placement.asset)
494
+ )
495
+ return undefined;
496
+ const crag = ["mountain", "volcanic", "reveal"].includes(placement.asset);
497
+ return {
498
+ share: placement.id.endsWith(":outcrop")
499
+ ? 0.35
500
+ : placement.asset === "mountain"
501
+ ? 0.82
502
+ : crag
503
+ ? 0.55
504
+ : BOULDER_BURIAL,
505
+ crag,
506
+ };
507
+ },
508
+ footprint: (placement) => ["boulder", "riverrock", "scree"].includes(placement.asset),
509
+ footprintThreshold: 0.08,
510
+ baseRing: (placement) => placement.asset === "mountain" && !placement.id.endsWith(":outcrop"),
511
+ baseRingClearance: 0.5,
512
+ };
513
+
514
+ /** The package's pose, grounded by this world's rules and the placement's variant. */
515
+ export function preparePose(
516
+ geometry: BufferGeometry,
517
+ material: Material,
518
+ placement: IPlacement,
519
+ transform: IPlacementOverride | undefined,
520
+ groundAt: PropGroundQuery,
521
+ pose?: IPropPoseOverride,
522
+ ) {
523
+ return preparePoseIn(geometry, material, placement, transform, groundAt, GROUND_RULES, pose);
524
+ }
525
+
526
+ export function preparePropTransform(
527
+ instance: IPropInstance,
528
+ transform: IPlacementOverride | undefined,
529
+ groundAt: PropGroundQuery,
530
+ ) {
531
+ return preparePropTransformIn(instance, transform, groundAt, GROUND_RULES);
532
+ }
533
+
534
+ /** The model a record draws, with the variant this kit's `variantFor` picks for it. */
535
+ export function propKey(placement: IPlacement): string {
536
+ return propKeyIn(placement, variantFor(placement, placement.asset));
537
+ }
538
+
539
+ export {
540
+ authoredQuaternion,
541
+ propRatio,
542
+ readPropTransform,
543
+ withAuthoredPose,
544
+ writePropTransform,
545
+ } from "@threenative/terrain/starter";
546
+ export type { IPropInstance, IPropPoseOverride, PropGroundQuery };
547
+
548
+ /**
549
+ * Assign every placement a variant, deterministically from its own id.
550
+ *
551
+ * The id rather than the array order, so re-baking the terrain and getting the same candidates back
552
+ * gives the same trees in the same places, and the editor's saved override for one placement still
553
+ * describes the same shape it did last time.
554
+ */
555
+ export function variantFor(placement: IPlacement, asset: string): number {
556
+ const count = PROP_ASSETS[asset];
557
+ if (count === undefined) throw new Error(`Unregistered prop asset '${asset}'`);
558
+ if (asset === "mountain" && placement.id.endsWith(":outcrop")) return 0;
559
+ let hash = 0x811c9dc5;
560
+ for (let i = 0; i < placement.id.length; i += 1) {
561
+ hash ^= placement.id.charCodeAt(i);
562
+ hash = Math.imul(hash, 0x01000193) >>> 0;
563
+ }
564
+ // Full trees dominate; the half-crown forms are occasional stand variation, and the mix leans on
565
+ // the two Kite pines evenly — pack.ts reads the variant through `variant % 2`.
566
+ return asset === "spruce" ? ([0, 1, 0, 1, 2, 0, 1, 0, 1, 3, 4][hash % 11] ?? 0) : hash % count;
567
+ }
568
+
569
+ export interface IPropMaterials {
570
+ readonly bark: Material;
571
+ readonly crown: Material;
572
+ /** Bracken under the spruces, cut against Poly Haven's fern frond atlas. */
573
+ readonly fern: Material;
574
+ readonly grass: Material;
575
+ /** The far cross-card: the whole tree past the last band, one card and eight triangles. */
576
+ readonly impostor: Material;
577
+ /** The prepared CC0 fir's own cutout, sampled against Poly Haven's twig atlas. */
578
+ readonly needles: Material;
579
+ readonly petal: Material;
580
+ /** The prepared pine's own cutout, sampled against its own leaf atlas. */
581
+ readonly pine: Material;
582
+ readonly stem: Material;
583
+ readonly stone: Material;
584
+ }
585
+
586
+ /**
587
+ * A flat stand-in surface per role, drawn until the real ones arrive.
588
+ *
589
+ * The meshes exist on the first frame because `enter` is synchronous and the maps are not, and a
590
+ * missing material has to mean "plain spruce" rather than "no forest". Vertex colours are on, so
591
+ * grass and stems already read correctly from their own gradient.
592
+ */
593
+ export function flatPropMaterials(): IPropMaterials & { dispose: () => void } {
594
+ const materials: IPropMaterials = {
595
+ bark: new MeshStandardMaterial({ color: 0x4a3428, roughness: 0.95 }),
596
+ crown: new MeshStandardMaterial({ color: 0x2c4a2a, roughness: 0.9, side: DoubleSide }),
597
+ fern: new MeshStandardMaterial({ color: 0x2f4d22, roughness: 0.9, side: DoubleSide }),
598
+ grass: new MeshStandardMaterial({
599
+ color: 0xffffff,
600
+ roughness: 0.93,
601
+ side: DoubleSide,
602
+ vertexColors: true,
603
+ }),
604
+ // The far card and the pine's crown are the same green: one is a picture of the other, so a
605
+ // tree that steps down a band does not change colour on the way.
606
+ impostor: new MeshStandardMaterial({ color: 0x24401f, roughness: 0.94, side: DoubleSide }),
607
+ needles: new MeshStandardMaterial({ color: 0x24401f, roughness: 0.94, side: DoubleSide }),
608
+ petal: new MeshStandardMaterial({ color: 0xb8181a, roughness: 0.75, side: DoubleSide }),
609
+ pine: new MeshStandardMaterial({ color: 0x24401f, roughness: 0.94, side: DoubleSide }),
610
+ stem: new MeshStandardMaterial({
611
+ color: 0xffffff,
612
+ roughness: 0.9,
613
+ side: DoubleSide,
614
+ vertexColors: true,
615
+ }),
616
+ stone: new MeshStandardMaterial({ color: 0x6e6f62, roughness: 0.93 }),
617
+ };
618
+ return {
619
+ ...materials,
620
+ dispose: () => {
621
+ for (const material of Object.values(materials)) material.dispose();
622
+ },
623
+ };
624
+ }