@threenative/terrain 0.1.7 → 0.1.8

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 (127) hide show
  1. package/AGENT_GUIDE.md +19 -4
  2. package/dist/editor/index.d.ts +160 -5
  3. package/dist/editor/index.js +3783 -1406
  4. package/dist/editor/server.d.ts +2 -2
  5. package/dist/editor/server.js +555 -121
  6. package/dist/editor/worker.d.ts +33 -1
  7. package/dist/editor/worker.js +444 -110
  8. package/dist/export.d.ts +11 -9
  9. package/dist/export.js +22 -34
  10. package/dist/index.d.ts +727 -73
  11. package/dist/index.js +2434 -553
  12. package/dist/kit.d.ts +56 -0
  13. package/dist/kit.js +2524 -0
  14. package/dist/mcp/cook-child.d.ts +2 -0
  15. package/dist/mcp/cook-child.js +3705 -0
  16. package/dist/mcp/server.d.ts +7 -0
  17. package/dist/mcp/server.js +3279 -0
  18. package/dist/{server-ByM2hmYJ.d.ts → server-C8Ydr_IM.d.ts} +3 -2
  19. package/dist/starter.d.ts +143 -0
  20. package/dist/starter.js +1030 -0
  21. package/dist/{terrain-gPnkCU6S.d.ts → terrain-B3DkduPw.d.ts} +3 -2
  22. package/dist/three.d.ts +1 -1
  23. package/dist/{types-Ant8-Axc.d.ts → types-CPYAc9vo.d.ts} +13 -4
  24. package/dist/world-package-B7KGYIou.d.ts +94 -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 +114 -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 +77 -1
  33. package/starter/coastal/bake.mjs +4 -116
  34. package/starter/coastal/biome.data.json +135 -0
  35. package/starter/coastal/heightmap.r16 +0 -0
  36. package/starter/coastal/recipe.json +3 -66051
  37. package/starter/coastal/sea.ts +49 -16
  38. package/starter/coastal/world.ts +53 -318
  39. package/starter/desert/README.md +77 -1
  40. package/starter/desert/bake.mjs +4 -116
  41. package/starter/desert/biome.data.json +114 -0
  42. package/starter/desert/heightmap.r16 +0 -0
  43. package/starter/desert/recipe.json +3 -66051
  44. package/starter/desert/world.ts +45 -293
  45. package/starter/forest/README.md +84 -4
  46. package/starter/forest/assets.json +32 -0
  47. package/starter/forest/bake.mjs +6 -116
  48. package/starter/forest/biome.data.json +150 -0
  49. package/starter/forest/heightmap.r16 +0 -0
  50. package/starter/forest/recipe.json +192 -4428
  51. package/starter/forest/sky.ts +11 -0
  52. package/starter/forest/water.ts +30 -20
  53. package/starter/forest/world.ts +86 -322
  54. package/starter/tundra/README.md +77 -1
  55. package/starter/tundra/bake.mjs +4 -116
  56. package/starter/tundra/biome.data.json +131 -0
  57. package/starter/tundra/heightmap.r16 +0 -0
  58. package/starter/tundra/recipe.json +18 -66066
  59. package/starter/tundra/world.ts +65 -319
  60. package/starter-assets.json +6 -0
  61. package/{starter-assets/credits.json → starter-credits.json} +12 -105
  62. package/starter-assets/bark_brown_02/bark_brown_02_diff_1k.jpg +0 -0
  63. package/starter-assets/bark_brown_02/bark_brown_02_nor_gl_1k.jpg +0 -0
  64. package/starter-assets/bark_brown_02/bark_brown_02_rough_1k.jpg +0 -0
  65. package/starter-assets/boulder_01/boulder-mid.glb +0 -0
  66. package/starter-assets/boulder_01/boulder-near.glb +0 -0
  67. package/starter-assets/cliff_side/cliff_side_ao_1k.jpg +0 -0
  68. package/starter-assets/cliff_side/cliff_side_diff_1k.jpg +0 -0
  69. package/starter-assets/cliff_side/cliff_side_nor_gl_1k.jpg +0 -0
  70. package/starter-assets/cliff_side/cliff_side_rough_1k.jpg +0 -0
  71. package/starter-assets/fern_02/fern_02_alpha_512.png +0 -0
  72. package/starter-assets/fern_02/fern_02_diff_512.jpg +0 -0
  73. package/starter-assets/fern_02/fern_02_nor_gl_512.jpg +0 -0
  74. package/starter-assets/fir_tree_01/fir-b-lod1.glb +0 -0
  75. package/starter-assets/fir_tree_01/fir-b-lod2.glb +0 -0
  76. package/starter-assets/fir_tree_01/fir-c-lod1.glb +0 -0
  77. package/starter-assets/fir_tree_01/fir-c-lod2.glb +0 -0
  78. package/starter-assets/fir_tree_01/fir_tree_01_twig_arm_1k.jpg +0 -0
  79. package/starter-assets/fir_tree_01/fir_tree_01_twig_diff_1k.jpg +0 -0
  80. package/starter-assets/fir_tree_01/fir_tree_01_twig_nor_gl_1k.jpg +0 -0
  81. package/starter-assets/forest_ground_04/forest_ground_04_ao_1k.jpg +0 -0
  82. package/starter-assets/forest_ground_04/forest_ground_04_diff_1k.jpg +0 -0
  83. package/starter-assets/forest_ground_04/forest_ground_04_nor_gl_1k.jpg +0 -0
  84. package/starter-assets/forest_ground_04/forest_ground_04_rough_1k.jpg +0 -0
  85. package/starter-assets/forest_leaves_02/forest_leaves_02_arm_512.jpg +0 -0
  86. package/starter-assets/forest_leaves_02/forest_leaves_02_diff_512.jpg +0 -0
  87. package/starter-assets/forest_leaves_02/forest_leaves_02_nor_gl_512.jpg +0 -0
  88. package/starter-assets/grass_medium_02/grass_medium_02_alpha_512.png +0 -0
  89. package/starter-assets/grass_medium_02/grass_medium_02_diff_512.jpg +0 -0
  90. package/starter-assets/grass_medium_02/grass_medium_02_nor_gl_512.jpg +0 -0
  91. package/starter-assets/hdri/kloofendal_48d_partly_cloudy_1k.hdr +0 -0
  92. package/starter-assets/leafy_grass/leafy_grass_ao_1k.jpg +0 -0
  93. package/starter-assets/leafy_grass/leafy_grass_diff_1k.jpg +0 -0
  94. package/starter-assets/leafy_grass/leafy_grass_nor_gl_1k.jpg +0 -0
  95. package/starter-assets/leafy_grass/leafy_grass_rough_1k.jpg +0 -0
  96. package/starter-assets/lichen_rock/lichen_rock_arm_512.jpg +0 -0
  97. package/starter-assets/lichen_rock/lichen_rock_diff_512.jpg +0 -0
  98. package/starter-assets/lichen_rock/lichen_rock_nor_gl_512.jpg +0 -0
  99. package/starter-assets/mossy_rock/mossy_rock_ao_1k.jpg +0 -0
  100. package/starter-assets/mossy_rock/mossy_rock_diff_1k.jpg +0 -0
  101. package/starter-assets/mossy_rock/mossy_rock_nor_gl_1k.jpg +0 -0
  102. package/starter-assets/mossy_rock/mossy_rock_rough_1k.jpg +0 -0
  103. package/starter-assets/needle-atlas.png +0 -0
  104. package/starter-assets/needle-surface.png +0 -0
  105. package/starter-assets/river_small_rocks/river_small_rocks_arm_512.jpg +0 -0
  106. package/starter-assets/river_small_rocks/river_small_rocks_diff_512.jpg +0 -0
  107. package/starter-assets/river_small_rocks/river_small_rocks_nor_gl_512.jpg +0 -0
  108. package/starter-assets/rock_boulder_dry/rock_boulder_dry_arm_512.jpg +0 -0
  109. package/starter-assets/rock_boulder_dry/rock_boulder_dry_diff_512.jpg +0 -0
  110. package/starter-assets/rock_boulder_dry/rock_boulder_dry_nor_gl_512.jpg +0 -0
  111. package/starter-assets/rocks/boulder-mid.glb +0 -0
  112. package/starter-assets/rocks/boulder-near.glb +0 -0
  113. package/starter-assets/rocks/boulder-prep.json +0 -37
  114. package/starter-assets/rocks/rock01-mid.glb +0 -0
  115. package/starter-assets/rocks/rock01-near.glb +0 -0
  116. package/starter-assets/rocks/rock01-prep.json +0 -37
  117. package/starter-assets/rocks/rock04-mid.glb +0 -0
  118. package/starter-assets/rocks/rock04-near.glb +0 -0
  119. package/starter-assets/rocks/rock04-prep.json +0 -37
  120. package/starter-assets/sand_01/sand_01_ao_1k.jpg +0 -0
  121. package/starter-assets/sand_01/sand_01_diff_1k.jpg +0 -0
  122. package/starter-assets/sand_01/sand_01_nor_gl_1k.jpg +0 -0
  123. package/starter-assets/sand_01/sand_01_rough_1k.jpg +0 -0
  124. package/starter-assets/snow_02/snow_02_ao_1k.jpg +0 -0
  125. package/starter-assets/snow_02/snow_02_diff_1k.jpg +0 -0
  126. package/starter-assets/snow_02/snow_02_nor_gl_1k.jpg +0 -0
  127. package/starter-assets/snow_02/snow_02_rough_1k.jpg +0 -0
