@threenative/terrain 0.1.11 → 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 (218) hide show
  1. package/README.md +1 -0
  2. package/dist/bake-DJ5cxg0C.d.ts +82 -0
  3. package/dist/editor/index.d.ts +4 -4
  4. package/dist/editor/index.js +1 -1
  5. package/dist/editor/server.d.ts +2 -2
  6. package/dist/editor/worker.d.ts +1 -1
  7. package/dist/editor/worker.js +1 -1
  8. package/dist/export.d.ts +1 -1
  9. package/dist/index.d.ts +51 -222
  10. package/dist/index.js +111 -2
  11. package/dist/kit-world.d.ts +107 -0
  12. package/dist/kit-world.js +5134 -0
  13. package/dist/kit.d.ts +21 -4
  14. package/dist/kit.js +19 -4
  15. package/dist/mcp/cook-child.js +9 -6
  16. package/dist/mcp/server.js +14 -4
  17. package/dist/prop-package-Dwz0EWoB.d.ts +141 -0
  18. package/dist/{server-B5RdvEAC.d.ts → server-LnFwY8sr.d.ts} +1 -1
  19. package/dist/starter.d.ts +1141 -6
  20. package/dist/starter.js +1999 -17
  21. package/dist/{terrain-CAEaW0mQ.d.ts → terrain-DYCyAOCJ.d.ts} +1 -1
  22. package/dist/three.d.ts +1 -1
  23. package/dist/{types-BpH00qsx.d.ts → types-kpI0C4hW.d.ts} +1 -1
  24. package/dist/{world-package-B8QgHjAQ.d.ts → world-package-DqJC3-Nn.d.ts} +2 -2
  25. package/docs/authoring/new-environment.md +97 -0
  26. package/package.json +8 -8
  27. package/starter/alpine/README.md +22 -14
  28. package/starter/alpine/bake.mjs +14 -1
  29. package/starter/alpine/biome.data.json +187 -25
  30. package/starter/alpine/heightmap.r16 +0 -0
  31. package/starter/alpine/playerRig.ts +89 -0
  32. package/starter/alpine/recipe.json +169 -15
  33. package/starter/alpine/render/bakedFile.ts +17 -0
  34. package/starter/alpine/render/benchmark.ts +77 -0
  35. package/starter/alpine/render/biomeData.ts +14 -0
  36. package/starter/alpine/render/biomes.ts +687 -0
  37. package/starter/alpine/render/ground/cover.ts +565 -0
  38. package/starter/alpine/render/ground/horizon.ts +219 -0
  39. package/starter/alpine/render/ground/palette.d.ts +1 -0
  40. package/starter/alpine/render/ground/palette.js +11 -0
  41. package/starter/alpine/render/ground/scatter.ts +104 -0
  42. package/starter/alpine/render/ground/terrain.ts +1860 -0
  43. package/starter/alpine/render/kitAssets.ts +28 -0
  44. package/starter/alpine/render/loading.ts +354 -0
  45. package/starter/alpine/render/lookKnobs.ts +37 -0
  46. package/starter/alpine/render/orbitCamera.ts +155 -0
  47. package/starter/alpine/render/props/farForest.ts +94 -0
  48. package/starter/alpine/render/props/pack.ts +1114 -0
  49. package/starter/alpine/render/props/prepared.ts +225 -0
  50. package/starter/alpine/render/props/propMaterials.ts +1239 -0
  51. package/starter/alpine/render/props/propProgress.ts +2 -0
  52. package/starter/alpine/render/props/propWorld.ts +105 -0
  53. package/starter/alpine/render/props/props.ts +633 -0
  54. package/starter/alpine/render/props/spruce.ts +440 -0
  55. package/starter/alpine/render/sky/atmosphere.ts +329 -0
  56. package/starter/alpine/render/sky/sky.ts +382 -0
  57. package/starter/alpine/render/texturePreparation.ts +135 -0
  58. package/starter/alpine/render/water/river.ts +1132 -0
  59. package/starter/alpine/render/worldNames.ts +6 -0
  60. package/starter/alpine/scene.ts +715 -0
  61. package/starter/alpine/sceneProps.ts +561 -0
  62. package/starter/alpine/sceneState.ts +33 -0
  63. package/starter/alpine/world/terrainAssets.ts +145 -0
  64. package/starter/alpine/world/walkBand.ts +47 -0
  65. package/starter/alpine/world/water.ts +74 -0
  66. package/starter/alpine/worlds.ts +13 -0
  67. package/starter/coastal/README.md +26 -27
  68. package/starter/coastal/assets.json +10 -0
  69. package/starter/coastal/bake.mjs +14 -1
  70. package/starter/coastal/biome.data.json +18 -3
  71. package/starter/coastal/playerRig.ts +89 -0
  72. package/starter/coastal/recipe.json +220 -18
  73. package/starter/coastal/render/bakedFile.ts +17 -0
  74. package/starter/coastal/render/benchmark.ts +81 -0
  75. package/starter/coastal/render/biomeData.ts +14 -0
  76. package/starter/coastal/render/biomes.ts +678 -0
  77. package/starter/coastal/render/ground/cover.ts +565 -0
  78. package/starter/coastal/render/ground/horizon.ts +219 -0
  79. package/starter/coastal/render/ground/palette.d.ts +1 -0
  80. package/starter/coastal/render/ground/palette.js +11 -0
  81. package/starter/coastal/render/ground/scatter.ts +104 -0
  82. package/starter/coastal/render/ground/terrain.ts +1829 -0
  83. package/starter/coastal/render/kitAssets.ts +28 -0
  84. package/starter/coastal/render/loading.ts +354 -0
  85. package/starter/coastal/render/lookKnobs.ts +37 -0
  86. package/starter/coastal/render/orbitCamera.ts +155 -0
  87. package/starter/coastal/render/props/farForest.ts +94 -0
  88. package/starter/coastal/render/props/pack.ts +1109 -0
  89. package/starter/coastal/render/props/prepared.ts +225 -0
  90. package/starter/coastal/render/props/propMaterials.ts +1239 -0
  91. package/starter/coastal/render/props/propProgress.ts +2 -0
  92. package/starter/coastal/render/props/propWorld.ts +105 -0
  93. package/starter/coastal/render/props/props.ts +633 -0
  94. package/starter/coastal/render/props/spruce.ts +440 -0
  95. package/starter/coastal/render/sky/atmosphere.ts +329 -0
  96. package/starter/coastal/render/sky/sky.ts +382 -0
  97. package/starter/coastal/render/texturePreparation.ts +135 -0
  98. package/starter/coastal/render/water/ocean.ts +284 -0
  99. package/starter/coastal/render/water/river.ts +1132 -0
  100. package/starter/coastal/render/worldNames.ts +6 -0
  101. package/starter/coastal/scene.ts +740 -0
  102. package/starter/coastal/sceneProps.ts +559 -0
  103. package/starter/coastal/sceneState.ts +33 -0
  104. package/starter/coastal/world/terrainAssets.ts +151 -0
  105. package/starter/coastal/world/walkBand.ts +47 -0
  106. package/starter/coastal/world/water.ts +74 -0
  107. package/starter/coastal/worlds.ts +13 -0
  108. package/starter/desert/README.md +51 -25
  109. package/starter/desert/bake-flora.mjs +142 -0
  110. package/starter/desert/bake-rocks.mjs +291 -0
  111. package/starter/desert/bake.mjs +14 -1
  112. package/starter/desert/biome.data.json +24 -12
  113. package/starter/desert/playerRig.ts +89 -0
  114. package/starter/desert/recipe.json +63 -16
  115. package/starter/desert/render/bakedFile.ts +17 -0
  116. package/starter/desert/render/benchmark.ts +79 -0
  117. package/starter/desert/render/biomeData.ts +14 -0
  118. package/starter/desert/render/biomes.ts +660 -0
  119. package/starter/desert/render/ground/cover.ts +565 -0
  120. package/starter/desert/render/ground/debris.ts +136 -0
  121. package/starter/desert/render/ground/horizon.ts +219 -0
  122. package/starter/desert/render/ground/palette.d.ts +1 -0
  123. package/starter/desert/render/ground/palette.js +11 -0
  124. package/starter/desert/render/ground/scatter.ts +104 -0
  125. package/starter/desert/render/ground/terrain.ts +1854 -0
  126. package/starter/desert/render/kitAssets.ts +28 -0
  127. package/starter/desert/render/loading.ts +354 -0
  128. package/starter/desert/render/lookKnobs.ts +37 -0
  129. package/starter/desert/render/orbitCamera.ts +155 -0
  130. package/starter/desert/render/props/farForest.ts +96 -0
  131. package/starter/desert/render/props/formations.ts +630 -0
  132. package/starter/desert/render/props/pack.ts +1195 -0
  133. package/starter/desert/render/props/prepared.ts +225 -0
  134. package/starter/desert/render/props/propMaterials.ts +1255 -0
  135. package/starter/desert/render/props/propProgress.ts +2 -0
  136. package/starter/desert/render/props/propWorld.ts +105 -0
  137. package/starter/desert/render/props/props.ts +624 -0
  138. package/starter/desert/render/props/spruce.ts +440 -0
  139. package/starter/desert/render/sand.ts +581 -0
  140. package/starter/desert/render/sky/atmosphere.ts +329 -0
  141. package/starter/desert/render/sky/sky.ts +382 -0
  142. package/starter/desert/render/texturePreparation.ts +135 -0
  143. package/starter/desert/render/water/river.ts +1132 -0
  144. package/starter/desert/render/worldNames.ts +6 -0
  145. package/starter/desert/scene.ts +748 -0
  146. package/starter/desert/sceneProps.ts +562 -0
  147. package/starter/desert/sceneState.ts +33 -0
  148. package/starter/desert/world/terrainAssets.ts +162 -0
  149. package/starter/desert/world/walkBand.ts +47 -0
  150. package/starter/desert/world/water.ts +74 -0
  151. package/starter/desert/worlds.ts +13 -0
  152. package/starter/forest/README.md +8 -5
  153. package/starter/forest/bake.mjs +21 -413
  154. package/starter/forest/playerRig.ts +37 -171
  155. package/starter/forest/recipe.json +237 -47
  156. package/starter/forest/render/biomes.ts +2 -1
  157. package/starter/forest/render/ground/horizon.ts +4 -302
  158. package/starter/forest/render/ground/terrain.ts +14 -32
  159. package/starter/forest/render/kitAssets.ts +3 -2
  160. package/starter/forest/render/props/farForest.ts +2 -1
  161. package/starter/forest/render/props/pack.ts +4 -2
  162. package/starter/forest/render/props/prepared.ts +2 -1
  163. package/starter/forest/render/props/propProgress.ts +1 -11
  164. package/starter/forest/render/props/propWorld.ts +48 -662
  165. package/starter/forest/render/props/props.ts +64 -248
  166. package/starter/forest/render/sky/sky.ts +2 -1
  167. package/starter/forest/render/worldNames.ts +6 -2
  168. package/starter/forest/scene.ts +34 -25
  169. package/starter/forest/sceneProps.ts +2 -2
  170. package/starter/forest/sceneState.ts +5 -4
  171. package/starter/forest/surface.json +2 -2
  172. package/starter/forest/worlds.ts +3 -2
  173. package/starter/tundra/README.md +35 -16
  174. package/starter/tundra/bake.mjs +14 -1
  175. package/starter/tundra/biome.data.json +6 -6
  176. package/starter/tundra/playerRig.ts +89 -0
  177. package/starter/tundra/recipe.json +111 -110
  178. package/starter/tundra/render/bakedFile.ts +17 -0
  179. package/starter/tundra/render/benchmark.ts +79 -0
  180. package/starter/tundra/render/biomeData.ts +14 -0
  181. package/starter/tundra/render/biomes.ts +714 -0
  182. package/starter/tundra/render/ground/cover.ts +565 -0
  183. package/starter/tundra/render/ground/horizon.ts +219 -0
  184. package/starter/tundra/render/ground/palette.d.ts +1 -0
  185. package/starter/tundra/render/ground/palette.js +11 -0
  186. package/starter/tundra/render/ground/scatter.ts +104 -0
  187. package/starter/tundra/render/ground/terrain.ts +1874 -0
  188. package/starter/tundra/render/kitAssets.ts +28 -0
  189. package/starter/tundra/render/loading.ts +354 -0
  190. package/starter/tundra/render/lookKnobs.ts +37 -0
  191. package/starter/tundra/render/orbitCamera.ts +155 -0
  192. package/starter/tundra/render/props/farForest.ts +96 -0
  193. package/starter/tundra/render/props/pack.ts +1088 -0
  194. package/starter/tundra/render/props/prepared.ts +225 -0
  195. package/starter/tundra/render/props/propMaterials.ts +1247 -0
  196. package/starter/tundra/render/props/propProgress.ts +2 -0
  197. package/starter/tundra/render/props/propWorld.ts +105 -0
  198. package/starter/tundra/render/props/props.ts +624 -0
  199. package/starter/tundra/render/props/spruce.ts +440 -0
  200. package/starter/tundra/render/sky/atmosphere.ts +329 -0
  201. package/starter/tundra/render/sky/sky.ts +382 -0
  202. package/starter/tundra/render/texturePreparation.ts +135 -0
  203. package/starter/tundra/render/water/river.ts +1132 -0
  204. package/starter/tundra/render/worldNames.ts +6 -0
  205. package/starter/tundra/scene.ts +715 -0
  206. package/starter/tundra/sceneProps.ts +559 -0
  207. package/starter/tundra/sceneState.ts +33 -0
  208. package/starter/tundra/world/terrainAssets.ts +159 -0
  209. package/starter/tundra/world/walkBand.ts +47 -0
  210. package/starter/tundra/world/water.ts +74 -0
  211. package/starter/tundra/worlds.ts +13 -0
  212. package/starter-assets.json +4 -4
  213. package/starter-credits.json +613 -10
  214. package/starter/forest/diagnostics.ts +0 -1020
  215. package/starter/forest/render/sky/skyVisibility.ts +0 -121
  216. package/starter/forest/spawnGate.ts +0 -183
  217. package/starter/forest/viewStatistics.ts +0 -47
  218. package/starter/forest/world/streamedGround.ts +0 -139
