@call-me-sensei/toonlab 0.3.1 → 0.4.20

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 (761) hide show
  1. package/NPM-LIBRARY.md +225 -0
  2. package/README.md +588 -184
  3. package/agents/PROMPTS.md +87 -0
  4. package/agents/README.md +54 -0
  5. package/agents/claude/CLAUDE.md +8 -0
  6. package/agents/codex/AGENTS.md +159 -0
  7. package/agents/cursor/toonlab.mdc +37 -0
  8. package/agents/references/anime-art-direction.md +24 -0
  9. package/agents/references/asset-sourcing-policy.md +23 -0
  10. package/agents/references/custom-gap-report.md +16 -0
  11. package/agents/references/mcp-asset-discovery.md +104 -0
  12. package/agents/references/runtime-entry-points.md +175 -0
  13. package/agents/references/style-bundles.md +71 -0
  14. package/agents/skills/claude/asset-sourcing/SKILL.md +275 -0
  15. package/agents/skills/claude/environment/SKILL.md +59 -0
  16. package/agents/skills/claude/game-dev/SKILL.md +100 -0
  17. package/agents/skills/claude/post-processing/SKILL.md +44 -0
  18. package/agents/skills/claude/rock-ground-shaders/SKILL.md +134 -0
  19. package/agents/skills/claude/rockgen/SKILL.md +30 -0
  20. package/agents/skills/claude/scene-style-application/SKILL.md +74 -0
  21. package/agents/skills/claude/style-presets/SKILL.md +101 -0
  22. package/agents/skills/claude/toon-shading/SKILL.md +44 -0
  23. package/agents/skills/claude/vegetation-sky/SKILL.md +167 -0
  24. package/agents/skills/claude/visual-verification/SKILL.md +136 -0
  25. package/agents/skills/claude/water/SKILL.md +105 -0
  26. package/agents/skills/codex/asset-sourcing/SKILL.md +275 -0
  27. package/agents/skills/codex/environment/SKILL.md +59 -0
  28. package/agents/skills/codex/game-dev/SKILL.md +100 -0
  29. package/agents/skills/codex/post-processing/SKILL.md +44 -0
  30. package/agents/skills/codex/rock-ground-shaders/SKILL.md +134 -0
  31. package/agents/skills/codex/rockgen/SKILL.md +30 -0
  32. package/agents/skills/codex/scene-style-application/SKILL.md +74 -0
  33. package/agents/skills/codex/style-presets/SKILL.md +101 -0
  34. package/agents/skills/codex/toon-shading/SKILL.md +44 -0
  35. package/agents/skills/codex/vegetation-sky/SKILL.md +167 -0
  36. package/agents/skills/codex/visual-verification/SKILL.md +136 -0
  37. package/agents/skills/codex/water/SKILL.md +105 -0
  38. package/cli/toonlab.mjs +53 -0
  39. package/compose.yaml +20 -0
  40. package/database/apply-sql.mjs +141 -0
  41. package/database/client.mjs +39 -0
  42. package/database/creation-tags.mjs +23 -0
  43. package/database/env.mjs +16 -0
  44. package/database/fal-patina.mjs +131 -0
  45. package/database/generation-service.mjs +415 -0
  46. package/database/migrations/0001_local_workspace.sql +120 -0
  47. package/database/migrations/0002_file_ownership.sql +11 -0
  48. package/database/migrations/0003_remove_autosaves_from_library.sql +7 -0
  49. package/database/migrations/0004_catalog_asset_packs.sql +39 -0
  50. package/database/migrations/0005_creation_tag_discovery.sql +1 -0
  51. package/database/migrations/0006_normalize_creation_tags.sql +28 -0
  52. package/database/migrations/0007_creation_revisions.sql +80 -0
  53. package/database/migrations/0008_creation_revision_hardening.sql +98 -0
  54. package/database/migrations/0009_creation_revision_delete_integrity.sql +11 -0
  55. package/database/migrations/0010_external_catalog_assets.sql +28 -0
  56. package/database/providers.mjs +644 -0
  57. package/database/repository.mjs +1073 -0
  58. package/database/seeds/catalog/0001_empty_official_catalog.sql +4 -0
  59. package/database/seeds/catalog/0002_2026-08.sql +19454 -0
  60. package/database/seeds/catalog/0003_2026-08-open-assets.sql +159086 -0
  61. package/database/seeds/catalog/0004_2026-08-c7-rocks.sql +39405 -0
  62. package/mcp/lab-management.mjs +629 -0
  63. package/mcp/public-catalog.mjs +168 -0
  64. package/mcp/server.mjs +1044 -63
  65. package/mcp/vite-plugin.mjs +519 -26
  66. package/mcp/workspace.mjs +26 -1
  67. package/package.json +334 -46
  68. package/scripts/generate-catalog-seed.mjs +324 -0
  69. package/scripts/setup-local.mjs +128 -0
  70. package/src/agents/index.js +7 -0
  71. package/src/agents/sceneStyleOperations.js +169 -0
  72. package/src/asset-policy/catalogLicenses.js +102 -0
  73. package/src/asset-policy/index.js +315 -0
  74. package/src/assetlib/assetRef.js +1 -1
  75. package/src/assetlib/galleryMaterialFamily.js +165 -0
  76. package/src/assetlib/index.js +6 -2
  77. package/src/assetlib/loadImported.js +15 -1
  78. package/src/assetlib/plateau.js +188 -0
  79. package/src/assetlib/plateauLandmarks.js +144 -0
  80. package/src/assetlib/plateauViewer.js +348 -0
  81. package/src/assetlib/sources.js +16 -2
  82. package/src/catalog/manifest.js +11 -1
  83. package/src/catalog/officialCatalog.js +4 -0
  84. package/src/catalog/officialCatalogAssetRuntime.js +324 -0
  85. package/src/catalog/officialCatalogLod.js +183 -0
  86. package/src/catalog/officialCatalogPlacement.js +243 -0
  87. package/src/catalog/officialCatalogProvider.js +334 -0
  88. package/src/character/animationRetarget.js +1084 -0
  89. package/src/character/characterRig.js +6 -1
  90. package/src/character/characterRuntime.js +544 -0
  91. package/src/character/groundStabilizer.js +137 -0
  92. package/src/character/index.js +8 -0
  93. package/src/character/locomotionActions.js +74 -0
  94. package/src/character/locomotionStateMachine.js +241 -0
  95. package/src/character/mannequinAsset.js +15 -0
  96. package/src/character/mannequinAssetUrl.browser.js +4 -0
  97. package/src/character/mannequinAssetUrl.node.js +3 -0
  98. package/src/character/modelLoader.js +92 -12
  99. package/src/character/walkableCharacterRuntime.js +284 -0
  100. package/src/character/waterInteractionController.js +217 -0
  101. package/src/cloud/ambientSkyBaker.js +248 -0
  102. package/src/cloud/cloudLighting.js +1114 -0
  103. package/src/cloud/cloudParams.js +819 -0
  104. package/src/cloud/cloudReprojection.js +563 -0
  105. package/src/cloud/cloudStyle.js +780 -0
  106. package/src/cloud/cloudStyleSnapshots.js +387 -0
  107. package/src/cloud/cloudVolume.js +1903 -0
  108. package/src/cloud/heroCloudRecipe.js +404 -0
  109. package/src/cloud/index.js +42 -0
  110. package/src/cloud/noise/baseShapeVolume.js +331 -0
  111. package/src/cloud/noise/cirrusMap.js +131 -0
  112. package/src/cloud/noise/curlNoise.js +289 -0
  113. package/src/cloud/noise/erosionVolume.js +188 -0
  114. package/src/cloud/noise/noiseVolume.js +202 -0
  115. package/src/cloud/noise/periodicNoise3.js +295 -0
  116. package/src/cloud/noise/weatherMap.js +470 -0
  117. package/src/cloud/paramSchema.js +458 -0
  118. package/src/collisionMetadata.js +320 -0
  119. package/src/core/systemStylePolicy.js +32 -0
  120. package/src/environment/dayCurves.js +146 -0
  121. package/src/environment/environmentGroundFieldPass.js +354 -0
  122. package/src/environment/environmentMaterialAdapter.js +144 -6
  123. package/src/environment/environmentPresets.js +486 -90
  124. package/src/environment/environmentRigs.js +17 -2
  125. package/src/environment/environmentSettings.js +37 -1
  126. package/src/environment/environmentShaderMaterials.js +37 -6
  127. package/src/environment/environmentState.js +133 -0
  128. package/src/environment/environmentSunShadowPass.js +399 -6
  129. package/src/environment/environmentTextureResolver.js +7 -0
  130. package/src/environment/index.js +51 -0
  131. package/src/environment/manufacturedMaterialContract.js +837 -0
  132. package/src/environment/manufacturedReflectionProvider.js +114 -0
  133. package/src/environment/scanAssetStylize.js +4 -4
  134. package/src/environment/surfaceMaterialModes.js +71 -0
  135. package/src/environment/toonLabEnvironmentMaterials.js +353 -0
  136. package/src/environment/toonLabMaterialPassCoupling.js +347 -0
  137. package/src/environment/toonLabNormalIntegration.js +171 -0
  138. package/src/environment/toonLabRockMaterialResolver.js +592 -0
  139. package/src/environment/toonLabSourceDefaultLit.js +444 -0
  140. package/src/environment/toonLabSourceLibrary.js +762 -0
  141. package/src/environment/toonLabSourceMaterials.js +3718 -0
  142. package/src/environment/toonLabSourceSubsurfaceLighting.js +415 -0
  143. package/src/environment/toonLabSourceTemporal.js +717 -0
  144. package/src/environment/toonLabSurfaceLighting.js +462 -0
  145. package/src/environment/toonLabTextureReadiness.js +105 -0
  146. package/src/environment/toonLabTreeMaterials.js +450 -0
  147. package/src/environment/transparentMaterialProfile.js +87 -0
  148. package/src/environment/urbanPropMaterial.js +2976 -0
  149. package/src/ground-shader/groundPrintLayer.js +375 -0
  150. package/src/ground-shader/groundShaderMaterial.js +851 -0
  151. package/src/ground-shader/groundShaderSettings.js +468 -0
  152. package/src/ground-shader/index.js +3 -0
  153. package/src/index.js +52 -22
  154. package/src/lighting/callMeSenseiLightingContract.js +163 -0
  155. package/src/lighting/index.js +14 -7
  156. package/src/lighting/lightingCapabilities.js +2 -2
  157. package/src/lighting/lightingPresets.js +6 -3
  158. package/src/lighting/lightingStyle.js +41 -6
  159. package/src/lighting/lightingSystem.js +200 -6
  160. package/src/lighting/{unrealExport.js → toonLabExport.js} +40 -41
  161. package/src/post/postProcessing.js +71 -12
  162. package/src/react/index.js +66 -0
  163. package/src/renderer/index.js +16 -0
  164. package/src/renderer/rendererConfiguration.js +250 -0
  165. package/src/renderer/styleComparison.js +985 -0
  166. package/src/rock-shader/index.js +8 -0
  167. package/src/rock-shader/rockGeometryDetail.js +701 -0
  168. package/src/rock-shader/rockMaterial.js +2586 -0
  169. package/src/rock-shader/rockRegionRuntime.js +185 -0
  170. package/src/rock-shader/rockSemanticMaterialRuntime.js +337 -0
  171. package/src/rock-shader/rockShaderRuntime.js +781 -0
  172. package/src/rock-shader/rockShaderSettings.js +1099 -0
  173. package/src/rock-shader/rockTangentIntegrity.js +136 -0
  174. package/src/rock-shader/rockTextureIntegrity.js +115 -0
  175. package/src/rockgen/export/glbExport.js +104 -14
  176. package/src/rockgen/index.js +5 -3
  177. package/src/rockgen/lod/index.js +6 -0
  178. package/src/rockgen/lod/rockLodMetrics.js +168 -0
  179. package/src/rockgen/lod/rockLodPlanner.js +372 -0
  180. package/src/rockgen/lod/rockLodPolicy.js +235 -0
  181. package/src/rockgen/lod/rockLodRuntime.js +124 -0
  182. package/src/rockgen/lod/rockLodSimplifier.js +173 -0
  183. package/src/rockgen/lod/rockLodValidation.js +113 -0
  184. package/src/rockgen/mesh/meshAttributes.js +17 -0
  185. package/src/rockgen/mesh/meshDocument.js +6 -0
  186. package/src/rockgen/rockDocument.js +376 -9
  187. package/src/rockgen/rockgenPresets.js +114 -13
  188. package/src/rockgen/rockgenSettings.js +62 -11
  189. package/src/rockgen/surface/c7GeologySurface.js +372 -0
  190. package/src/runtime/index.js +14 -0
  191. package/src/runtime/sceneCollisionRuntime.js +317 -0
  192. package/src/runtime/sceneSurfaceRuntime.js +451 -0
  193. package/src/runtime/sceneUpdateScheduler.js +203 -0
  194. package/src/shaders-tsl/anime.js +9 -2
  195. package/src/shaders-tsl/chunks/environment-ground-field.js +174 -0
  196. package/src/shaders-tsl/chunks/environment-state.js +79 -0
  197. package/src/shaders-tsl/chunks/environment-sun-shadow.js +99 -32
  198. package/src/shaders-tsl/chunks/normalized-hue.js +41 -0
  199. package/src/shaders-tsl/chunks/pass-depth-color.js +4 -2
  200. package/src/shaders-tsl/chunks/scene-depth-color-pass.js +273 -0
  201. package/src/shaders-tsl/chunks/vegetation-style.js +116 -8
  202. package/src/shaders-tsl/chunks/water-color.js +19 -5
  203. package/src/shaders-tsl/chunks/water-shore-state.js +8 -1
  204. package/src/shaders-tsl/chunks/world-noise.js +30 -0
  205. package/src/shaders-tsl/environment.js +123 -17
  206. package/src/shaders-tsl/flower.js +51 -8
  207. package/src/shaders-tsl/grass.js +194 -29
  208. package/src/shaders-tsl/post-composite.js +83 -2
  209. package/src/shaders-tsl/tree-leaf.js +107 -16
  210. package/src/shaders-tsl/water-breaker.js +18 -4
  211. package/src/shaders-tsl/water.js +51 -3
  212. package/src/shaders-tsl/woody-surface.js +59 -7
  213. package/src/sky/atmosphereDome.js +193 -0
  214. package/src/sky/atmosphereParams.js +396 -0
  215. package/src/sky/atmosphereScattering.js +593 -0
  216. package/src/sky/atmosphereSky.js +371 -0
  217. package/src/sky/cloudShadow.js +379 -0
  218. package/src/sky/godRays.js +257 -0
  219. package/src/sky/index.js +55 -1
  220. package/src/sky/nightSky.js +1190 -0
  221. package/src/sky/renderLayers.js +120 -0
  222. package/src/sky/skyColor.js +582 -0
  223. package/src/sky/skyDayCycle.js +244 -0
  224. package/src/sky/skyParams.js +661 -0
  225. package/src/sky/skyPresets.js +772 -0
  226. package/src/sky/skyQualityTiers.js +383 -0
  227. package/src/sky/skyShaderSettings.js +699 -0
  228. package/src/sky/skyStyleSnapshots.js +211 -0
  229. package/src/sky/skySystem.js +1447 -0
  230. package/src/sky/skyTimeKeyframes.js +361 -0
  231. package/src/sky/stylizedSky.js +405 -116
  232. package/src/sky/sunDriver.js +499 -0
  233. package/src/sky/timeOfDay.js +335 -0
  234. package/src/styles/animeGameProfile.js +44 -0
  235. package/src/styles/index.js +157 -0
  236. package/src/styles/manufacturedStyleLabeling.js +204 -0
  237. package/src/styles/neutralStylePresets.js +712 -0
  238. package/src/styles/sceneLayerDocuments.js +185 -0
  239. package/src/styles/sceneLookComposition.js +156 -0
  240. package/src/styles/sceneQualityApplication.js +152 -0
  241. package/src/styles/sceneQualityProfiles.js +268 -0
  242. package/src/styles/sceneStyleAudit.js +512 -0
  243. package/src/styles/sceneStyleRuntime.js +923 -0
  244. package/src/styles/styleAdapters.js +177 -0
  245. package/src/styles/styleApplication.js +369 -0
  246. package/src/styles/styleBundle.js +445 -92
  247. package/src/styles/styleBundleProvider.js +83 -0
  248. package/src/styles/styleDomains.js +21 -0
  249. package/src/styles/styleInspector.js +262 -0
  250. package/src/styles/styleMaterialContract.js +375 -0
  251. package/src/styles/styleMetadata.js +73 -0
  252. package/src/styles/styleTargetDiscovery.js +162 -0
  253. package/src/styles/styleTargetLabels.js +206 -0
  254. package/src/styles/styleTargetMaterialCoverage.js +137 -0
  255. package/src/styles/styleTransaction.js +272 -0
  256. package/src/texgen/evaluateTexture.js +30 -3
  257. package/src/texgen/textureGenerators.js +83 -35
  258. package/src/texgen/textureSettings.js +25 -8
  259. package/src/toon/toonSettings.js +100 -2
  260. package/src/vegetation/branchTree.js +587 -0
  261. package/src/vegetation/callMeSenseiGrass.js +183 -0
  262. package/src/vegetation/compiledTree.js +506 -0
  263. package/src/vegetation/contactShadowField.js +107 -0
  264. package/src/vegetation/flowerSpecies.js +10 -2
  265. package/src/vegetation/grass.js +13 -0
  266. package/src/vegetation/grassClump.js +1179 -0
  267. package/src/vegetation/importedVegetationMaterial.js +183 -0
  268. package/src/vegetation/index.js +17 -1
  269. package/src/vegetation/legacyTreePresets.js +120 -0
  270. package/src/vegetation/scatter.js +688 -3
  271. package/src/vegetation/stylizedBush.js +14 -0
  272. package/src/vegetation/stylizedFlower.js +31 -0
  273. package/src/vegetation/stylizedFlowers.js +59 -7
  274. package/src/vegetation/stylizedForest.js +455 -147
  275. package/src/vegetation/stylizedGrass.js +188 -24
  276. package/src/vegetation/stylizedTree.js +676 -54
  277. package/src/vegetation/stylizedTreeFoliage.js +1111 -38
  278. package/src/vegetation/stylizedUnderstory.js +230 -0
  279. package/src/vegetation/treeExport.js +262 -47
  280. package/src/vegetation/treeSurfaceTextures.js +665 -0
  281. package/src/vegetation/vegetationShaders.js +617 -28
  282. package/src/version.js +3 -0
  283. package/src/water/water.js +2 -0
  284. package/src/water/waterBreakerSystem.js +2 -0
  285. package/src/water/waterCurrentField.js +1 -0
  286. package/src/water/waterMaterial.js +3 -0
  287. package/src/water/waterRain.js +2 -0
  288. package/src/water/waterScenePasses.js +170 -7
  289. package/src/water/waterSettings.js +250 -50
  290. package/src/water/waterShoreMaterial.js +16 -2
  291. package/src/water/waterShoreStateField.js +1 -1
  292. package/src/water/waterSplashSystem.js +2 -0
  293. package/src/water/waterStageSettings.js +60 -0
  294. package/src/water/waterSurface.js +144 -4
  295. package/src/water/waterUnderwaterAtmosphere.js +288 -0
  296. package/src/water/waterVegetation.js +20 -4
  297. package/src/worldCollision.js +64 -9
  298. package/types/agents/index.d.ts +1 -0
  299. package/types/agents/sceneStyleOperations.d.ts +484 -0
  300. package/types/asset-policy/catalogLicenses.d.ts +7 -0
  301. package/types/asset-policy/index.d.ts +20 -0
  302. package/types/assetlib/ambientcg.d.ts +81 -0
  303. package/types/assetlib/assetRef.d.ts +26 -0
  304. package/types/assetlib/galleryMaterialFamily.d.ts +13 -0
  305. package/types/assetlib/importedEntry.d.ts +18 -0
  306. package/types/assetlib/index.d.ts +16 -0
  307. package/types/assetlib/kaykit.d.ts +112 -0
  308. package/types/assetlib/kaykitStaticIndex.d.ts +38 -0
  309. package/types/assetlib/loadImported.d.ts +56 -0
  310. package/types/assetlib/opensource3d.d.ts +55 -0
  311. package/types/assetlib/plateau.d.ts +67 -0
  312. package/types/assetlib/plateauLandmarks.d.ts +238 -0
  313. package/types/assetlib/plateauViewer.d.ts +3 -0
  314. package/types/assetlib/polyhaven.d.ts +90 -0
  315. package/types/assetlib/polypizza.d.ts +10 -0
  316. package/types/assetlib/smithsonian.d.ts +9 -0
  317. package/types/assetlib/sources.d.ts +22 -0
  318. package/types/assetlib/zip.d.ts +8 -0
  319. package/types/catalog/manifest.d.ts +26 -0
  320. package/types/catalog/officialCatalog.d.ts +4 -0
  321. package/types/catalog/officialCatalogAssetRuntime.d.ts +2 -0
  322. package/types/catalog/officialCatalogLod.d.ts +63 -0
  323. package/types/catalog/officialCatalogPlacement.d.ts +49 -0
  324. package/types/catalog/officialCatalogProvider.d.ts +7 -0
  325. package/types/character/animationRetarget.d.ts +20 -0
  326. package/types/character/characterRig.d.ts +87 -0
  327. package/types/character/characterRuntime.d.ts +5 -0
  328. package/types/character/freestyleSwimClip.d.ts +5 -0
  329. package/types/character/groundStabilizer.d.ts +55 -0
  330. package/types/character/index.d.ts +10 -0
  331. package/types/character/locomotionActions.d.ts +4 -0
  332. package/types/character/locomotionStateMachine.d.ts +62 -0
  333. package/types/character/mannequinAsset.d.ts +12 -0
  334. package/types/character/mannequinAssetUrl.node.d.ts +1 -0
  335. package/types/character/modelLoader.d.ts +7 -0
  336. package/types/character/walkableCharacterRuntime.d.ts +343 -0
  337. package/types/character/waterInteractionController.d.ts +114 -0
  338. package/types/cloud/ambientSkyBaker.d.ts +18 -0
  339. package/types/cloud/cloudLighting.d.ts +38 -0
  340. package/types/cloud/cloudParams.d.ts +18 -0
  341. package/types/cloud/cloudReprojection.d.ts +15 -0
  342. package/types/cloud/cloudStyle.d.ts +1380 -0
  343. package/types/cloud/cloudStyleSnapshots.d.ts +10 -0
  344. package/types/cloud/cloudVolume.d.ts +43 -0
  345. package/types/cloud/heroCloudRecipe.d.ts +167 -0
  346. package/types/cloud/index.d.ts +12 -0
  347. package/types/cloud/noise/baseShapeVolume.d.ts +86 -0
  348. package/types/cloud/noise/cirrusMap.d.ts +24 -0
  349. package/types/cloud/noise/curlNoise.d.ts +106 -0
  350. package/types/cloud/noise/erosionVolume.d.ts +58 -0
  351. package/types/cloud/noise/noiseVolume.d.ts +63 -0
  352. package/types/cloud/noise/periodicNoise3.d.ts +75 -0
  353. package/types/cloud/noise/weatherMap.d.ts +227 -0
  354. package/types/cloud/paramSchema.d.ts +142 -0
  355. package/types/collisionMetadata.d.ts +11 -0
  356. package/types/core/generation.d.ts +95 -0
  357. package/types/core/materialRoles.d.ts +102 -0
  358. package/types/core/presetDocuments.d.ts +25 -0
  359. package/types/core/systemStylePolicy.d.ts +4 -0
  360. package/types/environment/dayCurves.d.ts +47 -0
  361. package/types/environment/environmentAmbientProbe.d.ts +2 -0
  362. package/types/environment/environmentGroundFieldPass.d.ts +2 -0
  363. package/types/environment/environmentMaterialAdapter.d.ts +44 -0
  364. package/types/environment/environmentMaterialClassifier.d.ts +26 -0
  365. package/types/environment/environmentPlanarReflection.d.ts +3 -0
  366. package/types/environment/environmentPresets.d.ts +171 -0
  367. package/types/environment/environmentRigs.d.ts +13 -0
  368. package/types/environment/environmentSettings.d.ts +161 -0
  369. package/types/environment/environmentShaderMaterials.d.ts +14 -0
  370. package/types/environment/environmentState.d.ts +6 -0
  371. package/types/environment/environmentSunShadowPass.d.ts +2 -0
  372. package/types/environment/environmentTextureResolver.d.ts +30 -0
  373. package/types/environment/environmentTimeOfDay.d.ts +25 -0
  374. package/types/environment/environmentVertexAo.d.ts +18 -0
  375. package/types/environment/index.d.ts +27 -0
  376. package/types/environment/manufacturedMaterialContract.d.ts +129 -0
  377. package/types/environment/manufacturedReflectionProvider.d.ts +3 -0
  378. package/types/environment/scanAssetStylize.d.ts +43 -0
  379. package/types/environment/surfaceMaterialModes.d.ts +14 -0
  380. package/types/environment/toonLabEnvironmentMaterials.d.ts +139 -0
  381. package/types/environment/toonLabMaterialPassCoupling.d.ts +7 -0
  382. package/types/environment/toonLabNormalIntegration.d.ts +29 -0
  383. package/types/environment/toonLabRockMaterialResolver.d.ts +270 -0
  384. package/types/environment/toonLabSourceDefaultLit.d.ts +136 -0
  385. package/types/environment/toonLabSourceLibrary.d.ts +19 -0
  386. package/types/environment/toonLabSourceMaterials.d.ts +14 -0
  387. package/types/environment/toonLabSourceSubsurfaceLighting.d.ts +85 -0
  388. package/types/environment/toonLabSourceTemporal.d.ts +20 -0
  389. package/types/environment/toonLabSurfaceLighting.d.ts +153 -0
  390. package/types/environment/toonLabTextureReadiness.d.ts +8 -0
  391. package/types/environment/toonLabTreeMaterials.d.ts +7 -0
  392. package/types/environment/transparentMaterialProfile.d.ts +76 -0
  393. package/types/environment/urbanPropMaterial.d.ts +25 -0
  394. package/types/ground-shader/groundPrintLayer.d.ts +4 -0
  395. package/types/ground-shader/groundShaderMaterial.d.ts +11 -0
  396. package/types/ground-shader/groundShaderSettings.d.ts +90 -0
  397. package/types/ground-shader/index.d.ts +3 -0
  398. package/types/index.d.ts +1591 -0
  399. package/types/lighting/callMeSenseiLightingContract.d.ts +14 -0
  400. package/types/lighting/colorIntensity.d.ts +44 -0
  401. package/types/lighting/index.d.ts +12 -0
  402. package/types/lighting/lightDescriptors.d.ts +803 -0
  403. package/types/lighting/lightingCapabilities.d.ts +85 -0
  404. package/types/lighting/lightingDocuments.d.ts +140 -0
  405. package/types/lighting/lightingFixtures.d.ts +171 -0
  406. package/types/lighting/lightingGenerator.d.ts +403 -0
  407. package/types/lighting/lightingPresets.d.ts +264 -0
  408. package/types/lighting/lightingRuntime.d.ts +401 -0
  409. package/types/lighting/lightingStyle.d.ts +156 -0
  410. package/types/lighting/lightingSystem.d.ts +440 -0
  411. package/types/lighting/toonLabExport.d.ts +46 -0
  412. package/types/lighting/utils.d.ts +18 -0
  413. package/types/loaders/index.d.ts +1 -0
  414. package/types/post/index.d.ts +2 -0
  415. package/types/post/postGenerator.d.ts +282 -0
  416. package/types/post/postProcessing.d.ts +16 -0
  417. package/types/react/index.d.ts +1785 -0
  418. package/types/renderer/index.d.ts +2 -0
  419. package/types/renderer/rendererConfiguration.d.ts +8 -0
  420. package/types/renderer/styleComparison.d.ts +409 -0
  421. package/types/rock-shader/index.d.ts +8 -0
  422. package/types/rock-shader/rockGeometryDetail.d.ts +300 -0
  423. package/types/rock-shader/rockMaterial.d.ts +21 -0
  424. package/types/rock-shader/rockRegionRuntime.d.ts +86 -0
  425. package/types/rock-shader/rockSemanticMaterialRuntime.d.ts +29 -0
  426. package/types/rock-shader/rockShaderRuntime.d.ts +10 -0
  427. package/types/rock-shader/rockShaderSettings.d.ts +184 -0
  428. package/types/rock-shader/rockTangentIntegrity.d.ts +51 -0
  429. package/types/rock-shader/rockTextureIntegrity.d.ts +61 -0
  430. package/types/rockgen/export/glbExport.d.ts +58 -0
  431. package/types/rockgen/heightfield/heightfieldErosion.d.ts +10 -0
  432. package/types/rockgen/heightfield/heightfieldPatch.d.ts +15 -0
  433. package/types/rockgen/heightfield/stylizedErosionSim.d.ts +41 -0
  434. package/types/rockgen/index.d.ts +12 -0
  435. package/types/rockgen/lod/index.d.ts +6 -0
  436. package/types/rockgen/lod/rockLodMetrics.d.ts +62 -0
  437. package/types/rockgen/lod/rockLodPlanner.d.ts +86 -0
  438. package/types/rockgen/lod/rockLodPolicy.d.ts +76 -0
  439. package/types/rockgen/lod/rockLodRuntime.d.ts +95 -0
  440. package/types/rockgen/lod/rockLodSimplifier.d.ts +15 -0
  441. package/types/rockgen/lod/rockLodValidation.d.ts +16 -0
  442. package/types/rockgen/mesh/meshAttributes.d.ts +32 -0
  443. package/types/rockgen/mesh/meshDocument.d.ts +40 -0
  444. package/types/rockgen/mesh/surfaceNets.d.ts +42 -0
  445. package/types/rockgen/noise/cellularNoise3.d.ts +24 -0
  446. package/types/rockgen/noise/prng.d.ts +16 -0
  447. package/types/rockgen/noise/simplexNoise3.d.ts +2 -0
  448. package/types/rockgen/noise/valueNoise3.d.ts +12 -0
  449. package/types/rockgen/rockDocument.d.ts +243 -0
  450. package/types/rockgen/rockHelpers.d.ts +2 -0
  451. package/types/rockgen/rockgenPresets.d.ts +10 -0
  452. package/types/rockgen/rockgenSettings.d.ts +531 -0
  453. package/types/rockgen/sdf/fieldCompiler.d.ts +20 -0
  454. package/types/rockgen/sdf/sculptEdits.d.ts +30 -0
  455. package/types/rockgen/sdf/sdfModifiers.d.ts +19 -0
  456. package/types/rockgen/sdf/sdfOps.d.ts +8 -0
  457. package/types/rockgen/sdf/sdfPrimitives.d.ts +22 -0
  458. package/types/rockgen/surface/c7GeologySurface.d.ts +8 -0
  459. package/types/runtime/index.d.ts +3 -0
  460. package/types/runtime/sceneCollisionRuntime.d.ts +94 -0
  461. package/types/runtime/sceneSurfaceRuntime.d.ts +90 -0
  462. package/types/runtime/sceneUpdateScheduler.d.ts +28 -0
  463. package/types/shaders-tsl/anime.d.ts +9 -0
  464. package/types/shaders-tsl/chunks/character-color.d.ts +6 -0
  465. package/types/shaders-tsl/chunks/character-highlights.d.ts +12 -0
  466. package/types/shaders-tsl/chunks/character-lighting.d.ts +20 -0
  467. package/types/shaders-tsl/chunks/character-material-maps.d.ts +18 -0
  468. package/types/shaders-tsl/chunks/character-roles.d.ts +21 -0
  469. package/types/shaders-tsl/chunks/character-scene-lights.d.ts +48 -0
  470. package/types/shaders-tsl/chunks/character-shadow-color.d.ts +5 -0
  471. package/types/shaders-tsl/chunks/character-skinning.d.ts +23 -0
  472. package/types/shaders-tsl/chunks/environment-color.d.ts +9 -0
  473. package/types/shaders-tsl/chunks/environment-debug.d.ts +24 -0
  474. package/types/shaders-tsl/chunks/environment-ground-field.d.ts +40 -0
  475. package/types/shaders-tsl/chunks/environment-lighting.d.ts +22 -0
  476. package/types/shaders-tsl/chunks/environment-state.d.ts +42 -0
  477. package/types/shaders-tsl/chunks/environment-sun-shadow.d.ts +19 -0
  478. package/types/shaders-tsl/chunks/foliage-fog.d.ts +21 -0
  479. package/types/shaders-tsl/chunks/normalized-hue.d.ts +1 -0
  480. package/types/shaders-tsl/chunks/pass-depth-color.d.ts +20 -0
  481. package/types/shaders-tsl/chunks/projected-water-caustics.d.ts +24 -0
  482. package/types/shaders-tsl/chunks/scene-depth-color-pass.d.ts +39 -0
  483. package/types/shaders-tsl/chunks/stylized-cloud-shadow.d.ts +9 -0
  484. package/types/shaders-tsl/chunks/vegetation-style.d.ts +60 -0
  485. package/types/shaders-tsl/chunks/water-color.d.ts +15 -0
  486. package/types/shaders-tsl/chunks/water-common.d.ts +9 -0
  487. package/types/shaders-tsl/chunks/water-foam.d.ts +8 -0
  488. package/types/shaders-tsl/chunks/water-lighting.d.ts +9 -0
  489. package/types/shaders-tsl/chunks/water-ripple.d.ts +8 -0
  490. package/types/shaders-tsl/chunks/water-shore-state.d.ts +7 -0
  491. package/types/shaders-tsl/chunks/water-waves.d.ts +18 -0
  492. package/types/shaders-tsl/chunks/world-noise.d.ts +4 -0
  493. package/types/shaders-tsl/environment-ao-overlay.d.ts +5 -0
  494. package/types/shaders-tsl/environment.d.ts +34 -0
  495. package/types/shaders-tsl/flower.d.ts +6 -0
  496. package/types/shaders-tsl/grass.d.ts +4 -0
  497. package/types/shaders-tsl/post-composite.d.ts +25 -0
  498. package/types/shaders-tsl/sky.d.ts +4 -0
  499. package/types/shaders-tsl/tree-leaf.d.ts +2 -0
  500. package/types/shaders-tsl/water-breaker.d.ts +15 -0
  501. package/types/shaders-tsl/water-kelp.d.ts +5 -0
  502. package/types/shaders-tsl/water-rain.d.ts +10 -0
  503. package/types/shaders-tsl/water-shore-state-simulation.d.ts +12 -0
  504. package/types/shaders-tsl/water-simulation.d.ts +5 -0
  505. package/types/shaders-tsl/water-splash.d.ts +12 -0
  506. package/types/shaders-tsl/water.d.ts +22 -0
  507. package/types/shaders-tsl/woody-surface.d.ts +3 -0
  508. package/types/sky/atmosphereDome.d.ts +2 -0
  509. package/types/sky/atmosphereParams.d.ts +185 -0
  510. package/types/sky/atmosphereScattering.d.ts +11 -0
  511. package/types/sky/atmosphereSky.d.ts +2 -0
  512. package/types/sky/cloudShadow.d.ts +69 -0
  513. package/types/sky/godRays.d.ts +5 -0
  514. package/types/sky/index.d.ts +18 -0
  515. package/types/sky/nightSky.d.ts +22 -0
  516. package/types/sky/renderLayers.d.ts +59 -0
  517. package/types/sky/sceneOverrideLayers.d.ts +10 -0
  518. package/types/sky/skyColor.d.ts +704 -0
  519. package/types/sky/skyDayCycle.d.ts +86 -0
  520. package/types/sky/skyParams.d.ts +3407 -0
  521. package/types/sky/skyPresets.d.ts +160 -0
  522. package/types/sky/skyQuality.d.ts +21 -0
  523. package/types/sky/skyQualityTiers.d.ts +223 -0
  524. package/types/sky/skyShaderSettings.d.ts +152 -0
  525. package/types/sky/skyStyleSnapshots.d.ts +11 -0
  526. package/types/sky/skySystem.d.ts +3 -0
  527. package/types/sky/skyTimeKeyframes.d.ts +230 -0
  528. package/types/sky/stylizedSky.d.ts +341 -0
  529. package/types/sky/sunDriver.d.ts +15 -0
  530. package/types/sky/timeOfDay.d.ts +145 -0
  531. package/types/styles/animeGameProfile.d.ts +27 -0
  532. package/types/styles/index.d.ts +18 -0
  533. package/types/styles/manufacturedStyleLabeling.d.ts +119 -0
  534. package/types/styles/neutralStylePresets.d.ts +944 -0
  535. package/types/styles/sceneLayerDocuments.d.ts +145 -0
  536. package/types/styles/sceneLookComposition.d.ts +53 -0
  537. package/types/styles/sceneQualityApplication.d.ts +34 -0
  538. package/types/styles/sceneQualityProfiles.d.ts +13 -0
  539. package/types/styles/sceneStyleAudit.d.ts +80 -0
  540. package/types/styles/sceneStyleRuntime.d.ts +1802 -0
  541. package/types/styles/styleAdapters.d.ts +14 -0
  542. package/types/styles/styleApplication.d.ts +47 -0
  543. package/types/styles/styleBundle.d.ts +19 -0
  544. package/types/styles/styleBundleProvider.d.ts +44 -0
  545. package/types/styles/styleDomains.d.ts +18 -0
  546. package/types/styles/styleInspector.d.ts +59 -0
  547. package/types/styles/styleMaterialContract.d.ts +46 -0
  548. package/types/styles/styleMetadata.d.ts +11 -0
  549. package/types/styles/styleTargetDiscovery.d.ts +48 -0
  550. package/types/styles/styleTargetLabels.d.ts +32 -0
  551. package/types/styles/styleTargetMaterialCoverage.d.ts +20 -0
  552. package/types/styles/styleTransaction.d.ts +10 -0
  553. package/types/styles/styleTypes.d.ts +66 -0
  554. package/types/texgen/evaluateTexture.d.ts +40 -0
  555. package/types/texgen/index.d.ts +7 -0
  556. package/types/texgen/noise2.d.ts +46 -0
  557. package/types/texgen/textureAi.d.ts +6 -0
  558. package/types/texgen/textureGenerators.d.ts +261 -0
  559. package/types/texgen/texturePresets.d.ts +45 -0
  560. package/types/texgen/textureSettings.d.ts +121 -0
  561. package/types/texgen/textureThree.d.ts +13 -0
  562. package/types/toon/characterRenderPasses.d.ts +3 -0
  563. package/types/toon/index.d.ts +3 -0
  564. package/types/toon/settings/alphaSettings.d.ts +125 -0
  565. package/types/toon/settings/averageShadowSettings.d.ts +39 -0
  566. package/types/toon/settings/baseTextureSettings.d.ts +39 -0
  567. package/types/toon/settings/celShadeSettings.d.ts +37 -0
  568. package/types/toon/settings/contactShadowSettings.d.ts +30 -0
  569. package/types/toon/settings/eyeHighlightSettings.d.ts +55 -0
  570. package/types/toon/settings/faceLightingSettings.d.ts +32 -0
  571. package/types/toon/settings/furSettings.d.ts +23 -0
  572. package/types/toon/settings/glitterSettings.d.ts +43 -0
  573. package/types/toon/settings/hairHighlightSettings.d.ts +89 -0
  574. package/types/toon/settings/indirectLightSettings.d.ts +43 -0
  575. package/types/toon/settings/localLightSettings.d.ts +46 -0
  576. package/types/toon/settings/materialMapSettings.d.ts +86 -0
  577. package/types/toon/settings/outlineSettings.d.ts +125 -0
  578. package/types/toon/settings/perspectiveRemovalSettings.d.ts +14 -0
  579. package/types/toon/settings/rimLightSettings.d.ts +79 -0
  580. package/types/toon/settings/sceneShadowSettings.d.ts +32 -0
  581. package/types/toon/settings/selfShadowSettings.d.ts +44 -0
  582. package/types/toon/settings/shadowColorSettings.d.ts +77 -0
  583. package/types/toon/settings/skinToneSettings.d.ts +30 -0
  584. package/types/toon/settings/specularSettings.d.ts +96 -0
  585. package/types/toon/settings/stickerSettings.d.ts +40 -0
  586. package/types/toon/toonMaterialAdapter.d.ts +883 -0
  587. package/types/toon/toonSettings.d.ts +1182 -0
  588. package/types/vegetation/branchTree.d.ts +14 -0
  589. package/types/vegetation/callMeSenseiGrass.d.ts +8 -0
  590. package/types/vegetation/compiledTree.d.ts +75 -0
  591. package/types/vegetation/contactShadowField.d.ts +26 -0
  592. package/types/vegetation/flowerSpecies.d.ts +107 -0
  593. package/types/vegetation/grass.d.ts +4 -0
  594. package/types/vegetation/grassClump.d.ts +7 -0
  595. package/types/vegetation/grassPalettes.d.ts +29 -0
  596. package/types/vegetation/importedVegetationMaterial.d.ts +13 -0
  597. package/types/vegetation/index.d.ts +225 -0
  598. package/types/vegetation/legacyTreePresets.d.ts +22 -0
  599. package/types/vegetation/scatter.d.ts +13 -0
  600. package/types/vegetation/stylizedBush.d.ts +2 -0
  601. package/types/vegetation/stylizedFlower.d.ts +2 -0
  602. package/types/vegetation/stylizedFlowers.d.ts +8 -0
  603. package/types/vegetation/stylizedForest.d.ts +3 -0
  604. package/types/vegetation/stylizedGrass.d.ts +21 -0
  605. package/types/vegetation/stylizedTree.d.ts +20 -0
  606. package/types/vegetation/stylizedTreeFoliage.d.ts +19 -0
  607. package/types/vegetation/stylizedUnderstory.d.ts +50 -0
  608. package/types/vegetation/treeExport.d.ts +6 -0
  609. package/types/vegetation/treeSurfaceTextures.d.ts +72 -0
  610. package/types/vegetation/vegetationShaders.d.ts +74 -0
  611. package/types/version.d.ts +1 -0
  612. package/types/water/index.d.ts +1 -0
  613. package/types/water/sceneOverrideLayers.d.ts +16 -0
  614. package/types/water/water.d.ts +17 -0
  615. package/types/water/waterBreakerSystem.d.ts +46 -0
  616. package/types/water/waterCurrentField.d.ts +115 -0
  617. package/types/water/waterInteraction.d.ts +21 -0
  618. package/types/water/waterMaterial.d.ts +60 -0
  619. package/types/water/waterNearshorePhase.d.ts +5 -0
  620. package/types/water/waterRain.d.ts +17 -0
  621. package/types/water/waterRippleSimulation.d.ts +52 -0
  622. package/types/water/waterScenePasses.d.ts +70 -0
  623. package/types/water/waterSettings.d.ts +648 -0
  624. package/types/water/waterShoreMaterial.d.ts +3 -0
  625. package/types/water/waterShoreStateField.d.ts +2 -0
  626. package/types/water/waterSplashSystem.d.ts +2 -0
  627. package/types/water/waterStageSettings.d.ts +9 -0
  628. package/types/water/waterSurface.d.ts +2 -0
  629. package/types/water/waterUnderwaterAtmosphere.d.ts +103 -0
  630. package/types/water/waterVegetation.d.ts +16 -0
  631. package/types/worldCollision.d.ts +22 -0
  632. package/AGENTS.md +0 -254
  633. package/ATTRIBUTION.md +0 -78
  634. package/docs/characters.md +0 -144
  635. package/docs/debug-panel.md +0 -126
  636. package/docs/docs.css +0 -589
  637. package/docs/environment.md +0 -186
  638. package/docs/getting-started.md +0 -180
  639. package/docs/index.html +0 -14
  640. package/docs/lab-architecture.md +0 -100
  641. package/docs/lighting.md +0 -825
  642. package/docs/main.jsx +0 -752
  643. package/docs/mcp.md +0 -97
  644. package/docs/post-processing.md +0 -98
  645. package/docs/settings-reference.md +0 -1878
  646. package/docs/shader-constants.md +0 -77
  647. package/docs/sky.md +0 -182
  648. package/docs/style-labs.md +0 -309
  649. package/docs/texture-lab.md +0 -135
  650. package/docs/toon-shading.md +0 -183
  651. package/docs/tsl-conventions.md +0 -167
  652. package/docs/vegetation-sky.md +0 -275
  653. package/docs/water.md +0 -430
  654. package/docs/weather.md +0 -200
  655. package/docs/world-scale.md +0 -111
  656. package/mcp/style-lab-tools.mjs +0 -371
  657. package/src/ambientfx/INTEGRATION.md +0 -164
  658. package/src/ambientfx/ambientFxPresets.js +0 -83
  659. package/src/ambientfx/ambientFxSettings.js +0 -368
  660. package/src/ambientfx/emitters.js +0 -169
  661. package/src/ambientfx/index.js +0 -5
  662. package/src/ambientfx/particleBackbone.js +0 -493
  663. package/src/ambientfx/stylizedAmbientFx.js +0 -450
  664. package/src/biome/biomeGenerator.js +0 -385
  665. package/src/biome/biomeRuntime.js +0 -299
  666. package/src/biome/index.js +0 -2
  667. package/src/buildinggen/buildingAsset.js +0 -44
  668. package/src/buildinggen/buildingGrammar.js +0 -311
  669. package/src/buildinggen/buildingMesh.js +0 -451
  670. package/src/buildinggen/buildingPresets.js +0 -46
  671. package/src/buildinggen/buildingRecipe.js +0 -100
  672. package/src/buildinggen/buildingSettings.js +0 -238
  673. package/src/buildinggen/index.js +0 -6
  674. package/src/camera/cameraDirector.js +0 -157
  675. package/src/camera/cameraGenerator.js +0 -367
  676. package/src/camera/cameraRig.js +0 -570
  677. package/src/camera/cameraSettings.js +0 -236
  678. package/src/camera/index.js +0 -7
  679. package/src/catalog/builtinEntries.js +0 -245
  680. package/src/catalog/catalog.js +0 -210
  681. package/src/catalog/index.js +0 -3
  682. package/src/core/shaderBackend.js +0 -24
  683. package/src/debrisgen/debrisFields.js +0 -544
  684. package/src/debrisgen/debrisGenerator.js +0 -1929
  685. package/src/debrisgen/debrisPalettes.js +0 -71
  686. package/src/debrisgen/debrisPhysics.js +0 -198
  687. package/src/debrisgen/debrisPresets.js +0 -162
  688. package/src/debrisgen/debrisSettings.js +0 -333
  689. package/src/debrisgen/debrisTextures.js +0 -380
  690. package/src/debrisgen/index.js +0 -5
  691. package/src/debug/fieldValues.js +0 -95
  692. package/src/debug/index.js +0 -7
  693. package/src/debug/settingsPanel.js +0 -170
  694. package/src/fauna/INTEGRATION.md +0 -174
  695. package/src/fauna/boids.js +0 -861
  696. package/src/fauna/faunaBodies.js +0 -492
  697. package/src/fauna/faunaPresets.js +0 -52
  698. package/src/fauna/faunaSettings.js +0 -525
  699. package/src/fauna/index.js +0 -5
  700. package/src/fauna/stylizedFauna.js +0 -395
  701. package/src/game-feel/gameFeelGenerator.js +0 -402
  702. package/src/game-feel/gameFeelRuntime.js +0 -549
  703. package/src/game-feel/index.js +0 -2
  704. package/src/motion/index.js +0 -5
  705. package/src/motion/motionClip.js +0 -441
  706. package/src/motion/motionController.js +0 -628
  707. package/src/motion/motionDocuments.js +0 -225
  708. package/src/motion/motionGraph.js +0 -307
  709. package/src/motion/motionSettings.js +0 -222
  710. package/src/pathgen/index.js +0 -7
  711. package/src/pathgen/pathBridge.js +0 -232
  712. package/src/pathgen/pathPresets.js +0 -35
  713. package/src/pathgen/pathRibbon.js +0 -410
  714. package/src/pathgen/pathRouter.js +0 -380
  715. package/src/pathgen/pathSettings.js +0 -335
  716. package/src/pathgen/pathTextures.js +0 -123
  717. package/src/pathgen/stylizedPaths.js +0 -453
  718. package/src/propgen/generatorsWave1.js +0 -379
  719. package/src/propgen/generatorsWave2.js +0 -462
  720. package/src/propgen/index.js +0 -5
  721. package/src/propgen/propAsset.js +0 -323
  722. package/src/propgen/propParts.js +0 -170
  723. package/src/propgen/propPlacement.js +0 -459
  724. package/src/propgen/propPresets.js +0 -82
  725. package/src/propgen/propSettings.js +0 -395
  726. package/src/soundscape/index.js +0 -4
  727. package/src/soundscape/soundscapeGenerator.js +0 -179
  728. package/src/soundscape/soundscapeRuntime.js +0 -806
  729. package/src/soundscape/soundscapeSettings.js +0 -292
  730. package/src/stylizedTerrain.js +0 -631
  731. package/src/stylizedWorld.js +0 -903
  732. package/src/vegetation/treeRecipe.js +0 -647
  733. package/src/vfxgen/INTEGRATION.md +0 -145
  734. package/src/vfxgen/core/burstBackbone.js +0 -380
  735. package/src/vfxgen/core/projectileCore.js +0 -92
  736. package/src/vfxgen/core/spriteShapes.js +0 -98
  737. package/src/vfxgen/core/trailRibbon.js +0 -272
  738. package/src/vfxgen/core/vfxRandom.js +0 -29
  739. package/src/vfxgen/effects/emitHelpers.js +0 -37
  740. package/src/vfxgen/effects/magicEffects.js +0 -162
  741. package/src/vfxgen/effects/movementEffects.js +0 -87
  742. package/src/vfxgen/effects/weaponEffects.js +0 -118
  743. package/src/vfxgen/index.js +0 -18
  744. package/src/vfxgen/moves/moveController.js +0 -146
  745. package/src/vfxgen/moves/moveLibrary.js +0 -335
  746. package/src/vfxgen/vfxPresets.js +0 -98
  747. package/src/vfxgen/vfxSettings.js +0 -384
  748. package/src/vfxgen/vfxSystem.js +0 -449
  749. package/src/vfxgen/weapons/stylizedWeapons.js +0 -137
  750. package/src/villagegen/index.js +0 -4
  751. package/src/villagegen/stylizedVillage.js +0 -490
  752. package/src/villagegen/villageArchetypes.js +0 -160
  753. package/src/villagegen/villageNames.js +0 -40
  754. package/src/villagegen/villageSites.js +0 -105
  755. package/src/weather/index.js +0 -6
  756. package/src/weather/weatherPrecipitation.js +0 -221
  757. package/src/weather/weatherPresets.js +0 -258
  758. package/src/weather/weatherSettings.js +0 -269
  759. package/src/weather/weatherSystem.js +0 -871
  760. package/src/worldMinimap.js +0 -214
  761. package/src/worldPresets.js +0 -125