@@ -21,6 +21,7 @@ import {
21
21
  clamp,
22
22
  color,
23
23
  float,
24
+ fwidth,
24
25
  mix,
25
26
  mx_fractal_noise_float,
26
27
  mx_noise_float,
@@ -124,6 +125,11 @@ function createSeaMesh(ocean: SpectralOcean, data: ICoastalSeaData): Mesh {
124
125
  // through more than 2 m of water leaves sheltered lagoons out of the breaking-surf mask.
125
126
  const n = data.resolution;
126
127
  const cell = data.size / (n - 1);
128
+ // The surveyed deepest bed sets the tint range and the open-sea continuation.
129
+ const deepDepth = data.heights.reduce(
130
+ (deepest, height) => Math.max(deepest, level - height),
131
+ cell,
132
+ );
127
133
  const distance = Float32Array.from(data.heights, (height) => (height >= level ? 0 : 1e4));
128
134
  const exposed = new Uint8Array(n * n);
129
135
  const queue: number[] = [];
@@ -207,12 +213,15 @@ function createSeaMesh(ocean: SpectralOcean, data: ICoastalSeaData): Mesh {
207
213
  roughness: 0.12,
208
214
  });
209
215
  const shoreUV = (x: Node<"float">, z: Node<"float">) =>
210
- vec2(x.div(data.size).add(0.5), z.div(data.size).add(0.5));
216
+ vec2(x.div(data.size).add(0.5), z.div(data.size).add(0.5))
217
+ .mul((n - 1) / n)
218
+ .add(0.5 / n);
219
+ // Outside the surveyed bed, continue its edge depth before easing into open sea.
211
220
  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())));