@@ -0,0 +1,382 @@
1
+ // Game-owned sun, shadows and daylight; atmosphere.ts owns the LUT sky and surface air.
2
+ import { Atmosphere, Daylight, type ICtx, VirtualShadowNode } from "@threenative/core";
3
+ import { Color, DirectionalLight, Mesh, type Object3D, SphereGeometry, Vector3 } from "three";
4
+ import { denoise } from "three/addons/tsl/display/DenoiseNode.js";
5
+ import { ao } from "three/addons/tsl/display/GTAONode.js";
6
+ import { traa } from "three/addons/tsl/display/TRAANode.js";
7
+ import {
8
+ abs,
9
+ cameraPosition,
10
+ dot,
11
+ float,
12
+ getViewPosition,
13
+ max,
14
+ mix,
15
+ mrt,
16
+ normalView,
17
+ normalize,
18
+ output,
19
+ pass,
20
+ positionWorld,
21
+ saturation,
22
+ screenSize,
23
+ screenUV,
24
+ smoothstep,
25
+ uniform,
26
+ vec2,
27
+ vec3,
28
+ vec4,
29
+ } from "three/tsl";
30
+ import type { Node } from "three/webgpu";
31
+ import { BIOMES, type IBiome } from "../biomes.js";
32
+ import { setCanopySun } from "../props/propMaterials.js";
33
+ import { WORLD } from "../worldNames.js";
34
+ import { aerialPerspective, cloudDome, createAtmosphere, skyColour } from "./atmosphere.js";
35
+
36
+ /**
37
+ * The sun, in the same units the `L` key swings it: a position, not a direction, so the toggle and
38
+ * the playtest's `sunX` read the same number they always have.
39
+ */
40
+ export const SUN = {
41
+ colour: new Color(0xffeed0),
42
+ /** Towards the sun. A 35 degree afternoon sun: high enough to light the meadow, low enough that
43
+ * every spruce throws a shadow long enough to see the ground between the trees. */
44
+ direction: new Vector3(-180, 150, -120),
45
+ /** Irradiance in three's physical units — the same number a Blender sun strength carries. */
46
+ intensity: 4.6,
47
+ } as const;
48
+
49
+ /**
50
+ * The physical sky, the fill and the haze.
51
+ *
52
+ * The `sky` numbers are Preetham's, as three's `SkyMesh` takes them: low turbidity for clean air,
53
+ * rayleigh near 2.4 for a deep blue zenith, and a small mie coefficient so the sun's halo stays a
54
+ * halo. `haze` is the horizon colour the sky itself fades to and the density the ground fades to it
55
+ * at: a 300 metre ridge is a third hazed, which is the aerial perspective the alpine reference is
56
+ * built on, and the sea's far edge is gone before it reaches its own boundary.
57
+ */
58
+ /**
59
+ * The sun's direction as a shader node, for anything in the scene that has to agree with the light:
60
+ * the water's glint and its caustics read this rather than normalising `SUN.direction` a second time,
61
+ * so `L` moves them with the rig.
62
+ */
63
+ export const SUN_VECTOR = uniform(SUN.direction.clone().normalize()) as unknown as Node<"vec3">;
64
+
65
+ const RIG = {
66
+ sky: { turbidity: 2.0, rayleigh: 3.0, mieCoefficient: 0.003, mieDirectionalG: 0.82 },
67
+ /** Blue sky fill preserves detail in shade without cancelling the directional sun. */
68
+ fill: { sky: new Color(0xa8c8e8), ground: new Color(0x464937), intensity: 0.62 },
69
+ /** Near terrain stays clear; kilometre-scale ridges fade gradually into blue air. */
70
+ haze: { color: new Color(0x8ca8ba), density: 0.0008 },
71
+ /** Linear exposure for the AgX curve, as 2^EV. AgX already rolls its highlights off, so this sits
72
+ * below one: a temperate noon here is a bright sky and green that still has detail in it. */
73
+ exposure: 2 ** -0.38,
74
+ /** Edge of the sky box in metres. The camera's far plane is 5000, and the box's corners are half a
75
+ * diagonal inside that, so this is as large as the world can carry. */
76
+ skySize: 5000,
77
+ /** Two cached levels retain four bindings; alpine/desert refine the far level to 15.6 cm. */
78
+ shadowExtents: [24, 320],
79
+ } as const;
80
+
81
+ /** The sun's outer shadow window, metres: past it the shadow fades out and nothing is shaded. */
82
+ export const SHADOW_REACH: number = RIG.shadowExtents[1];
83
+
84
+ /** The rig, the sun that can be swung, and the one call that moves both. */
85
+ export interface IOutdoorSky {
86
+ /** Installed follow, fill, shadows and tone mapping. Add it to the scene. */
87
+ readonly daylight: Daylight;
88
+ /** Add through ctx.add so its LUT kernels warm before the first world draw. */
89
+ readonly atmosphere: Atmosphere;
90
+ /** This game's sun, with the rig's clipmap shadows on it. Add it to the scene. */
91
+ readonly sun: DirectionalLight;
92
+ /** The sun's x in the sun's own metres: what the `L` key swings and the playtest reads. */
93
+ readonly sunX: number;
94
+ setSunX(x: number): void;
95
+ /** Aim the sun along a world vector: the light, the sky, the air and the needles follow. */
96
+ setSunDirection(x: number, y: number, z: number): void;
97
+ /**
98
+ * Centre the sun's shadow levels, and the fade of the outer one, on the player instead of the camera
99
+ * (`undefined` hands them back). The orbit camera's eye travels a 9 m arm when it turns; windows, level
100
+ * picks and the fade centred on the eye moved shadow edges with it. Call it each frame with the player.
101
+ */
102
+ focusShadows(point: Vector3 | undefined): void;
103
+ }
104
+
105
+ /** Shared daylight plumbing with game-owned LUT sky, clouds and surface air. */
106
+ /**
107
+ * `renderer` is read only to tell the two engines apart: the owned engine publishes `info.engine`,
108
+ * upstream three does not.
109
+ */
110
+ export function createOutdoorSky(
111
+ camera: Object3D,
112
+ biome?: IBiome,
113
+ renderer?: { readonly info?: unknown },
114
+ ): IOutdoorSky {
115
+ const direction = biome ? new Vector3(...biome.sun.direction) : SUN.direction;
116
+ const sunColor = biome ? new Color(biome.sun.color) : SUN.colour;
117
+ const rig = biome
118
+ ? {
119
+ ...RIG,
120
+ sky: biome.sky,
121
+ fill: {
122
+ sky: new Color(biome.fill.sky),
123
+ ground: new Color(biome.fill.ground),
124
+ intensity: biome.fill.intensity,
125
+ },
126
+ haze: { color: new Color(biome.haze.color), density: biome.haze.density },
127
+ exposure: biome.exposure,
128
+ }
129
+ : RIG;
130
+ const look = biome ?? BIOMES.desert;
131
+ const sun = new DirectionalLight(sunColor, biome?.sun.intensity ?? SUN.intensity);
132
+ sun.name = "temperate-sun";
133
+ sun.castShadow = true;
134
+ sun.shadow.radius = biome?.sun.shadowRadius ?? BIOMES[WORLD].sun.shadowRadius;
135
+ // The owned engine (the default) filters its own virtual shadow maps with PCF; upstream three's
136
+ // `PCFShadowFilter` node is refused by name there (`TN_NATIVE_UNCATALOGUED_PCFSHADOWFILTER`), so the
137
+ // kit names no filter node.
138
+ const engineInfo = (renderer?.info as { engine?: unknown } | null | undefined)?.engine;
139
+ const mapSize = look.shadowMapSize;
140
+ // A look whose stones showed a lit rim wins a normal bias tied to the shadow resolution; every
141
+ // other look keeps its judged bias until close-ups prove a change.
142
+ const tightContacts = look.tightShadowContacts;
143
+ sun.shadow.normalBias = tightContacts ? (2 * rig.shadowExtents[0]) / mapSize : 0.035;
144
+ const outerExtent = rig.shadowExtents[rig.shadowExtents.length - 1] ?? 320;
145
+ const shadows = new VirtualShadowNode(sun, {
146
+ clipExtents: [...rig.shadowExtents],
147
+ mapSize,
148
+ // engine-override: footprint-wide slope bias detaches low-relief contacts such as beach stones.
149
+ ...(tightContacts ? { receiverPlaneBias: false } : {}),
150
+ ...(look.shadowRefreshStep ? { refreshStep: [...look.shadowRefreshStep] } : {}),
151
+ // engine-override: the owned engine cannot measure the depth of wind-swayed (GPU-deformed) casters, so
152
+ // its light-space depth spans the outer cascade's whole window. The three.js path keeps derived depth.
153
+ ...(engineInfo === undefined
154
+ ? {}
155
+ : { lightDistance: 2 * outerExtent, depthRange: 4 * outerExtent }),
156
+ });
157
+ // The fade is centred where the windows are: the eye, or the player once `focusShadows` names it.
158
+ const focusAt = uniform(new Vector3());
159
+ const focusOn = uniform(0);
160
+ // Fade the outer cascade before its cached window ends, including its refresh trail.
161
+ const shadowSetup = shadows.setup.bind(shadows);
162
+ shadows.setup = (builder) => {
163
+ const value = shadowSetup(builder);
164
+ if (!value) return value;
165
+ const right = normalize(SUN_VECTOR.cross(vec3(0, 1, 0)));
166
+ const up = normalize(right.cross(SUN_VECTOR));
167
+ const offset = positionWorld.sub(mix(cameraPosition, focusAt, focusOn));
168
+ const distance = max(abs(dot(offset, right)), abs(dot(offset, up)));
169
+ const extent = rig.shadowExtents[rig.shadowExtents.length - 1] ?? 320;
170
+ return mix(
171
+ vec4(value as Node<"vec4">),
172
+ vec4(1),
173
+ smoothstep(extent * 0.65, extent * 0.8, distance),
174
+ );
175
+ };
176
+ sun.shadow.shadowNode = shadows;
177
+ // A fixed world-origin target keeps the L-key direction independent of the following sky.
178
+ sun.position.copy(direction);
179
+
180
+ const daylight = new Daylight({
181
+ exposure: rig.exposure,
182
+ fill: rig.fill,
183
+ follow: camera,
184
+ haze: rig.haze,
185
+ shadowExtents: [...rig.shadowExtents],
186
+ sky: rig.sky,
187
+ skySize: RIG.skySize,
188
+ sunColor,
189
+ sunDirection: direction,
190
+ sunIntensity: 0,
191
+ toneMapping: (biome ?? BIOMES.desert).toneMapping,
192
+ });
193
+ const atmosphere = createAtmosphere(biome ?? BIOMES.desert);
194
+ atmosphere.setSunDirection(direction);
195
+ daylight.sky.cloudCoverage.value = 0;
196
+ daylight.sky.material.colorNode = skyColour(atmosphere, SUN_VECTOR, biome ?? BIOMES.desert);
197
+ daylight.sun.visible = false; // engine-override: omit the sun disc while retaining directional lighting
198
+ daylight.add(sun.target);
199
+
200
+ const sunDirection = SUN_VECTOR;
201
+ // The deck rides inside the rig's own sky box, so it needs no follow of its own: the box is put
202
+ // back on the eye every frame and the dome is its child. 64 by 32 is enough, because the pattern
203
+ // is per fragment and nothing here is shaded from the dome's own normals.
204
+ const deck = new Mesh(
205
+ new SphereGeometry(1, 64, 32),
206
+ cloudDome(atmosphere, sunDirection, biome ?? BIOMES.desert),
207
+ );
208
+ deck.name = "cumulus-deck";
209
+ deck.scale.setScalar(0.9);
210
+ deck.frustumCulled = false;
211
+ daylight.sky.add(deck);
212
+
213
+ function setSunX(x: number): void {
214
+ setSunDirection(x, direction.y, direction.z);
215
+ }
216
+ function setSunDirection(x: number, y: number, z: number): void {
217
+ sun.position.set(x, y, z);
218
+ // The sky's sun disc, its brightest quadrant and the cloud deck's lighting all follow the light.
219
+ daylight.sky.sunPosition.value.copy(sun.position).normalize();
220
+ atmosphere.setSunDirection(sun.position);
221
+ (sunDirection as unknown as { value: Vector3 }).value.copy(sun.position).normalize();
222
+ // And so does the light coming through the needles, which reads the same vector.
223
+ setCanopySun(sun.position);
224
+ }
225
+ setSunX(direction.x);
226
+ return {
227
+ atmosphere,
228
+ daylight,
229
+ get sunX() {
230
+ return sun.position.x;
231
+ },
232
+ setSunX,
233
+ setSunDirection,
234
+ sun,
235
+ focusShadows(point: Vector3 | undefined) {
236
+ shadows.setFocus(point);
237
+ if (point !== undefined) focusAt.value.copy(point);
238
+ focusOn.value = point === undefined ? 0 : 1;
239
+ },
240
+ };
241
+ }
242
+
243
+ export function createOutdoorTRAA(
244
+ input: Node,
245
+ depth: Parameters<typeof traa>[1],
246
+ velocityNode: Parameters<typeof traa>[2],
247
+ camera: ICtx["camera"],
248
+ renderer: Pick<ICtx["renderer"], "surface">,
249
+ ): Node {
250
+ const node = traa(input as Node<"vec4">, depth, velocityNode as never, camera) as unknown as Node;
251
+ const surface = renderer.surface();
252
+ Reflect.get(node, "beautyNode").setSize(surface.drawingBufferWidth, surface.drawingBufferHeight);
253
+ return node;
254
+ }
255
+
256
+ /** Contact-scale occlusion through the installed chain; daylight still owns exposure and tone. */
257
+ export function installOutdoorOcclusion(
258
+ ctx: Pick<ICtx, "renderer" | "scene" | "camera">,
259
+ biome?: IBiome,
260
+ ): () => void {
261
+ const { renderer, scene, camera } = ctx;
262
+ if (renderer.kind !== "webgpu" || renderer.createRenderChain === undefined) return () => {};
263
+ const look = biome ?? BIOMES.desert;
264
+ const previousFog = scene.fogNode;
265
+ const previousClassicFog = scene.fog;
266
+ const atmosphere = scene.getObjectByName("world-atmosphere");
267
+ if (!(atmosphere instanceof Atmosphere))
268
+ throw new Error("Outdoor sky must be added before its air.");
269
+ // Disable the rig's legacy material fog; air is composited once after the lit scene.
270
+ scene.fogNode = null;
271
+ scene.fog = null;
272
+ // AO darkens RGB only; multiplying alpha leaked the backdrop through dark alpine crags.
273
+ // 4x MSAA is the anti-aliasing: TRAA left every still pixel jittering (frame-to-frame change 20x
274
+ // MSAA's on a still camera).
275
+ const world = pass(scene, camera);
276
+ world.setMRT(mrt({ output, normal: normalView }));
277
+ const daylight = scene.children.find((child) => child instanceof Daylight);
278
+ const depth = world.getTextureNode("depth");
279
+ // An uncovered MSAA depth sample must not leave a one-pixel terrain edge against the sky.
280
+ // Single-sampled under TRAA there is no uncovered sample, and the dilation would paint a hard
281
+ // one-pixel seam of surface air along every silhouette against the sky.
282
+ const airDepth = depth.r.min(depth.sample(screenUV.add(vec2(0, screenSize.y.reciprocal()))).r);
283
+ const cameraWorld = uniform(camera.matrixWorld);
284
+ const surface = cameraWorld.mul(
285
+ vec4(getViewPosition(screenUV, airDepth, uniform(camera.projectionMatrixInverse)), 1),
286
+ ).xyz;
287
+ const air = aerialPerspective(
288
+ atmosphere,
289
+ SUN_VECTOR,
290
+ look,
291
+ true,
292
+ surface,
293
+ cameraWorld.mul(vec4(0, 0, 0, 1)).xyz,
294
+ world.getTextureNode("output"),
295
+ );
296
+ const airOutput = mix(
297
+ air,
298
+ world.getTextureNode("output"),
299
+ airDepth.greaterThanEqual(1).toFloat(),
300
+ );
301
+ // GTAO and its denoise derive normals from depth, as UE 5.8.3 does by default (r.GTAO.UseNormals 0,
302
+ // PostProcessAmbientOcclusion.cpp:104). Nothing then reads the MRT normal, so the engine skips its
303
+ // second full-scene normal pass: forest, RTX 2080, 1600x900, two interleaved rounds, GPU frame
304
+ // 13.9/14.9 -> 10.3/12.6 ms at the player pose and 42.9/48.1 -> 27.8/40.1 ms at the overview.
305
+ // three's typings omit the null its nodes accept.
306
+ const normals = null as unknown as Node;
307
+ const contact = ao(depth, normals, camera);
308
+ contact.radius.value = 0.85;
309
+ contact.scale.value = 0.8;
310
+ contact.samples.value = 8;
311
+ contact.resolutionScale = 0.5;
312
+ const filtered = denoise(contact.getTextureNode(), depth, normals, camera);
313
+ const occlusion = filtered as unknown as Node<"vec4">;
314
+ const chain = renderer.createRenderChain({
315
+ input: airOutput,
316
+ worldPass: world,
317
+ request: {
318
+ stages: ["ambientOcclusion", "grade"],
319
+ tier: "high",
320
+ },
321
+ targetFps: 60,
322
+ stages: [
323
+ {
324
+ name: "ambientOcclusion",
325
+ minimumTier: "medium",
326
+ build: (input) =>
327
+ (input as Node<"vec4">).mul(
328
+ vec4(
329
+ vec3(
330
+ mix(
331
+ 1,
332
+ occlusion.r,
333
+ float(0.72).mul(float(1).sub(smoothstep(40, 180, world.getViewZNode().negate()))),
334
+ ),
335
+ ),
336
+ 1,
337
+ ),
338
+ ),
339
+ },
340
+ {
341
+ name: "traa",
342
+ minimumTier: "high",
343
+ build: (input, context) =>
344
+ createOutdoorTRAA(input as Node, depth, context.velocityNode as never, camera, renderer),
345
+ },
346
+ {
347
+ name: "grade",
348
+ after: "ambientOcclusion",
349
+ minimumTier: "low",
350
+ build: (input) =>
351
+ vec4(
352
+ saturation(
353
+ (input as Node<"vec4">).rgb,
354
+ mix(
355
+ look.saturation,
356
+ look.skySaturation,
357
+ smoothstep(400, 1500, world.getViewZNode().negate()),
358
+ ),
359
+ ),
360
+ // Opaque frame: cutout edges keep coverage alpha through the chain, and an alpha
361
+ // canvas composited them over the page background (a blue-grey fringe on every blade).
362
+ 1,
363
+ ),
364
+ },
365
+ ],
366
+ });
367
+ return () => {
368
+ if (scene.fogNode === null) scene.fogNode = previousFog;
369
+ if (scene.fog === null) scene.fog = previousClassicFog;
370
+ // The example owns these shadow maps. Removing the lights alone retained their targets.
371
+ const sun = scene.getObjectByName("temperate-sun");
372
+ for (const light of [sun, daylight instanceof Daylight ? daylight.sun : undefined]) {
373
+ if (!(light instanceof DirectionalLight)) continue;
374
+ if (light.shadow.shadowNode instanceof VirtualShadowNode) light.shadow.shadowNode.dispose();
375
+ light.dispose();
376
+ }
377
+ chain.dispose();
378
+ world.dispose();
379
+ contact.dispose();
380
+ filtered.dispose();
381
+ };
382
+ }
@@ -0,0 +1,135 @@
1
+ import type { ICtx } from "@threenative/core";
2
+ import type { Material, Texture } from "three";
3
+ import type { MeshPhysicalNodeMaterial, Node } from "three/webgpu";
4
+
5
+ // These are the texture inputs used by Strata's ordinary and node-based prop surfaces.
6
+ const mapInputs = [
7
+ "map",
8
+ "normalMap",
9
+ "alphaMap",
10
+ "aoMap",
11
+ "roughnessMap",
12
+ "metalnessMap",
13
+ "emissiveMap",
14
+ "lightMap",
15
+ "bumpMap",
16
+ "displacementMap",
17
+ "clearcoatMap",
18
+ "clearcoatNormalMap",
19
+ "clearcoatRoughnessMap",
20
+ "transmissionMap",
21
+ "thicknessMap",
22
+ "specularIntensityMap",
23
+ "specularColorMap",
24
+ "envMap",
25
+ ] as const;
26
+ const nodeInputs = [
27
+ "colorNode",
28
+ "normalNode",
29
+ "opacityNode",
30
+ "alphaTestNode",
31
+ "aoNode",
32
+ "roughnessNode",
33
+ "emissiveNode",
34
+ "positionNode",
35
+ "castShadowPositionNode",
36
+ "envNode",
37
+ ] as const;
38
+
39
+ function materialInputs(materials: Iterable<Material>, textures: Set<Texture>): Node[] {
40
+ const nodes: Node[] = [];
41
+ for (const material of new Set(materials)) {
42
+ const surface = material as Material & Partial<MeshPhysicalNodeMaterial>;
43
+ for (const key of mapInputs) {
44
+ const value = surface[key];
45
+ if (value?.isTexture) textures.add(value);
46
+ }
47
+ for (const key of nodeInputs) {
48
+ const node = surface[key];
49
+ if (node?.isNode) nodes.push(node);
50
+ }
51
+ }
52
+ return nodes;
53
+ }
54
+
55
+ function sampledTextures(nodes: Node[], textures: Set<Texture>): Node[] {
56
+ const seen = new Set<Node>();
57
+ const sampledNodes: Node[] = [];
58
+ for (const node of nodes) {
59
+ if (seen.has(node)) continue;
60
+ seen.add(node);
61
+ const sampled = node as Node & { isTextureNode?: boolean; value?: Texture };
62
+ if (sampled.isTextureNode && sampled.value?.isTexture) {
63
+ textures.add(sampled.value);
64
+ sampledNodes.push(node);
65
+ }
66
+ // engine-override: an owned-engine node is opaque (no getChildren); the engine samples the textures
67
+ // in its graph directly, so only its material maps above take part in preparation.
68
+ if (typeof node.getChildren !== "function") continue;
69
+ for (const child of node.getChildren()) nodes.push(child);
70
+ }
71
+ return sampledNodes;
72
+ }
73
+
74
+ /** Points every borrowed material map and TSL texture node at its prepared replacement. */
75
+ function applyReplacements(
76
+ materials: Iterable<Material>,
77
+ sampledNodes: Node[],
78
+ replacements: Map<Texture, Texture>,
79
+ ): number {
80
+ if (replacements.size === 0) return 0;
81
+ const applied = new Set<Texture>();
82
+ for (const material of new Set(materials)) {
83
+ const surface = material as Material &
84
+ Partial<MeshPhysicalNodeMaterial> &
85
+ Record<string, unknown>;
86
+ for (const key of mapInputs) {
87
+ const value = surface[key] as Texture | undefined;
88
+ const prepared = value?.isTexture === true ? replacements.get(value) : undefined;
89
+ if (value?.isTexture && prepared?.isTexture && prepared !== value) {
90
+ surface[key] = prepared;
91
+ if ((value as Texture & { isCompressedTexture?: boolean }).isCompressedTexture)
92
+ applied.add(value);
93
+ }
94
+ }
95
+ }
96
+ for (const node of sampledNodes) {
97
+ const sampled = node as Node & { value?: Texture };
98
+ if (sampled.value === undefined) continue;
99
+ const prepared = replacements.get(sampled.value);
100
+ if (prepared?.isTexture && prepared !== sampled.value) {
101
+ if ((sampled.value as Texture & { isCompressedTexture?: boolean }).isCompressedTexture)
102
+ applied.add(sampled.value);
103
+ sampled.value = prepared;
104
+ }
105
+ }
106
+ return applied.size;
107
+ }
108
+
109
+ /**
110
+ * Borrow actual material texture identities; asset loading continues to own their lifetime. The
111
+ * renderer prepares copies it owns and this call swaps every map and TSL texture node reference
112
+ * for its prepared replacement, so a compressed material samples uploaded GPU data. The numeric
113
+ * completion count, progress callback and errors keep the renderer's contract. Compressed completion
114
+ * reports distinct compressed inputs actually replaced after preparation succeeds.
115
+ */
116
+ export async function preparePropTextures(
117
+ renderer: Pick<ICtx["renderer"], "prepareTextures">,
118
+ materials: Iterable<Material>,
119
+ signal?: AbortSignal,
120
+ onProgress?: (completed: number) => void,
121
+ onCompressedPrepared?: (completed: number) => void,
122
+ ): Promise<number> {
123
+ // Snapshot the iterable once so a generator is not consumed before replacements are applied.
124
+ const materialList = [...new Set(materials)];
125
+ const textures = new Set<Texture>();
126
+ const nodes = materialInputs(materialList, textures);
127
+ const sampledNodes = sampledTextures(nodes, textures);
128
+ if (!renderer.prepareTextures)
129
+ throw new Error("Renderer lacks bounded prop texture preparation.");
130
+ const replacements = new Map<Texture, Texture>();
131
+ const completed = await renderer.prepareTextures(textures, signal, onProgress, replacements);
132
+ const compressedPrepared = applyReplacements(materialList, sampledNodes, replacements);
133
+ onCompressedPrepared?.(compressedPrepared);
134
+ return completed;
135
+ }