@@ -0,0 +1,2586 @@
1
+ // Canonical rock and mountain material runtime, reconstructed from ToonLab's
2
+ // S_Rock and S_Mountain graphs. This module belongs to the reusable rock
3
+ // shader domain; procedural rock generation consumes it through the public
4
+ // rock-shader contract but does not own it.
5
+ //
6
+ // This is intentionally separate from referenceSourceMaterial.js. The ToonLab and
7
+ // ToonLab packages share art direction and source textures, but their rock graphs,
8
+ // material values, distance metrics, and PBR attribute semantics are not identical.
9
+
10
+ import {
11
+ Color,
12
+ ClampToEdgeWrapping,
13
+ LinearFilter,
14
+ LinearMipmapLinearFilter,
15
+ LinearMipmapNearestFilter,
16
+ MirroredRepeatWrapping,
17
+ NearestFilter,
18
+ NearestMipmapNearestFilter,
19
+ NoColorSpace,
20
+ RepeatWrapping,
21
+ SRGBColorSpace,
22
+ TextureLoader,
23
+ } from 'three';
24
+ import { MeshPhysicalNodeMaterial } from 'three/webgpu';
25
+ import { mx_fractal_noise_float } from 'three/tsl';
26
+ import {
27
+ TBNViewMatrix,
28
+ abs,
29
+ attribute,
30
+ cameraPosition,
31
+ cameraViewMatrix,
32
+ clamp,
33
+ cos,
34
+ distance,
35
+ dot,
36
+ float,
37
+ max,
38
+ mix,
39
+ normalWorldGeometry,
40
+ normalize,
41
+ positionWorld,
42
+ pow,
43
+ sin,
44
+ smoothstep,
45
+ step,
46
+ texture,
47
+ transformNormalByViewMatrix,
48
+ transpose,
49
+ uniform,
50
+ uv,
51
+ vec2,
52
+ vec3,
53
+ vertexColor,
54
+ } from 'three/tsl';
55
+ import {
56
+ applyToonLabNormalStrengthNode as toonLabNormalStrength,
57
+ createToonLabNormalIntegrationMetadata,
58
+ decodeToonLabNormalNode as decodeToonLabNormal,
59
+ } from '../environment/toonLabNormalIntegration.js';
60
+ import {
61
+ SURFACE_MATERIAL_MODE,
62
+ registerSurfaceMaterialMode,
63
+ } from '../environment/surfaceMaterialModes.js';
64
+ import {
65
+ sampleGroundColor,
66
+ sampleGroundSurface,
67
+ } from '../shaders-tsl/chunks/environment-ground-field.js';
68
+ import {
69
+ normalizeToonLabRockMaterialLibrarySchema,
70
+ } from '../environment/toonLabRockMaterialResolver.js';
71
+ import { installToonLabSurfaceLighting } from '../environment/toonLabSurfaceLighting.js';
72
+ import {
73
+ ROCK_CAVITY_ATTRIBUTE,
74
+ ROCK_EXPOSURE_ATTRIBUTE,
75
+ } from './rockGeometryDetail.js';
76
+
77
+ export const TOONLAB_ROCK_MANIFEST_SCHEMA = 'toonlab.rock-material-library';
78
+ export const TOONLAB_ROCK_MANIFEST_VERSION = 1;
79
+ export const TOONLAB_ROCK_SHADER_GUID = 'a6fcfd526cd108942a6a8db5ebeda498';
80
+ export const TOONLAB_MOUNTAIN_SHADER_GUID = '6e81e92635c971147869e2fa22f70601';
81
+ export const DEFAULT_TOONLAB_ROCK_LIBRARY_BASE_URL = null;
82
+
83
+ // Both source ToonLab Graphs retain ToonLab's default Position/Normal/Tangent
84
+ // vertex blocks, but none of those blocks has an incoming edge. Neither graph
85
+ // contains a Time node. Their generated vertex position is therefore the
86
+ // authored mesh position in visible, depth, motion-vector and ShadowCaster
87
+ // passes; Terrain placement must not classify rock prototypes as wind trees.
88
+ export const TOONLAB_ROCK_FAMILY_VERTEX_MOTION_CONTRACT = Object.freeze({
89
+ [TOONLAB_ROCK_SHADER_GUID]: Object.freeze({
90
+ mode: 'authored-static',
91
+ sourceShader: 'ToonLab Graphs/S_Rock',
92
+ sourceVertexPositionConnected: false,
93
+ timeDependent: false,
94
+ }),
95
+ [TOONLAB_MOUNTAIN_SHADER_GUID]: Object.freeze({
96
+ mode: 'authored-static',
97
+ sourceShader: 'ToonLab Graphs/S_Mountain',
98
+ sourceVertexPositionConnected: false,
99
+ timeDependent: false,
100
+ }),
101
+ });
102
+
103
+ const TOONLAB_CONTRAST_MIDPOINT = 0.217637640824031;
104
+ const TOONLAB_FLOAT_EPSILON = 5.960464478e-8;
105
+ const texturePromiseCache = new Map();
106
+
107
+ /**
108
+ * Clean, engine-independent representation of the exposed S_Rock properties.
109
+ * Distances and texture scales are ToonLab world meters. Colors are the numeric
110
+ * shader-property values; texture color-space decoding is controlled by the
111
+ * manifest's texture import metadata.
112
+ *
113
+ * `layers.*.smoothness`, `moss.specular`, `layers.worldAligned`, and the
114
+ * serialized Sand Blend Offset are deliberately absent: those exposed ToonLab
115
+ * properties do not reach S_Rock's connected master outputs.
116
+ */
117
+ export const TOONLAB_ROCK_PROFILE_DEFAULTS = Object.freeze({
118
+ id: 'toonlab-rock-default',
119
+ sourceName: 'S_Rock graph defaults',
120
+ sourcePath: null,
121
+ sourceGuid: null,
122
+ coordinates: Object.freeze({
123
+ // Provisional ToonLab-world handedness bridge. Keep +1 while applying this
124
+ // material to already-authored Three geometry; use -1 when the paired
125
+ // scene conversion maps ToonLab (x,y,z) to Three (x,y,-z).
126
+ zSign: 1,
127
+ // Multiplies authored world-distance thresholds without changing any
128
+ // triplanar texture scale. ToonLab-authored values and the glTF/Three scene
129
+ // are both expressed in metres, including ToonLab exports whose centimetres
130
+ // were converted by the glTF exporter, so the parity value is 1.
131
+ distanceScale: 1,
132
+ }),
133
+ base: Object.freeze({
134
+ scale: 1,
135
+ tint: Object.freeze([1, 1, 1]),
136
+ saturation: 1,
137
+ contrast: 1,
138
+ brightness: 0,
139
+ nearDetailScale: 1.4,
140
+ nearDetailStrength: 0.24,
141
+ nearDetailDistance: 55,
142
+ projectionContrast: 0.5,
143
+ sideOnly: false,
144
+ closeTintDistance: 500,
145
+ farTintDistance: 15000,
146
+ distantTint: Object.freeze([0.7882353663, 0.7882353663, 0.7882353663]),
147
+ distantTintMix: 0.5,
148
+ metallic: 0,
149
+ smoothness: 0,
150
+ useSmoothnessTexture: false,
151
+ smoothnessContrast: 1,
152
+ emissiveStrength: 0.3,
153
+ striping: Object.freeze({
154
+ enabled: false,
155
+ scale: 2500,
156
+ contrast: 0.25,
157
+ color: Object.freeze([1, 0, 1]),
158
+ }),
159
+ }),
160
+ lighting: Object.freeze({
161
+ exposure: 1,
162
+ ambientFloor: 0.04,
163
+ skyColorInfluence: 0.35,
164
+ skyFillStrength: 1,
165
+ skyFillTint: Object.freeze([1, 1, 1]),
166
+ shadowFill: 0,
167
+ shadowFillTint: Object.freeze([1, 1, 1]),
168
+ }),
169
+ shoreline: Object.freeze({
170
+ wetBandWidth: 0.8,
171
+ wetBandDarkening: 0.22,
172
+ wetRoughness: 0.26,
173
+ }),
174
+ normals: Object.freeze({
175
+ distance: 20000,
176
+ nearFlatten: 0,
177
+ farFlatten: 1,
178
+ useSmoothed: false,
179
+ // ToonLab's texture import flipGreenChannel is false for the supplied maps.
180
+ // Set to -1 only when a resolver supplies a green-flipped normal texture.
181
+ normalGreenSign: 1,
182
+ }),
183
+ moss: Object.freeze({
184
+ enabled: false,
185
+ size: 1200,
186
+ sharpness: 1,
187
+ offset: 0.3,
188
+ multiply: 2,
189
+ colorPower: 1.3,
190
+ lowColor: Object.freeze([0.2156862915, 0.3254902065, 0.1019607931]),
191
+ highColor: Object.freeze([0.3333333433, 0.4078431726, 0.2470588386]),
192
+ // --- moss as a material rather than a tint -------------------------
193
+ // All three default to "off" so the shipped look is unchanged: a moss
194
+ // that only mixes color is exactly the previous behaviour.
195
+ //
196
+ // Moss is a matte cushion; stone is not. Leaving roughness alone is why
197
+ // moss reads as a stain *under* the stone's own specular rather than as
198
+ // a plant sitting on it. -1 disables the response.
199
+ roughness: -1,
200
+ // A moss cushion buries the relief it grows over. Flattening the rock's
201
+ // detail normal under the mask is what makes it sit ON the surface;
202
+ // without it the stone's crevices show straight through the moss.
203
+ relief: 0,
204
+ // Break-up of the coverage boundary. The mask is a smooth power curve,
205
+ // so its edge is an airbrushed gradient — the single strongest reason
206
+ // moss reads as paint. A high-frequency sample pushed through the
207
+ // threshold gives the ragged fringe real moss has.
208
+ fringe: 0,
209
+ fringeScale: 0.35,
210
+ // 0..1 blend of the coverage source from the moss albedo's luminance
211
+ // toward a constant, handing patch shape to the geometric moisture field.
212
+ formDriven: 0,
213
+ coverage: -1,
214
+ band: 0.18,
215
+ patchScale: 0.6,
216
+ patchStrength: 0.8,
217
+ patchOctaves: 3,
218
+ patchContrast: 1.6,
219
+ // --- value, form and depth (D19-210 … D19-213) ---------------------
220
+ // Inert defaults: -1 and 0 reproduce the shipped render byte for byte.
221
+ // Remap of the moss map's own luminance range onto the colour ramp. The
222
+ // shipped path uses the raw rgb sample, and the shipped moss albedo lives
223
+ // in a linear luminance band of 0.092-0.279, so the ramp coordinate never
224
+ // clears ~0.09 and `highColor` is unreachable.
225
+ patternFloor: -1,
226
+ patternCeiling: 1,
227
+ // Darkens stone across the wet field, so moss and stone meet at a close
228
+ // value the way they do in life instead of green-on-white.
229
+ damp: 0,
230
+ // Convex, weather-exposed form suppressing moss. Without it the support
231
+ // term can add moss to hollows but cannot take it off a crown.
232
+ exposure: 0,
233
+ // The moss cushion's own raised form, and the occlusion it casts where it
234
+ // meets bare stone.
235
+ cushion: 0,
236
+ contact: 0,
237
+ }),
238
+ layers: Object.freeze({
239
+ maskEnabled: true,
240
+ sharpness: 0.8,
241
+ offset: 0.3,
242
+ heightStart: 0.48,
243
+ heightEnd: 0.88,
244
+ cavityStrength: 0,
245
+ exposureStrength: 0,
246
+ semanticMaskStrength: 1,
247
+ grass: Object.freeze({
248
+ enabled: true,
249
+ useGroundShader: false,
250
+ scale: 1,
251
+ tint: Object.freeze([1, 1, 1]),
252
+ saturation: 1,
253
+ emission: 0,
254
+ roughness: -1,
255
+ metalness: -1,
256
+ }),
257
+ snow: Object.freeze({
258
+ enabled: false,
259
+ scale: 500,
260
+ tint: Object.freeze([0, 0, 0]),
261
+ saturation: 1,
262
+ emission: 0,
263
+ roughness: -1,
264
+ metalness: -1,
265
+ }),
266
+ sand: Object.freeze({
267
+ enabled: true,
268
+ useGroundShader: false,
269
+ scale: 500,
270
+ tint: Object.freeze([0, 0, 0]),
271
+ saturation: 0,
272
+ emission: 0,
273
+ roughness: -1,
274
+ metalness: -1,
275
+ normalScale: 0,
276
+ normalStrength: 1,
277
+ normalRotationDegrees: 30,
278
+ }),
279
+ }),
280
+ textureRefs: Object.freeze({}),
281
+ });
282
+
283
+ export const TOONLAB_MOUNTAIN_PROFILE_DEFAULTS = Object.freeze({
284
+ id: 'toonlab-mountain-default',
285
+ sourceName: 'S_Mountain graph defaults',
286
+ sourcePath: null,
287
+ sourceGuid: null,
288
+ coordinates: Object.freeze({
289
+ zSign: 1,
290
+ // ToonLab's FBX UVs are bottom-origin. ToonLab's glTF exporter writes the same
291
+ // mesh UVs in glTF's top-origin convention; texture sampling compensates
292
+ // through image conventions, but S_Mountain's procedural UV.y gradients
293
+ // require an explicit flip for those exported meshes.
294
+ flipProceduralUvY: false,
295
+ }),
296
+ textureScale: 500,
297
+ grassSlopeMax: 0,
298
+ grassTopFadeout: 0.6,
299
+ grassNoiseStrength: 0.25,
300
+ noiseSize: 1000,
301
+ smoothness: 0,
302
+ snowNoiseStrength: 0.5,
303
+ snowTopAmount: 0.3,
304
+ textureRefs: Object.freeze({}),
305
+ });
306
+
307
+ function finite(value, fallback) {
308
+ const result = Number(value);
309
+ return Number.isFinite(result) ? result : fallback;
310
+ }
311
+
312
+ /**
313
+ * Numeric clamp for the JS-side normalizers.
314
+ *
315
+ * NOT `clamp` from `three/tsl`. That name is imported into this module for the
316
+ * shader graph, and calling it on a plain number returns a NODE, not a number —
317
+ * which is silently almost-correct, because a node operand is legal everywhere
318
+ * the graph consumes these values. It is catastrophically wrong everywhere JS
319
+ * does: `node > 0` is false, `node === 0.85` is false, `Number(node)` is NaN,
320
+ * and `JSON.stringify(node)` is not the value.
321
+ *
322
+ * That is not hypothetical. `vertexCavityStrength` was clamped with the TSL
323
+ * function and then gated with `> 0`, so the gate was permanently false and the
324
+ * `rockCavity` attribute never reached the moss mask at all — the support term
325
+ * that the whole patch model is built on was pure slope, which saturates. See
326
+ * D19-214. Four profile scalars were leaking nodes the same way.
327
+ */
328
+ function clampNumber(value, min, max) {
329
+ return Math.min(max, Math.max(min, value));
330
+ }
331
+
332
+ function bool(value, fallback) {
333
+ if (typeof value === 'boolean') return value;
334
+ if (Number.isFinite(Number(value))) return Number(value) !== 0;
335
+ return fallback;
336
+ }
337
+
338
+ function color3(value, fallback) {
339
+ if (Array.isArray(value)) {
340
+ return [
341
+ finite(value[0], fallback[0]),
342
+ finite(value[1], fallback[1]),
343
+ finite(value[2], fallback[2]),
344
+ ];
345
+ }
346
+ if (value && typeof value === 'object') {
347
+ return [
348
+ finite(value.r ?? value.x, fallback[0]),
349
+ finite(value.g ?? value.y, fallback[1]),
350
+ finite(value.b ?? value.z, fallback[2]),
351
+ ];
352
+ }
353
+ return [...fallback];
354
+ }
355
+
356
+ function toonLabSrgbChannelToLinear(value) {
357
+ const channel = finite(value, 0);
358
+ return channel <= 0.04045
359
+ ? channel / 12.92
360
+ : ((channel + 0.055) / 1.055) ** 2.4;
361
+ }
362
+
363
+ function toonLabColorProperty(value) {
364
+ // Every exposed S_Rock color is ColorMode.Default. ToonLab graph declares
365
+ // those values as ToonLab material `Color` properties, so ToonLab converts the
366
+ // serialized inspector/sRGB value to linear before placing it in the
367
+ // material CBUFFER. TSL constants are already working-space values and need
368
+ // that conversion explicitly; using the YAML numbers directly made moss,
369
+ // distant tint, and layer tints substantially too bright.
370
+ return vec3(...color3(value, [0, 0, 0]).map(toonLabSrgbChannelToLinear));
371
+ }
372
+
373
+ /**
374
+ * Fills omitted profile fields from the serialized S_Rock graph defaults.
375
+ * The returned object is detached from both the input and exported defaults.
376
+ */
377
+ export function normalizeToonLabRockProfile(profile = {}) {
378
+ const defaults = TOONLAB_ROCK_PROFILE_DEFAULTS;
379
+ const coordinates = profile.coordinates ?? {};
380
+ const base = profile.base ?? {};
381
+ const striping = base.striping ?? {};
382
+ const lighting = profile.lighting ?? {};
383
+ const shoreline = profile.shoreline ?? {};
384
+ const normals = profile.normals ?? {};
385
+ const moss = profile.moss ?? {};
386
+ const layers = profile.layers ?? {};
387
+ const grass = layers.grass ?? {};
388
+ const snow = layers.snow ?? {};
389
+ const sand = layers.sand ?? {};
390
+
391
+ return {
392
+ id: String(profile.id ?? defaults.id),
393
+ sourceName: String(profile.sourceName ?? defaults.sourceName),
394
+ sourcePath: profile.sourcePath == null ? null : String(profile.sourcePath),
395
+ sourceGuid: profile.sourceGuid == null ? null : String(profile.sourceGuid),
396
+ coordinates: {
397
+ zSign: finite(coordinates.zSign, defaults.coordinates.zSign) < 0 ? -1 : 1,
398
+ distanceScale: Math.max(
399
+ finite(coordinates.distanceScale, defaults.coordinates.distanceScale),
400
+ 0.000001,
401
+ ),
402
+ },
403
+ base: {
404
+ scale: finite(base.scale, defaults.base.scale),
405
+ tint: color3(base.tint, defaults.base.tint),
406
+ saturation: finite(base.saturation, defaults.base.saturation),
407
+ contrast: finite(base.contrast, defaults.base.contrast),
408
+ brightness: finite(base.brightness, defaults.base.brightness),
409
+ nearDetailScale: Math.max(
410
+ finite(base.nearDetailScale, defaults.base.nearDetailScale),
411
+ 0.0001,
412
+ ),
413
+ nearDetailStrength: clampNumber(
414
+ finite(base.nearDetailStrength, defaults.base.nearDetailStrength),
415
+ 0,
416
+ 1,
417
+ ),
418
+ nearDetailDistance: Math.max(
419
+ finite(base.nearDetailDistance, defaults.base.nearDetailDistance),
420
+ 0.0001,
421
+ ),
422
+ projectionContrast: finite(
423
+ base.projectionContrast,
424
+ defaults.base.projectionContrast,
425
+ ),
426
+ sideOnly: bool(base.sideOnly, defaults.base.sideOnly),
427
+ closeTintDistance: finite(
428
+ base.closeTintDistance,
429
+ defaults.base.closeTintDistance,
430
+ ),
431
+ farTintDistance: finite(base.farTintDistance, defaults.base.farTintDistance),
432
+ distantTint: color3(base.distantTint, defaults.base.distantTint),
433
+ distantTintMix: finite(base.distantTintMix, defaults.base.distantTintMix),
434
+ metallic: finite(base.metallic, defaults.base.metallic),
435
+ smoothness: finite(base.smoothness, defaults.base.smoothness),
436
+ useSmoothnessTexture: bool(
437
+ base.useSmoothnessTexture,
438
+ defaults.base.useSmoothnessTexture,
439
+ ),
440
+ smoothnessContrast: finite(
441
+ base.smoothnessContrast,
442
+ defaults.base.smoothnessContrast,
443
+ ),
444
+ emissiveStrength: finite(base.emissiveStrength, defaults.base.emissiveStrength),
445
+ striping: {
446
+ enabled: bool(striping.enabled, defaults.base.striping.enabled),
447
+ scale: finite(striping.scale, defaults.base.striping.scale),
448
+ contrast: finite(striping.contrast, defaults.base.striping.contrast),
449
+ color: color3(striping.color, defaults.base.striping.color),
450
+ },
451
+ },
452
+ lighting: {
453
+ exposure: Math.max(finite(lighting.exposure, defaults.lighting.exposure), 0),
454
+ ambientFloor: clampNumber(
455
+ finite(lighting.ambientFloor, defaults.lighting.ambientFloor),
456
+ 0,
457
+ 1,
458
+ ),
459
+ skyColorInfluence: clampNumber(
460
+ finite(lighting.skyColorInfluence, defaults.lighting.skyColorInfluence),
461
+ 0,
462
+ 1,
463
+ ),
464
+ skyFillStrength: Math.max(
465
+ finite(lighting.skyFillStrength, defaults.lighting.skyFillStrength),
466
+ 0,
467
+ ),
468
+ skyFillTint: color3(lighting.skyFillTint, defaults.lighting.skyFillTint),
469
+ shadowFill: clampNumber(
470
+ finite(lighting.shadowFill, defaults.lighting.shadowFill),
471
+ 0,
472
+ 1,
473
+ ),
474
+ shadowFillTint: color3(
475
+ lighting.shadowFillTint,
476
+ defaults.lighting.shadowFillTint,
477
+ ),
478
+ },
479
+ shoreline: {
480
+ // Spread first, coerce after — the same shape the moss group uses. The
481
+ // entries below still clamp every field that has a meaningful range; the
482
+ // spread only ensures a field added to the schema later reaches the
483
+ // shader instead of being dropped silently between validation and use.
484
+ ...shoreline,
485
+ wetBandWidth: Math.max(
486
+ finite(shoreline.wetBandWidth, defaults.shoreline.wetBandWidth),
487
+ 0,
488
+ ),
489
+ wetBandDarkening: clampNumber(
490
+ finite(shoreline.wetBandDarkening, defaults.shoreline.wetBandDarkening),
491
+ 0,
492
+ 1,
493
+ ),
494
+ wetRoughness: clampNumber(
495
+ finite(shoreline.wetRoughness, defaults.shoreline.wetRoughness),
496
+ 0.02,
497
+ 1,
498
+ ),
499
+ },
500
+ normals: {
501
+ ...normals,
502
+ distance: finite(normals.distance, defaults.normals.distance),
503
+ // Do not clamp: shipped Classic Rocks deliberately uses -0.1, producing
504
+ // Normal Strength 1.1 in the source graph.
505
+ nearFlatten: finite(normals.nearFlatten, defaults.normals.nearFlatten),
506
+ farFlatten: finite(normals.farFlatten, defaults.normals.farFlatten),
507
+ useSmoothed: bool(normals.useSmoothed, defaults.normals.useSmoothed),
508
+ normalGreenSign: finite(normals.normalGreenSign, defaults.normals.normalGreenSign),
509
+ },
510
+ moss: {
511
+ // Spread first so a field the settings schema gained still reaches the
512
+ // shader; the explicit entries below then coerce and default the ones
513
+ // the graph reads directly. See the note in `rockShaderSettingsToProfile`.
514
+ ...moss,
515
+ enabled: bool(moss.enabled, defaults.moss.enabled),
516
+ size: finite(moss.size, defaults.moss.size),
517
+ sharpness: finite(moss.sharpness, defaults.moss.sharpness),
518
+ offset: finite(moss.offset, defaults.moss.offset),
519
+ multiply: finite(moss.multiply, defaults.moss.multiply),
520
+ colorPower: finite(moss.colorPower, defaults.moss.colorPower),
521
+ lowColor: color3(moss.lowColor, defaults.moss.lowColor),
522
+ highColor: color3(moss.highColor, defaults.moss.highColor),
523
+ roughness: finite(moss.roughness, defaults.moss.roughness),
524
+ relief: finite(moss.relief, defaults.moss.relief),
525
+ fringe: finite(moss.fringe, defaults.moss.fringe),
526
+ fringeScale: finite(moss.fringeScale, defaults.moss.fringeScale),
527
+ formDriven: finite(moss.formDriven, defaults.moss.formDriven),
528
+ coverage: finite(moss.coverage, defaults.moss.coverage),
529
+ band: finite(moss.band, defaults.moss.band),
530
+ patchScale: finite(moss.patchScale, defaults.moss.patchScale),
531
+ patchStrength: finite(moss.patchStrength, defaults.moss.patchStrength),
532
+ patchOctaves: finite(moss.patchOctaves, defaults.moss.patchOctaves),
533
+ patchContrast: finite(moss.patchContrast, defaults.moss.patchContrast),
534
+ patternFloor: finite(moss.patternFloor, defaults.moss.patternFloor),
535
+ patternCeiling: finite(moss.patternCeiling, defaults.moss.patternCeiling),
536
+ damp: finite(moss.damp, defaults.moss.damp),
537
+ exposure: finite(moss.exposure, defaults.moss.exposure),
538
+ cushion: finite(moss.cushion, defaults.moss.cushion),
539
+ contact: finite(moss.contact, defaults.moss.contact),
540
+ },
541
+ layers: {
542
+ maskEnabled: bool(layers.maskEnabled, defaults.layers.maskEnabled),
543
+ sharpness: finite(layers.sharpness, defaults.layers.sharpness),
544
+ offset: finite(layers.offset, defaults.layers.offset),
545
+ heightStart: finite(layers.heightStart, defaults.layers.heightStart),
546
+ heightEnd: finite(layers.heightEnd, defaults.layers.heightEnd),
547
+ cavityStrength: finite(layers.cavityStrength, defaults.layers.cavityStrength),
548
+ exposureStrength: finite(layers.exposureStrength, defaults.layers.exposureStrength),
549
+ semanticMaskStrength: clampNumber(
550
+ finite(layers.semanticMaskStrength, defaults.layers.semanticMaskStrength),
551
+ 0,
552
+ 1,
553
+ ),
554
+ grass: {
555
+ ...grass,
556
+ enabled: bool(grass.enabled, defaults.layers.grass.enabled),
557
+ useGroundShader: bool(
558
+ grass.useGroundShader,
559
+ defaults.layers.grass.useGroundShader,
560
+ ),
561
+ scale: finite(grass.scale, defaults.layers.grass.scale),
562
+ tint: color3(grass.tint, defaults.layers.grass.tint),
563
+ saturation: finite(grass.saturation, defaults.layers.grass.saturation),
564
+ emission: finite(grass.emission, defaults.layers.grass.emission),
565
+ roughness: finite(grass.roughness, defaults.layers.grass.roughness),
566
+ metalness: finite(grass.metalness, defaults.layers.grass.metalness),
567
+ },
568
+ snow: {
569
+ ...snow,
570
+ enabled: bool(snow.enabled, defaults.layers.snow.enabled),
571
+ scale: finite(snow.scale, defaults.layers.snow.scale),
572
+ tint: color3(snow.tint, defaults.layers.snow.tint),
573
+ saturation: finite(snow.saturation, defaults.layers.snow.saturation),
574
+ emission: finite(snow.emission, defaults.layers.snow.emission),
575
+ roughness: finite(snow.roughness, defaults.layers.snow.roughness),
576
+ metalness: finite(snow.metalness, defaults.layers.snow.metalness),
577
+ },
578
+ sand: {
579
+ ...sand,
580
+ enabled: bool(sand.enabled, defaults.layers.sand.enabled),
581
+ useGroundShader: bool(
582
+ sand.useGroundShader,
583
+ defaults.layers.sand.useGroundShader,
584
+ ),
585
+ scale: finite(sand.scale, defaults.layers.sand.scale),
586
+ tint: color3(sand.tint, defaults.layers.sand.tint),
587
+ saturation: finite(sand.saturation, defaults.layers.sand.saturation),
588
+ emission: finite(sand.emission, defaults.layers.sand.emission),
589
+ roughness: finite(sand.roughness, defaults.layers.sand.roughness),
590
+ metalness: finite(sand.metalness, defaults.layers.sand.metalness),
591
+ normalScale: finite(sand.normalScale, defaults.layers.sand.normalScale),
592
+ normalStrength: finite(sand.normalStrength, defaults.layers.sand.normalStrength),
593
+ normalRotationDegrees: finite(
594
+ sand.normalRotationDegrees,
595
+ defaults.layers.sand.normalRotationDegrees,
596
+ ),
597
+ },
598
+ },
599
+ textureRefs: { ...(profile.textureRefs ?? {}) },
600
+ };
601
+ }
602
+
603
+ export function normalizeToonLabMountainProfile(profile = {}) {
604
+ const defaults = TOONLAB_MOUNTAIN_PROFILE_DEFAULTS;
605
+ const coordinates = profile.coordinates ?? {};
606
+ return {
607
+ id: String(profile.id ?? defaults.id),
608
+ sourceName: String(profile.sourceName ?? defaults.sourceName),
609
+ sourcePath: profile.sourcePath == null ? null : String(profile.sourcePath),
610
+ sourceGuid: profile.sourceGuid == null ? null : String(profile.sourceGuid),
611
+ coordinates: {
612
+ zSign: finite(coordinates.zSign, defaults.coordinates.zSign) < 0 ? -1 : 1,
613
+ flipProceduralUvY: bool(
614
+ coordinates.flipProceduralUvY,
615
+ defaults.coordinates.flipProceduralUvY,
616
+ ),
617
+ },
618
+ textureScale: finite(profile.textureScale, defaults.textureScale),
619
+ grassSlopeMax: finite(profile.grassSlopeMax, defaults.grassSlopeMax),
620
+ grassTopFadeout: finite(
621
+ profile.grassTopFadeout,
622
+ defaults.grassTopFadeout,
623
+ ),
624
+ grassNoiseStrength: finite(
625
+ profile.grassNoiseStrength,
626
+ defaults.grassNoiseStrength,
627
+ ),
628
+ noiseSize: finite(profile.noiseSize, defaults.noiseSize),
629
+ smoothness: finite(profile.smoothness, defaults.smoothness),
630
+ snowNoiseStrength: finite(
631
+ profile.snowNoiseStrength,
632
+ defaults.snowNoiseStrength,
633
+ ),
634
+ snowTopAmount: finite(profile.snowTopAmount, defaults.snowTopAmount),
635
+ textureRefs: { ...(profile.textureRefs ?? {}) },
636
+ };
637
+ }
638
+
639
+ function resolvedNumber(resolved, key, fallback) {
640
+ return finite(resolved?.floats?.[key] ?? resolved?.ints?.[key], fallback);
641
+ }
642
+
643
+ function resolvedBool(resolved, key, fallback) {
644
+ const value = resolved?.floats?.[key] ?? resolved?.ints?.[key];
645
+ return bool(value, fallback);
646
+ }
647
+
648
+ function resolvedColor(resolved, key, fallback) {
649
+ return color3(resolved?.colors?.[key], fallback);
650
+ }
651
+
652
+ function firstTextureSlot(resolved, ...keys) {
653
+ for (const key of keys) {
654
+ const slot = resolved?.textures?.[key];
655
+ if (slot && Number(slot.fileID) !== 0 && slot.guid) return slot;
656
+ }
657
+ return null;
658
+ }
659
+
660
+ /**
661
+ * Converts one material entry from rock-material-library.json into the clean
662
+ * profile contract consumed by createToonRockMaterial().
663
+ */
664
+ export function toonLabRockProfileFromResolvedMaterial(materialEntry) {
665
+ if (!materialEntry?.resolved) {
666
+ throw new TypeError('A ToonLab rock material entry with resolved properties is required.');
667
+ }
668
+ const shaderGuid = materialEntry.shader?.guid ?? materialEntry.directShader?.guid;
669
+ if (shaderGuid && shaderGuid !== TOONLAB_ROCK_SHADER_GUID) {
670
+ throw new Error(
671
+ `${materialEntry.name ?? materialEntry.assetPath ?? 'Material'} uses ${shaderGuid}, not S_Rock.`,
672
+ );
673
+ }
674
+
675
+ const d = TOONLAB_ROCK_PROFILE_DEFAULTS;
676
+ const r = materialEntry.resolved;
677
+ return normalizeToonLabRockProfile({
678
+ id: materialEntry.guid ?? materialEntry.assetPath ?? materialEntry.name,
679
+ sourceName: materialEntry.name,
680
+ sourcePath: materialEntry.assetPath,
681
+ sourceGuid: materialEntry.guid,
682
+ base: {
683
+ scale: resolvedNumber(r, '_Rock_Scale', d.base.scale),
684
+ tint: resolvedColor(r, '_Rock_Tint', d.base.tint),
685
+ saturation: resolvedNumber(r, '_Saturation', d.base.saturation),
686
+ contrast: resolvedNumber(r, '_Contrast', d.base.contrast),
687
+ brightness: resolvedNumber(r, '_Rock_Brightness', d.base.brightness),
688
+ projectionContrast: resolvedNumber(
689
+ r,
690
+ '_Projection_Contrast',
691
+ d.base.projectionContrast,
692
+ ),
693
+ sideOnly: resolvedBool(r, '_Side_Project_Only', d.base.sideOnly),
694
+ closeTintDistance: resolvedNumber(
695
+ r,
696
+ '_Close_Tint_Blend_Distance',
697
+ d.base.closeTintDistance,
698
+ ),
699
+ farTintDistance: resolvedNumber(
700
+ r,
701
+ '_Far_Tint_Blend_Distance',
702
+ d.base.farTintDistance,
703
+ ),
704
+ distantTint: resolvedColor(r, '_Distant_Tint_Blend', d.base.distantTint),
705
+ distantTintMix: resolvedNumber(
706
+ r,
707
+ '_Distant_Tint_Blend_Lerp_Alpha_Mix',
708
+ d.base.distantTintMix,
709
+ ),
710
+ metallic: resolvedNumber(r, '_RockMetallic', d.base.metallic),
711
+ smoothness: resolvedNumber(r, '_Smoothness', d.base.smoothness),
712
+ useSmoothnessTexture: resolvedBool(
713
+ r,
714
+ '_Smoothness_Texture_1',
715
+ d.base.useSmoothnessTexture,
716
+ ),
717
+ smoothnessContrast: resolvedNumber(
718
+ r,
719
+ '_Smoothness_Contrast',
720
+ d.base.smoothnessContrast,
721
+ ),
722
+ emissiveStrength: resolvedNumber(
723
+ r,
724
+ '_Emissive_Strength',
725
+ d.base.emissiveStrength,
726
+ ),
727
+ striping: {
728
+ enabled: resolvedBool(r, '_RockStriping', d.base.striping.enabled),
729
+ scale: resolvedNumber(r, '_Rock_Strping_Scale', d.base.striping.scale),
730
+ contrast: resolvedNumber(
731
+ r,
732
+ '_Rock_Striping_Contrast',
733
+ d.base.striping.contrast,
734
+ ),
735
+ color: resolvedColor(
736
+ r,
737
+ '_Rock_Striping_Overlay_Color',
738
+ d.base.striping.color,
739
+ ),
740
+ },
741
+ },
742
+ normals: {
743
+ distance: resolvedNumber(r, '_Rock_Normal_Distance', d.normals.distance),
744
+ nearFlatten: resolvedNumber(r, '_Rock_Normal_Flatten', d.normals.nearFlatten),
745
+ farFlatten: resolvedNumber(
746
+ r,
747
+ '_Distant_Rock_Normal_Flatten',
748
+ d.normals.farFlatten,
749
+ ),
750
+ useSmoothed: resolvedBool(r, '_UseSmoothedNormalMap', d.normals.useSmoothed),
751
+ normalGreenSign: d.normals.normalGreenSign,
752
+ },
753
+ moss: {
754
+ // Spread the defaults first. No TOONLAB renderer property backs the
755
+ // ToonLab-added fields — they are capability, not Unity-shader parity —
756
+ // so they must resolve from the defaults and stay off unless a caller
757
+ // sets them. Naming them one by one meant every new field silently
758
+ // vanished from this path until someone remembered a fifth edit; the
759
+ // spread makes that structurally impossible. The entries below then
760
+ // override exactly the fields a renderer property does back.
761
+ ...d.moss,
762
+ enabled: resolvedBool(r, '_Moss', d.moss.enabled),
763
+ size: resolvedNumber(r, '_Moss_Size', d.moss.size),
764
+ sharpness: resolvedNumber(r, '_Moss_Sharpness', d.moss.sharpness),
765
+ offset: resolvedNumber(r, '_Moss_Offset', d.moss.offset),
766
+ multiply: resolvedNumber(r, '_Moss_Multiply', d.moss.multiply),
767
+ colorPower: resolvedNumber(r, '_Moss_Smoothness', d.moss.colorPower),
768
+ lowColor: resolvedColor(r, '_Moss_Color_2', d.moss.lowColor),
769
+ highColor: resolvedColor(r, '_Moss_Color', d.moss.highColor),
770
+ },
771
+ layers: {
772
+ maskEnabled: resolvedBool(r, '_MaskTopLayer', d.layers.maskEnabled),
773
+ sharpness: resolvedNumber(
774
+ r,
775
+ '_TopLayer_Blend_Sharpness',
776
+ d.layers.sharpness,
777
+ ),
778
+ offset: resolvedNumber(r, '_TopLayer_Blend_Offset', d.layers.offset),
779
+ grass: {
780
+ enabled: resolvedBool(r, '_TopGrass', d.layers.grass.enabled),
781
+ scale: resolvedNumber(r, '_Grass_Scale', d.layers.grass.scale),
782
+ tint: resolvedColor(r, '_Grass_Tint', d.layers.grass.tint),
783
+ saturation: resolvedNumber(r, '_Grass_Saturation', d.layers.grass.saturation),
784
+ emission: resolvedNumber(r, '_Grass_Emission', d.layers.grass.emission),
785
+ },
786
+ snow: {
787
+ enabled: resolvedBool(r, '_TopSnow', d.layers.snow.enabled),
788
+ scale: resolvedNumber(r, '_Snow_Scale', d.layers.snow.scale),
789
+ tint: resolvedColor(r, '_Snow_Tint', d.layers.snow.tint),
790
+ // S_Rock leaves the SG_SubLayer saturation input disconnected for snow.
791
+ saturation: 1,
792
+ emission: resolvedNumber(r, '_Snow_Emission', d.layers.snow.emission),
793
+ },
794
+ sand: {
795
+ enabled: resolvedBool(r, '_TopSand', d.layers.sand.enabled),
796
+ scale: resolvedNumber(r, '_Sand_Scale', d.layers.sand.scale),
797
+ tint: resolvedColor(r, '_Sand_Tint', d.layers.sand.tint),
798
+ saturation: resolvedNumber(r, '_Sand_Saturation', d.layers.sand.saturation),
799
+ emission: resolvedNumber(r, '_Sand_Emission', d.layers.sand.emission),
800
+ normalScale: resolvedNumber(r, '_Sand_Normal_Scale', d.layers.sand.normalScale),
801
+ normalStrength: resolvedNumber(
802
+ r,
803
+ '_Sand_Normal_Strength',
804
+ d.layers.sand.normalStrength,
805
+ ),
806
+ normalRotationDegrees: 30,
807
+ },
808
+ },
809
+ textureRefs: {
810
+ rock: firstTextureSlot(r, '_Rock_Texture'),
811
+ rockNormal: firstTextureSlot(r, '_Rock_Normal_Texture'),
812
+ stylizedNormal: firstTextureSlot(r, '_Stylized_Normal_Map'),
813
+ smoothness: firstTextureSlot(r, '_Smoothness_Texture'),
814
+ stripe: firstTextureSlot(r, '_Rock_Striping_Texture'),
815
+ moss: firstTextureSlot(r, '_MossTexture'),
816
+ // `_Base_Color` is a serialized legacy slot and is disconnected from
817
+ // S_Rock. A null `_Top_Layer_Mask` means the ToonLab graph default white.
818
+ topMask: firstTextureSlot(r, '_Top_Layer_Mask'),
819
+ grass: firstTextureSlot(r, '_Grass_Texture'),
820
+ snow: firstTextureSlot(r, '_Snow_Texture'),
821
+ sand: firstTextureSlot(r, '_Sand_Texture'),
822
+ sandNormal: firstTextureSlot(r, '_Sand_Normal_Texture'),
823
+ },
824
+ });
825
+ }
826
+
827
+ /** Converts one resolved S_Mountain material entry into its connected graph inputs. */
828
+ export function toonLabMountainProfileFromResolvedMaterial(materialEntry) {
829
+ if (!materialEntry?.resolved) {
830
+ throw new TypeError('A ToonLab mountain material entry with resolved properties is required.');
831
+ }
832
+ const shaderGuid = materialEntry.shader?.guid ?? materialEntry.directShader?.guid;
833
+ if (shaderGuid && shaderGuid !== TOONLAB_MOUNTAIN_SHADER_GUID) {
834
+ throw new Error(
835
+ `${materialEntry.name ?? materialEntry.assetPath ?? 'Material'} uses ${shaderGuid}, not S_Mountain.`,
836
+ );
837
+ }
838
+
839
+ const d = TOONLAB_MOUNTAIN_PROFILE_DEFAULTS;
840
+ const r = materialEntry.resolved;
841
+ return normalizeToonLabMountainProfile({
842
+ id: materialEntry.guid ?? materialEntry.assetPath ?? materialEntry.name,
843
+ sourceName: materialEntry.name,
844
+ sourcePath: materialEntry.assetPath,
845
+ sourceGuid: materialEntry.guid,
846
+ textureScale: resolvedNumber(r, '_Texture_Scale', d.textureScale),
847
+ grassSlopeMax: resolvedNumber(r, '_Grass_Slope_Max', d.grassSlopeMax),
848
+ grassTopFadeout: resolvedNumber(
849
+ r,
850
+ '_Grass_Top_Fadeout',
851
+ d.grassTopFadeout,
852
+ ),
853
+ grassNoiseStrength: resolvedNumber(
854
+ r,
855
+ '_Grass_Noise_Strength',
856
+ d.grassNoiseStrength,
857
+ ),
858
+ noiseSize: resolvedNumber(r, '_Noise_Size', d.noiseSize),
859
+ smoothness: resolvedNumber(r, '_Smoothness', d.smoothness),
860
+ snowNoiseStrength: resolvedNumber(
861
+ r,
862
+ '_Snow_Noise_Strength',
863
+ d.snowNoiseStrength,
864
+ ),
865
+ snowTopAmount: resolvedNumber(r, '_Snow_Top_Amount', d.snowTopAmount),
866
+ textureRefs: {
867
+ noise: firstTextureSlot(
868
+ r,
869
+ '_SampleTexture2D_4da0d8ebd864413a95e355934b01bf4b_Texture_1_Texture2D',
870
+ ),
871
+ rock: firstTextureSlot(
872
+ r,
873
+ '_SampleTexture2D_5fb9278c5b51455bb51fcf51e6afd491_Texture_1_Texture2D',
874
+ ),
875
+ snow: firstTextureSlot(
876
+ r,
877
+ '_SampleTexture2D_d8b599d9da0b48309b3bf5702f47bc6c_Texture_1_Texture2D',
878
+ ),
879
+ grass: firstTextureSlot(
880
+ r,
881
+ '_SampleTexture2D_f70ef7e3c77a4c2b97e36f9585a47570_Texture_1_Texture2D',
882
+ ),
883
+ },
884
+ });
885
+ }
886
+
887
+ function safeScale(value) {
888
+ return max(abs(float(value)), 0.000001);
889
+ }
890
+
891
+ function toonLabSourcePosition(coordinates) {
892
+ return vec3(
893
+ positionWorld.x,
894
+ positionWorld.y,
895
+ positionWorld.z.mul(coordinates.zSign),
896
+ );
897
+ }
898
+
899
+ function toonLabSourceGeometryNormal(coordinates) {
900
+ return vec3(
901
+ normalWorldGeometry.x,
902
+ normalWorldGeometry.y,
903
+ normalWorldGeometry.z.mul(coordinates.zSign),
904
+ );
905
+ }
906
+
907
+ // Exact ToonLab graph Saturation node coefficients.
908
+ function toonLabSaturation(input, amount) {
909
+ const luma = dot(input, vec3(0.2126729, 0.7151522, 0.0721750));
910
+ return vec3(luma).add(input.sub(vec3(luma)).mul(float(amount)));
911
+ }
912
+
913
+ // Exact ToonLab graph Contrast node: gamma-space midpoint, no output clamp.
914
+ function toonLabContrast(input, amount) {
915
+ return input.sub(TOONLAB_CONTRAST_MIDPOINT)
916
+ .mul(float(amount))
917
+ .add(TOONLAB_CONTRAST_MIDPOINT);
918
+ }
919
+
920
+ function toonLabLinearRamp(input, low, high) {
921
+ return clamp(
922
+ input.sub(float(low)).div(max(float(high).sub(float(low)), 0.000001)),
923
+ 0,
924
+ 1,
925
+ );
926
+ }
927
+
928
+ function toonLabTriplanarWeights(normalNode, blend) {
929
+ // ToonLab graph's SafePositivePow clamps abs(base) to FLT_EPS. Its exponent
930
+ // cap is irrelevant to the supplied 0.5-3.0 material values.
931
+ const safeNormal = max(abs(normalNode), vec3(TOONLAB_FLOAT_EPSILON));
932
+ const weights = pow(safeNormal, vec3(Math.max(finite(blend, 1), 0.000001)));
933
+ return weights.div(max(weights.x.add(weights.y).add(weights.z), 0.000001));
934
+ }
935
+
936
+ export function toonLabTriplanarColor(map, scale, blend = 1, coordinates = { zSign: 1 }) {
937
+ const mapNode = texture(map);
938
+ const sourcePosition = toonLabSourcePosition(coordinates);
939
+ const sourceNormal = toonLabSourceGeometryNormal(coordinates);
940
+ const projected = sourcePosition.div(safeScale(scale));
941
+ const weights = toonLabTriplanarWeights(sourceNormal, blend);
942
+ return mapNode.sample(projected.zy).rgb.mul(weights.x)
943
+ .add(mapNode.sample(projected.xz).rgb.mul(weights.y))
944
+ .add(mapNode.sample(projected.xy).rgb.mul(weights.z));
945
+ }
946
+
947
+ function toonLabSideProjection(map, scale, projectionContrast, {
948
+ negativeScale = true,
949
+ clampResult = true,
950
+ coordinates = { zSign: 1 },
951
+ } = {}) {
952
+ const denominator = negativeScale ? safeScale(scale).negate() : safeScale(scale);
953
+ const sourcePosition = toonLabSourcePosition(coordinates);
954
+ const sourceNormal = toonLabSourceGeometryNormal(coordinates);
955
+ const projected = sourcePosition.div(denominator);
956
+ const mapNode = texture(map);
957
+ // The Contrast result is intentionally not saturated before Lerp. Values
958
+ // above one extrapolate when Projection Contrast is high.
959
+ const blend = toonLabContrast(abs(sourceNormal.x), projectionContrast);
960
+ const projectedColor = mix(
961
+ mapNode.sample(projected.xy).rgb,
962
+ mapNode.sample(projected.zy).rgb,
963
+ blend,
964
+ );
965
+ return clampResult ? clamp(projectedColor, 0, 1) : projectedColor;
966
+ }
967
+
968
+ function toonLabRockProjection(map, profile) {
969
+ return profile.base.sideOnly
970
+ ? toonLabSideProjection(map, profile.base.scale, profile.base.projectionContrast, {
971
+ coordinates: profile.coordinates,
972
+ })
973
+ : toonLabTriplanarColor(
974
+ map,
975
+ profile.base.scale,
976
+ profile.base.projectionContrast,
977
+ profile.coordinates,
978
+ );
979
+ }
980
+
981
+ function toonLabOverlay(base, blend, opacity) {
982
+ const low = base.mul(blend).mul(2);
983
+ const high = vec3(1).sub(vec3(1).sub(base).mul(vec3(1).sub(blend)).mul(2));
984
+ const overlay = mix(low, high, step(vec3(0.5), base));
985
+ return mix(base, overlay, opacity);
986
+ }
987
+
988
+ function normalGreenSignForTexture(map, profileSign) {
989
+ // texture import.flipGreenChannel is applied while ToonLab builds the
990
+ // runtime normal texture. ToonLab samples the licensed source PNG directly,
991
+ // so reproduce that import transform before the ToonLab graph sees it.
992
+ const importerSign = map?.userData?.toonLabImportSettings?.flipGreenChannel ? -1 : 1;
993
+ return finite(profileSign, 1) * importerSign;
994
+ }
995
+
996
+ function worldNormalToTangent(worldNormal) {
997
+ const viewNormal = transformNormalByViewMatrix(worldNormal, cameraViewMatrix);
998
+ return normalize(transpose(TBNViewMatrix).mul(viewNormal));
999
+ }
1000
+
1001
+ export function tangentNormalToView(tangentNormal) {
1002
+ return normalize(TBNViewMatrix.mul(tangentNormal));
1003
+ }
1004
+
1005
+ export function toonLabTriplanarNormal(map, scale, blend, greenSign, coordinates) {
1006
+ const projected = toonLabSourcePosition(coordinates).div(safeScale(scale));
1007
+ const geometryNormal = toonLabSourceGeometryNormal(coordinates);
1008
+ const weights = toonLabTriplanarWeights(geometryNormal, blend);
1009
+ const mapNode = texture(map);
1010
+ let normalX = decodeToonLabNormal(mapNode.sample(projected.zy).rgb, greenSign);
1011
+ let normalY = decodeToonLabNormal(mapNode.sample(projected.xz).rgb, greenSign);
1012
+ let normalZ = decodeToonLabNormal(mapNode.sample(projected.xy).rgb, greenSign);
1013
+
1014
+ // ToonLab graph Triplanar's normal-texture whiteout blend, before its
1015
+ // AbsoluteWorld -> Tangent space conversion.
1016
+ normalX = vec3(normalX.xy.add(geometryNormal.zy), abs(normalX.z).mul(geometryNormal.x));
1017
+ normalY = vec3(normalY.xy.add(geometryNormal.xz), abs(normalY.z).mul(geometryNormal.y));
1018
+ normalZ = vec3(normalZ.xy.add(geometryNormal.xy), abs(normalZ.z).mul(geometryNormal.z));
1019
+ const sourceWorldNormal = normalX.zyx.mul(weights.x)
1020
+ .add(normalY.xzy.mul(weights.y))
1021
+ .add(normalZ.xyz.mul(weights.z));
1022
+ const worldNormal = vec3(
1023
+ sourceWorldNormal.x,
1024
+ sourceWorldNormal.y,
1025
+ sourceWorldNormal.z.mul(coordinates.zSign),
1026
+ );
1027
+ return worldNormalToTangent(worldNormal);
1028
+ }
1029
+
1030
+ function toonLabNormalBlend(a, b) {
1031
+ // S_Rock's Normal Blend node uses BlendMode.Default, not RNM.
1032
+ return normalize(vec3(a.xy.add(b.xy), a.z.mul(b.z)));
1033
+ }
1034
+
1035
+ function toonLabRotateDegrees(inputUv, degrees) {
1036
+ const centered = inputUv.sub(vec2(0.5));
1037
+ const angle = float(degrees * (Math.PI / 180));
1038
+ const sine = sin(angle);
1039
+ const cosine = cos(angle);
1040
+ return vec2(
1041
+ centered.x.mul(cosine).add(centered.y.mul(sine)),
1042
+ centered.x.mul(sine).negate().add(centered.y.mul(cosine)),
1043
+ ).add(vec2(0.5));
1044
+ }
1045
+
1046
+ function toonLabSandNormal(map, layer, greenSign, coordinates) {
1047
+ // The source graph uses Absolute World XZ / -abs(scale), then a fixed
1048
+ // 30-degree rotation around (0.5, 0.5), not UV0 or triplanar sampling.
1049
+ const projected = toonLabSourcePosition(coordinates)
1050
+ .div(safeScale(layer.normalScale).negate());
1051
+ const rotatedUv = toonLabRotateDegrees(projected.xz, layer.normalRotationDegrees);
1052
+ const decoded = decodeToonLabNormal(
1053
+ texture(map).sample(rotatedUv).rgb,
1054
+ normalGreenSignForTexture(map, greenSign),
1055
+ );
1056
+ return toonLabNormalStrength(decoded, layer.normalStrength);
1057
+ }
1058
+
1059
+ function toonLabTopMask(profile, topMaskTexture, assetIntegration) {
1060
+ const denominator = Math.max(1 - profile.layers.offset, 0.000001);
1061
+ let mask = clamp(
1062
+ normalWorldGeometry.y
1063
+ .sub(profile.layers.offset)
1064
+ .div(denominator)
1065
+ .mul(profile.layers.sharpness),
1066
+ 0,
1067
+ 1,
1068
+ );
1069
+ if (assetIntegration.semanticMaskAttributes) {
1070
+ const height = smoothstep(
1071
+ float(profile.layers.heightStart),
1072
+ float(Math.max(profile.layers.heightEnd, profile.layers.heightStart + 0.0001)),
1073
+ attribute('rockHeight', 'float'),
1074
+ );
1075
+ const cavity = attribute('rockCavity', 'float').mul(profile.layers.cavityStrength);
1076
+ const exposure = attribute('rockExposure', 'float').mul(profile.layers.exposureStrength);
1077
+ const form = clamp(height.mul(float(1).add(cavity)).mul(float(1).sub(exposure)), 0, 1);
1078
+ mask = mask.mul(form);
1079
+ }
1080
+ if (profile.layers.maskEnabled && topMaskTexture) {
1081
+ const authored = texture(topMaskTexture).sample(uv()).r;
1082
+ mask = mask.mul(mix(1, authored, profile.layers.semanticMaskStrength));
1083
+ }
1084
+ return clamp(mask, 0, 1);
1085
+ }
1086
+
1087
+ function applyToonLabSubLayer(state, layer, map, mask, coordinates) {
1088
+ if (!layer.enabled) return state;
1089
+ let sampled = toonLabSaturation(
1090
+ toonLabTriplanarColor(map, layer.scale, 1, coordinates),
1091
+ layer.saturation,
1092
+ ).mul(toonLabColorProperty(layer.tint));
1093
+ // The environment ground-field pass contains the actual styled ground
1094
+ // shader color at this world XZ position. For selected grass-capped rocks,
1095
+ // use it as the top surface so the cap continues the surrounding terrain
1096
+ // instead of sampling a separate neon/noisy grass bitmap. The projected
1097
+ // texture remains a deterministic fallback before/outside the ground field.
1098
+ if (layer.useGroundShader) {
1099
+ const groundColor = sampleGroundColor(positionWorld);
1100
+ sampled = mix(sampled, groundColor.rgb, groundColor.a);
1101
+ }
1102
+ const color = mix(state.color, sampled, mask);
1103
+ // This unusual dependency is exact SG_SubLayer behavior: emission is based
1104
+ // on the already blended Out_BC and multiplied by Alpha a second time.
1105
+ const emission = state.emission.add(color.mul(layer.emission).mul(mask));
1106
+ return { color, emission };
1107
+ }
1108
+
1109
+ function assertTexture(value, key, reason) {
1110
+ if (!value?.isTexture) {
1111
+ throw new TypeError(`ToonLab S_Rock requires textures.${key} ${reason}.`);
1112
+ }
1113
+ }
1114
+
1115
+ function validateTextures(profile, textures) {
1116
+ assertTexture(textures.rock, 'rock', 'for the base projection');
1117
+ if (profile.base.useSmoothnessTexture) {
1118
+ assertTexture(textures.smoothness, 'smoothness', 'when useSmoothnessTexture is true');
1119
+ }
1120
+ if (profile.base.striping.enabled) {
1121
+ assertTexture(textures.stripe, 'stripe', 'when striping is enabled');
1122
+ }
1123
+ if (profile.moss.enabled) assertTexture(textures.moss, 'moss', 'when moss is enabled');
1124
+ if (profile.layers.grass.enabled) {
1125
+ assertTexture(textures.grass, 'grass', 'when the grass sublayer is enabled');
1126
+ }
1127
+ if (profile.layers.snow.enabled) {
1128
+ assertTexture(textures.snow, 'snow', 'when the snow sublayer is enabled');
1129
+ }
1130
+ if (profile.layers.sand.enabled) {
1131
+ assertTexture(textures.sand, 'sand', 'when the sand sublayer is enabled');
1132
+ if (profile.layers.sand.normalStrength > 0) {
1133
+ assertTexture(
1134
+ textures.sandNormal,
1135
+ 'sandNormal',
1136
+ 'when the sand sublayer normal strength is greater than zero',
1137
+ );
1138
+ }
1139
+ }
1140
+ }
1141
+
1142
+ function textureKeysForProfile(profile, { includeInactive = false } = {}) {
1143
+ const keys = new Set(['rock']);
1144
+ if (includeInactive) {
1145
+ for (const [key, slot] of Object.entries(profile.textureRefs)) {
1146
+ if (slot) keys.add(key);
1147
+ }
1148
+ return keys;
1149
+ }
1150
+ if (profile.textureRefs.rockNormal) keys.add('rockNormal');
1151
+ if (profile.normals.useSmoothed && profile.textureRefs.stylizedNormal) {
1152
+ keys.add('stylizedNormal');
1153
+ }
1154
+ if (profile.base.useSmoothnessTexture) keys.add('smoothness');
1155
+ if (profile.base.striping.enabled) keys.add('stripe');
1156
+ if (profile.moss.enabled) keys.add('moss');
1157
+ // Alpha also suppresses smoothness without an enabled color sublayer.
1158
+ if (profile.layers.maskEnabled && profile.textureRefs.topMask) keys.add('topMask');
1159
+ if (profile.layers.grass.enabled) keys.add('grass');
1160
+ if (profile.layers.snow.enabled) keys.add('snow');
1161
+ if (profile.layers.sand.enabled) {
1162
+ keys.add('sand');
1163
+ if (profile.layers.sand.normalStrength > 0) keys.add('sandNormal');
1164
+ }
1165
+ return keys;
1166
+ }
1167
+
1168
+ /**
1169
+ * Builds a TSL material from a normalized profile and resolved THREE.Texture
1170
+ * objects. Source alpha semantics are retained when an imported material uses
1171
+ * masking or transparency. This ports the S_Rock graph inputs; final pixels still
1172
+ * depend on matching ToonLab's deferred BRDF, SSAO, shadows, ambient probe,
1173
+ * fog, TAA, and post-processing.
1174
+ */
1175
+ export function createToonRockMaterial({
1176
+ assetIntegration = null,
1177
+ profile = {},
1178
+ textures = {},
1179
+ name = null,
1180
+ } = {}) {
1181
+ const resolvedProfile = normalizeToonLabRockProfile(profile);
1182
+ validateTextures(resolvedProfile, textures);
1183
+ const resolvedAssetIntegration = {
1184
+ sourceAlbedoStrength: clampNumber(
1185
+ finite(assetIntegration?.sourceAlbedoStrength, 0),
1186
+ 0,
1187
+ 1,
1188
+ ),
1189
+ sourceNormalStrength: clampNumber(
1190
+ finite(assetIntegration?.sourceNormalStrength, 1),
1191
+ 0,
1192
+ 2,
1193
+ ),
1194
+ sourceAoStrength: clampNumber(
1195
+ finite(assetIntegration?.sourceAoStrength, 1),
1196
+ 0,
1197
+ 2,
1198
+ ),
1199
+ // glTF material factors are already linear working-space values. Keep
1200
+ // them separate from ToonLab inspector colors, which require sRGB decode.
1201
+ sourceColor: color3(assetIntegration?.sourceColor, [1, 1, 1]),
1202
+ sourceEmissive: color3(assetIntegration?.sourceEmissive, [0, 0, 0]),
1203
+ sourceEmissiveIntensity: Math.max(0, finite(assetIntegration?.sourceEmissiveIntensity, 1)),
1204
+ sourceOpacity: clampNumber(finite(assetIntegration?.sourceOpacity, 1), 0, 1),
1205
+ sourceAlphaTest: clampNumber(finite(assetIntegration?.sourceAlphaTest, 0), 0, 1),
1206
+ sourceTransparent: Boolean(assetIntegration?.sourceTransparent),
1207
+ sourceDepthWrite: assetIntegration?.sourceDepthWrite !== false,
1208
+ sourceSide: Number.isInteger(assetIntegration?.sourceSide) ? assetIntegration.sourceSide : null,
1209
+ sourceMetalnessFactor: clampNumber(finite(assetIntegration?.sourceMetalnessFactor, 0), 0, 1),
1210
+ sourceRoughnessFactor: clampNumber(finite(assetIntegration?.sourceRoughnessFactor, 1), 0, 1),
1211
+ sourceSpecularFactor: clampNumber(finite(assetIntegration?.sourceSpecularFactor, 1), 0, 1),
1212
+ primaryNormalStrength: clampNumber(
1213
+ finite(assetIntegration?.primaryNormalStrength, 1),
1214
+ 0,
1215
+ 2,
1216
+ ),
1217
+ primarySpecularStrength: clampNumber(
1218
+ finite(assetIntegration?.primarySpecularStrength, 1),
1219
+ 0,
1220
+ 2,
1221
+ ),
1222
+ semanticMaskAttributes: Boolean(assetIntegration?.semanticMaskAttributes),
1223
+ rockRegionAttributes: Boolean(assetIntegration?.rockRegionAttributes),
1224
+ regionTintStrength: clampNumber(
1225
+ finite(assetIntegration?.regionTintStrength, 0),
1226
+ 0,
1227
+ 1,
1228
+ ),
1229
+ regionBaseTint: color3(assetIntegration?.regionBaseTint, [1, 1, 1]),
1230
+ regionShaftTint: color3(assetIntegration?.regionShaftTint, [1, 1, 1]),
1231
+ regionNeckTint: color3(assetIntegration?.regionNeckTint, [1, 1, 1]),
1232
+ regionCapTint: color3(assetIntegration?.regionCapTint, [1, 1, 1]),
1233
+ regionNeckOverlayStrength: clampNumber(
1234
+ finite(assetIntegration?.regionNeckOverlayStrength, 0),
1235
+ 0,
1236
+ 1,
1237
+ ),
1238
+ vertexAoStrength: Math.max(0, finite(assetIntegration?.vertexAoStrength, 0)),
1239
+ // Reads the `rockCavity` channel written by rockGeometryDetail. Gated the
1240
+ // same way as the other optional vertex channels: 0 means the attribute is
1241
+ // not required to exist, so meshes without geometry detail are unaffected.
1242
+ vertexCavityStrength: clampNumber(
1243
+ finite(assetIntegration?.vertexCavityStrength, 0),
1244
+ 0,
1245
+ 4,
1246
+ ),
1247
+ vertexColorStrength: clampNumber(
1248
+ finite(assetIntegration?.vertexColorStrength, 0),
1249
+ 0,
1250
+ 1,
1251
+ ),
1252
+ };
1253
+
1254
+ const radialDistance = distance(cameraPosition, positionWorld);
1255
+ const authoredDistanceScale = resolvedProfile.coordinates.distanceScale;
1256
+ const topMask = toonLabTopMask(resolvedProfile, textures.topMask, resolvedAssetIntegration);
1257
+ const rockProjection = toonLabRockProjection(textures.rock, resolvedProfile);
1258
+ let colorNode = toonLabContrast(
1259
+ toonLabSaturation(rockProjection, resolvedProfile.base.saturation),
1260
+ resolvedProfile.base.contrast,
1261
+ ).add(resolvedProfile.base.brightness).mul(
1262
+ toonLabColorProperty(resolvedProfile.base.tint),
1263
+ );
1264
+ if (
1265
+ resolvedAssetIntegration.sourceAlbedoStrength > 0
1266
+ && textures.sourceRock?.isTexture
1267
+ ) {
1268
+ // Imported catalog albedo is authored in mesh UV space. Re-projecting it
1269
+ // at the package macro scale erased precisely the baked cracks and strata
1270
+ // that the controlled blend is meant to retain.
1271
+ const sourceProjection = texture(textures.sourceRock).sample(uv()).rgb.mul(
1272
+ vec3(...resolvedAssetIntegration.sourceColor),
1273
+ );
1274
+ colorNode = mix(
1275
+ colorNode,
1276
+ toonLabContrast(
1277
+ toonLabSaturation(sourceProjection, resolvedProfile.base.saturation),
1278
+ resolvedProfile.base.contrast,
1279
+ ).add(resolvedProfile.base.brightness).mul(
1280
+ toonLabColorProperty(resolvedProfile.base.tint),
1281
+ ),
1282
+ resolvedAssetIntegration.sourceAlbedoStrength,
1283
+ );
1284
+ }
1285
+
1286
+ // The macro projection carries the authored silhouette-scale color breakup;
1287
+ // a second metre-scale octave preserves readable rock surface detail close
1288
+ // to the camera without changing that macro identity.
1289
+ const nearDetailSample = toonLabTriplanarColor(
1290
+ textures.rock,
1291
+ resolvedProfile.base.nearDetailScale,
1292
+ resolvedProfile.base.projectionContrast,
1293
+ resolvedProfile.coordinates,
1294
+ );
1295
+ const nearDetailValue = dot(nearDetailSample, vec3(0.2126, 0.7152, 0.0722));
1296
+ const nearDetailFade = clamp(
1297
+ radialDistance.div(resolvedProfile.base.nearDetailDistance),
1298
+ 0,
1299
+ 1,
1300
+ ).oneMinus().mul(resolvedProfile.base.nearDetailStrength);
1301
+ colorNode = colorNode.mul(mix(
1302
+ 1,
1303
+ mix(0.78, 1.22, nearDetailValue),
1304
+ nearDetailFade,
1305
+ ));
1306
+
1307
+ const distantAmount = toonLabLinearRamp(
1308
+ radialDistance,
1309
+ resolvedProfile.base.closeTintDistance * authoredDistanceScale,
1310
+ resolvedProfile.base.farTintDistance * authoredDistanceScale,
1311
+ );
1312
+ colorNode = mix(
1313
+ colorNode,
1314
+ mix(
1315
+ colorNode,
1316
+ toonLabColorProperty(resolvedProfile.base.distantTint),
1317
+ resolvedProfile.base.distantTintMix,
1318
+ ),
1319
+ distantAmount,
1320
+ );
1321
+
1322
+ if (resolvedProfile.base.striping.enabled) {
1323
+ const stripeProjected = toonLabSideProjection(
1324
+ textures.stripe,
1325
+ resolvedProfile.base.striping.scale,
1326
+ resolvedProfile.base.projectionContrast,
1327
+ {
1328
+ negativeScale: false,
1329
+ clampResult: false,
1330
+ coordinates: resolvedProfile.coordinates,
1331
+ },
1332
+ );
1333
+ const stripeOpacity = clamp(
1334
+ toonLabContrast(stripeProjected.r, resolvedProfile.base.striping.contrast),
1335
+ 0,
1336
+ 1,
1337
+ );
1338
+ colorNode = toonLabOverlay(
1339
+ colorNode,
1340
+ toonLabColorProperty(resolvedProfile.base.striping.color),
1341
+ stripeOpacity,
1342
+ );
1343
+ }
1344
+
1345
+ if (
1346
+ resolvedAssetIntegration.rockRegionAttributes
1347
+ && resolvedAssetIntegration.regionTintStrength > 0
1348
+ ) {
1349
+ const regions = attribute('_tl_rock_region', 'vec4');
1350
+ const primaryTint = vec3(...resolvedAssetIntegration.regionBaseTint).mul(regions.x)
1351
+ .add(vec3(...resolvedAssetIntegration.regionShaftTint).mul(regions.y))
1352
+ .add(vec3(...resolvedAssetIntegration.regionCapTint).mul(regions.w));
1353
+ const neckBlend = regions.z.mul(resolvedAssetIntegration.regionNeckOverlayStrength);
1354
+ const geologicalTint = mix(
1355
+ primaryTint,
1356
+ vec3(...resolvedAssetIntegration.regionNeckTint),
1357
+ neckBlend,
1358
+ );
1359
+ colorNode = colorNode.mul(mix(
1360
+ vec3(1),
1361
+ geologicalTint,
1362
+ resolvedAssetIntegration.regionTintStrength,
1363
+ ));
1364
+ }
1365
+
1366
+ // Hoisted so the roughness and normal stages downstream can read the same
1367
+ // coverage the color stage used. Moss that only tints is moss that cannot
1368
+ // sit on the stone.
1369
+ let mossMaskNode = null;
1370
+ let mossDampNode = null;
1371
+ let mossCushionNode = null;
1372
+ if (resolvedProfile.moss.enabled) {
1373
+ const mossSample = toonLabTriplanarColor(
1374
+ textures.moss,
1375
+ resolvedProfile.moss.size,
1376
+ 1,
1377
+ resolvedProfile.coordinates,
1378
+ );
1379
+ const mossLuminance = dot(max(mossSample, vec3(0)), vec3(0.2126, 0.7152, 0.0722));
1380
+ // --- colour ramp ----------------------------------------------------
1381
+ //
1382
+ // The shipped path feeds the raw rgb sample straight into the palette
1383
+ // `mix()`. That silently assumes the moss map's channels span 0..1, and the
1384
+ // shipped map does not come close: its linear luminance occupies
1385
+ // 0.092-0.279 with 99.3% of texels inside one decile, and its channel means
1386
+ // are r 0.079 / g 0.147 / b 0.041. Two things follow, and together they are
1387
+ // most of why moss rendered as near-black-green camouflage on near-white
1388
+ // stone (D19-210):
1389
+ //
1390
+ // * the ramp coordinate never clears ~0.09, so moss resolves to
1391
+ // `lowColor` — the darkest working stop — essentially everywhere, and
1392
+ // `highColor` and the whole upper half of the authored palette are
1393
+ // unreachable. Five carefully chosen stops collapse to one flat dark
1394
+ // green with no internal variation for the eye to read as texture.
1395
+ // * the coordinate is a vec3, so each palette channel is driven by the
1396
+ // matching texture channel. The map's red is half its green, so the
1397
+ // ramp's red end stays pinned while green rises, skewing hue on top of
1398
+ // crushing value. The coverage mask below was already fixed for exactly
1399
+ // this cross-channel bug; the colour stage was not.
1400
+ //
1401
+ // A floor of 0 or more switches to a scalar coordinate remapped from the
1402
+ // map's measured range, which reaches the full palette and fixes the hue
1403
+ // skew at once. -1 keeps the shipped behaviour byte for byte.
1404
+ let mossPattern;
1405
+ if (resolvedProfile.moss.patternFloor >= 0) {
1406
+ const floor = resolvedProfile.moss.patternFloor;
1407
+ const ceiling = Math.max(floor + 1e-4, resolvedProfile.moss.patternCeiling);
1408
+ mossPattern = pow(
1409
+ clamp(mossLuminance.sub(floor).div(ceiling - floor), 0, 1),
1410
+ float(resolvedProfile.moss.colorPower),
1411
+ );
1412
+ } else {
1413
+ mossPattern = pow(
1414
+ max(mossSample, vec3(0)),
1415
+ vec3(resolvedProfile.moss.colorPower),
1416
+ );
1417
+ }
1418
+ const mossColor = mix(
1419
+ toonLabColorProperty(resolvedProfile.moss.lowColor),
1420
+ toonLabColorProperty(resolvedProfile.moss.highColor),
1421
+ mossPattern,
1422
+ );
1423
+ const slope = clamp(
1424
+ normalWorldGeometry.y
1425
+ .mul(resolvedProfile.moss.sharpness)
1426
+ .sub(resolvedProfile.moss.offset),
1427
+ 0,
1428
+ 1,
1429
+ );
1430
+ // Coverage is scalar. Using RGB moss texels as the interpolation mask
1431
+ // cross-mixed color channels and could turn green source moss magenta.
1432
+ let mossCoverage = dot(mossSample, vec3(0.2126, 0.7152, 0.0722));
1433
+ // The shader has no coverage-mask input: it reuses the moss ALBEDO as its
1434
+ // own mask. That texture is a colour map, so its luminance is
1435
+ // high-frequency, and pushing it through the gain needed to clear its dark
1436
+ // average (D19-032) binarises the grain into pepper — isolated bright
1437
+ // texels scattered over the stone. It reads as lichen spotting, which is
1438
+ // fine for incidental weathering on a distant cliff and wrong wherever
1439
+ // moss is supposed to be a continuous cushion.
1440
+ //
1441
+ // `formDriven` blends the coverage source toward a constant, handing the
1442
+ // patch shape to the smooth geometric moisture field (slope + cavity)
1443
+ // instead. The texture then modulates a continuous cap rather than
1444
+ // defining it, and `fringe` supplies the ragged boundary. 0 is the shipped
1445
+ // behaviour. See D19-193.
1446
+ if (resolvedProfile.moss.formDriven > 0) {
1447
+ mossCoverage = mix(
1448
+ mossCoverage,
1449
+ float(1),
1450
+ float(Math.min(1, resolvedProfile.moss.formDriven)),
1451
+ );
1452
+ }
1453
+ // Moisture, not slope. Slope alone puts moss on upward faces and nowhere
1454
+ // else, which is why a slope-only mask reads as a flat tint painted onto
1455
+ // ledges. Real moss follows where water lingers and light is indirect:
1456
+ // crevices, hollows, and the shaded junctions between slabs. `rockCavity`
1457
+ // carries that concavity per vertex, so it adds moisture on vertical and
1458
+ // shaded surfaces that the slope term scores at zero — and because it is an
1459
+ // interpolated geometric field rather than a threshold on a constant, the
1460
+ // resulting boundary is irregular and follows the form.
1461
+ let moisture = resolvedAssetIntegration.vertexCavityStrength > 0
1462
+ ? clamp(
1463
+ slope.add(
1464
+ attribute(ROCK_CAVITY_ATTRIBUTE, 'float')
1465
+ .mul(resolvedAssetIntegration.vertexCavityStrength),
1466
+ ),
1467
+ 0,
1468
+ 1,
1469
+ )
1470
+ : slope;
1471
+ // ...and the other half of the same fact. `rockCavity` says where water
1472
+ // lingers; nothing said where it never does. Both terms above only ever
1473
+ // ADD, and `slope` saturates hard — at the garden's resolved sharpness 2.19
1474
+ // / offset -0.205 it reaches 1.0 by n.y = 0.36, which is roughly the top
1475
+ // two-thirds of a boulder. Across that whole region the support field is a
1476
+ // constant 1 and carries no information about the form at all, so the
1477
+ // colonisation noise alone decides where moss lands. Noise uncorrelated
1478
+ // with form is exactly what camouflage is, and it is why moss sat as
1479
+ // happily on an exposed sunlit crown as in a shaded hollow (D19-212).
1480
+ //
1481
+ // `rockExposure` is the rectified negative curvature from the same
1482
+ // estimator, so crowns, ridges and shoulders finally score above zero and
1483
+ // can be subtracted back out. Bare crowns are not a side effect here —
1484
+ // they are the single strongest cue that moss grew rather than was printed.
1485
+ if (
1486
+ resolvedProfile.moss.exposure > 0
1487
+ && resolvedAssetIntegration.vertexCavityStrength > 0
1488
+ ) {
1489
+ moisture = clamp(
1490
+ moisture.sub(
1491
+ attribute(ROCK_EXPOSURE_ATTRIBUTE, 'float')
1492
+ .mul(resolvedProfile.moss.exposure),
1493
+ ),
1494
+ 0,
1495
+ 1,
1496
+ );
1497
+ }
1498
+ let mossMask;
1499
+ if (resolvedProfile.moss.coverage >= 0) {
1500
+ // --- coverage-mask path -------------------------------------------
1501
+ //
1502
+ // The legacy expression below squares its product and clamps, which
1503
+ // makes the transition band extremely narrow: coverage crosses from 0 to
1504
+ // 1 over a sliver of the moisture range. Since moisture is dominated by
1505
+ // the upward-slope term, the result is a near-horizontal waterline with
1506
+ // uniform moss above and bare stone below — the stone reads as dip-dyed
1507
+ // to a level rather than colonised.
1508
+ //
1509
+ // Real moss is patchy: dense in hollows and on shaded faces, thinning to
1510
+ // bare crowns and exposed ridges, with an irregular broken edge and
1511
+ // detached islands. That needs a second, independent field — WHERE it
1512
+ // actually took hold — which the shader had no input for. This is it.
1513
+ //
1514
+ // support = where moss CAN grow (slope + rockCavity)
1515
+ // patch = where it DID colonise (fractal noise, world space)
1516
+ // gate = support gated by patch
1517
+ // mask = smoothstep across a WIDE band, not a squared clamp
1518
+ //
1519
+ // Noise is evaluated in world space, so two placements of the same asset
1520
+ // colonise differently without needing a per-asset uniform, and a stone
1521
+ // does not swim when the scene moves it.
1522
+ const patchNoise = mx_fractal_noise_float(
1523
+ positionWorld.div(Math.max(resolvedProfile.moss.patchScale, 0.01)),
1524
+ Math.max(1, Math.trunc(resolvedProfile.moss.patchOctaves)),
1525
+ 2,
1526
+ 0.5,
1527
+ 1,
1528
+ );
1529
+ // fBm returns roughly [-1, 1]; remap, then push contrast so cushions
1530
+ // separate into distinct masses instead of a smooth cloud.
1531
+ const patch = clamp(
1532
+ patchNoise.mul(0.5).add(0.5).sub(0.5)
1533
+ .mul(resolvedProfile.moss.patchContrast)
1534
+ .add(0.5),
1535
+ 0,
1536
+ 1,
1537
+ );
1538
+ const gate = moisture.mul(
1539
+ mix(float(1), patch, float(resolvedProfile.moss.patchStrength)),
1540
+ );
1541
+ // Threshold IS the coverage dial: at coverage 1 moss takes every
1542
+ // supported surface, at 0.15 only the wettest, best-colonised pockets.
1543
+ const threshold = Math.min(0.98, Math.max(0.02,
1544
+ 1 - resolvedProfile.moss.coverage));
1545
+ const band = Math.max(0.001, resolvedProfile.moss.band);
1546
+ mossMask = clamp(
1547
+ smoothstep(float(threshold - band), float(threshold + band), gate),
1548
+ 0,
1549
+ 1,
1550
+ );
1551
+ // Damp stone. Moss and stone read at a close value in life for a physical
1552
+ // reason: moss only grows where the stone stays wet, and wet stone is
1553
+ // markedly darker than dry stone. The shipped shader had no term for it,
1554
+ // so the only levers on the moss/stone value gap were the shared palette
1555
+ // (which belongs to the ground and the props owner too) and the scene's
1556
+ // global grade. This is the correct third lever, and it also leaves a
1557
+ // damp halo just outside each cushion — moss does not begin at a dry
1558
+ // edge. The halo comes free by taking the same gate at a threshold one
1559
+ // band-width lower, so it always tracks the moss it surrounds.
1560
+ if (resolvedProfile.moss.damp > 0) {
1561
+ mossDampNode = clamp(
1562
+ smoothstep(
1563
+ float(threshold - (band * 3)),
1564
+ float(threshold + band),
1565
+ gate,
1566
+ ),
1567
+ 0,
1568
+ 1,
1569
+ );
1570
+ }
1571
+ // The cushion's own form. `relief` flattens the STONE's detail normal
1572
+ // under the moss, which stops crevices showing through, but nothing ever
1573
+ // raised the moss itself — so the patch stayed geometrically identical to
1574
+ // the rock beneath it and read as a decal (D19-213). A cushion is a soft
1575
+ // raised mass, and what makes the eye read "raised" is that its shading
1576
+ // normal tilts away from the surface as the mass swells.
1577
+ //
1578
+ // The patch field is already a height field in all but name: high inside
1579
+ // a cushion, low outside. Its world-space gradient is therefore the slope
1580
+ // of the cushion's surface, and the finite differences below cost three
1581
+ // extra fBm evaluations at the same period the mask already uses, so the
1582
+ // relief lands exactly on the patches rather than as unrelated bumps.
1583
+ if (resolvedProfile.moss.cushion > 0) {
1584
+ const period = Math.max(resolvedProfile.moss.patchScale, 0.01);
1585
+ // TWO octaves, not the mask's five, and a step sized to them. The
1586
+ // cushion's shape is the MASS of the mound, which is the low-frequency
1587
+ // part of the patch field; the high octaves are the fibrous margin the
1588
+ // `fringe` term already owns. Differencing across all five aliases
1589
+ // those fine octaves and returns a noisy gradient that reads as grain
1590
+ // rather than as a swelling — which is why the first attempt at this
1591
+ // was invisible at any strength.
1592
+ const octaves = 2;
1593
+ const step = 0.14;
1594
+ const at = (dx, dy, dz) => mx_fractal_noise_float(
1595
+ positionWorld.div(period).add(vec3(dx, dy, dz)),
1596
+ octaves,
1597
+ 2,
1598
+ 0.5,
1599
+ 1,
1600
+ );
1601
+ const centre = at(0, 0, 0);
1602
+ mossCushionNode = vec3(
1603
+ at(step, 0, 0).sub(centre),
1604
+ at(0, step, 0).sub(centre),
1605
+ at(0, 0, step).sub(centre),
1606
+ ).div(step);
1607
+ }
1608
+ } else {
1609
+ mossMask = clamp(
1610
+ pow(mossCoverage.mul(resolvedProfile.moss.multiply).mul(moisture), 2),
1611
+ 0,
1612
+ 1,
1613
+ );
1614
+ }
1615
+ if (resolvedProfile.moss.fringe > 0) {
1616
+ // The mask above is a smooth curve, so its boundary is an airbrushed
1617
+ // gradient — moss fading politely to nothing. Real moss ends in a ragged
1618
+ // margin that breaks into detached fragments. Pushing the mask through a
1619
+ // high-frequency field breaks the contour without moving the coverage:
1620
+ // values well inside a patch stay saturated because the perturbation is
1621
+ // weighted by `edge`, which is zero except in the transition band.
1622
+ //
1623
+ // THE SOURCE HAD TO CHANGE. This sampled the moss ALBEDO at a smaller
1624
+ // period and centred it on 0.5, which cannot work and never did: that
1625
+ // texture's linear luminance is 0.092-0.279 with 99.3% of its texels
1626
+ // inside a single decile, so the term evaluated to a near-constant -0.75
1627
+ // and the "fringe" was a uniform erosion of the boundary — the contour
1628
+ // moved inward and stayed just as smooth. The centring assumed a balanced
1629
+ // noise map and got a flat dark colour map (D19-211).
1630
+ //
1631
+ // World-space fBm at a fraction of the patch period is an actual noise
1632
+ // field: balanced about zero by construction, independent of whatever
1633
+ // albedo happens to be bound, and coherent across the triplanar seams the
1634
+ // texture sample was not.
1635
+ const fringeNoise = mx_fractal_noise_float(
1636
+ positionWorld.div(Math.max(
1637
+ resolvedProfile.moss.patchScale * resolvedProfile.moss.fringeScale,
1638
+ 0.01,
1639
+ )),
1640
+ 3,
1641
+ 2,
1642
+ 0.5,
1643
+ 1,
1644
+ );
1645
+ // `edge` peaks at 1 in the middle of the transition and vanishes at both
1646
+ // ends, so the fringe chews the boundary and leaves the interior alone.
1647
+ const edge = mossMask.mul(mossMask.oneMinus()).mul(4);
1648
+ mossMask = clamp(
1649
+ mossMask.add(
1650
+ fringeNoise.mul(edge).mul(resolvedProfile.moss.fringe),
1651
+ ),
1652
+ 0,
1653
+ 1,
1654
+ );
1655
+ }
1656
+ mossMaskNode = mossMask;
1657
+ // Damp the STONE before the moss is mixed over it, so the darkening lands
1658
+ // on bare rock in the halo and is simply overwritten inside the patches.
1659
+ if (mossDampNode) {
1660
+ colorNode = colorNode.mul(
1661
+ float(1).sub(mossDampNode.mul(resolvedProfile.moss.damp)),
1662
+ );
1663
+ }
1664
+ colorNode = mix(colorNode, mossColor, mossMask);
1665
+ // Contact shading. A raised mass occludes the crease where it meets the
1666
+ // surface it sits on; without that line the eye has no evidence the cushion
1667
+ // has any thickness, which is the other half of why moss read as flat. The
1668
+ // `edge` weighting confines it to the margin, so cushion interiors and open
1669
+ // stone are both untouched.
1670
+ if (resolvedProfile.moss.contact > 0) {
1671
+ // Cubed, not linear. `mask·(1-mask)·4` peaks at 1 but falls off slowly,
1672
+ // and once `fringe` has chewed the boundary the mask is in transition
1673
+ // across a wide, noisy region — so a linear weight smears sooty lace over
1674
+ // half the stone instead of drawing a crease. The cube pulls it back to a
1675
+ // narrow line hugging the actual margin.
1676
+ const margin = pow(mossMask.mul(mossMask.oneMinus()).mul(4), float(3));
1677
+ colorNode = colorNode.mul(
1678
+ float(1).sub(margin.mul(resolvedProfile.moss.contact)),
1679
+ );
1680
+ }
1681
+ }
1682
+
1683
+ let layerState = {
1684
+ color: colorNode,
1685
+ // The base emission multiply receives the post-moss color branch.
1686
+ emission: colorNode.mul(resolvedProfile.base.emissiveStrength),
1687
+ };
1688
+ // Exact graph order: later enabled calls paint over earlier calls.
1689
+ layerState = applyToonLabSubLayer(
1690
+ layerState,
1691
+ resolvedProfile.layers.grass,
1692
+ textures.grass,
1693
+ topMask,
1694
+ resolvedProfile.coordinates,
1695
+ );
1696
+ const sceneWaterLevel = uniform(-10000);
1697
+ const sceneSkyColor = uniform(new Color(1, 1, 1));
1698
+ const skyPeak = max(
1699
+ max(sceneSkyColor.r, sceneSkyColor.g),
1700
+ max(sceneSkyColor.b, float(0.001)),
1701
+ );
1702
+ const skyChroma = sceneSkyColor.div(skyPeak);
1703
+ const lowLightProbeBlend = float(1).sub(smoothstep(
1704
+ float(0.45),
1705
+ float(0.8),
1706
+ skyPeak,
1707
+ ));
1708
+ const readabilityTint = mix(
1709
+ vec3(1, 1, 1),
1710
+ skyChroma,
1711
+ resolvedProfile.lighting.skyColorInfluence,
1712
+ );
1713
+ const wetBandMask = clamp(
1714
+ abs(positionWorld.y.sub(sceneWaterLevel)).div(max(
1715
+ resolvedProfile.shoreline.wetBandWidth,
1716
+ 0.0001,
1717
+ )),
1718
+ 0,
1719
+ 1,
1720
+ ).oneMinus();
1721
+ const wetColorScale = float(1).sub(
1722
+ wetBandMask.mul(resolvedProfile.shoreline.wetBandDarkening),
1723
+ );
1724
+ layerState = {
1725
+ color: layerState.color
1726
+ .mul(wetColorScale),
1727
+ emission: layerState.emission
1728
+ // A small albedo-relative floor keeps deep faces legible, but its color
1729
+ // is transient scene state. Feeding the active sky here means the same
1730
+ // sandstone is cool under a daylight sky and warm at golden hour without
1731
+ // baking either cast into its geological Base Color.
1732
+ .add(mix(
1733
+ layerState.color.mul(readabilityTint),
1734
+ vec3(dot(layerState.color, vec3(0.2126, 0.7152, 0.0722)))
1735
+ .mul(readabilityTint),
1736
+ lowLightProbeBlend.mul(0.7),
1737
+ ).mul(
1738
+ float(resolvedProfile.lighting.ambientFloor)
1739
+ .mul(lowLightProbeBlend.mul(3).add(1)),
1740
+ ))
1741
+ .mul(wetColorScale),
1742
+ };
1743
+ layerState = applyToonLabSubLayer(
1744
+ layerState,
1745
+ resolvedProfile.layers.snow,
1746
+ textures.snow,
1747
+ topMask,
1748
+ resolvedProfile.coordinates,
1749
+ );
1750
+ layerState = applyToonLabSubLayer(
1751
+ layerState,
1752
+ resolvedProfile.layers.sand,
1753
+ textures.sand,
1754
+ topMask,
1755
+ resolvedProfile.coordinates,
1756
+ );
1757
+ if (resolvedAssetIntegration.vertexColorStrength > 0) {
1758
+ const assetColor = vertexColor().rgb;
1759
+ const styledAssetColor = layerState.color.mul(assetColor);
1760
+ layerState = {
1761
+ color: mix(
1762
+ layerState.color,
1763
+ styledAssetColor,
1764
+ resolvedAssetIntegration.vertexColorStrength,
1765
+ ),
1766
+ emission: mix(
1767
+ layerState.emission,
1768
+ layerState.emission.mul(assetColor),
1769
+ resolvedAssetIntegration.vertexColorStrength,
1770
+ ),
1771
+ };
1772
+ }
1773
+
1774
+ const smoothnessSource = resolvedProfile.base.useSmoothnessTexture
1775
+ ? toonLabContrast(
1776
+ clamp(toonLabRockProjection(textures.smoothness, resolvedProfile).r, 0, 1),
1777
+ resolvedProfile.base.smoothnessContrast,
1778
+ )
1779
+ : float(1);
1780
+ let rockSmoothness = smoothnessSource.mul(resolvedProfile.base.smoothness);
1781
+ if (
1782
+ resolvedAssetIntegration.sourceAlbedoStrength > 0
1783
+ && textures.sourceRoughness?.isTexture
1784
+ ) {
1785
+ // glTF metallic-roughness textures store perceptual roughness in G.
1786
+ // Blend that authored breakup into the shared rock smoothness instead of
1787
+ // retaining a texture reference that the visible shader never consumes.
1788
+ const sourceSmoothness = clamp(
1789
+ texture(textures.sourceRoughness).sample(uv()).g
1790
+ .mul(resolvedAssetIntegration.sourceRoughnessFactor),
1791
+ 0,
1792
+ 1,
1793
+ ).oneMinus();
1794
+ rockSmoothness = mix(
1795
+ rockSmoothness,
1796
+ sourceSmoothness,
1797
+ resolvedAssetIntegration.sourceAlbedoStrength,
1798
+ );
1799
+ }
1800
+ // The S_Rock graph applies this mask even when every top-layer toggle is off.
1801
+ const finalSmoothness = rockSmoothness.mul(topMask.oneMinus());
1802
+
1803
+ const stylizedNormal = resolvedProfile.normals.useSmoothed && textures.stylizedNormal
1804
+ ? decodeToonLabNormal(
1805
+ texture(textures.stylizedNormal).sample(uv()).rgb,
1806
+ normalGreenSignForTexture(
1807
+ textures.stylizedNormal,
1808
+ resolvedProfile.normals.normalGreenSign,
1809
+ ),
1810
+ )
1811
+ : vec3(0, 0, 1);
1812
+ let combinedNormal = stylizedNormal;
1813
+ if (textures.rockNormal) {
1814
+ const crackNormal = toonLabTriplanarNormal(
1815
+ textures.rockNormal,
1816
+ resolvedProfile.base.scale,
1817
+ resolvedProfile.base.projectionContrast,
1818
+ normalGreenSignForTexture(
1819
+ textures.rockNormal,
1820
+ resolvedProfile.normals.normalGreenSign,
1821
+ ),
1822
+ resolvedProfile.coordinates,
1823
+ );
1824
+ const normalFade = clamp(
1825
+ radialDistance.div(Math.max(
1826
+ resolvedProfile.normals.distance * authoredDistanceScale,
1827
+ 0.000001,
1828
+ )),
1829
+ 0,
1830
+ 1,
1831
+ );
1832
+ const flatness = mix(
1833
+ resolvedProfile.normals.nearFlatten,
1834
+ resolvedProfile.normals.farFlatten,
1835
+ normalFade,
1836
+ );
1837
+ combinedNormal = toonLabNormalBlend(
1838
+ stylizedNormal,
1839
+ toonLabNormalStrength(
1840
+ crackNormal,
1841
+ float(1).sub(flatness).mul(resolvedAssetIntegration.primaryNormalStrength),
1842
+ ),
1843
+ );
1844
+ }
1845
+ if (
1846
+ resolvedAssetIntegration.sourceNormalStrength > 0
1847
+ && textures.sourceNormal?.isTexture
1848
+ ) {
1849
+ const sourceNormal = decodeToonLabNormal(
1850
+ texture(textures.sourceNormal).sample(uv()).rgb,
1851
+ normalGreenSignForTexture(
1852
+ textures.sourceNormal,
1853
+ resolvedProfile.normals.normalGreenSign,
1854
+ ),
1855
+ );
1856
+ combinedNormal = toonLabNormalBlend(
1857
+ combinedNormal,
1858
+ toonLabNormalStrength(
1859
+ sourceNormal,
1860
+ resolvedAssetIntegration.sourceNormalStrength,
1861
+ ),
1862
+ );
1863
+ }
1864
+
1865
+ // A moss cushion buries the relief underneath it. Flattening the rock's
1866
+ // detail normal toward the surface normal wherever moss is dense is what
1867
+ // separates "moss growing on stone" from "green painted over stone" — with
1868
+ // the stone's crevice normals still showing through, the eye reads one
1869
+ // surface with a colour on it. Applied before the top-layer blend so a
1870
+ // grass/snow layer still wins where it overlaps.
1871
+ if (mossMaskNode && resolvedProfile.moss.relief > 0) {
1872
+ combinedNormal = normalize(mix(
1873
+ combinedNormal,
1874
+ vec3(0, 0, 1),
1875
+ mossMaskNode.mul(resolvedProfile.moss.relief),
1876
+ ));
1877
+ }
1878
+
1879
+ const hasTopLayer = resolvedProfile.layers.grass.enabled
1880
+ || resolvedProfile.layers.snow.enabled
1881
+ || resolvedProfile.layers.sand.enabled;
1882
+ const hasSandNormalResponse = resolvedProfile.layers.sand.enabled
1883
+ && resolvedProfile.layers.sand.normalStrength > 0
1884
+ && Boolean(textures.sandNormal);
1885
+ if (hasTopLayer) {
1886
+ const topNormal = hasSandNormalResponse
1887
+ ? toonLabSandNormal(
1888
+ textures.sandNormal,
1889
+ resolvedProfile.layers.sand,
1890
+ resolvedProfile.normals.normalGreenSign,
1891
+ resolvedProfile.coordinates,
1892
+ )
1893
+ : stylizedNormal;
1894
+ combinedNormal = normalize(mix(combinedNormal, topNormal, topMask));
1895
+ }
1896
+
1897
+ const useGroundTopSurface = (
1898
+ resolvedProfile.layers.grass.enabled
1899
+ && resolvedProfile.layers.grass.useGroundShader
1900
+ ) || (
1901
+ resolvedProfile.layers.sand.enabled
1902
+ && resolvedProfile.layers.sand.useGroundShader
1903
+ );
1904
+ let metalnessNode = clamp(float(resolvedProfile.base.metallic), 0, 1);
1905
+ if (
1906
+ resolvedAssetIntegration.sourceAlbedoStrength > 0
1907
+ && textures.sourceMetalness?.isTexture
1908
+ ) {
1909
+ // glTF packs metalness in B and roughness in G.
1910
+ const sourceMetalness = clamp(
1911
+ texture(textures.sourceMetalness).sample(uv()).b
1912
+ .mul(resolvedAssetIntegration.sourceMetalnessFactor),
1913
+ 0,
1914
+ 1,
1915
+ );
1916
+ metalnessNode = mix(
1917
+ metalnessNode,
1918
+ sourceMetalness,
1919
+ resolvedAssetIntegration.sourceAlbedoStrength,
1920
+ );
1921
+ }
1922
+ let roughnessNode = mix(
1923
+ clamp(finalSmoothness.oneMinus(), 0, 1),
1924
+ resolvedProfile.shoreline.wetRoughness,
1925
+ wetBandMask,
1926
+ );
1927
+ // Moss is matte and stone is not. Without this the moss patch carries the
1928
+ // stone's specular response and lights like wet rock, which is most of why
1929
+ // it reads as a stain rather than a plant.
1930
+ if (mossMaskNode && resolvedProfile.moss.roughness >= 0) {
1931
+ roughnessNode = mix(
1932
+ roughnessNode,
1933
+ float(Math.min(1, Math.max(0, resolvedProfile.moss.roughness))),
1934
+ mossMaskNode,
1935
+ );
1936
+ }
1937
+ let specularIntensityNode = float(resolvedAssetIntegration.primarySpecularStrength);
1938
+ if (
1939
+ resolvedAssetIntegration.sourceAlbedoStrength > 0
1940
+ && textures.sourceSpecular?.isTexture
1941
+ ) {
1942
+ // KHR_materials_specular stores dielectric intensity in alpha.
1943
+ const sourceSpecular = clamp(
1944
+ texture(textures.sourceSpecular).sample(uv()).a
1945
+ .mul(resolvedAssetIntegration.sourceSpecularFactor),
1946
+ 0,
1947
+ 1,
1948
+ );
1949
+ specularIntensityNode = mix(
1950
+ specularIntensityNode,
1951
+ sourceSpecular,
1952
+ resolvedAssetIntegration.sourceAlbedoStrength,
1953
+ );
1954
+ }
1955
+ // Each replaceable top layer owns its complete surface response. Applying
1956
+ // these in the same grass -> snow -> sand order as color guarantees that a
1957
+ // sand selection cannot retain grass color, roughness, metalness, or normal.
1958
+ for (const [layer, roughnessMap] of [
1959
+ [resolvedProfile.layers.grass, textures.grassRoughness],
1960
+ [resolvedProfile.layers.snow, null],
1961
+ [resolvedProfile.layers.sand, null],
1962
+ ]) {
1963
+ if (!layer.enabled) continue;
1964
+ let layerRoughness = layer.roughness >= 0
1965
+ ? float(Math.min(1, Math.max(0, layer.roughness)))
1966
+ : roughnessNode;
1967
+ if (roughnessMap?.isTexture) {
1968
+ layerRoughness = clamp(
1969
+ toonLabTriplanarColor(
1970
+ roughnessMap,
1971
+ layer.scale,
1972
+ 1,
1973
+ resolvedProfile.coordinates,
1974
+ ).r,
1975
+ 0,
1976
+ 1,
1977
+ );
1978
+ }
1979
+ roughnessNode = mix(roughnessNode, layerRoughness, topMask);
1980
+ if (layer.metalness >= 0) {
1981
+ metalnessNode = mix(
1982
+ metalnessNode,
1983
+ float(Math.min(1, Math.max(0, layer.metalness))),
1984
+ topMask,
1985
+ );
1986
+ }
1987
+ // Source sublayers expose no separate specular map; replacing the layer
1988
+ // therefore resets dielectric intensity instead of leaking stone response.
1989
+ specularIntensityNode = mix(specularIntensityNode, float(1), topMask);
1990
+ }
1991
+ if (useGroundTopSurface) {
1992
+ const groundSurface = sampleGroundSurface(positionWorld);
1993
+ const groundSurfaceMask = topMask.mul(groundSurface.a);
1994
+ roughnessNode = mix(roughnessNode, groundSurface.r, groundSurfaceMask);
1995
+ specularIntensityNode = mix(
1996
+ specularIntensityNode,
1997
+ groundSurface.g,
1998
+ groundSurfaceMask,
1999
+ );
2000
+ metalnessNode = mix(metalnessNode, groundSurface.b, groundSurfaceMask);
2001
+ }
2002
+
2003
+ const material = new MeshPhysicalNodeMaterial();
2004
+ material.name = name ?? `ToonLab_${resolvedProfile.sourceName}`;
2005
+ material.colorNode = layerState.color;
2006
+ // A flat tangent-space normal is mathematically the geometry normal, but
2007
+ // forcing it through TBN still depends on valid mesh tangents. Some authored
2008
+ // cliff side UV islands are degenerate and therefore carry zero tangents;
2009
+ // their invalid TBN turns otherwise healthy surfaces literal black. Only
2010
+ // install a tangent-space normal node when a connected texture contributes
2011
+ // a real normal response.
2012
+ const hasNormalResponse = Boolean(textures.rockNormal)
2013
+ || (resolvedAssetIntegration.sourceAlbedoStrength > 0 && Boolean(textures.sourceNormal))
2014
+ || (resolvedProfile.normals.useSmoothed && Boolean(textures.stylizedNormal))
2015
+ || hasSandNormalResponse;
2016
+ if (hasNormalResponse) material.normalNode = tangentNormalToView(combinedNormal);
2017
+ // The moss cushion's relief, applied in WORLD space after the tangent chain
2018
+ // rather than inside it. The cushion field is world-space fBm and the mask is
2019
+ // built from world-space terms, so expressing the tilt in tangent space would
2020
+ // mean routing a world gradient through a TBN that some authored rock UV
2021
+ // islands cannot supply — the same degenerate-tangent hazard the guard above
2022
+ // exists for. Perturbing the geometric normal instead needs no tangents at
2023
+ // all, which also lets the cushion be the sole normal response on an asset
2024
+ // that binds no normal map.
2025
+ if (mossMaskNode && mossCushionNode && resolvedProfile.moss.cushion > 0) {
2026
+ const surface = normalWorldGeometry;
2027
+ // Keep only the component of the gradient lying in the surface's tangent
2028
+ // plane; the part along the normal would scale the normal rather than tilt
2029
+ // it, which is not a slope.
2030
+ const tangential = mossCushionNode.sub(
2031
+ surface.mul(dot(mossCushionNode, surface)),
2032
+ );
2033
+ // Downhill on the height field means the surface tips that way, hence the
2034
+ // subtraction. Scaled by the mask so bare stone is untouched and the tilt
2035
+ // fades in exactly where the cushion swells.
2036
+ const cushionWorld = normalize(
2037
+ surface.sub(tangential.mul(
2038
+ mossMaskNode.mul(resolvedProfile.moss.cushion * 1.6),
2039
+ )),
2040
+ );
2041
+ // Two arguments, not one: the second is the matrix to transform BY. The
2042
+ // cushion normal is world-space, so that is the camera view matrix.
2043
+ const cushionView = transformNormalByViewMatrix(cushionWorld, cameraViewMatrix);
2044
+ material.normalNode = hasNormalResponse
2045
+ ? normalize(mix(material.normalNode, cushionView, mossMaskNode))
2046
+ : cushionView;
2047
+ }
2048
+ material.metalnessNode = metalnessNode;
2049
+ // TOONLAB exposes smoothness while Three exposes roughness.
2050
+ material.roughnessNode = roughnessNode;
2051
+ // TOONLAB metallic workflow's dielectric reflectance is 0.04, matching IOR 1.5.
2052
+ material.iorNode = float(1.5);
2053
+ material.specularIntensityNode = specularIntensityNode;
2054
+ const sourceEmission = textures.sourceEmissive?.isTexture
2055
+ ? texture(textures.sourceEmissive).sample(uv()).rgb.mul(
2056
+ vec3(...resolvedAssetIntegration.sourceEmissive),
2057
+ ).mul(resolvedAssetIntegration.sourceEmissiveIntensity)
2058
+ : vec3(...resolvedAssetIntegration.sourceEmissive)
2059
+ .mul(resolvedAssetIntegration.sourceEmissiveIntensity);
2060
+ material.emissiveNode = layerState.emission.add(
2061
+ sourceEmission.mul(resolvedAssetIntegration.sourceAlbedoStrength),
2062
+ );
2063
+ const vertexAoNode = resolvedAssetIntegration.vertexAoStrength > 0
2064
+ ? clamp(
2065
+ mix(
2066
+ float(1),
2067
+ attribute('envVertexAo', 'float'),
2068
+ resolvedAssetIntegration.vertexAoStrength,
2069
+ ),
2070
+ 0,
2071
+ 1,
2072
+ )
2073
+ : float(1);
2074
+ const primaryAoNode = textures.rockAo?.isTexture
2075
+ ? clamp(toonLabRockProjection(textures.rockAo, resolvedProfile).r, 0, 1)
2076
+ : float(1);
2077
+ const authoredAoNode = vertexAoNode.mul(primaryAoNode);
2078
+ material.aoNode = (
2079
+ resolvedAssetIntegration.sourceAoStrength > 0
2080
+ && textures.sourceAo?.isTexture
2081
+ )
2082
+ ? authoredAoNode.mul(mix(
2083
+ float(1),
2084
+ texture(textures.sourceAo).sample(uv()).r,
2085
+ resolvedAssetIntegration.sourceAoStrength,
2086
+ ))
2087
+ : authoredAoNode;
2088
+ const usesSourceAlpha = resolvedAssetIntegration.sourceAlphaTest > 0
2089
+ || resolvedAssetIntegration.sourceTransparent
2090
+ || resolvedAssetIntegration.sourceOpacity < 1;
2091
+ if (usesSourceAlpha) {
2092
+ material.opacityNode = textures.sourceRock?.isTexture
2093
+ ? texture(textures.sourceRock).sample(uv()).a.mul(resolvedAssetIntegration.sourceOpacity)
2094
+ : float(resolvedAssetIntegration.sourceOpacity);
2095
+ material.alphaTestNode = resolvedAssetIntegration.sourceAlphaTest > 0
2096
+ ? float(resolvedAssetIntegration.sourceAlphaTest)
2097
+ : null;
2098
+ }
2099
+ material.transparent = usesSourceAlpha && resolvedAssetIntegration.sourceTransparent;
2100
+ material.opacity = usesSourceAlpha ? resolvedAssetIntegration.sourceOpacity : 1;
2101
+ material.alphaTest = 0;
2102
+ material.depthWrite = usesSourceAlpha ? resolvedAssetIntegration.sourceDepthWrite : true;
2103
+ if (resolvedAssetIntegration.sourceSide !== null) material.side = resolvedAssetIntegration.sourceSide;
2104
+ material.userData.toonLabRockProfile = resolvedProfile;
2105
+ material.userData.toonLabRockSceneState = {
2106
+ setSkyColor(value) {
2107
+ const channels = value?.isColor
2108
+ ? [value.r, value.g, value.b]
2109
+ : Array.isArray(value) || ArrayBuffer.isView(value)
2110
+ ? Array.from(value).slice(0, 3).map(Number)
2111
+ : null;
2112
+ if (channels?.length === 3 && channels.every(Number.isFinite)) {
2113
+ sceneSkyColor.value.setRGB(...channels);
2114
+ }
2115
+ return sceneSkyColor.value.toArray();
2116
+ },
2117
+ setWaterLevel(value) {
2118
+ const next = Number(value);
2119
+ if (Number.isFinite(next)) sceneWaterLevel.value = next;
2120
+ return sceneWaterLevel.value;
2121
+ },
2122
+ skyColor: sceneSkyColor,
2123
+ waterLevel: sceneWaterLevel,
2124
+ };
2125
+ material.userData.toonLabRockAssetIntegration = resolvedAssetIntegration;
2126
+ material.userData.toonLabSourceShader = {
2127
+ assetPath: 'Environment/Rocks/Shaders/S_Rock.toonlabgraph',
2128
+ guid: TOONLAB_ROCK_SHADER_GUID,
2129
+ };
2130
+ material.userData.toonLabVertexMotion = {
2131
+ ...TOONLAB_ROCK_FAMILY_VERTEX_MOTION_CONTRACT[TOONLAB_ROCK_SHADER_GUID],
2132
+ };
2133
+ material.userData.toonLabNormalImport = {
2134
+ decode: 'UnpackNormalMapRGorAG-compatible RG + reconstructed positive Z',
2135
+ perTextureFlipGreenChannel: true,
2136
+ };
2137
+ const rockTextureFlipY = textures.rockNormal?.isTexture
2138
+ ? Boolean(textures.rockNormal.flipY)
2139
+ : null;
2140
+ material.userData.toonLabNormalIntegration =
2141
+ createToonLabNormalIntegrationMetadata({
2142
+ coordinateZSign: resolvedProfile.coordinates.zSign,
2143
+ decode: 'RG + per-texture importer green transform + reconstructed positive Z; ToonLab graph Normal Strength',
2144
+ family: 'toonlab-s-rock',
2145
+ flipGreenChannel: 'per-texture texture import state',
2146
+ textureFlipY: rockTextureFlipY,
2147
+ });
2148
+ // Live Preview diagnostics must be sourced by the material family itself.
2149
+ // The raw branch is the untouched source albedo projection: no tint,
2150
+ // distance color, moss/top layers, normal response, emission, or lighting.
2151
+ // Keeping it here prevents pages from substituting a flat fallback color for
2152
+ // any S_Rock material loaded through the ToonLab source-material path.
2153
+ registerSurfaceMaterialMode(material, SURFACE_MATERIAL_MODE.neutralLit, {
2154
+ colorNode: rockProjection,
2155
+ family: 'rock',
2156
+ keepsLighting: true,
2157
+ keepsTextures: true,
2158
+ vertexDeformation: false,
2159
+ });
2160
+ registerSurfaceMaterialMode(material, SURFACE_MATERIAL_MODE.rawTexture, {
2161
+ colorNode: rockProjection,
2162
+ family: 'rock',
2163
+ keepsLighting: false,
2164
+ keepsTextures: true,
2165
+ vertexDeformation: false,
2166
+ });
2167
+ const warmSkyBlend = smoothstep(
2168
+ float(0),
2169
+ float(0.25),
2170
+ sceneSkyColor.r.sub(sceneSkyColor.b),
2171
+ );
2172
+ const preserveProbeChroma = max(warmSkyBlend, lowLightProbeBlend);
2173
+ installToonLabSurfaceLighting(material, {
2174
+ // Keep geological Base Color invariant. The captured intensity-8 sun still
2175
+ // needs the historical rock calibration, but applying it to albedo also
2176
+ // crushed the sky probe and every shaded face. Direct light owns that
2177
+ // calibration now; indirect light and the readability floor see the real
2178
+ // material color.
2179
+ directStrength: resolvedProfile.lighting.exposure,
2180
+ indirectStrength: resolvedProfile.lighting.skyFillStrength,
2181
+ indirectTint: resolvedProfile.lighting.skyFillTint,
2182
+ // The scene probe supplies irradiance magnitude, while this live uniform
2183
+ // supplies its visible time-of-day colour. This preserves geological Base
2184
+ // Color and makes the same shaded face blue at noon, warm at sunset, and
2185
+ // deep blue at night without rebuilding or retexturing the material.
2186
+ // A bright neutral daytime probe receives visible-sky chroma. Low-light
2187
+ // and warm-hour probes already contain their authored colour, so preserve
2188
+ // them instead of multiplying that colour a second time. Double-tinting
2189
+ // the dark-blue night probe crushed red sandstone almost to black.
2190
+ indirectTintNode: mix(skyChroma, vec3(1), preserveProbeChroma)
2191
+ .mul(vec3(...resolvedProfile.lighting.skyFillTint)),
2192
+ indirectTintMode: 'multiply',
2193
+ shadowFill: resolvedProfile.lighting.shadowFill,
2194
+ shadowFillTint: resolvedProfile.lighting.shadowFillTint,
2195
+ // Native directional shadows already cover these meshes. Re-sampling the
2196
+ // package depth atlas here double-shadowed the full rock at sunset; cloud
2197
+ // transmittance remains shared inside the lighting bridge.
2198
+ useSharedSunShadow: false,
2199
+ workflow: 'metallic',
2200
+ });
2201
+ return material;
2202
+ }
2203
+
2204
+ function validateMountainTextures(textures) {
2205
+ for (const key of ['noise', 'rock', 'grass', 'snow']) {
2206
+ assertTexture(textures[key], key, 'for the connected S_Mountain graph input');
2207
+ }
2208
+ }
2209
+
2210
+ /**
2211
+ * Exact connected outputs of ToonLab's separate S_Mountain ToonLab graph.
2212
+ * Unlike S_Rock, this graph has no normal texture or emission branch: it
2213
+ * projects rock/grass/snow in world XZ, then derives grass and snow masks from
2214
+ * geometry normal, UV0.y, and one shared noise sample.
2215
+ */
2216
+ export function createToonLabMountainMaterial({
2217
+ profile = {},
2218
+ textures = {},
2219
+ name = null,
2220
+ } = {}) {
2221
+ const resolvedProfile = normalizeToonLabMountainProfile(profile);
2222
+ validateMountainTextures(textures);
2223
+
2224
+ const sourcePosition = toonLabSourcePosition(resolvedProfile.coordinates);
2225
+ const planar = vec2(sourcePosition.x, sourcePosition.z);
2226
+ const baseUv = planar.div(safeScale(resolvedProfile.textureScale));
2227
+ const noiseUv = planar.div(safeScale(resolvedProfile.noiseSize));
2228
+ const rock = texture(textures.rock).sample(baseUv).rgb;
2229
+ const grass = texture(textures.grass).sample(baseUv.mul(2)).rgb;
2230
+ const snow = texture(textures.snow).sample(baseUv).rgb;
2231
+ const centeredNoise = texture(textures.noise).sample(noiseUv).r.sub(0.5);
2232
+
2233
+ const sourceUvY = resolvedProfile.coordinates.flipProceduralUvY
2234
+ ? uv().y.oneMinus()
2235
+ : uv().y;
2236
+ const authoredUvY = clamp(sourceUvY, 0, 1);
2237
+ const slopeStart = 1 - resolvedProfile.grassSlopeMax;
2238
+ // S_Mountain uses an unclamped Remap here; the product is saturated only
2239
+ // after the procedural UV-height fade has been applied.
2240
+ const grassSlope = normalWorldGeometry.y
2241
+ .add(centeredNoise.mul(resolvedProfile.grassNoiseStrength))
2242
+ .sub(slopeStart)
2243
+ .div(0.04);
2244
+ // The first two-key Gradient is black->white. Its subsequent remap from
2245
+ // [fade-1, fade] to [1, 0] reduces exactly to fade - UV.y.
2246
+ const grassHeight = clamp(
2247
+ float(resolvedProfile.grassTopFadeout).sub(authoredUvY),
2248
+ 0,
2249
+ 1,
2250
+ );
2251
+ const grassMask = clamp(grassSlope.mul(grassHeight), 0, 1);
2252
+
2253
+ // The snow Gradient is white->black; noise is added before the reversed
2254
+ // 0.05-wide threshold remap.
2255
+ const snowHeight = authoredUvY.oneMinus().add(
2256
+ centeredNoise.mul(resolvedProfile.snowNoiseStrength),
2257
+ );
2258
+ const snowMask = clamp(
2259
+ float(1).sub(
2260
+ snowHeight.sub(resolvedProfile.snowTopAmount).div(0.05),
2261
+ ),
2262
+ 0,
2263
+ 1,
2264
+ );
2265
+
2266
+ const material = new MeshPhysicalNodeMaterial();
2267
+ material.name = name ?? `ToonLab_${resolvedProfile.sourceName}`;
2268
+ material.colorNode = mix(mix(rock, grass, grassMask), snow, snowMask);
2269
+ material.metalnessNode = float(0);
2270
+ material.roughnessNode = clamp(float(1 - resolvedProfile.smoothness), 0, 1);
2271
+ material.iorNode = float(1.5);
2272
+ material.specularIntensityNode = float(1);
2273
+ material.emissiveNode = vec3(0);
2274
+ material.aoNode = float(1);
2275
+ material.transparent = false;
2276
+ material.opacity = 1;
2277
+ material.alphaTest = 0;
2278
+ material.depthWrite = true;
2279
+ material.userData.toonLabMountainProfile = resolvedProfile;
2280
+ material.userData.toonLabSourceShader = {
2281
+ assetPath: 'Environment/Rocks/Shaders/S_Mountain.toonlabgraph',
2282
+ guid: TOONLAB_MOUNTAIN_SHADER_GUID,
2283
+ };
2284
+ material.userData.toonLabVertexMotion = {
2285
+ ...TOONLAB_ROCK_FAMILY_VERTEX_MOTION_CONTRACT[TOONLAB_MOUNTAIN_SHADER_GUID],
2286
+ };
2287
+ const mountainTexture = textures.rock ?? textures.noise;
2288
+ material.userData.toonLabNormalIntegration =
2289
+ createToonLabNormalIntegrationMetadata({
2290
+ coordinateZSign: resolvedProfile.coordinates.zSign,
2291
+ decode: 'geometry-only; S_Mountain has no connected normal-map input',
2292
+ family: 'toonlab-s-mountain',
2293
+ textureFlipY: mountainTexture?.isTexture
2294
+ ? Boolean(mountainTexture.flipY)
2295
+ : null,
2296
+ });
2297
+ installToonLabSurfaceLighting(material, { workflow: 'metallic' });
2298
+ return material;
2299
+ }
2300
+
2301
+ function joinUrl(baseUrl, relativePath) {
2302
+ if (!relativePath) return null;
2303
+ if (/^(?:data:|blob:|https?:\/\/|\/\/)/i.test(relativePath)) return relativePath;
2304
+ return `${String(baseUrl).replace(/\/$/, '')}/${String(relativePath).replace(/^\//, '')}`;
2305
+ }
2306
+
2307
+ function manifestDirectory(url) {
2308
+ const value = String(url);
2309
+ const slash = value.lastIndexOf('/');
2310
+ return slash >= 0 ? value.slice(0, slash) : '.';
2311
+ }
2312
+
2313
+ async function resolveManifest(manifest, baseUrl) {
2314
+ if (manifest && typeof manifest === 'object') {
2315
+ return { manifest, baseUrl: baseUrl ?? DEFAULT_TOONLAB_ROCK_LIBRARY_BASE_URL };
2316
+ }
2317
+ if (!manifest && (typeof baseUrl !== 'string' || !baseUrl.trim())) {
2318
+ throw new Error('A rock material manifest or configured baseUrl is required.');
2319
+ }
2320
+ const manifestUrl = typeof manifest === 'string'
2321
+ ? joinUrl(baseUrl ?? '', manifest)
2322
+ : joinUrl(
2323
+ baseUrl ?? DEFAULT_TOONLAB_ROCK_LIBRARY_BASE_URL,
2324
+ 'rock-material-library.json',
2325
+ );
2326
+ const response = await fetch(manifestUrl, { cache: 'no-cache' });
2327
+ if (!response.ok) {
2328
+ throw new Error(`ToonLab rock material manifest is unavailable (${response.status}).`);
2329
+ }
2330
+ const responseText = await response.text();
2331
+ let resolvedManifest;
2332
+ try {
2333
+ resolvedManifest = JSON.parse(responseText);
2334
+ } catch (error) {
2335
+ const contentType = response.headers.get('content-type') ?? 'unknown';
2336
+ throw new Error(
2337
+ `ToonLab rock material manifest returned invalid JSON `
2338
+ + `(${response.status}; ${contentType}).`,
2339
+ { cause: error },
2340
+ );
2341
+ }
2342
+ return {
2343
+ manifest: resolvedManifest,
2344
+ baseUrl: baseUrl ?? manifestDirectory(manifestUrl),
2345
+ };
2346
+ }
2347
+
2348
+ function validateManifest(manifest) {
2349
+ if (normalizeToonLabRockMaterialLibrarySchema(manifest?.schema)
2350
+ !== TOONLAB_ROCK_MANIFEST_SCHEMA
2351
+ || Number(manifest?.schemaVersion) !== TOONLAB_ROCK_MANIFEST_VERSION) {
2352
+ throw new Error('Invalid ToonLab rock material library manifest.');
2353
+ }
2354
+ if (!Array.isArray(manifest.materials) || !manifest.texturesByGuid) {
2355
+ throw new Error('ToonLab rock manifest is missing materials or texturesByGuid.');
2356
+ }
2357
+ }
2358
+
2359
+ function findMaterialEntry(manifest, selector) {
2360
+ if (selector?.resolved) return selector;
2361
+ const value = String(selector ?? '');
2362
+ const entry = manifest.materials.find((candidate) => (
2363
+ candidate.assetPath === value || candidate.guid === value || candidate.name === value
2364
+ ));
2365
+ if (!entry) throw new Error(`ToonLab rock material was not found: ${value || '(empty selector)'}`);
2366
+ return entry;
2367
+ }
2368
+
2369
+ function wrappingFromToonLab(value) {
2370
+ if (Number(value) === 1) return ClampToEdgeWrapping;
2371
+ if (Number(value) === 2 || Number(value) === 3) return MirroredRepeatWrapping;
2372
+ return RepeatWrapping;
2373
+ }
2374
+
2375
+ function applyTextureImportSettings(result, record, { textureFlipY = false } = {}) {
2376
+ const settings = record?.importSettings ?? {};
2377
+ result.name = record?.assetPath?.split('/').at(-1) ?? record?.guid ?? result.name;
2378
+ result.colorSpace = settings.sRGBTexture || settings.colorSpace === 'srgb'
2379
+ ? SRGBColorSpace
2380
+ : NoColorSpace;
2381
+ result.flipY = Boolean(textureFlipY);
2382
+ result.wrapS = wrappingFromToonLab(settings.wrapU);
2383
+ result.wrapT = wrappingFromToonLab(settings.wrapV);
2384
+ result.generateMipmaps = settings.mipmapEnabled !== false;
2385
+ const filterMode = Number(settings.filterMode ?? 1);
2386
+ if (filterMode === 0) {
2387
+ result.magFilter = NearestFilter;
2388
+ result.minFilter = result.generateMipmaps ? NearestMipmapNearestFilter : NearestFilter;
2389
+ } else if (filterMode === 2) {
2390
+ result.magFilter = LinearFilter;
2391
+ result.minFilter = result.generateMipmaps ? LinearMipmapLinearFilter : LinearFilter;
2392
+ } else {
2393
+ result.magFilter = LinearFilter;
2394
+ result.minFilter = result.generateMipmaps ? LinearMipmapNearestFilter : LinearFilter;
2395
+ }
2396
+ result.anisotropy = Math.max(1, finite(settings.aniso, 1));
2397
+ result.userData.toonLabTextureGuid = record?.guid ?? null;
2398
+ result.userData.toonLabImportSettings = {
2399
+ ...settings,
2400
+ textureFlipY: Boolean(textureFlipY),
2401
+ };
2402
+ result.needsUpdate = true;
2403
+ return result;
2404
+ }
2405
+
2406
+ async function loadManifestTexture({
2407
+ key,
2408
+ slot,
2409
+ manifest,
2410
+ material,
2411
+ baseUrl,
2412
+ resolveTexture,
2413
+ textureFlipY,
2414
+ textureLoader,
2415
+ }) {
2416
+ if (!slot || Number(slot.fileID) === 0 || !slot.guid) return null;
2417
+ const record = manifest.texturesByGuid[slot.guid];
2418
+ if (!record?.outputFile) {
2419
+ throw new Error(`ToonLab texture ${slot.guid} for ${material.name}/${key} is unresolved.`);
2420
+ }
2421
+ if (resolveTexture) {
2422
+ const resolved = await resolveTexture({
2423
+ key,
2424
+ slot,
2425
+ record,
2426
+ manifest,
2427
+ material,
2428
+ baseUrl,
2429
+ textureFlipY,
2430
+ });
2431
+ if (resolved != null && !resolved.isTexture) {
2432
+ throw new TypeError(`resolveTexture returned a non-Texture for ${material.name}/${key}.`);
2433
+ }
2434
+ return resolved;
2435
+ }
2436
+ if (typeof baseUrl !== 'string' || !baseUrl.trim()) {
2437
+ throw new Error(
2438
+ `A configured baseUrl or resolveTexture callback is required for ${material.name}/${key}.`,
2439
+ );
2440
+ }
2441
+
2442
+ const url = joinUrl(baseUrl, record.outputFile);
2443
+ const cacheKey = `${url}|flipY=${Boolean(textureFlipY)}`;
2444
+ if (!texturePromiseCache.has(cacheKey)) {
2445
+ texturePromiseCache.set(cacheKey, textureLoader.loadAsync(url)
2446
+ .then((result) => applyTextureImportSettings(result, record, { textureFlipY }))
2447
+ .catch((error) => {
2448
+ texturePromiseCache.delete(cacheKey);
2449
+ throw error;
2450
+ }));
2451
+ }
2452
+ return texturePromiseCache.get(cacheKey);
2453
+ }
2454
+
2455
+ /**
2456
+ * High-level loader for the generated ToonLab library manifest.
2457
+ *
2458
+ * `material` may be an assetPath, GUID, material name, or a manifest entry.
2459
+ * `resolveTexture({ key, slot, record, manifest, material, baseUrl })` can be
2460
+ * supplied by hosts with their own cache/asset system. Without it, outputFile
2461
+ * paths are loaded relative to baseUrl with texture import metadata applied.
2462
+ * `coordinates: { zSign: -1 }` reconstructs ToonLab projection space when the
2463
+ * paired scene conversion reflects ToonLab Z into Three Z. `distanceScale`
2464
+ * bridges source distance units without changing world-projected texture
2465
+ * scales. ToonLab material values and glTF/Three scene coordinates are both
2466
+ * metres after export, so source parity normally uses 1.
2467
+ * `textureFlipY` is false for the supplied ToonLabShowcase ToonLab glTF bridge and true
2468
+ * for ToonLabSceneExport.cs geometry, whose UV.y values are copied unchanged.
2469
+ */
2470
+ export async function loadToonRockMaterialInputs({
2471
+ manifest = null,
2472
+ material,
2473
+ baseUrl = null,
2474
+ resolveTexture = null,
2475
+ textureLoader = new TextureLoader(),
2476
+ coordinates = null,
2477
+ normalGreenSign = null,
2478
+ textureFlipY = false,
2479
+ includeInactiveTextures = false,
2480
+ } = {}) {
2481
+ const resolvedLibrary = await resolveManifest(manifest, baseUrl);
2482
+ validateManifest(resolvedLibrary.manifest);
2483
+ const entry = findMaterialEntry(resolvedLibrary.manifest, material);
2484
+ let profile = toonLabRockProfileFromResolvedMaterial(entry);
2485
+ if (coordinates) profile = normalizeToonLabRockProfile({ ...profile, coordinates });
2486
+ if (normalGreenSign != null) {
2487
+ profile = normalizeToonLabRockProfile({
2488
+ ...profile,
2489
+ normals: {
2490
+ ...profile.normals,
2491
+ normalGreenSign,
2492
+ },
2493
+ });
2494
+ }
2495
+ const textures = {};
2496
+ const textureKeys = textureKeysForProfile(profile, {
2497
+ includeInactive: includeInactiveTextures,
2498
+ });
2499
+ await Promise.all([...textureKeys].map(async (key) => {
2500
+ const slot = profile.textureRefs[key];
2501
+ textures[key] = await loadManifestTexture({
2502
+ key,
2503
+ slot,
2504
+ manifest: resolvedLibrary.manifest,
2505
+ material: entry,
2506
+ baseUrl: resolvedLibrary.baseUrl,
2507
+ resolveTexture,
2508
+ textureFlipY,
2509
+ textureLoader,
2510
+ });
2511
+ }));
2512
+ return {
2513
+ entry,
2514
+ manifest: resolvedLibrary.manifest,
2515
+ profile,
2516
+ textures,
2517
+ };
2518
+ }
2519
+
2520
+ export async function loadToonRockMaterial({
2521
+ manifest = null,
2522
+ material,
2523
+ baseUrl = null,
2524
+ resolveTexture = null,
2525
+ textureLoader = new TextureLoader(),
2526
+ name = null,
2527
+ coordinates = null,
2528
+ normalGreenSign = null,
2529
+ textureFlipY = false,
2530
+ includeInactiveTextures = false,
2531
+ } = {}) {
2532
+ const {
2533
+ profile,
2534
+ textures,
2535
+ } = await loadToonRockMaterialInputs({
2536
+ manifest,
2537
+ material,
2538
+ baseUrl,
2539
+ resolveTexture,
2540
+ textureLoader,
2541
+ coordinates,
2542
+ normalGreenSign,
2543
+ textureFlipY,
2544
+ includeInactiveTextures,
2545
+ });
2546
+ const result = createToonRockMaterial({ profile, textures, name });
2547
+ result.userData.toonLabNormalIntegration.textureFlipY = Boolean(textureFlipY);
2548
+ return result;
2549
+ }
2550
+
2551
+ /** High-level loader for the S_Mountain entries in the shared ToonLab manifest. */
2552
+ export async function loadToonLabMountainMaterial({
2553
+ manifest = null,
2554
+ material,
2555
+ baseUrl = null,
2556
+ resolveTexture = null,
2557
+ textureLoader = new TextureLoader(),
2558
+ name = null,
2559
+ coordinates = null,
2560
+ textureFlipY = false,
2561
+ } = {}) {
2562
+ const resolvedLibrary = await resolveManifest(manifest, baseUrl);
2563
+ validateManifest(resolvedLibrary.manifest);
2564
+ const entry = findMaterialEntry(resolvedLibrary.manifest, material);
2565
+ let profile = toonLabMountainProfileFromResolvedMaterial(entry);
2566
+ if (coordinates) {
2567
+ profile = normalizeToonLabMountainProfile({ ...profile, coordinates });
2568
+ }
2569
+ const textures = {};
2570
+ await Promise.all(['noise', 'rock', 'grass', 'snow'].map(async (key) => {
2571
+ const slot = profile.textureRefs[key];
2572
+ textures[key] = await loadManifestTexture({
2573
+ key,
2574
+ slot,
2575
+ manifest: resolvedLibrary.manifest,
2576
+ material: entry,
2577
+ baseUrl: resolvedLibrary.baseUrl,
2578
+ resolveTexture,
2579
+ textureFlipY,
2580
+ textureLoader,
2581
+ });
2582
+ }));
2583
+ const result = createToonLabMountainMaterial({ profile, textures, name });
2584
+ result.userData.toonLabNormalIntegration.textureFlipY = Boolean(textureFlipY);
2585
+ return result;
2586
+ }