221
+ float(1).sub(smoothstep(data.size / 2, data.size * 0.75, x.abs().max(z.abs())));
213
222
  const vertexLand = texture(heightTexture, shoreUV(positionLocal.x, positionLocal.z)).r;
214
223
  const vertexDepth = mix(
215
- float(28),
224
+ float(deepDepth),
216
225
  float(level).sub(vertexLand),
217
226
  inside(positionLocal.x, positionLocal.z),
218
227
  );
@@ -246,7 +255,7 @@ function createSeaMesh(ocean: SpectralOcean, data: ICoastalSeaData): Mesh {
246
255
  );
247
256
  const shore = texture(heightTexture, shoreUV(positionWorld.x, positionWorld.z));
248
257
  const local = inside(positionWorld.x, positionWorld.z);
249
- const depth = mix(float(28), positionWorld.y.sub(shore.r), local);
258
+ const depth = mix(float(deepDepth), float(level).sub(shore.r), local);
250
259
  const damp = smoothstep(0.1, 2.5, depth);
251
260
  const wind = mx_noise_float(
252
261
  vec3(positionWorld.x.mul(0.07).sub(time.mul(0.04)), positionWorld.z.mul(0.07), time.mul(0.015)),
@@ -269,24 +278,48 @@ function createSeaMesh(ocean: SpectralOcean, data: ICoastalSeaData): Mesh {
269
278
  const bounced = view.negate().reflect(normal);
270
279
  // The standard material supplies Fresnel and the sun's specular lobe; the sky supplies the radiance.
271
280
  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
- )
281
+ const water = mix(
282
+ OCEAN_LOOK.shallow,
283
+ OCEAN_LOOK.deep,
284
+ smoothstep(deepDepth * 0.25, deepDepth, depth).pow(2),
285
+ );
286
+ const surfPoint = vec3(positionWorld.x, positionWorld.z, time.mul(0.45));
287
+ const broadSurf = mx_noise_float(surfPoint.mul(vec3(0.18, 0.18, 0.3)))
288
+ .mul(0.5)
289
+ .add(0.5);
290
+ const surf = mx_noise_float(surfPoint.mul(vec3(0.9, 0.9, 1)))
276
291
  .mul(0.5)
277
292
  .add(0.5);
293
+ // A pixel covering a bubble fades it out; derivative-wide thresholds soften the remaining edges.
294
+ const footprint = fwidth(positionWorld.xz).length().mul(0.9);
295
+ const antialias = fwidth(surf).max(0.025);
296
+ const bubbles = smoothstep(
297
+ float(0.5).sub(broadSurf.mul(0.16)).sub(antialias),
298
+ float(0.65).sub(broadSurf.mul(0.16)).add(antialias),
299
+ surf,
300
+ ).mul(float(1).sub(smoothstep(0.35, 1, footprint)));
301
+ const shoreReach = float(1)
302
+ .sub(smoothstep(3, 12, shore.g))
303
+ .mul(shore.b.mul(0.65).add(0.35))
304
+ .mul(local);
278
305
  const shoreFoam = float(1)
279
- .sub(smoothstep(0.25, 1.8, depth))
306
+ .sub(smoothstep(0.25, 1.8, depth.add(time.mul(0.85).sin().mul(0.18))))
280
307
  .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);
308
+ .mul(bubbles)
309
+ .mul(broadSurf.mul(0.6).add(0.25))
310
+ .mul(shoreReach);
311
+ const swash = float(1)
312
+ .sub(smoothstep(0.1, 2.5, depth))
313
+ .mul(smoothstep(0, 0.12, depth))
314
+ .mul(broadSurf.mul(0.5).add(0.5))
315
+ .mul(shoreReach)
316
+ .mul(0.12);
317
+ material.colorNode = mix(water, color(FOAM), shoreFoam.add(swash));
287
318
  // The surface runs to the fogged horizon, and fades into the sky there rather than ending on a hard band.
288
319
  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);
320
+ material.opacityNode = smoothstep(0, Math.min(2.5, deepDepth), depth)
321
+ .max(shoreFoam.mul(0.9))
322
+ .mul(horizonFade);
290
323
  material.roughnessNode = mix(
291
324
  float(0.12).add(smoothstep(70, 700, eyeDistance).mul(0.07)),
292
325
  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.