@call-me-sensei/toonlab 0.3.0 → 0.4.19

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 (736) hide show
  1. package/README.md +549 -184
  2. package/agents/README.md +59 -0
  3. package/agents/references/anime-art-direction.md +24 -0
  4. package/agents/references/asset-sourcing-policy.md +23 -0
  5. package/agents/references/custom-gap-report.md +16 -0
  6. package/agents/references/geology-playbook.md +118 -0
  7. package/agents/references/mcp-asset-discovery.md +104 -0
  8. package/agents/references/runtime-entry-points.md +174 -0
  9. package/agents/references/style-bundles.md +71 -0
  10. package/agents/skills/claude/asset-sourcing/SKILL.md +275 -0
  11. package/agents/skills/claude/environment/SKILL.md +59 -0
  12. package/agents/skills/claude/game-dev/SKILL.md +100 -0
  13. package/agents/skills/claude/karst-cliff-construction/SKILL.md +258 -0
  14. package/agents/skills/claude/outdoor-world/SKILL.md +492 -0
  15. package/agents/skills/claude/outdoor-world/references/coastal-landform-formation.md +100 -0
  16. package/agents/skills/claude/post-processing/SKILL.md +44 -0
  17. package/agents/skills/claude/rock-ground-shaders/SKILL.md +118 -0
  18. package/agents/skills/claude/rockgen/SKILL.md +30 -0
  19. package/agents/skills/claude/scene-style-application/SKILL.md +74 -0
  20. package/agents/skills/claude/style-presets/SKILL.md +101 -0
  21. package/agents/skills/claude/toon-shading/SKILL.md +44 -0
  22. package/agents/skills/claude/vegetation-sky/SKILL.md +167 -0
  23. package/agents/skills/claude/visual-verification/SKILL.md +136 -0
  24. package/agents/skills/claude/water/SKILL.md +105 -0
  25. package/agents/skills/codex/asset-sourcing/SKILL.md +275 -0
  26. package/agents/skills/codex/environment/SKILL.md +59 -0
  27. package/agents/skills/codex/game-dev/SKILL.md +100 -0
  28. package/agents/skills/codex/karst-cliff-construction/SKILL.md +258 -0
  29. package/agents/skills/codex/outdoor-world/SKILL.md +492 -0
  30. package/agents/skills/codex/outdoor-world/references/coastal-landform-formation.md +100 -0
  31. package/agents/skills/codex/post-processing/SKILL.md +44 -0
  32. package/agents/skills/codex/rock-ground-shaders/SKILL.md +118 -0
  33. package/agents/skills/codex/rockgen/SKILL.md +30 -0
  34. package/agents/skills/codex/scene-style-application/SKILL.md +74 -0
  35. package/agents/skills/codex/style-presets/SKILL.md +101 -0
  36. package/agents/skills/codex/toon-shading/SKILL.md +44 -0
  37. package/agents/skills/codex/vegetation-sky/SKILL.md +167 -0
  38. package/agents/skills/codex/visual-verification/SKILL.md +136 -0
  39. package/agents/skills/codex/water/SKILL.md +105 -0
  40. package/cli/toonlab.mjs +52 -0
  41. package/compose.yaml +20 -0
  42. package/database/apply-sql.mjs +141 -0
  43. package/database/client.mjs +39 -0
  44. package/database/creation-tags.mjs +23 -0
  45. package/database/env.mjs +16 -0
  46. package/database/generation-service.mjs +314 -0
  47. package/database/migrations/0001_local_workspace.sql +120 -0
  48. package/database/migrations/0002_file_ownership.sql +11 -0
  49. package/database/migrations/0003_remove_autosaves_from_library.sql +7 -0
  50. package/database/migrations/0004_catalog_asset_packs.sql +39 -0
  51. package/database/migrations/0005_creation_tag_discovery.sql +1 -0
  52. package/database/migrations/0006_normalize_creation_tags.sql +28 -0
  53. package/database/providers.mjs +465 -0
  54. package/database/repository.mjs +625 -0
  55. package/database/seeds/catalog/0001_empty_official_catalog.sql +4 -0
  56. package/database/seeds/catalog/0002_2026-08.sql +19454 -0
  57. package/mcp/lab-management.mjs +629 -0
  58. package/mcp/public-catalog.mjs +168 -0
  59. package/mcp/server.mjs +1026 -63
  60. package/mcp/vite-plugin.mjs +443 -26
  61. package/mcp/workspace.mjs +26 -1
  62. package/package.json +312 -45
  63. package/scripts/generate-catalog-seed.mjs +297 -0
  64. package/scripts/setup-local.mjs +128 -0
  65. package/src/agents/index.js +7 -0
  66. package/src/agents/sceneStyleOperations.js +169 -0
  67. package/src/asset-policy/catalogLicenses.js +44 -0
  68. package/src/asset-policy/index.js +315 -0
  69. package/src/assetlib/assetRef.js +1 -1
  70. package/src/assetlib/galleryMaterialFamily.js +165 -0
  71. package/src/assetlib/index.js +6 -2
  72. package/src/assetlib/plateau.js +188 -0
  73. package/src/assetlib/plateauLandmarks.js +144 -0
  74. package/src/assetlib/plateauViewer.js +348 -0
  75. package/src/assetlib/sources.js +16 -2
  76. package/src/catalog/manifest.js +11 -1
  77. package/src/catalog/officialCatalog.js +4 -0
  78. package/src/catalog/officialCatalogAssetRuntime.js +313 -0
  79. package/src/catalog/officialCatalogLod.js +150 -0
  80. package/src/catalog/officialCatalogPlacement.js +228 -0
  81. package/src/catalog/officialCatalogProvider.js +334 -0
  82. package/src/character/animationRetarget.js +1082 -0
  83. package/src/character/characterRuntime.js +376 -0
  84. package/src/character/groundStabilizer.js +137 -0
  85. package/src/character/index.js +8 -0
  86. package/src/character/locomotionActions.js +74 -0
  87. package/src/character/locomotionStateMachine.js +241 -0
  88. package/src/character/mannequinAsset.js +15 -0
  89. package/src/character/mannequinAssetUrl.browser.js +4 -0
  90. package/src/character/mannequinAssetUrl.node.js +3 -0
  91. package/src/character/modelLoader.js +92 -12
  92. package/src/character/walkableCharacterRuntime.js +284 -0
  93. package/src/character/waterInteractionController.js +217 -0
  94. package/src/cloud/ambientSkyBaker.js +248 -0
  95. package/src/cloud/cloudLighting.js +1114 -0
  96. package/src/cloud/cloudParams.js +819 -0
  97. package/src/cloud/cloudReprojection.js +563 -0
  98. package/src/cloud/cloudStyle.js +780 -0
  99. package/src/cloud/cloudStyleSnapshots.js +387 -0
  100. package/src/cloud/cloudVolume.js +1903 -0
  101. package/src/cloud/heroCloudRecipe.js +404 -0
  102. package/src/cloud/index.js +42 -0
  103. package/src/cloud/noise/baseShapeVolume.js +331 -0
  104. package/src/cloud/noise/cirrusMap.js +131 -0
  105. package/src/cloud/noise/curlNoise.js +289 -0
  106. package/src/cloud/noise/erosionVolume.js +188 -0
  107. package/src/cloud/noise/noiseVolume.js +202 -0
  108. package/src/cloud/noise/periodicNoise3.js +295 -0
  109. package/src/cloud/noise/weatherMap.js +470 -0
  110. package/src/cloud/paramSchema.js +458 -0
  111. package/src/collisionMetadata.js +320 -0
  112. package/src/core/systemStylePolicy.js +32 -0
  113. package/src/environment/dayCurves.js +146 -0
  114. package/src/environment/environmentGroundFieldPass.js +354 -0
  115. package/src/environment/environmentMaterialAdapter.js +114 -6
  116. package/src/environment/environmentPresets.js +396 -90
  117. package/src/environment/environmentRigs.js +17 -2
  118. package/src/environment/environmentSettings.js +37 -1
  119. package/src/environment/environmentShaderMaterials.js +37 -6
  120. package/src/environment/environmentState.js +133 -0
  121. package/src/environment/environmentSunShadowPass.js +357 -6
  122. package/src/environment/environmentTextureResolver.js +7 -0
  123. package/src/environment/index.js +51 -0
  124. package/src/environment/manufacturedMaterialContract.js +837 -0
  125. package/src/environment/manufacturedReflectionProvider.js +114 -0
  126. package/src/environment/scanAssetStylize.js +4 -4
  127. package/src/environment/surfaceMaterialModes.js +71 -0
  128. package/src/environment/toonLabEnvironmentMaterials.js +353 -0
  129. package/src/environment/toonLabMaterialPassCoupling.js +347 -0
  130. package/src/environment/toonLabNormalIntegration.js +171 -0
  131. package/src/environment/toonLabRockMaterialResolver.js +592 -0
  132. package/src/environment/toonLabSourceDefaultLit.js +444 -0
  133. package/src/environment/toonLabSourceLibrary.js +762 -0
  134. package/src/environment/toonLabSourceMaterials.js +3718 -0
  135. package/src/environment/toonLabSourceSubsurfaceLighting.js +415 -0
  136. package/src/environment/toonLabSourceTemporal.js +717 -0
  137. package/src/environment/toonLabSurfaceLighting.js +364 -0
  138. package/src/environment/toonLabTextureReadiness.js +105 -0
  139. package/src/environment/toonLabTreeMaterials.js +450 -0
  140. package/src/environment/transparentMaterialProfile.js +87 -0
  141. package/src/environment/urbanPropMaterial.js +2874 -0
  142. package/src/ground-shader/groundPrintLayer.js +375 -0
  143. package/src/ground-shader/groundShaderMaterial.js +851 -0
  144. package/src/ground-shader/groundShaderSettings.js +468 -0
  145. package/src/ground-shader/index.js +3 -0
  146. package/src/index.js +52 -22
  147. package/src/lighting/callMeSenseiLightingContract.js +163 -0
  148. package/src/lighting/index.js +14 -7
  149. package/src/lighting/lightingCapabilities.js +2 -2
  150. package/src/lighting/lightingPresets.js +6 -3
  151. package/src/lighting/lightingStyle.js +41 -6
  152. package/src/lighting/lightingSystem.js +140 -1
  153. package/src/lighting/{unrealExport.js → toonLabExport.js} +40 -41
  154. package/src/post/postProcessing.js +71 -12
  155. package/src/react/index.js +66 -0
  156. package/src/renderer/index.js +9 -0
  157. package/src/renderer/rendererConfiguration.js +250 -0
  158. package/src/rock-shader/index.js +3 -0
  159. package/src/rock-shader/rockMaterial.js +1843 -0
  160. package/src/rock-shader/rockShaderRuntime.js +494 -0
  161. package/src/rock-shader/rockShaderSettings.js +869 -0
  162. package/src/rockgen/export/glbExport.js +104 -14
  163. package/src/rockgen/index.js +4 -3
  164. package/src/rockgen/lod/index.js +6 -0
  165. package/src/rockgen/lod/rockLodMetrics.js +168 -0
  166. package/src/rockgen/lod/rockLodPlanner.js +372 -0
  167. package/src/rockgen/lod/rockLodPolicy.js +235 -0
  168. package/src/rockgen/lod/rockLodRuntime.js +124 -0
  169. package/src/rockgen/lod/rockLodSimplifier.js +173 -0
  170. package/src/rockgen/lod/rockLodValidation.js +113 -0
  171. package/src/rockgen/mesh/meshAttributes.js +17 -0
  172. package/src/rockgen/mesh/meshDocument.js +6 -0
  173. package/src/rockgen/rockDocument.js +352 -9
  174. package/src/rockgen/rockgenPresets.js +114 -13
  175. package/src/rockgen/rockgenSettings.js +62 -11
  176. package/src/runtime/index.js +14 -0
  177. package/src/runtime/sceneCollisionRuntime.js +317 -0
  178. package/src/runtime/sceneSurfaceRuntime.js +451 -0
  179. package/src/runtime/sceneUpdateScheduler.js +203 -0
  180. package/src/shaders-tsl/anime.js +9 -2
  181. package/src/shaders-tsl/chunks/environment-ground-field.js +174 -0
  182. package/src/shaders-tsl/chunks/environment-state.js +79 -0
  183. package/src/shaders-tsl/chunks/environment-sun-shadow.js +99 -32
  184. package/src/shaders-tsl/chunks/normalized-hue.js +41 -0
  185. package/src/shaders-tsl/chunks/pass-depth-color.js +4 -2
  186. package/src/shaders-tsl/chunks/scene-depth-color-pass.js +273 -0
  187. package/src/shaders-tsl/chunks/vegetation-style.js +116 -8
  188. package/src/shaders-tsl/chunks/water-color.js +19 -5
  189. package/src/shaders-tsl/chunks/water-shore-state.js +8 -1
  190. package/src/shaders-tsl/chunks/world-noise.js +30 -0
  191. package/src/shaders-tsl/environment.js +123 -17
  192. package/src/shaders-tsl/flower.js +51 -8
  193. package/src/shaders-tsl/grass.js +194 -29
  194. package/src/shaders-tsl/post-composite.js +83 -2
  195. package/src/shaders-tsl/tree-leaf.js +107 -16
  196. package/src/shaders-tsl/water-breaker.js +18 -4
  197. package/src/shaders-tsl/water.js +43 -3
  198. package/src/shaders-tsl/woody-surface.js +59 -7
  199. package/src/sky/atmosphereDome.js +193 -0
  200. package/src/sky/atmosphereParams.js +396 -0
  201. package/src/sky/atmosphereScattering.js +593 -0
  202. package/src/sky/atmosphereSky.js +371 -0
  203. package/src/sky/cloudShadow.js +355 -0
  204. package/src/sky/godRays.js +257 -0
  205. package/src/sky/index.js +55 -1
  206. package/src/sky/nightSky.js +1190 -0
  207. package/src/sky/renderLayers.js +120 -0
  208. package/src/sky/skyColor.js +582 -0
  209. package/src/sky/skyDayCycle.js +244 -0
  210. package/src/sky/skyParams.js +661 -0
  211. package/src/sky/skyPresets.js +772 -0
  212. package/src/sky/skyQualityTiers.js +383 -0
  213. package/src/sky/skyShaderSettings.js +699 -0
  214. package/src/sky/skyStyleSnapshots.js +211 -0
  215. package/src/sky/skySystem.js +1438 -0
  216. package/src/sky/skyTimeKeyframes.js +361 -0
  217. package/src/sky/stylizedSky.js +405 -116
  218. package/src/sky/sunDriver.js +499 -0
  219. package/src/sky/timeOfDay.js +335 -0
  220. package/src/styles/animeGameProfile.js +44 -0
  221. package/src/styles/index.js +134 -0
  222. package/src/styles/manufacturedStyleLabeling.js +204 -0
  223. package/src/styles/sceneLayerDocuments.js +185 -0
  224. package/src/styles/sceneLookComposition.js +156 -0
  225. package/src/styles/sceneQualityApplication.js +152 -0
  226. package/src/styles/sceneQualityProfiles.js +268 -0
  227. package/src/styles/sceneStyleAudit.js +512 -0
  228. package/src/styles/sceneStyleRuntime.js +876 -0
  229. package/src/styles/styleAdapters.js +166 -0
  230. package/src/styles/styleApplication.js +369 -0
  231. package/src/styles/styleBundle.js +444 -91
  232. package/src/styles/styleBundleProvider.js +83 -0
  233. package/src/styles/styleDomains.js +21 -0
  234. package/src/styles/styleInspector.js +262 -0
  235. package/src/styles/styleMaterialContract.js +375 -0
  236. package/src/styles/styleMetadata.js +73 -0
  237. package/src/styles/styleTargetDiscovery.js +162 -0
  238. package/src/styles/styleTargetLabels.js +206 -0
  239. package/src/styles/styleTargetMaterialCoverage.js +137 -0
  240. package/src/styles/styleTransaction.js +272 -0
  241. package/src/texgen/textureGenerators.js +21 -5
  242. package/src/toon/toonSettings.js +4 -0
  243. package/src/vegetation/branchTree.js +302 -0
  244. package/src/vegetation/callMeSenseiGrass.js +183 -0
  245. package/src/vegetation/compiledTree.js +506 -0
  246. package/src/vegetation/contactShadowField.js +107 -0
  247. package/src/vegetation/flowerSpecies.js +10 -2
  248. package/src/vegetation/grass.js +13 -0
  249. package/src/vegetation/grassClump.js +1179 -0
  250. package/src/vegetation/importedVegetationMaterial.js +183 -0
  251. package/src/vegetation/index.js +15 -1
  252. package/src/vegetation/legacyTreePresets.js +120 -0
  253. package/src/vegetation/scatter.js +322 -3
  254. package/src/vegetation/stylizedBush.js +14 -0
  255. package/src/vegetation/stylizedFlower.js +31 -0
  256. package/src/vegetation/stylizedFlowers.js +59 -7
  257. package/src/vegetation/stylizedForest.js +455 -147
  258. package/src/vegetation/stylizedGrass.js +188 -24
  259. package/src/vegetation/stylizedTree.js +378 -46
  260. package/src/vegetation/stylizedTreeFoliage.js +889 -38
  261. package/src/vegetation/stylizedUnderstory.js +230 -0
  262. package/src/vegetation/treeExport.js +262 -47
  263. package/src/vegetation/treeSurfaceTextures.js +337 -0
  264. package/src/vegetation/vegetationShaders.js +617 -28
  265. package/src/version.js +3 -0
  266. package/src/water/water.js +2 -0
  267. package/src/water/waterBreakerSystem.js +2 -0
  268. package/src/water/waterCurrentField.js +1 -0
  269. package/src/water/waterMaterial.js +3 -0
  270. package/src/water/waterRain.js +2 -0
  271. package/src/water/waterScenePasses.js +170 -7
  272. package/src/water/waterSettings.js +235 -43
  273. package/src/water/waterShoreMaterial.js +16 -2
  274. package/src/water/waterShoreStateField.js +1 -1
  275. package/src/water/waterSplashSystem.js +2 -0
  276. package/src/water/waterStageSettings.js +60 -0
  277. package/src/water/waterSurface.js +144 -4
  278. package/src/water/waterUnderwaterAtmosphere.js +288 -0
  279. package/src/water/waterVegetation.js +20 -4
  280. package/src/worldCollision.js +64 -9
  281. package/types/agents/index.d.ts +1 -0
  282. package/types/agents/sceneStyleOperations.d.ts +484 -0
  283. package/types/asset-policy/catalogLicenses.d.ts +5 -0
  284. package/types/asset-policy/index.d.ts +18 -0
  285. package/types/assetlib/ambientcg.d.ts +81 -0
  286. package/types/assetlib/assetRef.d.ts +26 -0
  287. package/types/assetlib/galleryMaterialFamily.d.ts +13 -0
  288. package/types/assetlib/importedEntry.d.ts +18 -0
  289. package/types/assetlib/index.d.ts +16 -0
  290. package/types/assetlib/kaykit.d.ts +112 -0
  291. package/types/assetlib/kaykitStaticIndex.d.ts +38 -0
  292. package/types/assetlib/loadImported.d.ts +54 -0
  293. package/types/assetlib/opensource3d.d.ts +55 -0
  294. package/types/assetlib/plateau.d.ts +67 -0
  295. package/types/assetlib/plateauLandmarks.d.ts +238 -0
  296. package/types/assetlib/plateauViewer.d.ts +3 -0
  297. package/types/assetlib/polyhaven.d.ts +90 -0
  298. package/types/assetlib/polypizza.d.ts +10 -0
  299. package/types/assetlib/smithsonian.d.ts +9 -0
  300. package/types/assetlib/sources.d.ts +22 -0
  301. package/types/assetlib/zip.d.ts +8 -0
  302. package/types/catalog/manifest.d.ts +26 -0
  303. package/types/catalog/officialCatalog.d.ts +4 -0
  304. package/types/catalog/officialCatalogAssetRuntime.d.ts +2 -0
  305. package/types/catalog/officialCatalogLod.d.ts +5 -0
  306. package/types/catalog/officialCatalogPlacement.d.ts +49 -0
  307. package/types/catalog/officialCatalogProvider.d.ts +7 -0
  308. package/types/character/animationRetarget.d.ts +20 -0
  309. package/types/character/characterRig.d.ts +28 -0
  310. package/types/character/characterRuntime.d.ts +4 -0
  311. package/types/character/freestyleSwimClip.d.ts +5 -0
  312. package/types/character/groundStabilizer.d.ts +55 -0
  313. package/types/character/index.d.ts +10 -0
  314. package/types/character/locomotionActions.d.ts +4 -0
  315. package/types/character/locomotionStateMachine.d.ts +62 -0
  316. package/types/character/mannequinAsset.d.ts +12 -0
  317. package/types/character/mannequinAssetUrl.node.d.ts +1 -0
  318. package/types/character/modelLoader.d.ts +7 -0
  319. package/types/character/walkableCharacterRuntime.d.ts +343 -0
  320. package/types/character/waterInteractionController.d.ts +114 -0
  321. package/types/cloud/ambientSkyBaker.d.ts +18 -0
  322. package/types/cloud/cloudLighting.d.ts +38 -0
  323. package/types/cloud/cloudParams.d.ts +18 -0
  324. package/types/cloud/cloudReprojection.d.ts +15 -0
  325. package/types/cloud/cloudStyle.d.ts +1380 -0
  326. package/types/cloud/cloudStyleSnapshots.d.ts +10 -0
  327. package/types/cloud/cloudVolume.d.ts +43 -0
  328. package/types/cloud/heroCloudRecipe.d.ts +167 -0
  329. package/types/cloud/index.d.ts +12 -0
  330. package/types/cloud/noise/baseShapeVolume.d.ts +86 -0
  331. package/types/cloud/noise/cirrusMap.d.ts +24 -0
  332. package/types/cloud/noise/curlNoise.d.ts +106 -0
  333. package/types/cloud/noise/erosionVolume.d.ts +58 -0
  334. package/types/cloud/noise/noiseVolume.d.ts +63 -0
  335. package/types/cloud/noise/periodicNoise3.d.ts +75 -0
  336. package/types/cloud/noise/weatherMap.d.ts +227 -0
  337. package/types/cloud/paramSchema.d.ts +142 -0
  338. package/types/collisionMetadata.d.ts +11 -0
  339. package/types/core/generation.d.ts +95 -0
  340. package/types/core/materialRoles.d.ts +102 -0
  341. package/types/core/presetDocuments.d.ts +25 -0
  342. package/types/core/systemStylePolicy.d.ts +4 -0
  343. package/types/environment/dayCurves.d.ts +47 -0
  344. package/types/environment/environmentAmbientProbe.d.ts +2 -0
  345. package/types/environment/environmentGroundFieldPass.d.ts +2 -0
  346. package/types/environment/environmentMaterialAdapter.d.ts +42 -0
  347. package/types/environment/environmentMaterialClassifier.d.ts +26 -0
  348. package/types/environment/environmentPlanarReflection.d.ts +3 -0
  349. package/types/environment/environmentPresets.d.ts +171 -0
  350. package/types/environment/environmentRigs.d.ts +13 -0
  351. package/types/environment/environmentSettings.d.ts +161 -0
  352. package/types/environment/environmentShaderMaterials.d.ts +14 -0
  353. package/types/environment/environmentState.d.ts +6 -0
  354. package/types/environment/environmentSunShadowPass.d.ts +2 -0
  355. package/types/environment/environmentTextureResolver.d.ts +30 -0
  356. package/types/environment/environmentTimeOfDay.d.ts +25 -0
  357. package/types/environment/environmentVertexAo.d.ts +18 -0
  358. package/types/environment/index.d.ts +27 -0
  359. package/types/environment/manufacturedMaterialContract.d.ts +129 -0
  360. package/types/environment/manufacturedReflectionProvider.d.ts +3 -0
  361. package/types/environment/scanAssetStylize.d.ts +43 -0
  362. package/types/environment/surfaceMaterialModes.d.ts +14 -0
  363. package/types/environment/toonLabEnvironmentMaterials.d.ts +139 -0
  364. package/types/environment/toonLabMaterialPassCoupling.d.ts +7 -0
  365. package/types/environment/toonLabNormalIntegration.d.ts +29 -0
  366. package/types/environment/toonLabRockMaterialResolver.d.ts +270 -0
  367. package/types/environment/toonLabSourceDefaultLit.d.ts +136 -0
  368. package/types/environment/toonLabSourceLibrary.d.ts +19 -0
  369. package/types/environment/toonLabSourceMaterials.d.ts +14 -0
  370. package/types/environment/toonLabSourceSubsurfaceLighting.d.ts +85 -0
  371. package/types/environment/toonLabSourceTemporal.d.ts +20 -0
  372. package/types/environment/toonLabSurfaceLighting.d.ts +136 -0
  373. package/types/environment/toonLabTextureReadiness.d.ts +8 -0
  374. package/types/environment/toonLabTreeMaterials.d.ts +7 -0
  375. package/types/environment/transparentMaterialProfile.d.ts +76 -0
  376. package/types/environment/urbanPropMaterial.d.ts +25 -0
  377. package/types/ground-shader/groundPrintLayer.d.ts +4 -0
  378. package/types/ground-shader/groundShaderMaterial.d.ts +11 -0
  379. package/types/ground-shader/groundShaderSettings.d.ts +90 -0
  380. package/types/ground-shader/index.d.ts +3 -0
  381. package/types/index.d.ts +1502 -0
  382. package/types/lighting/callMeSenseiLightingContract.d.ts +14 -0
  383. package/types/lighting/colorIntensity.d.ts +44 -0
  384. package/types/lighting/index.d.ts +12 -0
  385. package/types/lighting/lightDescriptors.d.ts +803 -0
  386. package/types/lighting/lightingCapabilities.d.ts +85 -0
  387. package/types/lighting/lightingDocuments.d.ts +140 -0
  388. package/types/lighting/lightingFixtures.d.ts +171 -0
  389. package/types/lighting/lightingGenerator.d.ts +403 -0
  390. package/types/lighting/lightingPresets.d.ts +264 -0
  391. package/types/lighting/lightingRuntime.d.ts +401 -0
  392. package/types/lighting/lightingStyle.d.ts +156 -0
  393. package/types/lighting/lightingSystem.d.ts +433 -0
  394. package/types/lighting/toonLabExport.d.ts +46 -0
  395. package/types/lighting/utils.d.ts +18 -0
  396. package/types/loaders/index.d.ts +1 -0
  397. package/types/post/index.d.ts +2 -0
  398. package/types/post/postGenerator.d.ts +282 -0
  399. package/types/post/postProcessing.d.ts +16 -0
  400. package/types/react/index.d.ts +1765 -0
  401. package/types/renderer/index.d.ts +1 -0
  402. package/types/renderer/rendererConfiguration.d.ts +8 -0
  403. package/types/rock-shader/index.d.ts +3 -0
  404. package/types/rock-shader/rockMaterial.d.ts +18 -0
  405. package/types/rock-shader/rockShaderRuntime.d.ts +8 -0
  406. package/types/rock-shader/rockShaderSettings.d.ts +170 -0
  407. package/types/rockgen/export/glbExport.d.ts +58 -0
  408. package/types/rockgen/heightfield/heightfieldErosion.d.ts +10 -0
  409. package/types/rockgen/heightfield/heightfieldPatch.d.ts +15 -0
  410. package/types/rockgen/heightfield/stylizedErosionSim.d.ts +41 -0
  411. package/types/rockgen/index.d.ts +11 -0
  412. package/types/rockgen/lod/index.d.ts +6 -0
  413. package/types/rockgen/lod/rockLodMetrics.d.ts +62 -0
  414. package/types/rockgen/lod/rockLodPlanner.d.ts +86 -0
  415. package/types/rockgen/lod/rockLodPolicy.d.ts +76 -0
  416. package/types/rockgen/lod/rockLodRuntime.d.ts +95 -0
  417. package/types/rockgen/lod/rockLodSimplifier.d.ts +15 -0
  418. package/types/rockgen/lod/rockLodValidation.d.ts +16 -0
  419. package/types/rockgen/mesh/meshAttributes.d.ts +32 -0
  420. package/types/rockgen/mesh/meshDocument.d.ts +40 -0
  421. package/types/rockgen/mesh/surfaceNets.d.ts +42 -0
  422. package/types/rockgen/noise/cellularNoise3.d.ts +24 -0
  423. package/types/rockgen/noise/prng.d.ts +16 -0
  424. package/types/rockgen/noise/simplexNoise3.d.ts +2 -0
  425. package/types/rockgen/noise/valueNoise3.d.ts +12 -0
  426. package/types/rockgen/rockDocument.d.ts +215 -0
  427. package/types/rockgen/rockHelpers.d.ts +2 -0
  428. package/types/rockgen/rockgenPresets.d.ts +10 -0
  429. package/types/rockgen/rockgenSettings.d.ts +531 -0
  430. package/types/rockgen/sdf/fieldCompiler.d.ts +20 -0
  431. package/types/rockgen/sdf/sculptEdits.d.ts +30 -0
  432. package/types/rockgen/sdf/sdfModifiers.d.ts +19 -0
  433. package/types/rockgen/sdf/sdfOps.d.ts +8 -0
  434. package/types/rockgen/sdf/sdfPrimitives.d.ts +22 -0
  435. package/types/runtime/index.d.ts +3 -0
  436. package/types/runtime/sceneCollisionRuntime.d.ts +94 -0
  437. package/types/runtime/sceneSurfaceRuntime.d.ts +90 -0
  438. package/types/runtime/sceneUpdateScheduler.d.ts +28 -0
  439. package/types/shaders-tsl/anime.d.ts +9 -0
  440. package/types/shaders-tsl/chunks/character-color.d.ts +6 -0
  441. package/types/shaders-tsl/chunks/character-highlights.d.ts +12 -0
  442. package/types/shaders-tsl/chunks/character-lighting.d.ts +20 -0
  443. package/types/shaders-tsl/chunks/character-material-maps.d.ts +18 -0
  444. package/types/shaders-tsl/chunks/character-roles.d.ts +21 -0
  445. package/types/shaders-tsl/chunks/character-scene-lights.d.ts +48 -0
  446. package/types/shaders-tsl/chunks/character-shadow-color.d.ts +5 -0
  447. package/types/shaders-tsl/chunks/character-skinning.d.ts +23 -0
  448. package/types/shaders-tsl/chunks/environment-color.d.ts +9 -0
  449. package/types/shaders-tsl/chunks/environment-debug.d.ts +24 -0
  450. package/types/shaders-tsl/chunks/environment-ground-field.d.ts +40 -0
  451. package/types/shaders-tsl/chunks/environment-lighting.d.ts +22 -0
  452. package/types/shaders-tsl/chunks/environment-state.d.ts +42 -0
  453. package/types/shaders-tsl/chunks/environment-sun-shadow.d.ts +19 -0
  454. package/types/shaders-tsl/chunks/foliage-fog.d.ts +21 -0
  455. package/types/shaders-tsl/chunks/normalized-hue.d.ts +1 -0
  456. package/types/shaders-tsl/chunks/pass-depth-color.d.ts +20 -0
  457. package/types/shaders-tsl/chunks/projected-water-caustics.d.ts +24 -0
  458. package/types/shaders-tsl/chunks/scene-depth-color-pass.d.ts +39 -0
  459. package/types/shaders-tsl/chunks/stylized-cloud-shadow.d.ts +9 -0
  460. package/types/shaders-tsl/chunks/vegetation-style.d.ts +60 -0
  461. package/types/shaders-tsl/chunks/water-color.d.ts +15 -0
  462. package/types/shaders-tsl/chunks/water-common.d.ts +9 -0
  463. package/types/shaders-tsl/chunks/water-foam.d.ts +8 -0
  464. package/types/shaders-tsl/chunks/water-lighting.d.ts +9 -0
  465. package/types/shaders-tsl/chunks/water-ripple.d.ts +8 -0
  466. package/types/shaders-tsl/chunks/water-shore-state.d.ts +7 -0
  467. package/types/shaders-tsl/chunks/water-waves.d.ts +18 -0
  468. package/types/shaders-tsl/chunks/world-noise.d.ts +4 -0
  469. package/types/shaders-tsl/environment-ao-overlay.d.ts +5 -0
  470. package/types/shaders-tsl/environment.d.ts +34 -0
  471. package/types/shaders-tsl/flower.d.ts +6 -0
  472. package/types/shaders-tsl/grass.d.ts +4 -0
  473. package/types/shaders-tsl/post-composite.d.ts +25 -0
  474. package/types/shaders-tsl/sky.d.ts +4 -0
  475. package/types/shaders-tsl/tree-leaf.d.ts +2 -0
  476. package/types/shaders-tsl/water-breaker.d.ts +15 -0
  477. package/types/shaders-tsl/water-kelp.d.ts +5 -0
  478. package/types/shaders-tsl/water-rain.d.ts +10 -0
  479. package/types/shaders-tsl/water-shore-state-simulation.d.ts +12 -0
  480. package/types/shaders-tsl/water-simulation.d.ts +5 -0
  481. package/types/shaders-tsl/water-splash.d.ts +12 -0
  482. package/types/shaders-tsl/water.d.ts +22 -0
  483. package/types/shaders-tsl/woody-surface.d.ts +3 -0
  484. package/types/sky/atmosphereDome.d.ts +2 -0
  485. package/types/sky/atmosphereParams.d.ts +185 -0
  486. package/types/sky/atmosphereScattering.d.ts +11 -0
  487. package/types/sky/atmosphereSky.d.ts +2 -0
  488. package/types/sky/cloudShadow.d.ts +68 -0
  489. package/types/sky/godRays.d.ts +5 -0
  490. package/types/sky/index.d.ts +18 -0
  491. package/types/sky/nightSky.d.ts +22 -0
  492. package/types/sky/renderLayers.d.ts +59 -0
  493. package/types/sky/sceneOverrideLayers.d.ts +10 -0
  494. package/types/sky/skyColor.d.ts +704 -0
  495. package/types/sky/skyDayCycle.d.ts +86 -0
  496. package/types/sky/skyParams.d.ts +3407 -0
  497. package/types/sky/skyPresets.d.ts +160 -0
  498. package/types/sky/skyQuality.d.ts +21 -0
  499. package/types/sky/skyQualityTiers.d.ts +223 -0
  500. package/types/sky/skyShaderSettings.d.ts +152 -0
  501. package/types/sky/skyStyleSnapshots.d.ts +11 -0
  502. package/types/sky/skySystem.d.ts +3 -0
  503. package/types/sky/skyTimeKeyframes.d.ts +230 -0
  504. package/types/sky/stylizedSky.d.ts +341 -0
  505. package/types/sky/sunDriver.d.ts +15 -0
  506. package/types/sky/timeOfDay.d.ts +145 -0
  507. package/types/styles/animeGameProfile.d.ts +27 -0
  508. package/types/styles/index.d.ts +17 -0
  509. package/types/styles/manufacturedStyleLabeling.d.ts +119 -0
  510. package/types/styles/sceneLayerDocuments.d.ts +145 -0
  511. package/types/styles/sceneLookComposition.d.ts +53 -0
  512. package/types/styles/sceneQualityApplication.d.ts +34 -0
  513. package/types/styles/sceneQualityProfiles.d.ts +13 -0
  514. package/types/styles/sceneStyleAudit.d.ts +80 -0
  515. package/types/styles/sceneStyleRuntime.d.ts +1782 -0
  516. package/types/styles/styleAdapters.d.ts +14 -0
  517. package/types/styles/styleApplication.d.ts +47 -0
  518. package/types/styles/styleBundle.d.ts +19 -0
  519. package/types/styles/styleBundleProvider.d.ts +44 -0
  520. package/types/styles/styleDomains.d.ts +18 -0
  521. package/types/styles/styleInspector.d.ts +59 -0
  522. package/types/styles/styleMaterialContract.d.ts +46 -0
  523. package/types/styles/styleMetadata.d.ts +11 -0
  524. package/types/styles/styleTargetDiscovery.d.ts +48 -0
  525. package/types/styles/styleTargetLabels.d.ts +32 -0
  526. package/types/styles/styleTargetMaterialCoverage.d.ts +20 -0
  527. package/types/styles/styleTransaction.d.ts +10 -0
  528. package/types/styles/styleTypes.d.ts +66 -0
  529. package/types/texgen/evaluateTexture.d.ts +40 -0
  530. package/types/texgen/index.d.ts +7 -0
  531. package/types/texgen/noise2.d.ts +46 -0
  532. package/types/texgen/textureAi.d.ts +6 -0
  533. package/types/texgen/textureGenerators.d.ts +261 -0
  534. package/types/texgen/texturePresets.d.ts +45 -0
  535. package/types/texgen/textureSettings.d.ts +121 -0
  536. package/types/texgen/textureThree.d.ts +13 -0
  537. package/types/toon/characterRenderPasses.d.ts +3 -0
  538. package/types/toon/index.d.ts +3 -0
  539. package/types/toon/settings/alphaSettings.d.ts +125 -0
  540. package/types/toon/settings/averageShadowSettings.d.ts +39 -0
  541. package/types/toon/settings/baseTextureSettings.d.ts +39 -0
  542. package/types/toon/settings/celShadeSettings.d.ts +37 -0
  543. package/types/toon/settings/contactShadowSettings.d.ts +30 -0
  544. package/types/toon/settings/eyeHighlightSettings.d.ts +55 -0
  545. package/types/toon/settings/faceLightingSettings.d.ts +32 -0
  546. package/types/toon/settings/furSettings.d.ts +23 -0
  547. package/types/toon/settings/glitterSettings.d.ts +43 -0
  548. package/types/toon/settings/hairHighlightSettings.d.ts +89 -0
  549. package/types/toon/settings/indirectLightSettings.d.ts +43 -0
  550. package/types/toon/settings/localLightSettings.d.ts +46 -0
  551. package/types/toon/settings/materialMapSettings.d.ts +86 -0
  552. package/types/toon/settings/outlineSettings.d.ts +125 -0
  553. package/types/toon/settings/perspectiveRemovalSettings.d.ts +14 -0
  554. package/types/toon/settings/rimLightSettings.d.ts +79 -0
  555. package/types/toon/settings/sceneShadowSettings.d.ts +32 -0
  556. package/types/toon/settings/selfShadowSettings.d.ts +44 -0
  557. package/types/toon/settings/shadowColorSettings.d.ts +77 -0
  558. package/types/toon/settings/skinToneSettings.d.ts +30 -0
  559. package/types/toon/settings/specularSettings.d.ts +96 -0
  560. package/types/toon/settings/stickerSettings.d.ts +40 -0
  561. package/types/toon/toonMaterialAdapter.d.ts +883 -0
  562. package/types/toon/toonSettings.d.ts +1182 -0
  563. package/types/vegetation/branchTree.d.ts +10 -0
  564. package/types/vegetation/callMeSenseiGrass.d.ts +8 -0
  565. package/types/vegetation/compiledTree.d.ts +75 -0
  566. package/types/vegetation/contactShadowField.d.ts +26 -0
  567. package/types/vegetation/flowerSpecies.d.ts +107 -0
  568. package/types/vegetation/grass.d.ts +4 -0
  569. package/types/vegetation/grassClump.d.ts +7 -0
  570. package/types/vegetation/grassPalettes.d.ts +29 -0
  571. package/types/vegetation/importedVegetationMaterial.d.ts +13 -0
  572. package/types/vegetation/index.d.ts +216 -0
  573. package/types/vegetation/legacyTreePresets.d.ts +22 -0
  574. package/types/vegetation/scatter.d.ts +12 -0
  575. package/types/vegetation/stylizedBush.d.ts +2 -0
  576. package/types/vegetation/stylizedFlower.d.ts +2 -0
  577. package/types/vegetation/stylizedFlowers.d.ts +8 -0
  578. package/types/vegetation/stylizedForest.d.ts +3 -0
  579. package/types/vegetation/stylizedGrass.d.ts +21 -0
  580. package/types/vegetation/stylizedTree.d.ts +19 -0
  581. package/types/vegetation/stylizedTreeFoliage.d.ts +18 -0
  582. package/types/vegetation/stylizedUnderstory.d.ts +50 -0
  583. package/types/vegetation/treeExport.d.ts +6 -0
  584. package/types/vegetation/treeSurfaceTextures.d.ts +72 -0
  585. package/types/vegetation/vegetationShaders.d.ts +74 -0
  586. package/types/version.d.ts +1 -0
  587. package/types/water/index.d.ts +1 -0
  588. package/types/water/sceneOverrideLayers.d.ts +16 -0
  589. package/types/water/water.d.ts +17 -0
  590. package/types/water/waterBreakerSystem.d.ts +46 -0
  591. package/types/water/waterCurrentField.d.ts +115 -0
  592. package/types/water/waterInteraction.d.ts +21 -0
  593. package/types/water/waterMaterial.d.ts +60 -0
  594. package/types/water/waterNearshorePhase.d.ts +5 -0
  595. package/types/water/waterRain.d.ts +17 -0
  596. package/types/water/waterRippleSimulation.d.ts +52 -0
  597. package/types/water/waterScenePasses.d.ts +70 -0
  598. package/types/water/waterSettings.d.ts +648 -0
  599. package/types/water/waterShoreMaterial.d.ts +3 -0
  600. package/types/water/waterShoreStateField.d.ts +2 -0
  601. package/types/water/waterSplashSystem.d.ts +2 -0
  602. package/types/water/waterStageSettings.d.ts +9 -0
  603. package/types/water/waterSurface.d.ts +2 -0
  604. package/types/water/waterUnderwaterAtmosphere.d.ts +103 -0
  605. package/types/water/waterVegetation.d.ts +16 -0
  606. package/types/worldCollision.d.ts +22 -0
  607. package/AGENTS.md +0 -254
  608. package/ATTRIBUTION.md +0 -78
  609. package/docs/characters.md +0 -144
  610. package/docs/debug-panel.md +0 -126
  611. package/docs/docs.css +0 -589
  612. package/docs/environment.md +0 -186
  613. package/docs/getting-started.md +0 -180
  614. package/docs/index.html +0 -14
  615. package/docs/lab-architecture.md +0 -100
  616. package/docs/lighting.md +0 -825
  617. package/docs/main.jsx +0 -739
  618. package/docs/mcp.md +0 -97
  619. package/docs/post-processing.md +0 -98
  620. package/docs/settings-reference.md +0 -1878
  621. package/docs/shader-constants.md +0 -77
  622. package/docs/sky.md +0 -182
  623. package/docs/style-labs.md +0 -309
  624. package/docs/texture-lab.md +0 -135
  625. package/docs/toon-shading.md +0 -183
  626. package/docs/tsl-conventions.md +0 -167
  627. package/docs/vegetation-sky.md +0 -275
  628. package/docs/water.md +0 -430
  629. package/docs/weather.md +0 -200
  630. package/docs/world-scale.md +0 -111
  631. package/mcp/style-lab-tools.mjs +0 -371
  632. package/src/ambientfx/INTEGRATION.md +0 -164
  633. package/src/ambientfx/ambientFxPresets.js +0 -83
  634. package/src/ambientfx/ambientFxSettings.js +0 -368
  635. package/src/ambientfx/emitters.js +0 -169
  636. package/src/ambientfx/index.js +0 -5
  637. package/src/ambientfx/particleBackbone.js +0 -493
  638. package/src/ambientfx/stylizedAmbientFx.js +0 -450
  639. package/src/biome/biomeGenerator.js +0 -385
  640. package/src/biome/biomeRuntime.js +0 -299
  641. package/src/biome/index.js +0 -2
  642. package/src/buildinggen/buildingAsset.js +0 -44
  643. package/src/buildinggen/buildingGrammar.js +0 -311
  644. package/src/buildinggen/buildingMesh.js +0 -451
  645. package/src/buildinggen/buildingPresets.js +0 -46
  646. package/src/buildinggen/buildingRecipe.js +0 -100
  647. package/src/buildinggen/buildingSettings.js +0 -238
  648. package/src/buildinggen/index.js +0 -6
  649. package/src/camera/cameraDirector.js +0 -157
  650. package/src/camera/cameraGenerator.js +0 -367
  651. package/src/camera/cameraRig.js +0 -570
  652. package/src/camera/cameraSettings.js +0 -236
  653. package/src/camera/index.js +0 -7
  654. package/src/catalog/builtinEntries.js +0 -245
  655. package/src/catalog/catalog.js +0 -210
  656. package/src/catalog/index.js +0 -3
  657. package/src/core/shaderBackend.js +0 -24
  658. package/src/debrisgen/debrisFields.js +0 -544
  659. package/src/debrisgen/debrisGenerator.js +0 -1929
  660. package/src/debrisgen/debrisPalettes.js +0 -71
  661. package/src/debrisgen/debrisPhysics.js +0 -198
  662. package/src/debrisgen/debrisPresets.js +0 -162
  663. package/src/debrisgen/debrisSettings.js +0 -333
  664. package/src/debrisgen/debrisTextures.js +0 -380
  665. package/src/debrisgen/index.js +0 -5
  666. package/src/debug/fieldValues.js +0 -95
  667. package/src/debug/index.js +0 -7
  668. package/src/debug/settingsPanel.js +0 -170
  669. package/src/fauna/INTEGRATION.md +0 -174
  670. package/src/fauna/boids.js +0 -861
  671. package/src/fauna/faunaBodies.js +0 -492
  672. package/src/fauna/faunaPresets.js +0 -52
  673. package/src/fauna/faunaSettings.js +0 -525
  674. package/src/fauna/index.js +0 -5
  675. package/src/fauna/stylizedFauna.js +0 -395
  676. package/src/game-feel/gameFeelGenerator.js +0 -402
  677. package/src/game-feel/gameFeelRuntime.js +0 -549
  678. package/src/game-feel/index.js +0 -2
  679. package/src/motion/index.js +0 -5
  680. package/src/motion/motionClip.js +0 -441
  681. package/src/motion/motionController.js +0 -628
  682. package/src/motion/motionDocuments.js +0 -225
  683. package/src/motion/motionGraph.js +0 -307
  684. package/src/motion/motionSettings.js +0 -222
  685. package/src/pathgen/index.js +0 -7
  686. package/src/pathgen/pathBridge.js +0 -232
  687. package/src/pathgen/pathPresets.js +0 -35
  688. package/src/pathgen/pathRibbon.js +0 -410
  689. package/src/pathgen/pathRouter.js +0 -380
  690. package/src/pathgen/pathSettings.js +0 -335
  691. package/src/pathgen/pathTextures.js +0 -123
  692. package/src/pathgen/stylizedPaths.js +0 -453
  693. package/src/propgen/generatorsWave1.js +0 -379
  694. package/src/propgen/generatorsWave2.js +0 -462
  695. package/src/propgen/index.js +0 -5
  696. package/src/propgen/propAsset.js +0 -323
  697. package/src/propgen/propParts.js +0 -170
  698. package/src/propgen/propPlacement.js +0 -459
  699. package/src/propgen/propPresets.js +0 -82
  700. package/src/propgen/propSettings.js +0 -395
  701. package/src/soundscape/index.js +0 -4
  702. package/src/soundscape/soundscapeGenerator.js +0 -179
  703. package/src/soundscape/soundscapeRuntime.js +0 -806
  704. package/src/soundscape/soundscapeSettings.js +0 -292
  705. package/src/stylizedTerrain.js +0 -631
  706. package/src/stylizedWorld.js +0 -903
  707. package/src/vegetation/treeRecipe.js +0 -647
  708. package/src/vfxgen/INTEGRATION.md +0 -145
  709. package/src/vfxgen/core/burstBackbone.js +0 -380
  710. package/src/vfxgen/core/projectileCore.js +0 -92
  711. package/src/vfxgen/core/spriteShapes.js +0 -98
  712. package/src/vfxgen/core/trailRibbon.js +0 -272
  713. package/src/vfxgen/core/vfxRandom.js +0 -29
  714. package/src/vfxgen/effects/emitHelpers.js +0 -37
  715. package/src/vfxgen/effects/magicEffects.js +0 -162
  716. package/src/vfxgen/effects/movementEffects.js +0 -87
  717. package/src/vfxgen/effects/weaponEffects.js +0 -118
  718. package/src/vfxgen/index.js +0 -18
  719. package/src/vfxgen/moves/moveController.js +0 -146
  720. package/src/vfxgen/moves/moveLibrary.js +0 -335
  721. package/src/vfxgen/vfxPresets.js +0 -98
  722. package/src/vfxgen/vfxSettings.js +0 -384
  723. package/src/vfxgen/vfxSystem.js +0 -449
  724. package/src/vfxgen/weapons/stylizedWeapons.js +0 -137
  725. package/src/villagegen/index.js +0 -4
  726. package/src/villagegen/stylizedVillage.js +0 -490
  727. package/src/villagegen/villageArchetypes.js +0 -160
  728. package/src/villagegen/villageNames.js +0 -40
  729. package/src/villagegen/villageSites.js +0 -105
  730. package/src/weather/index.js +0 -6
  731. package/src/weather/weatherPrecipitation.js +0 -221
  732. package/src/weather/weatherPresets.js +0 -258
  733. package/src/weather/weatherSettings.js +0 -269
  734. package/src/weather/weatherSystem.js +0 -871
  735. package/src/worldMinimap.js +0 -214
  736. package/src/worldPresets.js +0 -125
