@threenative/terrain 0.1.7 → 0.1.9

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 (129) hide show
  1. package/AGENT_GUIDE.md +19 -4
  2. package/dist/editor/index.d.ts +218 -5
  3. package/dist/editor/index.js +4093 -1399
  4. package/dist/editor/server.d.ts +2 -2
  5. package/dist/editor/server.js +752 -124
  6. package/dist/editor/worker.d.ts +33 -1
  7. package/dist/editor/worker.js +642 -114
  8. package/dist/export.d.ts +11 -9
  9. package/dist/export.js +22 -34
  10. package/dist/index.d.ts +866 -73
  11. package/dist/index.js +3003 -523
  12. package/dist/kit.d.ts +57 -0
  13. package/dist/kit.js +2718 -0
  14. package/dist/mcp/cook-child.d.ts +2 -0
  15. package/dist/mcp/cook-child.js +5346 -0
  16. package/dist/mcp/server.d.ts +7 -0
  17. package/dist/mcp/server.js +3970 -0
  18. package/dist/{server-ByM2hmYJ.d.ts → server-B5RdvEAC.d.ts} +3 -2
  19. package/dist/starter.d.ts +143 -0
  20. package/dist/starter.js +1031 -0
  21. package/dist/{terrain-gPnkCU6S.d.ts → terrain-CAEaW0mQ.d.ts} +3 -2
  22. package/dist/three.d.ts +1 -1
  23. package/dist/{types-Ant8-Axc.d.ts → types-BpH00qsx.d.ts} +20 -4
  24. package/dist/world-package-B8QgHjAQ.d.ts +53 -0
  25. package/package.json +28 -6
  26. package/starter/alpine/README.md +77 -1
  27. package/starter/alpine/bake.mjs +4 -116
  28. package/starter/alpine/biome.data.json +134 -0
  29. package/starter/alpine/heightmap.r16 +0 -0
  30. package/starter/alpine/recipe.json +3 -66051
  31. package/starter/alpine/world.ts +45 -293
  32. package/starter/coastal/README.md +82 -3
  33. package/starter/coastal/assets.json +2 -1
  34. package/starter/coastal/bake.mjs +4 -116
  35. package/starter/coastal/biome.data.json +156 -0
  36. package/starter/coastal/heightmap.r16 +0 -0
  37. package/starter/coastal/recipe.json +3 -66051
  38. package/starter/coastal/sea.ts +51 -66
  39. package/starter/coastal/world.ts +53 -318
  40. package/starter/desert/README.md +77 -1
  41. package/starter/desert/bake.mjs +4 -116
  42. package/starter/desert/biome.data.json +124 -0
  43. package/starter/desert/heightmap.r16 +0 -0
  44. package/starter/desert/recipe.json +3 -66051
  45. package/starter/desert/world.ts +45 -293
  46. package/starter/forest/README.md +85 -5
  47. package/starter/forest/assets.json +34 -1
  48. package/starter/forest/bake.mjs +6 -116
  49. package/starter/forest/biome.data.json +173 -0
  50. package/starter/forest/heightmap.r16 +0 -0
  51. package/starter/forest/recipe.json +192 -4428
  52. package/starter/forest/sky.ts +11 -0
  53. package/starter/forest/water.ts +39 -48
  54. package/starter/forest/world.ts +92 -323
  55. package/starter/tundra/README.md +77 -1
  56. package/starter/tundra/bake.mjs +4 -116
  57. package/starter/tundra/biome.data.json +141 -0
  58. package/starter/tundra/heightmap.r16 +0 -0
  59. package/starter/tundra/recipe.json +18 -66066
  60. package/starter/tundra/water.ts +9 -28
  61. package/starter/tundra/world.ts +65 -319
  62. package/starter-assets.json +6 -0
  63. package/{starter-assets/credits.json → starter-credits.json} +12 -105
  64. package/starter-assets/bark_brown_02/bark_brown_02_diff_1k.jpg +0 -0
  65. package/starter-assets/bark_brown_02/bark_brown_02_nor_gl_1k.jpg +0 -0
  66. package/starter-assets/bark_brown_02/bark_brown_02_rough_1k.jpg +0 -0
  67. package/starter-assets/boulder_01/boulder-mid.glb +0 -0
  68. package/starter-assets/boulder_01/boulder-near.glb +0 -0
  69. package/starter-assets/cliff_side/cliff_side_ao_1k.jpg +0 -0
  70. package/starter-assets/cliff_side/cliff_side_diff_1k.jpg +0 -0
  71. package/starter-assets/cliff_side/cliff_side_nor_gl_1k.jpg +0 -0
  72. package/starter-assets/cliff_side/cliff_side_rough_1k.jpg +0 -0
  73. package/starter-assets/fern_02/fern_02_alpha_512.png +0 -0
  74. package/starter-assets/fern_02/fern_02_diff_512.jpg +0 -0
  75. package/starter-assets/fern_02/fern_02_nor_gl_512.jpg +0 -0
  76. package/starter-assets/fir_tree_01/fir-b-lod1.glb +0 -0
  77. package/starter-assets/fir_tree_01/fir-b-lod2.glb +0 -0
  78. package/starter-assets/fir_tree_01/fir-c-lod1.glb +0 -0
  79. package/starter-assets/fir_tree_01/fir-c-lod2.glb +0 -0
  80. package/starter-assets/fir_tree_01/fir_tree_01_twig_arm_1k.jpg +0 -0
  81. package/starter-assets/fir_tree_01/fir_tree_01_twig_diff_1k.jpg +0 -0
  82. package/starter-assets/fir_tree_01/fir_tree_01_twig_nor_gl_1k.jpg +0 -0
  83. package/starter-assets/forest_ground_04/forest_ground_04_ao_1k.jpg +0 -0
  84. package/starter-assets/forest_ground_04/forest_ground_04_diff_1k.jpg +0 -0
  85. package/starter-assets/forest_ground_04/forest_ground_04_nor_gl_1k.jpg +0 -0
  86. package/starter-assets/forest_ground_04/forest_ground_04_rough_1k.jpg +0 -0
  87. package/starter-assets/forest_leaves_02/forest_leaves_02_arm_512.jpg +0 -0
  88. package/starter-assets/forest_leaves_02/forest_leaves_02_diff_512.jpg +0 -0
  89. package/starter-assets/forest_leaves_02/forest_leaves_02_nor_gl_512.jpg +0 -0
  90. package/starter-assets/grass_medium_02/grass_medium_02_alpha_512.png +0 -0
  91. package/starter-assets/grass_medium_02/grass_medium_02_diff_512.jpg +0 -0
  92. package/starter-assets/grass_medium_02/grass_medium_02_nor_gl_512.jpg +0 -0
  93. package/starter-assets/hdri/kloofendal_48d_partly_cloudy_1k.hdr +0 -0
  94. package/starter-assets/leafy_grass/leafy_grass_ao_1k.jpg +0 -0
  95. package/starter-assets/leafy_grass/leafy_grass_diff_1k.jpg +0 -0
  96. package/starter-assets/leafy_grass/leafy_grass_nor_gl_1k.jpg +0 -0
  97. package/starter-assets/leafy_grass/leafy_grass_rough_1k.jpg +0 -0
  98. package/starter-assets/lichen_rock/lichen_rock_arm_512.jpg +0 -0
  99. package/starter-assets/lichen_rock/lichen_rock_diff_512.jpg +0 -0
  100. package/starter-assets/lichen_rock/lichen_rock_nor_gl_512.jpg +0 -0
  101. package/starter-assets/mossy_rock/mossy_rock_ao_1k.jpg +0 -0
  102. package/starter-assets/mossy_rock/mossy_rock_diff_1k.jpg +0 -0
  103. package/starter-assets/mossy_rock/mossy_rock_nor_gl_1k.jpg +0 -0
  104. package/starter-assets/mossy_rock/mossy_rock_rough_1k.jpg +0 -0
  105. package/starter-assets/needle-atlas.png +0 -0
  106. package/starter-assets/needle-surface.png +0 -0
  107. package/starter-assets/river_small_rocks/river_small_rocks_arm_512.jpg +0 -0
  108. package/starter-assets/river_small_rocks/river_small_rocks_diff_512.jpg +0 -0
  109. package/starter-assets/river_small_rocks/river_small_rocks_nor_gl_512.jpg +0 -0
  110. package/starter-assets/rock_boulder_dry/rock_boulder_dry_arm_512.jpg +0 -0
  111. package/starter-assets/rock_boulder_dry/rock_boulder_dry_diff_512.jpg +0 -0
  112. package/starter-assets/rock_boulder_dry/rock_boulder_dry_nor_gl_512.jpg +0 -0
  113. package/starter-assets/rocks/boulder-mid.glb +0 -0
  114. package/starter-assets/rocks/boulder-near.glb +0 -0
  115. package/starter-assets/rocks/boulder-prep.json +0 -37
  116. package/starter-assets/rocks/rock01-mid.glb +0 -0
  117. package/starter-assets/rocks/rock01-near.glb +0 -0
  118. package/starter-assets/rocks/rock01-prep.json +0 -37
  119. package/starter-assets/rocks/rock04-mid.glb +0 -0
  120. package/starter-assets/rocks/rock04-near.glb +0 -0
  121. package/starter-assets/rocks/rock04-prep.json +0 -37
  122. package/starter-assets/sand_01/sand_01_ao_1k.jpg +0 -0
  123. package/starter-assets/sand_01/sand_01_diff_1k.jpg +0 -0
  124. package/starter-assets/sand_01/sand_01_nor_gl_1k.jpg +0 -0
  125. package/starter-assets/sand_01/sand_01_rough_1k.jpg +0 -0
  126. package/starter-assets/snow_02/snow_02_ao_1k.jpg +0 -0
  127. package/starter-assets/snow_02/snow_02_diff_1k.jpg +0 -0
  128. package/starter-assets/snow_02/snow_02_nor_gl_1k.jpg +0 -0
  129. package/starter-assets/snow_02/snow_02_rough_1k.jpg +0 -0