@@ -0,0 +1,1438 @@
1
+ // The SkySystem: the one object the whole volumetric sky hangs off.
2
+ //
3
+ // It owns the dome, the cloud subsystem and its temporal reconstruction, the
4
+ // day/night clock, and every piece of atmospheric state. Nothing below it knows
5
+ // about anything above it — the dome does not know the clouds exist, the clock
6
+ // does not know a renderer exists — so this file is where the wiring, the frame
7
+ // order, and the lifetime live.
8
+ //
9
+ // `SkySystem` is ToonLab's stable public API. Keep its names, argument order,
10
+ // and semantics backward-compatible.
11
+ //
12
+ // Two ordering rules the rest of this file exists to enforce:
13
+ //
14
+ // 1. Clouds are NOT a post stage. They are marched into a reconstruction
15
+ // buffer by `update()` and drawn IN THE SCENE by a backdrop mesh, so opaque
16
+ // geometry occludes them and host transparency draws over them. Only the
17
+ // aerial-perspective fog and the god rays are post stages, and those are
18
+ // what `applyTo` returns.
19
+ // 2. The clock owns the sun's direction whenever it is running. `applyPreset`
20
+ // therefore lands the authored sun pose with the clock momentarily paused
21
+ // (see the comment there) — otherwise a preset's `sun.elevation` would be
22
+ // overwritten by the celestial solve before it could ever be read back, and
23
+ // `toParams()` would not be the inverse of `applyPreset` that it claims.
24
+ //
25
+ // NOT BUILT YET, and honest about it rather than silently absent:
26
+ //
27
+ // - The env-map bake (src/sky/skyEnvironment.js). Asking for it throws a
28
+ // message naming the module, because handing back a dead env map is worse
29
+ // than refusing.
30
+ //
31
+ // The night sky IS built, in src/sky/nightSky.js, and it is the one backdrop
32
+ // this file adds CONDITIONALLY: `sky.nightSky` is documented as null when no
33
+ // `nightSky` option was supplied, so a daylight-only host pays for no extra
34
+ // sphere. Everything about it beyond construction, scene membership, the frame
35
+ // tick and the `nightSky.intensity` param belongs to that module.
36
+ //
37
+ // The aerial-perspective fog IS built, here, because `applyTo` is useless
38
+ // without it. It is a private method rather than an export: when
39
+ // src/sky/skyFog.js lands, `#fogNode` becomes a call into it and nothing else in
40
+ // this file changes. Nothing about the stage is exported, so there is no
41
+ // second-owner hazard of the kind the spec's module-ownership table exists to
42
+ // prevent.
43
+
44
+ import * as THREE from 'three';
45
+ import { MeshBasicNodeMaterial } from 'three/webgpu';
46
+ import {
47
+ Fn,
48
+ If,
49
+ exp,
50
+ float,
51
+ length,
52
+ max,
53
+ mix,
54
+ normalize,
55
+ saturate,
56
+ screenUV,
57
+ smoothstep,
58
+ step,
59
+ texture,
60
+ uniform,
61
+ vec2,
62
+ vec3,
63
+ vec4,
64
+ } from 'three/tsl';
65
+
66
+ import { createCloudParams } from '../cloud/cloudParams.js';
67
+ import { createCloudStyleParams } from '../cloud/cloudStyle.js';
68
+ import { createCloudReprojection } from '../cloud/cloudReprojection.js';
69
+ import { createCloudVolumeMaterial } from '../cloud/cloudVolume.js';
70
+ import { getCloudBaseShapeVolume } from '../cloud/noise/baseShapeVolume.js';
71
+ import { getCloudCirrusMap } from '../cloud/noise/cirrusMap.js';
72
+ import { getCurlNoiseVolume } from '../cloud/noise/curlNoise.js';
73
+ import { getCloudErosionVolume } from '../cloud/noise/erosionVolume.js';
74
+ import { createWeatherMapProfile, getWeatherMap } from '../cloud/noise/weatherMap.js';
75
+ import { finiteNumber, isObject } from '../cloud/paramSchema.js';
76
+ import { markFactorySystemOwned } from '../styles/styleMetadata.js';
77
+ import { createAtmosphereDome } from './atmosphereDome.js';
78
+ import { createAtmosphereParams } from './atmosphereParams.js';
79
+ import { atmosphereRaymarchNodes, createAtmosphereScattering } from './atmosphereScattering.js';
80
+ import { applySkyColorNode, createSkyColorParams } from './skyColor.js';
81
+ import {
82
+ GOD_RAYS_PARAM_KEYS,
83
+ GOD_RAYS_PARAM_SCHEMA,
84
+ createGodRaysPass,
85
+ } from './godRays.js';
86
+ import {
87
+ clearEnvironmentCloudShadowPass,
88
+ createCloudShadowPass,
89
+ sampleCloudShadowNode,
90
+ syncEnvironmentCloudShadowPass,
91
+ } from './cloudShadow.js';
92
+ import { NIGHT_SKY_PARAM_SCHEMA, createNightSky } from './nightSky.js';
93
+ import { RenderLayer, placeInLayer } from './renderLayers.js';
94
+ import { createSkyParams } from './skyParams.js';
95
+ import {
96
+ CLOUD_MARCH_BUDGET,
97
+ DEFAULT_QUALITY_LEVEL,
98
+ resolveQuality,
99
+ resolveQualityLevelName,
100
+ } from './skyQualityTiers.js';
101
+ import { createSun, createSunDriver, sunDirectionAt } from './sunDriver.js';
102
+ import { createTimeOfDay } from './timeOfDay.js';
103
+
104
+ /**
105
+ * Steps in the fog stage's own sky march.
106
+ *
107
+ * Half the dome's 32, and the halving is invisible by construction: fog only
108
+ * ever *fades toward* this radiance, so the two differ most where the mix weight
109
+ * is smallest. It is a per-pixel march on every geometry pixel, which is why it
110
+ * is not simply the dome's count.
111
+ */
112
+ const FOG_SKY_MARCH_STEPS = 16;
113
+
114
+ // Where the cloud backdrop sits, as fractions of the camera's far plane and
115
+ // multiples of the cloud march ceiling.
116
+ //
117
+ // NOT at the far plane, and the reason is measured rather than cautious. A
118
+ // hyperbolic depth buffer has no usable resolution left out there: with the
119
+ // documented near 0.1 / far 1e6 camera, an untouched depth texel — the far plane
120
+ // itself — reconstructs through `perspectiveDepthToViewZ` as 0.8 * far, i.e. two
121
+ // least-significant bits of a 24-bit buffer land 200 km from where they belong,
122
+ // identically on the WebGPU and WebGL2 backends. A backdrop placed at 0.98 * far
123
+ // is therefore *behind* the cleared depth and every pixel of it is rejected.
124
+ //
125
+ // So the backdrop sits a tenth of the way out, floored well past the marcher's
126
+ // own horizon (`fade.maxMarchDist`, where cloud stops existing at all) and capped
127
+ // at half the far plane for a host with a short one. At the documented camera
128
+ // that is 100 km: any geometry nearer occludes the cloud, which is the whole
129
+ // contract, and geometry beyond 100 km is past the deck's own horizon.
130
+ const CLOUD_LAYER_FAR_FRACTION = 0.1;
131
+ const CLOUD_LAYER_FAR_CAP = 0.5;
132
+ const CLOUD_LAYER_MARCH_MARGIN = 1.5;
133
+
134
+ /**
135
+ * A pixel closer than this fraction of the far plane is showing geometry.
136
+ *
137
+ * Generous on purpose, for the depth-precision reason above: an untouched depth
138
+ * texel reconstructs as 0.8 * far, not far, so the obvious 0.999 classified the
139
+ * ENTIRE SKY as distant geometry. The fog then replaced every sky pixel with its
140
+ * own sky march — which looks almost identical to the dome, so the frame appeared
141
+ * fine while the cloud layer underneath it was being overwritten and no cloud
142
+ * ever reached the screen. 0.5 leaves a 1.6x margin under the measured value.
143
+ *
144
+ * The cost of being generous is that geometry past half the far plane is not
145
+ * fogged. At that distance the fog has long since saturated to the sky colour
146
+ * anyway, and `atmosphere.fogFarFadeStart` is the knob for the world's rim.
147
+ */
148
+ const SKY_DEPTH_FRACTION = 0.5;
149
+
150
+ // Per-frame scratch. `#refreshCamera` runs once a frame and must not allocate;
151
+ // nothing reads these across a call, so one set serves every system in the page.
152
+ const rightScratch = new THREE.Vector3();
153
+ const upScratch = new THREE.Vector3();
154
+ const forwardScratch = new THREE.Vector3();
155
+
156
+ // Same boolean rule as src/sky/skyQualityTiers.js and src/cloud/paramSchema.js:
157
+ // a real boolean, or the 0/1 a URL parameter or a store round-trip produces.
158
+ // `Boolean(value)` would read the string 'false' as true.
159
+ function readBoolean(value, fallback) {
160
+ if (typeof value === 'boolean') return value;
161
+ if (value === 0 || value === 1) return value === 1;
162
+ if (value === 'true') return true;
163
+ if (value === 'false') return false;
164
+ return fallback;
165
+ }
166
+
167
+ function clampToRange(range, value, fallback) {
168
+ const next = finiteNumber(value);
169
+ if (next === null) return fallback;
170
+ if (!range) return next;
171
+ return Math.min(Math.max(next, range.min), range.max);
172
+ }
173
+
174
+ function isNode(value) {
175
+ return Boolean(value) && typeof value === 'object' && value.isNode === true;
176
+ }
177
+
178
+ /**
179
+ * Normalises the `nightSky` option into the bag `createNightSky` takes, or null.
180
+ *
181
+ * `true` is accepted alongside an object because the two mean the same thing —
182
+ * "give me a night sky" — and the documented bag has no required field: with no
183
+ * `texture` the panorama is black and the moon still rises, which the reference
184
+ * states outright ("Omit the option and the night sky renders black", against a
185
+ * `nightSky` whose fields are all optional).
186
+ *
187
+ * Both texture slots may be a URL, and neither is resolved here: a string cannot
188
+ * become a THREE.Texture without awaiting, so `SkySystem.create` — which is
189
+ * already async — loads them first and hands this function real textures. The
190
+ * throw below is therefore about the ONE path that cannot work, direct
191
+ * construction with a URL, and it says which call does.
192
+ */
193
+ function resolveNightSkyOptions(option) {
194
+ if (option === undefined || option === null || option === false) return null;
195
+ const bag = isObject(option) ? option : {};
196
+ if (!isObject(option) && option !== true) {
197
+ throw new TypeError(
198
+ 'SkySystem nightSky must be an options object (or true for the defaults), '
199
+ + `not ${typeof option}.`,
200
+ );
201
+ }
202
+
203
+ const resolved = {};
204
+ for (const key of ['texture', 'moonTexture']) {
205
+ const value = bag[key];
206
+ if (value === undefined || value === null) continue;
207
+ if (typeof value === 'string') {
208
+ throw new TypeError(
209
+ `SkySystem nightSky.${key} is a URL, which only the async factory can load. `
210
+ + 'Use `await SkySystem.create(options)` instead of `new SkySystem(options)`, '
211
+ + 'or pass a THREE.Texture you loaded yourself.',
212
+ );
213
+ }
214
+ if (value.isTexture !== true) {
215
+ throw new TypeError(
216
+ `SkySystem nightSky.${key} must be a URL string or a THREE.Texture.`,
217
+ );
218
+ }
219
+ resolved[key] = value;
220
+ }
221
+
222
+ // Ownership defaults to false — a host's texture is the host's to dispose —
223
+ // and `create` sets it true for the ones it loaded itself.
224
+ if (bag.ownsTexture !== undefined) resolved.ownsTexture = readBoolean(bag.ownsTexture, false);
225
+ if (bag.ownsMoonTexture !== undefined) {
226
+ resolved.ownsMoonTexture = readBoolean(bag.ownsMoonTexture, false);
227
+ }
228
+ if (bag.radius !== undefined) resolved.radius = bag.radius;
229
+ if (bag.intensity !== undefined) resolved.intensity = bag.intensity;
230
+ return resolved;
231
+ }
232
+
233
+ /**
234
+ * Loads the `nightSky` texture fields that arrived as URLs.
235
+ *
236
+ * Rejects rather than falling back to black. The night-sky module's own rule is
237
+ * that an ABSENT panorama renders black because that is what the host asked for;
238
+ * a panorama that was asked for and failed to arrive is a different thing, and
239
+ * quietly swallowing it is exactly the "black sky while a starmap was supplied"
240
+ * this file refuses elsewhere. Loading happens before the SkySystem exists, so a
241
+ * rejection leaves nothing built and nothing to clean up.
242
+ */
243
+ async function loadNightSkyTextures(option) {
244
+ if (!isObject(option)) return option;
245
+ const urls = ['texture', 'moonTexture'].filter((key) => typeof option[key] === 'string');
246
+ if (urls.length === 0) return option;
247
+
248
+ const loader = new THREE.TextureLoader();
249
+ // allSettled rather than all: with a starmap and a moon map both given as
250
+ // URLs, `all` rejects on the first failure while the other download is still
251
+ // in flight, and the texture that DOES arrive is then owned by nobody. Every
252
+ // outcome is collected, then either all of them are kept or all of them are
253
+ // freed.
254
+ const settled = await Promise.allSettled(urls.map((key) => loader.loadAsync(option[key])));
255
+
256
+ const failure = settled.findIndex((outcome) => outcome.status === 'rejected');
257
+ if (failure >= 0) {
258
+ for (const outcome of settled) {
259
+ if (outcome.status === 'fulfilled') outcome.value.dispose();
260
+ }
261
+ throw new Error(
262
+ `SkySystem could not load nightSky.${urls[failure]} from "${option[urls[failure]]}".`,
263
+ { cause: settled[failure].reason },
264
+ );
265
+ }
266
+
267
+ const resolved = { ...option };
268
+ urls.forEach((key, index) => {
269
+ const map = settled[index].value;
270
+ map.name = map.name || `SkySystemNight_${key}`;
271
+ resolved[key] = map;
272
+ // This system loaded it, so this system disposes it — unless the caller
273
+ // already said otherwise about that slot.
274
+ const ownsKey = key === 'texture' ? 'ownsTexture' : 'ownsMoonTexture';
275
+ if (resolved[ownsKey] === undefined) resolved[ownsKey] = true;
276
+ });
277
+ return resolved;
278
+ }
279
+
280
+ /**
281
+ * The live `godRays` group.
282
+ *
283
+ * Built here from the schema src/sky/godRays.js owns rather than re-declaring
284
+ * one field: this is a live-object factory, not a second definition of the group,
285
+ * and it is not exported, so the `conflicting star exports` hazard the spec's
286
+ * ownership table guards against does not arise. It moves into godRays.js
287
+ * alongside the march when that lands.
288
+ *
289
+ * `enabled` and `moonGodRayScale` are plain properties and the other four are
290
+ * uniforms, which is what the reference publishes. `steps` is a uniform and
291
+ * deliberately not a params field — the quality tier owns it.
292
+ */
293
+ function createGodRaysGroup(params = {}) {
294
+ const uniforms = {
295
+ strength: uniform(GOD_RAYS_PARAM_SCHEMA.strength.value),
296
+ sharpness: uniform(GOD_RAYS_PARAM_SCHEMA.sharpness.value),
297
+ extinction: uniform(GOD_RAYS_PARAM_SCHEMA.extinction.value),
298
+ maxDistance: uniform(GOD_RAYS_PARAM_SCHEMA.maxDistance.value),
299
+ };
300
+
301
+ const group = {
302
+ ...uniforms,
303
+ enabled: GOD_RAYS_PARAM_SCHEMA.enabled.value,
304
+ moonGodRayScale: GOD_RAYS_PARAM_SCHEMA.moonGodRayScale.value,
305
+ steps: uniform(24),
306
+
307
+ applyParams(next = {}) {
308
+ const source = isObject(next) ? next : {};
309
+ if ('enabled' in source) group.enabled = readBoolean(source.enabled, group.enabled);
310
+ if ('moonGodRayScale' in source) {
311
+ group.moonGodRayScale = clampToRange(
312
+ GOD_RAYS_PARAM_SCHEMA.moonGodRayScale.range,
313
+ source.moonGodRayScale,
314
+ group.moonGodRayScale,
315
+ );
316
+ }
317
+ for (const key of Object.keys(uniforms)) {
318
+ if (!(key in source)) continue;
319
+ uniforms[key].value = clampToRange(
320
+ GOD_RAYS_PARAM_SCHEMA[key].range,
321
+ source[key],
322
+ uniforms[key].value,
323
+ );
324
+ }
325
+ return group;
326
+ },
327
+
328
+ toParams() {
329
+ const params = {};
330
+ for (const key of GOD_RAYS_PARAM_KEYS) {
331
+ params[key] = key in uniforms ? uniforms[key].value : group[key];
332
+ }
333
+ return params;
334
+ },
335
+ };
336
+
337
+ return group.applyParams(params);
338
+ }
339
+
340
+ /**
341
+ * The top-level sky. Build it with {@link SkySystem.create}, which is async
342
+ * because it waits for the renderer's backend and generates the cloud noise
343
+ * volumes before the first frame can be rendered.
344
+ */
345
+ export class SkySystem {
346
+ #renderer;
347
+ #camera;
348
+ #scene;
349
+
350
+ #atmosphere;
351
+ #skyColor;
352
+ #scattering;
353
+ #timeOfDay;
354
+ #sun;
355
+ #sunDriver;
356
+ #clouds;
357
+ #cloudStyle;
358
+ #godRays;
359
+ #nightSky = null;
360
+ #nightSkyParams;
361
+
362
+ #qualityName;
363
+ #qualityOverrides;
364
+ #quality;
365
+
366
+ #noise;
367
+ #dome;
368
+ #cloud;
369
+ #cloudShadow;
370
+ #cloudShadowMapNode;
371
+ #reprojection;
372
+ #cloudLayer;
373
+ #cloudTextureNode;
374
+ #cloudHitTextureNode;
375
+ #cloudWeatherOverride = null;
376
+ #godRayPass;
377
+
378
+ #post;
379
+ #cssWidth = 1;
380
+ #cssHeight = 1;
381
+ #disposed = false;
382
+
383
+ /**
384
+ * @param {object} options
385
+ * @param {THREE.WebGPURenderer} options.renderer required — the renderer the
386
+ * sky draws with, on either the WebGPU or the WebGL2 backend.
387
+ * @param {THREE.PerspectiveCamera} options.camera required.
388
+ * @param {THREE.Scene} options.scene required — the sky adds its backdrops to
389
+ * it, and `dispose()` removes them again.
390
+ * @param {string} [options.quality='high'] quality tier.
391
+ * @param {boolean} [options.godRays] overrides the tier's god-ray switch.
392
+ * @param {object|true} [options.nightSky] star panorama options:
393
+ * `{ texture, moonTexture, radius = 100000, intensity = 0.3 }`. Either
394
+ * texture may be a URL — this factory loads it before building — or a
395
+ * preloaded THREE.Texture, which stays the caller's to dispose unless
396
+ * `ownsTexture` / `ownsMoonTexture` hands it over. Omit `texture` and the
397
+ * panorama renders black while the moon still rises; omit the whole option
398
+ * and `sky.nightSky` is null.
399
+ * @param {object} [options.timeOfDay] starting time, latitude and moon state.
400
+ * @returns {Promise<SkySystem>}
401
+ */
402
+ static async create(options = {}) {
403
+ const { renderer, camera, scene } = isObject(options) ? options : {};
404
+ if (!renderer?.isRenderer && typeof renderer?.render !== 'function') {
405
+ throw new TypeError('SkySystem.create needs a renderer.');
406
+ }
407
+ if (!camera?.isCamera) throw new TypeError('SkySystem.create needs a camera.');
408
+ if (!scene?.isScene) throw new TypeError('SkySystem.create needs a scene.');
409
+
410
+ // Idempotent, and it returns the shared init promise, so this is also the
411
+ // right call for a host that already awaited it: the backend has to be up
412
+ // before any material is built or any render target allocated.
413
+ if (typeof renderer.init === 'function') await renderer.init();
414
+
415
+ // After the backend, before the constructor. After, because a texture
416
+ // uploaded through a renderer that has not initialised has nowhere to go;
417
+ // before, because the constructor is synchronous and a URL that only
418
+ // resolved later would leave the first frames starless.
419
+ const nightSky = await loadNightSkyTextures(options.nightSky);
420
+ return new SkySystem(nightSky === options.nightSky ? options : { ...options, nightSky });
421
+ }
422
+
423
+ constructor(options = {}) {
424
+ const {
425
+ renderer,
426
+ camera,
427
+ scene,
428
+ quality = DEFAULT_QUALITY_LEVEL,
429
+ godRays,
430
+ nightSky,
431
+ timeOfDay,
432
+ } = isObject(options) ? options : {};
433
+
434
+ // Validated before anything is built, so a bad option bag fails without
435
+ // leaving a half-constructed system holding GPU resources.
436
+ const nightSkyOptions = resolveNightSkyOptions(nightSky);
437
+
438
+ this.#renderer = renderer;
439
+ this.#camera = camera;
440
+ this.#scene = scene;
441
+
442
+ // --- atmospheric state, in dependency order ----------------------------
443
+ this.#atmosphere = createAtmosphereParams();
444
+ this.#skyColor = createSkyColorParams();
445
+ this.#scattering = createAtmosphereScattering({ params: this.#atmosphere });
446
+ this.#timeOfDay = createTimeOfDay(isObject(timeOfDay) ? timeOfDay : {});
447
+ this.#sun = createSun();
448
+
449
+ // A PAUSED clock frees `sun.direction` — sunDriver.js's rule, documented as
450
+ // "0 pauses the clock, which also stops the driver from rewriting
451
+ // sun.direction — pause it to hold a direction set through
452
+ // sun.setFromAngles()". At construction there is no such direction to hold:
453
+ // `createSun()` produced its default one line ago and SkySystem has no `sun`
454
+ // option, so the rule would protect an arbitrary 45-degree noon sun against
455
+ // a host that asked for midnight. `skyDarkness` would then be 0 at 00:29,
456
+ // which turns the whole night sky off — stars, moon lift and all — and makes
457
+ // the night sky look broken when what is wrong is the sun. So when the host
458
+ // supplied a clock AND paused it, the clock's own solve IS the authored pose,
459
+ // written here with the driver's own solver so there is no second copy of
460
+ // the celestial arc. A running clock needs nothing: apply() re-solves on
461
+ // every pass while `autoAdvanceSecondsPerDay > 0`, including its first.
462
+ if (isObject(timeOfDay) && this.#timeOfDay.autoAdvanceSecondsPerDay === 0) {
463
+ sunDirectionAt(
464
+ this.#timeOfDay.foldTime(),
465
+ this.#timeOfDay.latitude,
466
+ this.#timeOfDay.azimuth,
467
+ this.#sun.direction.value,
468
+ );
469
+ }
470
+
471
+ // Constructed after the clock and the sun, which is the order sunDriver.js
472
+ // documents: a paused clock then adopts its opening reading rather than
473
+ // claiming the sun's direction, so the pose above survives construction and
474
+ // every derived term — darkness, the moon's direction, the star rotation —
475
+ // is solved from it.
476
+ this.#sunDriver = createSunDriver({ sun: this.#sun, timeOfDay: this.#timeOfDay });
477
+ this.#clouds = createCloudParams();
478
+ this.#cloudStyle = createCloudStyleParams();
479
+ this.#godRays = createGodRaysGroup();
480
+ this.#nightSkyParams = { intensity: NIGHT_SKY_PARAM_SCHEMA.intensity.value };
481
+
482
+ this.#qualityName = resolveQualityLevelName(quality);
483
+ this.#qualityOverrides = {};
484
+ this.#quality = resolveQuality(this.#qualityName, this.#qualityOverrides);
485
+ this.#godRays.steps.value = this.#quality.godRaySteps;
486
+ // The tier sets the switch; an explicit option overrides it, which is what
487
+ // `godRays optional — Default: from tier` means.
488
+ this.#godRays.enabled = godRays === undefined
489
+ ? this.#quality.godRaysEnabled
490
+ : readBoolean(godRays, this.#quality.godRaysEnabled);
491
+
492
+ // The noise block is live state, not a copy of the tier: the tier seeds the
493
+ // weather resolution and a preset may then override it.
494
+ this.#noise = {
495
+ weather: {
496
+ resolution: this.#quality.weatherMapResolution,
497
+ seed: 1,
498
+ profile: createWeatherMapProfile(),
499
+ },
500
+ };
501
+
502
+ // --- the backdrops -----------------------------------------------------
503
+ this.#dome = createAtmosphereDome({
504
+ params: this.#atmosphere,
505
+ scattering: this.#scattering,
506
+ style: this.#skyColor,
507
+ sun: this.#sun,
508
+ timeOfDay: this.#timeOfDay,
509
+ });
510
+ markFactorySystemOwned(this.#dome.group, 'sky', 'toonlab/sky-system-atmosphere');
511
+ scene.add(this.#dome.group);
512
+
513
+ // The night sky, only when asked for — `sky.nightSky` is documented as null
514
+ // otherwise, and the sphere is a real draw call that a daylight-only host
515
+ // should not pay for. It goes in AFTER the dome because it is additive
516
+ // radiance on top of the atmosphere: nightSky.js places its own group in
517
+ // RenderLayer.backgroundOverlay, which is the only layer both blended and
518
+ // behind scene content, and the dome owns the opaque `background` layer
519
+ // underneath it.
520
+ if (nightSkyOptions) {
521
+ this.#nightSky = createNightSky({
522
+ ...nightSkyOptions,
523
+ style: this.#skyColor,
524
+ timeOfDay: this.#timeOfDay,
525
+ });
526
+ markFactorySystemOwned(this.#nightSky.group, 'sky', 'toonlab/sky-system-night');
527
+ scene.add(this.#nightSky.group);
528
+ // The option's `intensity` won over the schema default inside
529
+ // createNightSky and was clamped to the published range there, so the
530
+ // serialized value is read back FROM the live object rather than
531
+ // re-derived here — one clamp, one owner, and `toParams()` reports what
532
+ // the sky is actually rendering.
533
+ this.#nightSkyParams.intensity = this.#nightSky.toParams().intensity;
534
+ }
535
+
536
+ this.#cloud = createCloudVolumeMaterial({
537
+ atmosphere: this.#atmosphere,
538
+ params: this.#clouds,
539
+ skyColor: this.#skyColor,
540
+ style: this.#cloudStyle,
541
+ quality: this.#qualityName,
542
+ scattering: this.#scattering,
543
+ seed: this.#noise.weather.seed,
544
+ sun: this.#sun,
545
+ timeOfDay: this.#timeOfDay,
546
+ volumes: this.#resolveVolumes(),
547
+ });
548
+
549
+ // Post-stage uniforms. Owned here rather than read from TSL's camera
550
+ // built-ins for the same reason cloudVolume.js owns its own: a post pass is
551
+ // drawn by a fullscreen quad, and `cameraPosition` in that graph reports the
552
+ // quad's camera, not the scene's.
553
+ this.#post = {
554
+ cameraPosition: uniform(new THREE.Vector3()),
555
+ cloudsEnabled: uniform(1),
556
+ far: uniform(camera.far ?? 1),
557
+ rayBasis: uniform(new THREE.Matrix3()),
558
+ };
559
+
560
+ this.#cloudShadow = createCloudShadowPass({
561
+ cloudVolume: this.#cloud,
562
+ clouds: this.#clouds,
563
+ groundReferenceY: this.#dome.groundLevel,
564
+ resolution: this.#quality.cloudShadowResolution,
565
+ sun: this.#sun,
566
+ timeOfDay: this.#timeOfDay,
567
+ });
568
+ this.#cloudShadow.mipLevel.value = this.#quality.cloudShadowMipLevel;
569
+ this.#cloudShadowMapNode = texture(this.#cloudShadow.texture);
570
+ syncEnvironmentCloudShadowPass(this.#cloudShadow);
571
+
572
+ const size = renderer.getDrawingBufferSize(new THREE.Vector2());
573
+ this.#reprojection = this.#createReprojection(size.x, size.y);
574
+ this.#cloudTextureNode = texture(this.#reprojection.texture);
575
+ this.#cloudHitTextureNode = texture(this.#reprojection.hitDistanceTexture);
576
+ this.#godRayPass = createGodRaysPass({
577
+ atmosphere: this.#atmosphere,
578
+ cameraPosition: this.#post.cameraPosition,
579
+ cloudColorNode: this.#cloudTextureNode,
580
+ cloudDepthNode: this.#cloudHitTextureNode,
581
+ godRays: this.#godRays,
582
+ shadowProjection: this.#cloudShadow.projection,
583
+ shadowMapNode: this.#cloudShadowMapNode,
584
+ sun: this.#sun,
585
+ timeOfDay: this.#timeOfDay,
586
+ });
587
+ this.#cloudLayer = this.#createCloudLayer();
588
+ markFactorySystemOwned(this.#cloudLayer.mesh, 'cloud', 'toonlab/sky-system-clouds');
589
+ scene.add(this.#cloudLayer.mesh);
590
+
591
+ const pixelRatio = renderer.getPixelRatio?.() ?? 1;
592
+ this.#cssWidth = Math.max(1, size.x / pixelRatio);
593
+ this.#cssHeight = Math.max(1, size.y / pixelRatio);
594
+
595
+ // Every driven uniform valid before anything renders or bakes.
596
+ this.#refreshCamera();
597
+ }
598
+
599
+ // -------------------------------------------------------------------------
600
+ // Properties
601
+ // -------------------------------------------------------------------------
602
+
603
+ /** Turbidity, exposure and scattering controls. */
604
+ get atmosphere() {
605
+ return this.#atmosphere;
606
+ }
607
+
608
+ /** Optional sky-colour grade. Its master switch off is the physical atmosphere. */
609
+ get skyColor() {
610
+ return this.#skyColor;
611
+ }
612
+
613
+ /** Cloud shape, lighting, wind, cirrus, haze and fade, plus `enabled`. */
614
+ get clouds() {
615
+ return this.#clouds;
616
+ }
617
+
618
+ /** Optional modular art direction. The master switch off is the V1 renderer. */
619
+ get cloudStyle() {
620
+ return this.#cloudStyle;
621
+ }
622
+
623
+ /** God-ray look knobs. The quality tier owns the march step count. */
624
+ get godRays() {
625
+ return this.#godRays;
626
+ }
627
+
628
+ /**
629
+ * Star panorama, or null when no `nightSky` config was supplied.
630
+ *
631
+ * `intensity.value` scales the stars, `setTexture(map, ownsNewTexture)` swaps
632
+ * the panorama, and `radianceNode` is the same graph the mesh draws — which is
633
+ * what the env-map bake and water reflections will read rather than composing
634
+ * a second definition of the night sky.
635
+ */
636
+ get nightSky() {
637
+ return this.#nightSky;
638
+ }
639
+
640
+ /** The active tier name. Read-only: there is no setter, use setQualityLevel. */
641
+ get qualityLevel() {
642
+ return this.#qualityName;
643
+ }
644
+
645
+ /** The resolved tier config, tier merged with any overrides. Frozen. */
646
+ get quality() {
647
+ return this.#quality;
648
+ }
649
+
650
+ /** The march budget, fixed at 128 primary / 6 light steps for every tier. */
651
+ get marchBudget() {
652
+ return CLOUD_MARCH_BUDGET;
653
+ }
654
+
655
+ /** Sun direction, intensity, colour and disc size. */
656
+ get sun() {
657
+ return this.#sun;
658
+ }
659
+
660
+ /** Day/night clock. Drives the sun and moon positions. */
661
+ get timeOfDay() {
662
+ return this.#timeOfDay;
663
+ }
664
+
665
+ /**
666
+ * Scrubs the package clock without running any render passes.
667
+ *
668
+ * A style coordinator may also provide its authored sun direction. The
669
+ * driver is applied once to adopt the new clock, then again after the pose is
670
+ * written so moon direction, night weight, star rotation and horizon fades
671
+ * all agree with that pose. This is safe to call from UI/React effects while
672
+ * the renderer owns the frame loop.
673
+ *
674
+ * @param {number} hour local hour, wrapped to a 24-hour day.
675
+ * @param {object} [options]
676
+ * @param {number} [options.autoAdvanceSecondsPerDay=0] 0 pauses the clock.
677
+ * @param {THREE.Vector3|number[]} [options.sunDirection] optional world-space
678
+ * direction from the scene origin toward the sun.
679
+ * @returns {object} the current derived celestial state.
680
+ */
681
+ setTimeOfDay(hour, {
682
+ autoAdvanceSecondsPerDay = 0,
683
+ sunDirection = null,
684
+ } = {}) {
685
+ this.#assertLive();
686
+ const nextHour = finiteNumber(hour);
687
+ const time = nextHour === null
688
+ ? this.#timeOfDay.foldTime()
689
+ : nextHour / 24;
690
+ this.#timeOfDay.applyParams({ autoAdvanceSecondsPerDay, time });
691
+ this.#sunDriver.apply();
692
+
693
+ if (sunDirection) {
694
+ const target = this.#sun.direction.value;
695
+ if (sunDirection.isVector3) target.copy(sunDirection);
696
+ else if (Array.isArray(sunDirection) && sunDirection.length >= 3) {
697
+ target.fromArray(sunDirection);
698
+ }
699
+ if (target.lengthSq() > 0) target.normalize();
700
+ this.#sunDriver.apply();
701
+ }
702
+ return this.#sunDriver.state;
703
+ }
704
+
705
+ /** The sky dome. */
706
+ get dome() {
707
+ return this.#dome;
708
+ }
709
+
710
+ /** The cloud raymarcher. */
711
+ get cloud() {
712
+ return this.#cloud;
713
+ }
714
+
715
+ /** The cloud temporal reconstruction. */
716
+ get reprojection() {
717
+ return this.#reprojection;
718
+ }
719
+
720
+ /** The precomputed scattering tables. */
721
+ get scattering() {
722
+ return this.#scattering;
723
+ }
724
+
725
+ /**
726
+ * The backdrop meshes this system added to the scene, in draw order. Water Pro
727
+ * excludes them from refraction sampling; a host can read them for the same
728
+ * kind of filtering.
729
+ */
730
+ get backdrops() {
731
+ // In draw order, which is the layer order: the opaque dome, then the
732
+ // additive night sky over it, then the cloud layer. The night sky is only
733
+ // in the list when it exists — a caller filtering its scene against this
734
+ // array must not have to skip a null.
735
+ return Object.freeze(this.#nightSky
736
+ ? [this.#dome.group, this.#nightSky.group, this.#cloudLayer.mesh]
737
+ : [this.#dome.group, this.#cloudLayer.mesh]);
738
+ }
739
+
740
+ /** World Y treated as ground, in metres. Moves the dome and the cloud shell together. */
741
+ get groundLevel() {
742
+ return this.#dome.groundLevel;
743
+ }
744
+
745
+ set groundLevel(value) {
746
+ const next = finiteNumber(value);
747
+ if (next === null) return;
748
+ this.#dome.groundLevel = next;
749
+ // Writes the cloud pass's uniform, which the reprojection shares by
750
+ // reference, so all three intersect one shell.
751
+ this.#cloud.groundLevel = next;
752
+ this.#cloudShadow.groundReferenceY = next;
753
+ }
754
+
755
+ // -------------------------------------------------------------------------
756
+ // Presets
757
+ // -------------------------------------------------------------------------
758
+
759
+ /**
760
+ * Applies a preset. Look only: it never touches the quality tier or the march
761
+ * budgets. Applying one FULLY REPLACES sky state — anything the preset leaves
762
+ * out falls back to the schema default, not to whatever was on screen.
763
+ *
764
+ * @param {object} preset a SkyParams object.
765
+ * @returns {Promise<void>}
766
+ */
767
+ async applyPreset(preset) {
768
+ this.#assertLive();
769
+ // `createSkyParams(preset)` with no base is what makes this a replacement
770
+ // rather than a merge, and it is also the fixed point `toParams()` returns:
771
+ // clamps, folds and derived-value rules all run here, once.
772
+ const params = createSkyParams(isObject(preset) ? preset : {});
773
+
774
+ this.#atmosphere.applyParams(params.atmosphere);
775
+ this.#skyColor.applyParams(params.atmosphere.style);
776
+ this.#clouds.applyParams(params.cloud);
777
+ this.#cloudStyle.applyParams(params.cloud.style);
778
+ this.#godRays.applyParams(params.godRays);
779
+ this.#nightSkyParams.intensity = clampToRange(
780
+ NIGHT_SKY_PARAM_SCHEMA.intensity.range,
781
+ params.nightSky.intensity,
782
+ this.#nightSkyParams.intensity,
783
+ );
784
+ // Through applyParams, not the uniform, so the module that publishes the
785
+ // range is the only thing that ever writes it.
786
+ this.#nightSky?.applyParams({ intensity: this.#nightSkyParams.intensity });
787
+
788
+ // The clock and the sun, in the one order that lets both survive.
789
+ //
790
+ // A running clock owns `sun.direction` — sunDriver.js re-solves it on every
791
+ // tick and on every change of time/latitude/azimuth. So the authored pose is
792
+ // landed with the rate held at 0: the driver adopts the preset's clock
793
+ // reading without claiming the direction, the pose is written, a second
794
+ // `apply()` derives the moon direction, the horizon fade, the night terms
795
+ // and the star rotation FROM THAT POSE, and only then is the preset's rate
796
+ // restored. `toParams()` therefore reads back the sun the preset authored,
797
+ // and the next `update(dt)` with a running clock takes the direction back —
798
+ // exactly what "0 pauses, which also frees sun.direction" implies.
799
+ const rate = params.time.autoAdvanceSecondsPerDay;
800
+ this.#timeOfDay.applyParams({ ...params.time, autoAdvanceSecondsPerDay: 0 });
801
+ this.#sunDriver.apply();
802
+ this.#sun.applyParams(params.sun);
803
+ this.#sunDriver.apply();
804
+ this.#timeOfDay.autoAdvanceSecondsPerDay = rate;
805
+
806
+ // Last, because it regenerates textures on the CPU and is the only reason
807
+ // this method is async. `noise.weather.resolution` is a params field a
808
+ // preset may carry, which is why a preset can override the tier here.
809
+ await this.#applyNoise(params.noise);
810
+ }
811
+
812
+ /**
813
+ * Reads the current sky back as a SkyParams — the inverse of `applyPreset`.
814
+ *
815
+ * Colours and the weather profile are COPIED OUT, so later changes to the sky
816
+ * do not reach the returned value. The quality tier, the march budgets and the
817
+ * env-map bake config are not included; read the tier from `qualityLevel`.
818
+ *
819
+ * @returns {object} SkyParams
820
+ */
821
+ toParams() {
822
+ return {
823
+ // Every group's own toParams() already returns a fresh THREE.Color for
824
+ // each colour field, so the copy is theirs and is not repeated here. The
825
+ // weather profile has no owning group, so this method copies it.
826
+ atmosphere: {
827
+ ...this.#atmosphere.toParams(),
828
+ style: this.#skyColor.toParams(),
829
+ },
830
+ cloud: {
831
+ ...this.#clouds.toParams(),
832
+ style: this.#cloudStyle.toParams(),
833
+ },
834
+ godRays: this.#godRays.toParams(),
835
+ nightSky: { intensity: this.#nightSkyParams.intensity },
836
+ noise: {
837
+ weather: {
838
+ resolution: this.#noise.weather.resolution,
839
+ seed: this.#noise.weather.seed,
840
+ profile: { ...this.#noise.weather.profile },
841
+ },
842
+ },
843
+ sun: this.#sun.toParams(),
844
+ time: this.#timeOfDay.toParams(),
845
+ };
846
+ }
847
+
848
+ // -------------------------------------------------------------------------
849
+ // Quality
850
+ // -------------------------------------------------------------------------
851
+
852
+ /**
853
+ * Switches the runtime quality tier. Cost policy only: the only two SkyParams
854
+ * fields a tier is allowed to move are the two the reference documents as
855
+ * tier-driven — `godRays.enabled` and `noise.weather.resolution` — and it moves
856
+ * them only when the TIER'S OWN value for them changed. Re-asserting a value
857
+ * the outgoing tier already held would undo a preset's override for no reason:
858
+ * high and ultra agree about both fields, so switching between them leaves
859
+ * `toParams()` bit-identical. Nothing else in `toParams()` ever changes.
860
+ *
861
+ * @param {string} level tier name.
862
+ * @param {object} [overrides] Partial<QualityLevelConfig>, merged field by field.
863
+ * @returns {Promise<void>}
864
+ */
865
+ async setQualityLevel(level, overrides = {}) {
866
+ this.#assertLive();
867
+ const previous = this.#quality;
868
+ this.#qualityName = resolveQualityLevelName(level);
869
+ this.#qualityOverrides = isObject(overrides) ? { ...overrides } : {};
870
+ this.#quality = resolveQuality(this.#qualityName, this.#qualityOverrides);
871
+
872
+ // Not a params field — a pure tier uniform — so it is always written.
873
+ this.#godRays.steps.value = this.#quality.godRaySteps;
874
+ this.#cloudShadow.setResolution(this.#quality.cloudShadowResolution);
875
+ this.#cloudShadow.mipLevel.value = this.#quality.cloudShadowMipLevel;
876
+ if (this.#quality.godRaysEnabled !== previous.godRaysEnabled) {
877
+ this.#godRays.enabled = this.#quality.godRaysEnabled;
878
+ }
879
+
880
+ if (this.#quality.cloudHistoryDiv !== previous.cloudHistoryDiv) {
881
+ // `historyDiv` is fixed when the reconstruction is built — every target
882
+ // size, the jitter cycle and the warmup length are derived from it — so a
883
+ // change is a rebuild, which also drops the stale history.
884
+ const { fullWidth, fullHeight } = this.#reprojection.size;
885
+ this.#reprojection.dispose();
886
+ this.#reprojection = this.#createReprojection(fullWidth, fullHeight);
887
+ this.#cloudTextureNode.value = this.#reprojection.texture;
888
+ this.#cloudHitTextureNode.value = this.#reprojection.hitDistanceTexture;
889
+ }
890
+
891
+ const dimsChanged = this.#quality.baseShapeDims.x !== previous.baseShapeDims.x
892
+ || this.#quality.baseShapeDims.y !== previous.baseShapeDims.y
893
+ || this.#quality.baseShapeDims.z !== previous.baseShapeDims.z;
894
+ // Only when the tier's own opinion changed — see the doc comment. A preset
895
+ // that overrode the resolution keeps it across a switch between two tiers
896
+ // that agree about it.
897
+ const weatherChanged = this.#quality.weatherMapResolution !== previous.weatherMapResolution;
898
+ if (weatherChanged) this.#noise.weather.resolution = this.#quality.weatherMapResolution;
899
+ if (dimsChanged || weatherChanged) {
900
+ // Awaited so a host can gate on the regeneration finishing; the generators
901
+ // are synchronous CPU work, so this yields once rather than polling.
902
+ await Promise.resolve();
903
+ this.#cloud.setVolumes(this.#resolveVolumes());
904
+ this.#reprojection.reset();
905
+ }
906
+ }
907
+
908
+ // -------------------------------------------------------------------------
909
+ // Per-frame
910
+ // -------------------------------------------------------------------------
911
+
912
+ /**
913
+ * Per-frame tick: runs the cloud passes, advances the day/night clock, and
914
+ * refreshes uniforms. Call it once per frame BEFORE rendering — the cloud
915
+ * backdrop draws in the scene, so its image has to exist by the time the scene
916
+ * pass runs.
917
+ *
918
+ * @param {number} dt seconds since the last frame.
919
+ */
920
+ update(dt = 0) {
921
+ if (this.#disposed) return;
922
+ const delta = Math.max(0, finiteNumber(dt) ?? 0);
923
+
924
+ this.#sunDriver.update(delta);
925
+ this.#clouds.update(delta);
926
+ this.#dome.update(delta, this.#camera);
927
+ // After the driver, because every celestial term in the night sky reads the
928
+ // clock uniforms the driver just re-solved. The call itself only re-centres
929
+ // the sphere on the camera, so the star field cannot be walked out of.
930
+ this.#nightSky?.update(delta, this.#camera);
931
+ this.#refreshCamera();
932
+
933
+ const enabled = this.#clouds.enabled === true;
934
+ this.#post.cloudsEnabled.value = enabled ? 1 : 0;
935
+ this.#cloudLayer.mesh.visible = enabled;
936
+ this.#cloudShadow.enabled = enabled;
937
+ if (enabled) {
938
+ // The shadow bake samples an explicit mip before the primary cloud pass
939
+ // runs, so upload the authored 3D mip pyramid here as well as in the
940
+ // reconstruction path. The helper is idempotent per renderer.
941
+ this.#cloud.prepareNoiseMipmaps(this.#renderer);
942
+ this.#cloudShadow.updateFrame(this.#camera);
943
+ this.#cloudShadow.bake(this.#renderer);
944
+ }
945
+ syncEnvironmentCloudShadowPass(this.#cloudShadow);
946
+ this.#godRayPass.update();
947
+ if (enabled) {
948
+ // The reconstruction marches the cloud pass itself and returns the texture
949
+ // to composite; the target it wrote ping-pongs, so the backdrop's texture
950
+ // node is re-pointed every frame. Both targets are allocated with
951
+ // identical parameters, so this is a uniform change and not a recompile.
952
+ this.#cloudTextureNode.value = this.#reprojection.render(this.#renderer, this.#camera);
953
+ this.#cloudHitTextureNode.value = this.#reprojection.hitDistanceTexture;
954
+ } else {
955
+ // A disabled layer must warm up again when it comes back rather than
956
+ // popping in a stale image — the reference's documented ~16 frames.
957
+ this.#reprojection.reset();
958
+ }
959
+ }
960
+
961
+ /**
962
+ * Resizes the internal render targets and drops stale history.
963
+ *
964
+ * @param {number} width CSS (logical) pixels — the same units as
965
+ * `renderer.setSize()`. The renderer's pixel ratio is applied internally.
966
+ * @param {number} height CSS (logical) pixels.
967
+ */
968
+ resize(width, height) {
969
+ if (this.#disposed) return;
970
+ const cssWidth = Math.max(1, finiteNumber(width) ?? this.#cssWidth);
971
+ const cssHeight = Math.max(1, finiteNumber(height) ?? this.#cssHeight);
972
+ this.#cssWidth = cssWidth;
973
+ this.#cssHeight = cssHeight;
974
+ const ratio = this.#renderer.getPixelRatio?.() ?? 1;
975
+ this.#reprojection.setSize(
976
+ Math.max(1, Math.round(cssWidth * ratio)),
977
+ Math.max(1, Math.round(cssHeight * ratio)),
978
+ );
979
+ // setSize() only resets when the size actually changed, and this method is
980
+ // also the documented hook for a pixel-ratio change at the same CSS size.
981
+ this.#reprojection.reset();
982
+ this.#cloudTextureNode.value = this.#reprojection.texture;
983
+ this.#cloudHitTextureNode.value = this.#reprojection.hitDistanceTexture;
984
+ }
985
+
986
+ // -------------------------------------------------------------------------
987
+ // Compositing
988
+ // -------------------------------------------------------------------------
989
+
990
+ /**
991
+ * Composites the sky over the rendered scene: aerial-perspective fog, then god
992
+ * rays. Splice the returned node into a post graph in linear pre-exposure
993
+ * space — after the scene, before exposure and bloom.
994
+ *
995
+ * Clouds are not part of this. They draw in the scene with the rest of the
996
+ * sky, so opaque geometry hides them and host transparency draws over them.
997
+ *
998
+ * @param {object} sceneColor Node<vec4> — the colour node being chained. Need
999
+ * not be `scenePass`'s own output.
1000
+ * @param {object} scenePass the `pass(scene, camera)` node; supplies the depth
1001
+ * both stages composite against.
1002
+ * @returns {object} Node<vec4>
1003
+ */
1004
+ applyTo(sceneColor, scenePass) {
1005
+ this.#assertLive();
1006
+ if (!isNode(sceneColor)) {
1007
+ throw new TypeError('SkySystem.applyTo needs a colour node as its first argument.');
1008
+ }
1009
+ if (scenePass?.isPassNode !== true || typeof scenePass.getViewZNode !== 'function') {
1010
+ throw new TypeError(
1011
+ 'SkySystem.applyTo needs the pass(scene, camera) node as its second argument — '
1012
+ + 'both stages read the scene depth from it.',
1013
+ );
1014
+ }
1015
+
1016
+ const output = this.#fogNode(sceneColor, scenePass);
1017
+ const viewZ = scenePass.getViewZNode('depth');
1018
+ const ndc = vec2(screenUV.x.mul(2).sub(1), screenUV.y.mul(-2).add(1));
1019
+ const ray = this.#post.rayBasis.mul(vec3(ndc, 1));
1020
+ const viewDirection = normalize(ray);
1021
+ const sceneDistance = viewZ.negate().mul(length(ray));
1022
+ return this.#godRayPass.applyTo(output, viewDirection, sceneDistance);
1023
+ }
1024
+
1025
+ /**
1026
+ * Cloud sun-transmittance at a world position, 0..1, where 1 is full sun.
1027
+ * Multiply it into the DIRECT sun term of a material, never into ambient.
1028
+ *
1029
+ * The value is one filtered lookup into the camera-centred top-down
1030
+ * transmittance bake. It fades to full light over the outer 20% of the 8 km
1031
+ * footprint and returns full light outside it.
1032
+ *
1033
+ * @param {object} worldPos Node<vec3> world-space position, e.g. positionWorld.
1034
+ * @returns {object} Node<float> in [0, 1].
1035
+ */
1036
+ cloudShadow(worldPos) {
1037
+ this.#assertLive();
1038
+ if (!isNode(worldPos)) {
1039
+ throw new TypeError('SkySystem.cloudShadow needs a Node<vec3> world position.');
1040
+ }
1041
+
1042
+ return sampleCloudShadowNode(
1043
+ vec3(worldPos),
1044
+ this.#cloudShadowMapNode,
1045
+ this.#cloudShadow.projection,
1046
+ );
1047
+ }
1048
+
1049
+ // -------------------------------------------------------------------------
1050
+ // Textures and lifetime
1051
+ // -------------------------------------------------------------------------
1052
+
1053
+ /**
1054
+ * Sets or clears the cirrus-deck mask. `scale` and `strength` are live
1055
+ * uniforms on `clouds.cirrus`.
1056
+ *
1057
+ * @param {THREE.Texture|null} map the mask, or null to clear it.
1058
+ */
1059
+ setCirrusTexture(map) {
1060
+ this.#assertLive();
1061
+ this.#cloud.setCirrusTexture(map ?? null);
1062
+ }
1063
+
1064
+ /**
1065
+ * Overrides the generated weather map with a host-authored coverage texture.
1066
+ *
1067
+ * The override is runtime state rather than SkyParams art direction. It is
1068
+ * retained across preset and quality changes until cleared with `null`, and
1069
+ * is never disposed by the SkySystem because the host owns the texture.
1070
+ * Hero-cloud authoring uses this path to preview a doodled footprint through
1071
+ * the same physical volume marcher as the normal cloud deck.
1072
+ *
1073
+ * @param {THREE.Texture|null} map linear RGBA coverage/type/precipitation map.
1074
+ */
1075
+ setCloudWeatherTexture(map) {
1076
+ this.#assertLive();
1077
+ if (map !== null && map !== undefined && map.isTexture !== true) {
1078
+ throw new TypeError('SkySystem.setCloudWeatherTexture needs a THREE.Texture or null.');
1079
+ }
1080
+ this.#cloudWeatherOverride = map ?? null;
1081
+ this.#cloud.setVolumes({ weather: this.#cloudWeatherOverride ?? this.#resolveGeneratedWeather() });
1082
+ this.#reprojection.reset();
1083
+ }
1084
+
1085
+ /**
1086
+ * Builds a SkyEnvironment: a 2D equirectangular env map sharing this system's
1087
+ * atmosphere, sun, cloud state and noise textures.
1088
+ *
1089
+ * NOT IMPLEMENTED. The interface is `createEnvironmentMap(options)` where
1090
+ * options is a SkyEnvironmentOptions — `{ width, height, includeClouds,
1091
+ * cloudMarchSteps, cloudMipBase, origin, skipFrames }`, defaulting to
1092
+ * `DEFAULT_ENV_MAP_OPTIONS` from ./skyQualityTiers.js when built directly and
1093
+ * to the tier's `envMap*` fields when seeded from one. It throws rather than
1094
+ * returning a dead object, because a host cannot tell a frozen bake from a
1095
+ * black one.
1096
+ */
1097
+ createEnvironmentMap(options = {}) {
1098
+ this.#assertLive();
1099
+ void options;
1100
+ throw new Error(
1101
+ 'SkySystem.createEnvironmentMap() is not implemented yet: the live equirect bake lands '
1102
+ + 'in src/sky/skyEnvironment.js, which has not been built. The tier already carries its '
1103
+ + 'sizing (envMapEnabled, envMapClouds, envMapWidth, envMapHeight, envMapMarchSteps, '
1104
+ + 'envMapMipBase) and ./skyQualityTiers.js publishes DEFAULT_ENV_MAP_OPTIONS for a bake '
1105
+ + 'built directly.',
1106
+ );
1107
+ }
1108
+
1109
+ /**
1110
+ * Returns a SkyProvider for Three.js Water Pro.
1111
+ *
1112
+ * NOT IMPLEMENTED. The interface is `createSkyProvider({ envMap })` where
1113
+ * envMap is `false` (a clouds-free sky bake), `true` (an env map seeded from
1114
+ * the active tier), or a SkyEnvironmentOptions object. The returned provider
1115
+ * owes Water Pro `createFogSampler`, `createReflectionSampler`,
1116
+ * `followCamera`, `getEnvironmentTexture`, `getMeshes`, `getSun`, `setActive`
1117
+ * and `dispose`; `getMeshes` is already answerable from `backdrops` and
1118
+ * `getSun` from `sun`, but the two samplers need the env-map bake below.
1119
+ */
1120
+ createSkyProvider(options = {}) {
1121
+ this.#assertLive();
1122
+ void options;
1123
+ throw new Error(
1124
+ 'SkySystem.createSkyProvider() is not implemented yet: it needs the env-map bake in '
1125
+ + 'src/sky/skyEnvironment.js, which has not been built. `backdrops` and `sun` already '
1126
+ + 'answer the provider\'s getMeshes() and getSun().',
1127
+ );
1128
+ }
1129
+
1130
+ /** Releases GPU resources and removes the backdrops from the scene. */
1131
+ dispose() {
1132
+ if (this.#disposed) return;
1133
+ this.#disposed = true;
1134
+
1135
+ this.#cloudLayer.mesh.removeFromParent();
1136
+ this.#cloudLayer.mesh.geometry.dispose();
1137
+ this.#cloudLayer.material.dispose();
1138
+ this.#godRayPass.dispose();
1139
+ clearEnvironmentCloudShadowPass(this.#cloudShadow);
1140
+ this.#cloudShadow.dispose();
1141
+ this.#reprojection.dispose();
1142
+ this.#cloud.dispose();
1143
+ // Removes the dome group from the scene as well as freeing its geometry.
1144
+ this.#dome.dispose();
1145
+ // Same contract: its own dispose() detaches the group and frees the mesh.
1146
+ // Host panoramas survive it — the slot only disposes what ownership was
1147
+ // handed over for, which is the textures `create` loaded from a URL.
1148
+ this.#nightSky?.dispose();
1149
+ this.#scattering.dispose();
1150
+
1151
+ // The noise volumes and weather maps are deliberately NOT disposed. They
1152
+ // live in module-level caches keyed by (dims, seed) and (resolution, seed,
1153
+ // profile), shared with every other SkySystem and every lab in the page, so
1154
+ // freeing them here would pull textures out from under a live sibling. Call
1155
+ // disposeCloudBaseShapeVolumes / disposeCloudErosionVolumes /
1156
+ // disposeCurlNoiseVolumes / disposeWeatherMaps to drop the caches when the
1157
+ // last consumer is gone.
1158
+ }
1159
+
1160
+ // -------------------------------------------------------------------------
1161
+ // Internals
1162
+ // -------------------------------------------------------------------------
1163
+
1164
+ #assertLive() {
1165
+ if (this.#disposed) throw new Error('This SkySystem has been disposed.');
1166
+ }
1167
+
1168
+ /** The five noise textures for the current tier, seed and weather profile. */
1169
+ #resolveVolumes() {
1170
+ const { seed } = this.#noise.weather;
1171
+ return {
1172
+ baseShape: getCloudBaseShapeVolume({ dims: this.#quality.baseShapeDims, seed }),
1173
+ cirrus: getCloudCirrusMap({ seed }),
1174
+ curl: getCurlNoiseVolume({ seed }),
1175
+ erosion: getCloudErosionVolume({ seed }),
1176
+ weather: this.#cloudWeatherOverride ?? this.#resolveGeneratedWeather(),
1177
+ };
1178
+ }
1179
+
1180
+ #resolveGeneratedWeather() {
1181
+ const { profile, resolution, seed } = this.#noise.weather;
1182
+ return getWeatherMap({ profile, resolution, seed });
1183
+ }
1184
+
1185
+ /**
1186
+ * Applies the `noise` block, regenerating on the CPU only when something the
1187
+ * generators key on actually moved. A profile slider drag reaches here every
1188
+ * frame in the lab, and a 1024² FBM is not free.
1189
+ */
1190
+ async #applyNoise(noise) {
1191
+ const weather = noise?.weather ?? {};
1192
+ const profile = createWeatherMapProfile(weather.profile);
1193
+ const resolution = weather.resolution ?? this.#noise.weather.resolution;
1194
+ const seed = weather.seed ?? this.#noise.weather.seed;
1195
+ const changed = resolution !== this.#noise.weather.resolution
1196
+ || seed !== this.#noise.weather.seed
1197
+ || Object.keys(profile).some((key) => profile[key] !== this.#noise.weather.profile[key]);
1198
+
1199
+ this.#noise.weather = { profile, resolution, seed };
1200
+ if (!changed) return;
1201
+ await Promise.resolve();
1202
+ this.#cloud.setVolumes(this.#resolveVolumes());
1203
+ // The reconstruction is holding an image of a cloud field that no longer
1204
+ // exists, and the neighbourhood clamp cannot police a change this large.
1205
+ this.#reprojection.reset();
1206
+ }
1207
+
1208
+ #createReprojection(width, height) {
1209
+ return createCloudReprojection({
1210
+ cloudVolume: this.#cloud,
1211
+ fade: this.#clouds.fade,
1212
+ height,
1213
+ historyDiv: this.#quality.cloudHistoryDiv,
1214
+ shape: this.#clouds.shape,
1215
+ width,
1216
+ });
1217
+ }
1218
+
1219
+ /**
1220
+ * The cloud backdrop: the reconstructed cloud image, drawn in the scene.
1221
+ *
1222
+ * A camera-centred sphere, drawn from the inside, exactly like the dome — NOT
1223
+ * a clip-space quad written through `vertexNode`. The quad is the obvious
1224
+ * construction and it does not survive a `pass(scene, camera)`: measured on
1225
+ * both backends, a full-screen quad whose vertex node writes the far plane
1226
+ * drew 640/640 pixels of a direct `renderer.render()` and 0/640 of the same
1227
+ * frame through the pass, with byte-identical WGSL and no validation error, on
1228
+ * every combination of depth test, blending, side and geometry size tried. The
1229
+ * sphere renders in both, so the layer is built the way the dome already
1230
+ * proves works.
1231
+ *
1232
+ * The sphere's radius is what the depth test compares against, so
1233
+ * `#refreshCamera` keeps it beyond any geometry a host can plausibly draw while
1234
+ * staying inside the depth buffer's usable range — see CLOUD_LAYER_FAR_FRACTION
1235
+ * for the measurement that rules out the far plane itself. Anything nearer
1236
+ * occludes the cloud, which is what "hidden behind opaque geometry" has to mean.
1237
+ * `depthWrite: false` keeps the layer out of everyone else's depth test, and it
1238
+ * draws before host transparency, so glass and particles composite over it.
1239
+ *
1240
+ * One consequence worth naming: the depth is the sphere's radius, not the
1241
+ * cloud's own distance, so a mountain 60 km out has cloud drawn over it even
1242
+ * where the cloud it hides is nearer. The marcher already computes a
1243
+ * transmittance-weighted mean cloud distance; writing that as the layer's depth
1244
+ * is the fix, and it needs the reconstruction to carry the depth through.
1245
+ *
1246
+ * Premultiplied over, not alpha blending: the marcher writes
1247
+ * `vec4(scatteredRadiance, viewTransmittance)`, and the composite the cloud
1248
+ * module documents is `sky * T + scattered`. With src.rgb = scattered and
1249
+ * src.a = 1 - T that is exactly One / OneMinusSrcAlpha, and no multiply of the
1250
+ * radiance by an alpha is needed or wanted — the radiance is already the
1251
+ * cloud's contribution to the pixel. A basic material emits
1252
+ * `vec4(diffuseColor.rgb, diffuseColor.a)` without premultiplying, so the pair
1253
+ * arrives at the blender as written.
1254
+ */
1255
+ #createCloudLayer() {
1256
+ const cloudTexture = this.#cloudTextureNode;
1257
+
1258
+ const material = new MeshBasicNodeMaterial();
1259
+ material.name = 'ToonLabSkyCloudLayer';
1260
+ material.depthTest = true;
1261
+ material.depthWrite = false;
1262
+ material.transparent = true;
1263
+ material.toneMapped = false;
1264
+ material.fog = false;
1265
+ // Seen from the inside. BackSide rather than DoubleSide on purpose: three
1266
+ // renders a DoubleSide transparent material in two passes, which would march
1267
+ // the whole screen twice for nothing.
1268
+ material.side = THREE.BackSide;
1269
+ material.blending = THREE.CustomBlending;
1270
+ material.blendEquation = THREE.AddEquation;
1271
+ material.blendSrc = THREE.OneFactor;
1272
+ material.blendDst = THREE.OneMinusSrcAlphaFactor;
1273
+ material.blendEquationAlpha = THREE.AddEquation;
1274
+ material.blendSrcAlpha = THREE.OneFactor;
1275
+ material.blendDstAlpha = THREE.OneMinusSrcAlphaFactor;
1276
+ // The image is screen-space, so the sphere is only a carrier for coverage and
1277
+ // depth; its tessellation and radius do not enter the shading at all.
1278
+ material.colorNode = Fn(() => {
1279
+ const image = cloudTexture.sample(screenUV).toVar();
1280
+ return vec4(max(image.rgb, vec3(0)), saturate(image.a.oneMinus()));
1281
+ })();
1282
+
1283
+ const mesh = new THREE.Mesh(new THREE.SphereGeometry(1, 32, 16), material);
1284
+ mesh.name = 'ToonLabSkyCloudLayer';
1285
+ mesh.frustumCulled = false;
1286
+ placeInLayer(mesh, RenderLayer.backgroundOverlay);
1287
+
1288
+ return { material, mesh };
1289
+ }
1290
+
1291
+ /** Refreshes the camera-derived uniforms every stage reads. Allocation-free. */
1292
+ #refreshCamera() {
1293
+ const camera = this.#camera;
1294
+ camera.updateMatrixWorld();
1295
+ const world = camera.matrixWorld.elements;
1296
+ const projection = camera.projectionMatrix.elements;
1297
+ const tanX = projection[0] !== 0 ? 1 / projection[0] : 1;
1298
+ const tanY = projection[5] !== 0 ? 1 / projection[5] : 1;
1299
+ rightScratch.set(world[0], world[1], world[2]).normalize().multiplyScalar(tanX);
1300
+ upScratch.set(world[4], world[5], world[6]).normalize().multiplyScalar(tanY);
1301
+ forwardScratch.set(-world[8], -world[9], -world[10]).normalize();
1302
+ // Columns are right * tanX, up * tanY, forward — the same basis the marcher
1303
+ // and the reconstruction build, so every stage agrees where a pixel looks.
1304
+ // `dot(basis * vec3(ndc, 1), forward)` is 1 by construction, which is what
1305
+ // lets the fog turn a view-space depth into a distance along the ray with a
1306
+ // single length().
1307
+ this.#post.rayBasis.value.set(
1308
+ rightScratch.x, upScratch.x, forwardScratch.x,
1309
+ rightScratch.y, upScratch.y, forwardScratch.y,
1310
+ rightScratch.z, upScratch.z, forwardScratch.z,
1311
+ );
1312
+ this.#post.cameraPosition.value.setFromMatrixPosition(camera.matrixWorld);
1313
+ this.#post.far.value = camera.far ?? this.#post.far.value;
1314
+ // The atmosphere carrier is created at a world-scale radius, but a normal
1315
+ // gameplay camera often has a far plane of only a few hundred units. Keep
1316
+ // the package-owned carrier inside that host frustum automatically; its
1317
+ // shader depends only on view direction, so this changes no atmosphere
1318
+ // math and prevents the clear colour from replacing the sky entirely.
1319
+ const far = Number.isFinite(camera.far) ? Math.max(camera.far, 1e-3) : 1;
1320
+ const near = Number.isFinite(camera.near) ? Math.max(camera.near, 0) : 0;
1321
+ const domeRadius = Math.min(far * 0.99, Math.max(far * 0.9, near * 1.01));
1322
+ if (this.#dome.mesh.scale.x !== domeRadius) {
1323
+ this.#dome.mesh.scale.setScalar(domeRadius);
1324
+ this.#dome.mesh.updateMatrix();
1325
+ }
1326
+ // The cloud backdrop rides with the camera, far enough out that its depth
1327
+ // beats anything a host is going to draw and near enough that the depth
1328
+ // buffer can still tell the two apart — see CLOUD_LAYER_FAR_FRACTION. The
1329
+ // depth test then decides on its own where cloud is hidden.
1330
+ const layer = this.#cloudLayer.mesh;
1331
+ layer.position.copy(this.#post.cameraPosition.value);
1332
+ layer.scale.setScalar(Math.min(
1333
+ far * CLOUD_LAYER_FAR_CAP,
1334
+ Math.max(
1335
+ far * CLOUD_LAYER_FAR_FRACTION,
1336
+ this.#clouds.fade.maxMarchDist.value * CLOUD_LAYER_MARCH_MARGIN,
1337
+ ),
1338
+ ));
1339
+ // Keeps the cloud pass's own camera uniforms current even on a frame where
1340
+ // the layer is disabled, because `cloudShadow()` reads that field from host
1341
+ // materials whether or not the clouds are on screen.
1342
+ this.#cloud.update(camera);
1343
+ }
1344
+
1345
+ /**
1346
+ * Aerial-perspective fog: opaque geometry fades toward the sky radiance along
1347
+ * its own view direction, so a far ridge converges on the sky sitting directly
1348
+ * behind it rather than on a flat haze colour.
1349
+ *
1350
+ * The extinction is the real per-channel atmospheric extinction at the
1351
+ * camera's altitude, straight off the baked medium, which is why `fogDensity`
1352
+ * 1 half-fades near 23 km without a fitted constant anywhere: ln 2 divided by
1353
+ * a sea-level extinction around 0.03 1/km IS 23 km. Scaling that optical depth
1354
+ * is all the parameter does, so 0 switches the stage off exactly.
1355
+ *
1356
+ * The target radiance is the sky march WITHOUT the sun disc. A ridge has to
1357
+ * fade into the sky behind it, not into a disc three orders of magnitude
1358
+ * brighter that happens to be near the same bearing.
1359
+ *
1360
+ * Open sky is left alone, and clouds are never fogged, and both fall out of the
1361
+ * one depth test rather than needing a mask: the cloud backdrop writes no
1362
+ * depth, so a cloud pixel carries the depth of whatever opaque geometry stands
1363
+ * behind it, and a cloud that survived the backdrop's own depth test has
1364
+ * nothing behind it but the cleared far plane. The threshold that test uses is
1365
+ * the subtle part — see SKY_DEPTH_FRACTION.
1366
+ *
1367
+ * Moves to src/sky/skyFog.js when that module lands; nothing here is exported.
1368
+ */
1369
+ #fogNode(sceneColor, scenePass) {
1370
+ const viewZ = scenePass.getViewZNode('depth');
1371
+ const atmosphere = this.#atmosphere;
1372
+ const skyColor = this.#skyColor;
1373
+ const scattering = this.#scattering;
1374
+ const sun = this.#sun;
1375
+ const post = this.#post;
1376
+ const groundLevel = this.#dome.uniforms.groundLevel;
1377
+
1378
+ return Fn(() => {
1379
+ const source = vec4(sceneColor).toVar();
1380
+ const rgb = source.rgb.toVar();
1381
+ // screenUV is top-left origin on both backends, so NDC y is 1 - 2v.
1382
+ const ndc = vec2(screenUV.x.mul(2).sub(1), screenUV.y.mul(-2).add(1)).toVar();
1383
+ const ray = post.rayBasis.mul(vec3(ndc, 1)).toVar();
1384
+ const viewDir = normalize(ray).toVar();
1385
+ // viewZ is negative in view space; the basis above makes the forward
1386
+ // component exactly 1, so the distance along the ray is the forward
1387
+ // distance times the ray's length.
1388
+ const forwardDistance = viewZ.negate().toVar();
1389
+ const distance = forwardDistance.mul(length(ray)).toVar();
1390
+
1391
+ // Geometry only. Sky pixels skip the march entirely rather than paying for
1392
+ // a target they then mix by zero.
1393
+ If(forwardDistance.lessThan(post.far.mul(SKY_DEPTH_FRACTION)), () => {
1394
+ const cameraAltitude = max(post.cameraPosition.y.sub(groundLevel), 1).toVar();
1395
+ const cameraKm = cameraAltitude.mul(0.001).toVar();
1396
+ const air = scattering.mediumNodes(cameraKm);
1397
+ const opticalDepth = air.extinction
1398
+ .mul(distance.mul(0.001))
1399
+ .mul(max(atmosphere.fogDensity, 0))
1400
+ .toVar();
1401
+ const transmittance = exp(opticalDepth.negate()).toVar();
1402
+
1403
+ const skyTarget = applySkyColorNode(atmosphereRaymarchNodes({
1404
+ groundAlbedo: atmosphere.groundAlbedo,
1405
+ mieDirectionalG: atmosphere.mieDirectionalG,
1406
+ mieScatteringStrength: atmosphere.mieScatteringStrength,
1407
+ scattering,
1408
+ skyMultipleScattering: atmosphere.skyMultipleScattering,
1409
+ steps: FOG_SKY_MARCH_STEPS,
1410
+ sunDir: normalize(sun.direction),
1411
+ sunIrradiance: sun.color.mul(sun.intensity),
1412
+ viewDir,
1413
+ viewHeightKm: cameraKm,
1414
+ }).luminance, viewDir, skyColor, this.#timeOfDay).toVar();
1415
+
1416
+ // The far band replaces geometry with sky outright, which is what hides
1417
+ // the rim of a finite world. Kept strictly ordered so the smoothstep
1418
+ // cannot divide by zero.
1419
+ const farFade = smoothstep(
1420
+ atmosphere.fogFarFadeStart,
1421
+ max(atmosphere.fogFarFadeEnd, atmosphere.fogFarFadeStart.add(1)),
1422
+ distance,
1423
+ ).toVar();
1424
+ rgb.assign(mix(mix(skyTarget, rgb, transmittance), skyTarget, farFade));
1425
+ });
1426
+
1427
+ return vec4(max(rgb, vec3(0)), source.a);
1428
+ })();
1429
+ }
1430
+ }
1431
+
1432
+ /**
1433
+ * Convenience factory, matching this package's `createX` naming. Identical to
1434
+ * {@link SkySystem.create}.
1435
+ */
1436
+ export function createSkySystem(options = {}) {
1437
+ return SkySystem.create(options);
1438
+ }