@@ -5,6 +5,7 @@
5
5
  // the depth tint. Change `SEA`, `SURFACE` or `OCEAN_LOOK` to change the sea; nothing in a package decides it.
6
6
  import type { ICtx, ISpectralOceanOptions } from "@threenative/core";
7
7
  import { SpectralOcean } from "@threenative/core";
8
+ import { shoreField } from "@threenative/core/world";
8
9
  import type { IPhysicsContext } from "@threenative/physics";
9
10
  import {
10
11
  Color,
@@ -21,6 +22,7 @@ import {
21
22
  clamp,
22
23
  color,
23
24
  float,
25
+ fwidth,
24
26
  mix,
25
27
  mx_fractal_noise_float,
26
28
  mx_noise_float,
@@ -124,56 +126,12 @@ function createSeaMesh(ocean: SpectralOcean, data: ICoastalSeaData): Mesh {
124
126
  // through more than 2 m of water leaves sheltered lagoons out of the breaking-surf mask.
125
127
  const n = data.resolution;
126
128
  const cell = data.size / (n - 1);
127
- const distance = Float32Array.from(data.heights, (height) => (height >= level ? 0 : 1e4));
128
- const exposed = new Uint8Array(n * n);
129
- const queue: number[] = [];
130
- for (let i = 0; i < n * n; i++) {
131
- const row = Math.floor(i / n);
132
- const col = i % n;
133
- if (
134
- (row === 0 || col === 0 || row === n - 1 || col === n - 1) &&
135
- (data.heights[i] as number) < level - 2
136
- ) {
137
- exposed[i] = 1;
138
- queue.push(i);
139
- }
140
- if (col > 0) distance[i] = Math.min(distance[i] as number, (distance[i - 1] as number) + cell);
141
- if (row > 0) distance[i] = Math.min(distance[i] as number, (distance[i - n] as number) + cell);
142
- }
143
- for (let i = n * n - 1; i >= 0; i--) {
144
- if (i % n < n - 1)
145
- distance[i] = Math.min(distance[i] as number, (distance[i + 1] as number) + cell);
146
- if (i < n * (n - 1))
147
- distance[i] = Math.min(distance[i] as number, (distance[i + n] as number) + cell);
148
- }
149
- for (let head = 0; head < queue.length; head++) {
150
- const i = queue[head] as number;
151
- for (const next of [i % n > 0 ? i - 1 : -1, i % n < n - 1 ? i + 1 : -1, i - n, i + n]) {
152
- if (
153
- next < 0 ||
154
- next >= exposed.length ||
155
- exposed[next] ||
156
- (data.heights[next] as number) >= level - 2
157
- )
158
- continue;
159
- exposed[next] = 1;
160
- queue.push(next);
161
- }
162
- }
163
- // Carry exposure through the last eighteen metres of shallow water, never across a dry sand bar.
164
- for (let pass = 0; pass < Math.ceil(18 / cell); pass++) {
165
- const previous = exposed.slice();
166
- for (let i = 0; i < exposed.length; i++) {
167
- if ((data.heights[i] as number) >= level) continue;
168
- if (
169
- (i % n > 0 && previous[i - 1]) ||
170
- (i % n < n - 1 && previous[i + 1]) ||
171
- previous[i - n] ||
172
- previous[i + n]
173
- )
174
- exposed[i] = 1;
175
- }
176
- }
129
+ // The surveyed deepest bed sets the tint range and the open-sea continuation.
130
+ const deepDepth = data.heights.reduce(
131
+ (deepest, height) => Math.max(deepest, level - height),
132
+ cell,
133
+ );
134
+ const { distance, exposed } = shoreField(data.heights, n, data.size, level);
177
135
  const pixels = new Uint16Array(n * n * 4);
178
136
  for (let i = 0; i < n * n; i++) {
179
137
  pixels[i * 4] = DataUtils.toHalfFloat(data.heights[i] as number);
@@ -207,12 +165,15 @@ function createSeaMesh(ocean: SpectralOcean, data: ICoastalSeaData): Mesh {
207
165
  roughness: 0.12,
208
166
  });
209
167
  const shoreUV = (x: Node<"float">, z: Node<"float">) =>
210
- vec2(x.div(data.size).add(0.5), z.div(data.size).add(0.5));
168
+ vec2(x.div(data.size).add(0.5), z.div(data.size).add(0.5))
169
+ .mul((n - 1) / n)
170
+ .add(0.5 / n);
171
+ // Outside the surveyed bed, continue its edge depth before easing into open sea.
211
172
  const inside = (x: Node<"float">, z: Node<"float">) =>
212
- float(1).sub(smoothstep(data.size / 2 - 2, data.size / 2 + 2, x.abs().max(z.abs())));
173
+ float(1).sub(smoothstep(data.size / 2, data.size * 0.75, x.abs().max(z.abs())));
213
174
  const vertexLand = texture(heightTexture, shoreUV(positionLocal.x, positionLocal.z)).r;
214
175
  const vertexDepth = mix(
215
- float(28),
176
+ float(deepDepth),
216
177
  float(level).sub(vertexLand),
217
178
  inside(positionLocal.x, positionLocal.z),
218
179
  );
@@ -246,7 +207,7 @@ function createSeaMesh(ocean: SpectralOcean, data: ICoastalSeaData): Mesh {
246
207
  );
247
208
  const shore = texture(heightTexture, shoreUV(positionWorld.x, positionWorld.z));
248
209
  const local = inside(positionWorld.x, positionWorld.z);
249
- const depth = mix(float(28), positionWorld.y.sub(shore.r), local);
210
+ const depth = mix(float(deepDepth), float(level).sub(shore.r), local);
250
211
  const damp = smoothstep(0.1, 2.5, depth);
251
212
  const wind = mx_noise_float(
252
213
  vec3(positionWorld.x.mul(0.07).sub(time.mul(0.04)), positionWorld.z.mul(0.07), time.mul(0.015)),
@@ -269,24 +230,48 @@ function createSeaMesh(ocean: SpectralOcean, data: ICoastalSeaData): Mesh {
269
230
  const bounced = view.negate().reflect(normal);
270
231
  // The standard material supplies Fresnel and the sun's specular lobe; the sky supplies the radiance.
271
232
  material.envNode = mix(color(0xb6cbd5), color(0x568fbd), clamp(bounced.y, 0, 1)).mul(1.15);
272
- const water = mix(OCEAN_LOOK.shallow, OCEAN_LOOK.deep, smoothstep(0.4, 9, depth));
273
- const surf = mx_noise_float(
274
- vec3(positionWorld.x.mul(0.9), positionWorld.z.mul(0.9), time.mul(0.45)),
275
- )
233
+ const water = mix(
234
+ OCEAN_LOOK.shallow,
235
+ OCEAN_LOOK.deep,
236
+ smoothstep(deepDepth * 0.25, deepDepth, depth).pow(2),
237
+ );
238
+ const surfPoint = vec3(positionWorld.x, positionWorld.z, time.mul(0.45));
239
+ const broadSurf = mx_noise_float(surfPoint.mul(vec3(0.18, 0.18, 0.3)))
240
+ .mul(0.5)
241
+ .add(0.5);
242
+ const surf = mx_noise_float(surfPoint.mul(vec3(0.9, 0.9, 1)))
276
243
  .mul(0.5)
277
244
  .add(0.5);
245
+ // A pixel covering a bubble fades it out; derivative-wide thresholds soften the remaining edges.
246
+ const footprint = fwidth(positionWorld.xz).length().mul(0.9);
247
+ const antialias = fwidth(surf).max(0.025);
248
+ const bubbles = smoothstep(
249
+ float(0.5).sub(broadSurf.mul(0.16)).sub(antialias),
250
+ float(0.65).sub(broadSurf.mul(0.16)).add(antialias),
251
+ surf,
252
+ ).mul(float(1).sub(smoothstep(0.35, 1, footprint)));
253
+ const shoreReach = float(1)
254
+ .sub(smoothstep(3, 12, shore.g))
255
+ .mul(shore.b.mul(0.65).add(0.35))
256
+ .mul(local);
278
257
  const shoreFoam = float(1)
279
- .sub(smoothstep(0.25, 1.8, depth))
258
+ .sub(smoothstep(0.25, 1.8, depth.add(time.mul(0.85).sin().mul(0.18))))
280
259
  .mul(smoothstep(0.015, 0.08, depth))
281
- .mul(float(1).sub(smoothstep(1, 5.5, shore.g)))
282
- .mul(smoothstep(0.25, 0.65, surf).mul(0.7).add(0.3))
283
- .mul(shore.b)
284
- .mul(local)
285
- .mul(0.8);
286
- material.colorNode = mix(water, color(FOAM), shoreFoam);
260
+ .mul(bubbles)
261
+ .mul(broadSurf.mul(0.6).add(0.25))
262
+ .mul(shoreReach);
263
+ const swash = float(1)
264
+ .sub(smoothstep(0.1, 2.5, depth))
265
+ .mul(smoothstep(0, 0.12, depth))
266
+ .mul(broadSurf.mul(0.5).add(0.5))
267
+ .mul(shoreReach)
268
+ .mul(0.12);
269
+ material.colorNode = mix(water, color(FOAM), shoreFoam.add(swash));
287
270
  // The surface runs to the fogged horizon, and fades into the sky there rather than ending on a hard band.
288
271
  const horizonFade = float(1).sub(smoothstep(1200, 3500, eyeDistance));
289
- material.opacityNode = smoothstep(-0.03, 0.35, depth).max(shoreFoam.mul(0.9)).mul(horizonFade);
272
+ material.opacityNode = smoothstep(0, Math.min(2.5, deepDepth), depth)
273
+ .max(shoreFoam.mul(0.9))
274
+ .mul(horizonFade);
290
275
  material.roughnessNode = mix(
291
276
  float(0.12).add(smoothstep(70, 700, eyeDistance).mul(0.07)),
292
277
  float(0.7),
@@ -1,31 +1,25 @@
1
- // The coastal starter world, as the game that copied it draws and collides with it.
2
- //
3
- // `bake.mjs` wrote a world package into `world/`: heightmap, splat masks, placements and the CC0 fir.
4
- // The engine's `WorldCells` streams it. `loadTerrainSplat` textures its ground.
5
- // Everything that decides how the world looks, or what stops the player, is in this folder for the game to edit.
6
- import type { IComputeDriven, ICtx } from "@threenative/core";
1
+ import type { ICtx } from "@threenative/core";
7
2
  import {
8
- Heightfield,
9
- type IWorldCellsLoadOptions,
3
+ type ILoadTerrainSplatOptions,
10
4
  type IWorldPackage,
11
- WorldCells,
12
- heightSamplerFromHeightmap,
13
5
  loadTerrainSplat,
14
- loadWorldHeightmap,
15
6
  } from "@threenative/core/world";
16
- import { CollisionShape3D, type IPhysicsContext, RigidBody3D } from "@threenative/physics";
7
+ import type { IPhysicsContext } from "@threenative/physics";
8
+ import {
9
+ type IStarterWorld,
10
+ type IStarterWorldSpec,
11
+ PropColliders as StarterPropColliders,
12
+ addStarterWorld,
13
+ } from "@threenative/terrain/starter";
17
14
  import {
18
15
  EquirectangularReflectionMapping,
19
- type Material,
20
16
  type Mesh,
21
17
  type MeshStandardMaterial,
22
- Object3D,
18
+ type Object3D,
23
19
  type Texture,
24
- Vector3,
25
20
  } from "three";
26
- import { HDRLoader } from "three/addons/loaders/HDRLoader.js";
27
21
  import { type ICoastalSea, type ICoastalSeaData, addCoastalSea } from "./sea.js";
28
-
22
+ import surface from "./surface.json" with { type: "json" };
29
23
  /** Where the game's asset source holds the baked `world/` folder. */
30
24
  export const COASTAL_URL = "terrain/coastal/world.json";
31
25
 
@@ -43,24 +37,10 @@ export const PROP_SKY_LIGHT = 0.5;
43
37
  /** Metres around `follow` within which props collide. Beyond that, props only draw. */
44
38
  export const PROP_COLLIDER_REACH = 60;
45
39
 
46
- export interface ICoastalWorld {
47
- readonly world: WorldCells;
48
- /** One heightfield for the whole world, in place before `addCoastal` resolves. */
49
- readonly ground: RigidBody3D;
50
- /** The prop colliders near `follow`. They stream with it (see `PROP_COLLIDER_REACH`). */
51
- readonly colliders: PropColliders;
52
- /** The heightfield the ground stands on: `heightAt(x, z)` reads the terrain under any point. */
53
- readonly field: Heightfield;
54
- /** Every placed prop's record, eight floats each, as the bake wrote it. */
55
- readonly placements: Float32Array;
56
- /** The world's extent in metres, as the bake wrote it. */
57
- readonly extent: IWorldPackage["extent"];
58
- /** The sea's level in metres, as the bake wrote it. The scene keeps its spawn and its walk above it. */
40
+ export interface ICoastalWorld extends IStarterWorld {
59
41
  readonly seaLevel: number;
60
- /** The sea in the scene. `dispose` removes its mesh and releases its water surface. */
61
42
  readonly sea: ICoastalSea;
62
43
  }
63
-
64
44
  /** What `water.json` holds for the coastal kit: the sea, as one lake with a level. */
65
45
  interface ICoastalWaterFile {
66
46
  readonly lakes: readonly {
@@ -71,293 +51,62 @@ interface ICoastalWaterFile {
71
51
  readonly rivers: readonly unknown[];
72
52
  }
73
53
 
74
- /**
75
- * Stream the coastal world around `follow` (usually the player or the camera) and give it collision.
76
- * `whileCurrent` stops a departed scene's async load from attaching anything. Its resources are
77
- * released on cancellation, failure and when the game's entity registry ends this scene.
78
- */
54
+ const spec: IStarterWorldSpec<{ dispose(): void; sea: ICoastalSea; seaLevel: number }> = {
55
+ name: "Coastal",
56
+ url: COASTAL_URL,
57
+ colliders: COLLIDERS,
58
+ colliderReach: PROP_COLLIDER_REACH,
59
+ loadSurface: (ctx, url) =>
60
+ loadTerrainSplat({
61
+ assets: ctx.assets,
62
+ url,
63
+ table: surface as unknown as ILoadTerrainSplatOptions["table"],
64
+ }),
65
+ lighting: { sky: "sky.hdr", lods: false, dress: dressProp },
66
+ streaming: {
67
+ ring: 5,
68
+ impostors: false,
69
+ gpuScene: false,
70
+ shadows: { cast: true, receive: true },
71
+ budgets: { residentCells: 64, instances: 40_000, bytes: 64_000_000 },
72
+ terrain: { streamRadius: 6 },
73
+ },
74
+ water: (ctx, file, _field, manifest, heightmap) => {
75
+ const seaLevel = (file as ICoastalWaterFile).lakes[0]?.level;
76
+ if (seaLevel === undefined) throw new Error("Coastal world: water.json names no sea level.");
77
+ const sea = addCoastalSea(ctx, coastalSeaData(manifest, heightmap, seaLevel));
78
+ return { seaLevel, sea, dispose: () => sea.dispose() };
79
+ },
80
+ };
81
+ export class PropColliders extends StarterPropColliders {
82
+ constructor(
83
+ ctx: ICtx<Record<string, unknown>, IPhysicsContext>,
84
+ follow: Object3D,
85
+ manifest: IWorldPackage,
86
+ records: Float32Array,
87
+ ) {
88
+ super(ctx, follow, manifest, records, COLLIDERS, PROP_COLLIDER_REACH, "Coastal");
89
+ }
90
+ }
79
91
  export async function addCoastal(
80
92
  ctx: ICtx<Record<string, unknown>, IPhysicsContext>,
81
93
  follow: Object3D,
82
94
  url = COASTAL_URL,
83
95
  whileCurrent: () => boolean = () => true,
84
96
  ): Promise<ICoastalWorld> {
85
- const assertCurrent = () => {
86
- if (whileCurrent()) return;
87
- const error = new Error("Coastal world: its scene is no longer current.");
88
- error.name = "AbortError";
89
- throw error;
90
- };
91
- let surface: Material | undefined;
92
- let releaseLighting: (() => void) | undefined;
93
- let world: WorldCells | undefined;
94
- let ground: RigidBody3D | undefined;
95
- let colliders: PropColliders | undefined;
96
- let sea: ICoastalSea | undefined;
97
- let released = false;
98
- const dispose = () => {
99
- if (released) return;
100
- released = true;
101
- colliders?.detach();
102
- colliders?.removeFromParent();
103
- ground?.dispose();
104
- ground?.object?.removeFromParent();
105
- sea?.dispose();
106
- world?.dispose();
107
- surface?.dispose();
108
- releaseLighting?.();
109
- };
110
- try {
111
- assertCurrent();
112
- const manifest = (await (await fetchAsset(ctx, url, assertCurrent)).json()) as IWorldPackage;
113
- assertCurrent();
114
- const base = url.slice(0, url.lastIndexOf("/") + 1);
115
- const records = await (
116
- await fetchAsset(ctx, base + manifest.placements, assertCurrent)
117
- ).arrayBuffer();
118
- assertCurrent();
119
- const [heightmapUrl] = await ctx.assets.resolve(base + manifest.terrain.heightmap);
120
- assertCurrent();
121
- if (heightmapUrl === undefined) throw new Error("Coastal world: its heightmap is not served.");
122
- const heightmap = await loadWorldHeightmap(heightmapUrl);
123
- assertCurrent();
124
- surface = await loadTerrainSplat({ assets: ctx.assets, url });
125
- assertCurrent();
126
- releaseLighting = await lightProps(ctx, url, manifest, assertCurrent);
127
- assertCurrent();
128
- const options: IWorldCellsLoadOptions = {
129
- url,
130
- assets: ctx.assets,
131
- data: { manifest, placements: records, heightmap },
132
- surface,
133
- follow,
134
- ring: 5,
135
- impostors: false,
136
- gpuScene: false,
137
- shadows: { cast: true, receive: true },
138
- budgets: { residentCells: 64, instances: 40_000, bytes: 64_000_000 },
139
- terrain: { streamRadius: 6 },
140
- };
141
- world = await WorldCells.load(options);
142
- assertCurrent();
143
- const field = coastalField(manifest, heightmap);
144
- ground = groundCollider(ctx, manifest, field);
145
- const waterFile = (await (
146
- await fetchAsset(ctx, `${base}water.json`, assertCurrent)
147
- ).json()) as ICoastalWaterFile;
148
- assertCurrent();
149
- const seaLevel = waterFile.lakes[0]?.level;
150
- if (seaLevel === undefined) throw new Error("Coastal world: water.json names no sea level.");
151
- const ocean = addCoastalSea(ctx, coastalSeaData(manifest, heightmap, seaLevel));
152
- sea = ocean;
153
- const props = new Float32Array(records);
154
- colliders = new PropColliders(ctx, follow, manifest, props);
155
- ctx.add(world);
156
- if (ground.object !== undefined) ctx.add(ground.object);
157
- ctx.add(colliders);
158
- ctx.entities.add(`coastal-world.${world.uuid}`, { dispose });
159
- return {
160
- world,
161
- ground,
162
- colliders,
163
- field,
164
- placements: props,
165
- extent: manifest.extent,
166
- seaLevel,
167
- sea: ocean,
168
- };
169
- } catch (error) {
170
- dispose();
171
- throw error;
172
- }
97
+ const result = await addStarterWorld(ctx, follow, spec, url, whileCurrent);
98
+ if (!result.extra) throw new Error("Coastal world: missing sea.");
99
+ return { ...result, ...result.extra };
173
100
  }
174
-
175
- // Every prop gets the sky as its own envMap before WorldCells adopts the shared cached models.
176
- // Without it, a fir lit by the sun alone draws flat.
177
- async function lightProps(
178
- ctx: ICtx<Record<string, unknown>, IPhysicsContext>,
179
- url: string,
180
- manifest: IWorldPackage,
181
- assertCurrent: () => void,
182
- ): Promise<() => void> {
183
- const base = url.slice(0, url.lastIndexOf("/") + 1);
184
- const [skyUrl] = await ctx.assets.resolve(`${base}sky.hdr`);
185
- assertCurrent();
186
- if (skyUrl === undefined) throw new Error("Coastal world: 'sky.hdr' is not served.");
187
- const sky = await new HDRLoader().loadAsync(skyUrl);
188
- const originals = new Map<MeshStandardMaterial, { envMap: Texture | null; intensity: number }>();
189
- const dispose = () => {
190
- for (const [material, original] of originals) {
191
- if (material.envMap !== sky) continue;
192
- material.envMap = original.envMap;
193
- material.envMapIntensity = original.intensity;
194
- }
195
- sky.dispose();
196
- };
197
- try {
198
- assertCurrent();
199
- sky.mapping = EquirectangularReflectionMapping;
200
- for (const asset of Object.values(manifest.assets)) {
201
- const model = await ctx.assets.model<{ scene: Object3D }>(base + asset.glb);
202
- assertCurrent();
203
- model.scene.traverse((object) => {
204
- const mesh = object as Mesh;
205
- for (const material of [mesh.material ?? []].flat() as MeshStandardMaterial[])
206
- if (!originals.has(material))
207
- originals.set(material, {
208
- envMap: material.envMap,
209
- intensity: material.envMapIntensity,
210
- });
211
- dressProp(mesh, sky);
212
- });
213
- }
214
- return dispose;
215
- } catch (error) {
216
- dispose();
217
- throw error;
218
- }
219
- }
220
-
221
101
  /** One prop mesh: the sky as its envMap. */
222
102
  function dressProp(mesh: Mesh, sky: Texture): void {
223
103
  for (const material of [mesh.material ?? []].flat() as MeshStandardMaterial[]) {
104
+ sky.mapping = EquirectangularReflectionMapping;
224
105
  material.envMap = sky;
225
106
  material.envMapIntensity = PROP_SKY_LIGHT;
226
107
  }
227
108
  }
228
109
 
229
- // The streamed terrain tiles arrive over several frames. A player spawned before its tile would
230
- // fall through. One heightfield for the whole package avoids that, at a few hundred kilobytes.
231
- /** The kit's one heightfield: the collider stands on it. */
232
- function coastalField(manifest: IWorldPackage, heightmap: Uint16Array): Heightfield {
233
- const { extent, terrain } = manifest;
234
- return Heightfield.fromSampler({
235
- columns: terrain.columns,
236
- rows: terrain.rows,
237
- width: extent.sizeX,
238
- depth: extent.sizeZ,
239
- origin: { x: extent.minX + extent.sizeX / 2, z: extent.minZ + extent.sizeZ / 2 },
240
- sampleHeight: heightSamplerFromHeightmap(terrain, extent, heightmap),
241
- });
242
- }
243
-
244
- function groundCollider(
245
- ctx: ICtx<Record<string, unknown>, IPhysicsContext>,
246
- manifest: IWorldPackage,
247
- field: Heightfield,
248
- ): RigidBody3D {
249
- const { extent } = manifest;
250
- const anchor = new Object3D();
251
- anchor.position.set(extent.minX + extent.sizeX / 2, 0, extent.minZ + extent.sizeZ / 2);
252
- return new RigidBody3D({
253
- object: anchor,
254
- physics: ctx.physics,
255
- type: "fixed",
256
- entity: "terrain",
257
- shape: CollisionShape3D.heightfield(field.rows, field.columns, field.toColliderHeights(), {
258
- x: extent.sizeX,
259
- y: 1,
260
- z: extent.sizeZ,
261
- }),
262
- });
263
- }
264
-
265
- /**
266
- * Fixed bodies for the props within `PROP_COLLIDER_REACH` of `follow`, rebuilt when it has moved a few
267
- * metres. Thousands of resident bodies cost Rapier about 0.5 s per 8 s (measured). A hundred do not.
268
- */
269
- export class PropColliders extends Object3D implements IComputeDriven {
270
- readonly warmupNodes: readonly unknown[] = [];
271
- readonly processCadence = "render" as const;
272
- readonly #live = new Map<number, RigidBody3D>();
273
- readonly #runs: { asset: string; offset: number; count: number }[] = [];
274
- readonly #at = { x: Number.NaN, z: Number.NaN };
275
- readonly #followPosition = new Vector3();
276
- #released = false;
277
-
278
- constructor(
279
- private readonly ctx: ICtx<Record<string, unknown>, IPhysicsContext>,
280
- private readonly follow: Object3D,
281
- manifest: IWorldPackage,
282
- private readonly records: Float32Array,
283
- ) {
284
- super();
285
- this.name = "coastal-prop-colliders";
286
- for (const cell of manifest.cells)
287
- for (const run of cell.runs) if (COLLIDERS[run.asset]) this.#runs.push(run);
288
- try {
289
- this.#rebuild();
290
- } catch (error) {
291
- this.detach();
292
- throw error;
293
- }
294
- }
295
-
296
- /** How many prop bodies exist right now. */
297
- get active(): number {
298
- return this.#live.size;
299
- }
300
-
301
- get released(): boolean {
302
- return this.#released;
303
- }
304
-
305
- attachRenderer(): void {}
306
-
307
- process(): void {
308
- if (this.#released) return;
309
- const p = this.follow.getWorldPosition(this.#followPosition);
310
- if (Math.hypot(p.x - this.#at.x, p.z - this.#at.z) > 4 || Number.isNaN(this.#at.x))
311
- this.#rebuild();
312
- }
313
-
314
- detach(): void {
315
- for (const body of this.#live.values()) body.dispose();
316
- this.#live.clear();
317
- this.#released = true;
318
- }
319
-
320
- #rebuild(): void {
321
- const { x: fx, z: fz } = this.follow.getWorldPosition(this.#followPosition);
322
- this.#at.x = fx;
323
- this.#at.z = fz;
324
- const keep = new Set<number>();
325
- for (const run of this.#runs) {
326
- const shape = COLLIDERS[run.asset];
327
- if (!shape) continue;
328
- for (let i = run.offset; i < run.offset + run.count; i++) {
329
- const x = this.records[i * 8] as number;
330
- const z = this.records[i * 8 + 2] as number;
331
- if (Math.hypot(x - fx, z - fz) > PROP_COLLIDER_REACH) continue;
332
- keep.add(i);
333
- if (this.#live.has(i)) continue;
334
- const collider = CollisionShape3D.sphere(
335
- shape.sphere * (this.records[i * 8 + 7] as number),
336
- );
337
- this.#live.set(
338
- i,
339
- new RigidBody3D({
340
- physics: this.ctx.physics,
341
- type: "fixed",
342
- entity: `${run.asset}.${String(i)}`,
343
- position: { x, y: this.records[i * 8 + 1] as number, z },
344
- shape: collider,
345
- }),
346
- );
347
- }
348
- }
349
- for (const [i, body] of this.#live)
350
- if (!keep.has(i)) {
351
- body.dispose();
352
- this.#live.delete(i);
353
- }
354
- }
355
- }
356
-
357
- /**
358
- * The bake's heights on the world's grid, in metres, row-major by Z then X. The sea's shoreline, surf and
359
- * depth tint are read from these, so they match the terrain the player stands on.
360
- */
361
110
  function coastalSeaData(
362
111
  manifest: IWorldPackage,
363
112
  heightmap: Uint16Array,
@@ -370,17 +119,3 @@ function coastalSeaData(
370
119
  );
371
120
  return { heights, resolution: terrain.columns, size: extent.sizeX, waterLevel: seaLevel };
372
121
  }
373
-
374
- async function fetchAsset(
375
- ctx: ICtx<Record<string, unknown>, IPhysicsContext>,
376
- url: string,
377
- assertCurrent: () => void,
378
- ): Promise<Response> {
379
- const [resolved] = await ctx.assets.resolve(url);
380
- assertCurrent();
381
- if (resolved === undefined) throw new Error(`Coastal world: '${url}' is not served.`);
382
- const response = await fetch(resolved);
383
- assertCurrent();
384
- if (!response.ok) throw new Error(`Coastal world: '${url}' answered ${String(response.status)}.`);
385
- return response;
386
- }
@@ -13,7 +13,7 @@ source: once copied, every file is yours to edit.
13
13
  | `world.ts` | The runtime: streams the baked world, one heightfield for the ground, sphere colliders for the boulders near the player, and the sky as the props' light. |
14
14
  | `sky.ts` | The daylight: the sun, sky, fill, haze, exposure and tone curve. |
15
15
 
16
- Art is CC0 (Poly Haven); provenance is in `@threenative/terrain/starter-assets/credits.json`.
16
+ Art is CC0 (Poly Haven); provenance is in `@threenative/terrain/starter-credits.json`.
17
17
 
18
18
  ## Placeholder
19
19
 
@@ -33,3 +33,79 @@ colliders like any other prop, and the scene picks its spawn from the loaded hei
33
33
  2. Run `node src/terrain/desert/bake.mjs --out assets/terrain/desert` (needs `@threenative/terrain`
34
34
  as a devDependency). The same recipe always writes the same bytes.
35
35
  3. In the scene, call `addDesert(ctx, follow)` for the world and `desertDaylight(follow)` for the light.
36
+
37
+ ## Edit at startup, without rebaking
38
+
39
+ The copied `world.ts` loads its own `surface.json` as the ground table on every startup.
40
+ Edit tints, tiling and blend thresholds there, or the material graph and prop dressing in
41
+ `world.ts`, then reload. The package's `terrain-table.json` remains the baked default for
42
+ package-only consumers; its splat masks and texture descriptors still supply the ground data.
43
+ A source table cannot name a mask that the bake did not produce.
44
+
45
+ Add `edits` to the existing `spec` in your copied `world.ts`. Read real stable IDs from the
46
+ package's `placement-ids.json` (named by `world.json.placementIds`); these example IDs are placeholders:
47
+
48
+ ```ts
49
+ edits: {
50
+ assets: {
51
+ accent: { glb: "props/accent.glb", bounds: { min: [-1, -1, -1], max: [1, 1, 1] } },
52
+ },
53
+ remove: ["promote-id"],
54
+ clear: [{ center: [40, 18], radius: 6 }], // Optional assets: ["boulder"] filter.
55
+ overrides: {
56
+ "move-id": { position: [12, 0, -30], quaternion: [0, 0, 0, 1], scale: [1, 1, 1] },
57
+ },
58
+ add: [{ id: "camp-accent", asset: "accent", position: [44, 0, 20],
59
+ quaternion: [0, 0, 0, 1], scale: [1, 1, 1], grounding: true }],
60
+ },
61
+ ```
62
+
63
+ `assets` replaces or adds a kind; copy the GLB into the served package directory first.
64
+ GLB and LOD paths are package-relative, with no URL scheme, leading slash or `..` segment;
65
+ provide accurate model-local `bounds`. The existing `COLLIDERS` table and dress function still
66
+ choose each kind's collision and appearance. Positions must lie inside the world's extent,
67
+ quaternions must be nonzero, values finite and scale uniform. Grounding defaults on and sets
68
+ the origin Y to `field.heightAt(x, z)`; `grounding: false` preserves the authored Y.
69
+
70
+ Edits run in the order shown: assets, remove, clear, overrides, add. A clear skips IDs named
71
+ by overrides. Removing and overriding the same ID throws; additions need new IDs. Unmatched
72
+ removal/override IDs warn and appear in `editReport.unmatched`. Old packages work without a
73
+ sidecar for assets, clear and add; ID edits need one re-bake to write the sidecar. Without
74
+ `edits`, the decoded manifest and placement bytes pass through unchanged.
75
+
76
+ Promote only a few props to ordinary Three objects: remove their IDs from the instances,
77
+ then use the returned `editReport.removed` in the scene. This example replaces each with a
78
+ game-owned glowing box; use your own geometry, material, light and collision shape:
79
+
80
+ ```ts
81
+ import { CollisionShape3D, RigidBody3D } from "@threenative/physics";
82
+ import { BoxGeometry, Mesh, MeshStandardMaterial, PointLight } from "three";
83
+
84
+ const loaded = await addDesert(ctx, player);
85
+ for (const p of loaded.editReport.removed) {
86
+ const mesh = new Mesh(new BoxGeometry(1, 1, 1), new MeshStandardMaterial({ color: 0xffbb66 }));
87
+ mesh.position.set(p.position[0], loaded.field.heightAt(p.position[0], p.position[2]), p.position[2]);
88
+ mesh.quaternion.fromArray(p.quaternion);
89
+ mesh.scale.setScalar(p.scale);
90
+ mesh.castShadow = mesh.receiveShadow = true;
91
+ mesh.add(new PointLight(0xffaa55, 12, 6));
92
+ ctx.add(mesh);
93
+ const body = new RigidBody3D({ object: mesh, physics: ctx.physics, type: "fixed",
94
+ shape: CollisionShape3D.box(p.scale, p.scale, p.scale) });
95
+ ctx.entities.add(`promoted.${p.id}`, { dispose() {
96
+ body.dispose(); mesh.removeFromParent(); mesh.geometry.dispose(); mesh.material.dispose();
97
+ } });
98
+ }
99
+ ```
100
+
101
+ Rendering, nearby prop collision, dressing and returned `manifest`, `placements` and
102
+ `placementIds` all use the edited records. `clear` removals are not in the promotion report.
103
+ The separate `editWorldPlacements` helper and its types are exported from
104
+ `@threenative/terrain/starter` for callers that already own decoded package data.
105
+
106
+ Shape, topology, erosion, mask painting, distribution rules and water still require regeneration.
107
+ Changing cooked ground images requires the bake/cook texture normalization step; editing the
108
+ game table cannot replace baked texture descriptors or introduce new channels. To replace the
109
+ props' environment image at runtime, copy an HDR into the served package, change
110
+ `spec.lighting.sky` in `world.ts` to its package-relative path, then reload. The daylight and
111
+ background remain game choices in `sky.ts`. Package-only exports do not run these source edits.