@call-me-sensei/toonlab 0.3.0 → 0.4.19

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (736) hide show
  1. package/README.md +549 -184
  2. package/agents/README.md +59 -0
  3. package/agents/references/anime-art-direction.md +24 -0
  4. package/agents/references/asset-sourcing-policy.md +23 -0
  5. package/agents/references/custom-gap-report.md +16 -0
  6. package/agents/references/geology-playbook.md +118 -0
  7. package/agents/references/mcp-asset-discovery.md +104 -0
  8. package/agents/references/runtime-entry-points.md +174 -0
  9. package/agents/references/style-bundles.md +71 -0
  10. package/agents/skills/claude/asset-sourcing/SKILL.md +275 -0
  11. package/agents/skills/claude/environment/SKILL.md +59 -0
  12. package/agents/skills/claude/game-dev/SKILL.md +100 -0
  13. package/agents/skills/claude/karst-cliff-construction/SKILL.md +258 -0
  14. package/agents/skills/claude/outdoor-world/SKILL.md +492 -0
  15. package/agents/skills/claude/outdoor-world/references/coastal-landform-formation.md +100 -0
  16. package/agents/skills/claude/post-processing/SKILL.md +44 -0
  17. package/agents/skills/claude/rock-ground-shaders/SKILL.md +118 -0
  18. package/agents/skills/claude/rockgen/SKILL.md +30 -0
  19. package/agents/skills/claude/scene-style-application/SKILL.md +74 -0
  20. package/agents/skills/claude/style-presets/SKILL.md +101 -0
  21. package/agents/skills/claude/toon-shading/SKILL.md +44 -0
  22. package/agents/skills/claude/vegetation-sky/SKILL.md +167 -0
  23. package/agents/skills/claude/visual-verification/SKILL.md +136 -0
  24. package/agents/skills/claude/water/SKILL.md +105 -0
  25. package/agents/skills/codex/asset-sourcing/SKILL.md +275 -0
  26. package/agents/skills/codex/environment/SKILL.md +59 -0
  27. package/agents/skills/codex/game-dev/SKILL.md +100 -0
  28. package/agents/skills/codex/karst-cliff-construction/SKILL.md +258 -0
  29. package/agents/skills/codex/outdoor-world/SKILL.md +492 -0
  30. package/agents/skills/codex/outdoor-world/references/coastal-landform-formation.md +100 -0
  31. package/agents/skills/codex/post-processing/SKILL.md +44 -0
  32. package/agents/skills/codex/rock-ground-shaders/SKILL.md +118 -0
  33. package/agents/skills/codex/rockgen/SKILL.md +30 -0
  34. package/agents/skills/codex/scene-style-application/SKILL.md +74 -0
  35. package/agents/skills/codex/style-presets/SKILL.md +101 -0
  36. package/agents/skills/codex/toon-shading/SKILL.md +44 -0
  37. package/agents/skills/codex/vegetation-sky/SKILL.md +167 -0
  38. package/agents/skills/codex/visual-verification/SKILL.md +136 -0
  39. package/agents/skills/codex/water/SKILL.md +105 -0
  40. package/cli/toonlab.mjs +52 -0
  41. package/compose.yaml +20 -0
  42. package/database/apply-sql.mjs +141 -0
  43. package/database/client.mjs +39 -0
  44. package/database/creation-tags.mjs +23 -0
  45. package/database/env.mjs +16 -0
  46. package/database/generation-service.mjs +314 -0
  47. package/database/migrations/0001_local_workspace.sql +120 -0
  48. package/database/migrations/0002_file_ownership.sql +11 -0
  49. package/database/migrations/0003_remove_autosaves_from_library.sql +7 -0
  50. package/database/migrations/0004_catalog_asset_packs.sql +39 -0
  51. package/database/migrations/0005_creation_tag_discovery.sql +1 -0
  52. package/database/migrations/0006_normalize_creation_tags.sql +28 -0
  53. package/database/providers.mjs +465 -0
  54. package/database/repository.mjs +625 -0
  55. package/database/seeds/catalog/0001_empty_official_catalog.sql +4 -0
  56. package/database/seeds/catalog/0002_2026-08.sql +19454 -0
  57. package/mcp/lab-management.mjs +629 -0
  58. package/mcp/public-catalog.mjs +168 -0
  59. package/mcp/server.mjs +1026 -63
  60. package/mcp/vite-plugin.mjs +443 -26
  61. package/mcp/workspace.mjs +26 -1
  62. package/package.json +312 -45
  63. package/scripts/generate-catalog-seed.mjs +297 -0
  64. package/scripts/setup-local.mjs +128 -0
  65. package/src/agents/index.js +7 -0
  66. package/src/agents/sceneStyleOperations.js +169 -0
  67. package/src/asset-policy/catalogLicenses.js +44 -0
  68. package/src/asset-policy/index.js +315 -0
  69. package/src/assetlib/assetRef.js +1 -1
  70. package/src/assetlib/galleryMaterialFamily.js +165 -0
  71. package/src/assetlib/index.js +6 -2
  72. package/src/assetlib/plateau.js +188 -0
  73. package/src/assetlib/plateauLandmarks.js +144 -0
  74. package/src/assetlib/plateauViewer.js +348 -0
  75. package/src/assetlib/sources.js +16 -2
  76. package/src/catalog/manifest.js +11 -1
  77. package/src/catalog/officialCatalog.js +4 -0
  78. package/src/catalog/officialCatalogAssetRuntime.js +313 -0
  79. package/src/catalog/officialCatalogLod.js +150 -0
  80. package/src/catalog/officialCatalogPlacement.js +228 -0
  81. package/src/catalog/officialCatalogProvider.js +334 -0
  82. package/src/character/animationRetarget.js +1082 -0
  83. package/src/character/characterRuntime.js +376 -0
  84. package/src/character/groundStabilizer.js +137 -0
  85. package/src/character/index.js +8 -0
  86. package/src/character/locomotionActions.js +74 -0
  87. package/src/character/locomotionStateMachine.js +241 -0
  88. package/src/character/mannequinAsset.js +15 -0
  89. package/src/character/mannequinAssetUrl.browser.js +4 -0
  90. package/src/character/mannequinAssetUrl.node.js +3 -0
  91. package/src/character/modelLoader.js +92 -12
  92. package/src/character/walkableCharacterRuntime.js +284 -0
  93. package/src/character/waterInteractionController.js +217 -0
  94. package/src/cloud/ambientSkyBaker.js +248 -0
  95. package/src/cloud/cloudLighting.js +1114 -0
  96. package/src/cloud/cloudParams.js +819 -0
  97. package/src/cloud/cloudReprojection.js +563 -0
  98. package/src/cloud/cloudStyle.js +780 -0
  99. package/src/cloud/cloudStyleSnapshots.js +387 -0
  100. package/src/cloud/cloudVolume.js +1903 -0
  101. package/src/cloud/heroCloudRecipe.js +404 -0
  102. package/src/cloud/index.js +42 -0
  103. package/src/cloud/noise/baseShapeVolume.js +331 -0
  104. package/src/cloud/noise/cirrusMap.js +131 -0
  105. package/src/cloud/noise/curlNoise.js +289 -0
  106. package/src/cloud/noise/erosionVolume.js +188 -0
  107. package/src/cloud/noise/noiseVolume.js +202 -0
  108. package/src/cloud/noise/periodicNoise3.js +295 -0
  109. package/src/cloud/noise/weatherMap.js +470 -0
  110. package/src/cloud/paramSchema.js +458 -0
  111. package/src/collisionMetadata.js +320 -0
  112. package/src/core/systemStylePolicy.js +32 -0
  113. package/src/environment/dayCurves.js +146 -0
  114. package/src/environment/environmentGroundFieldPass.js +354 -0
  115. package/src/environment/environmentMaterialAdapter.js +114 -6
  116. package/src/environment/environmentPresets.js +396 -90
  117. package/src/environment/environmentRigs.js +17 -2
  118. package/src/environment/environmentSettings.js +37 -1
  119. package/src/environment/environmentShaderMaterials.js +37 -6
  120. package/src/environment/environmentState.js +133 -0
  121. package/src/environment/environmentSunShadowPass.js +357 -6
  122. package/src/environment/environmentTextureResolver.js +7 -0
  123. package/src/environment/index.js +51 -0
  124. package/src/environment/manufacturedMaterialContract.js +837 -0
  125. package/src/environment/manufacturedReflectionProvider.js +114 -0
  126. package/src/environment/scanAssetStylize.js +4 -4
  127. package/src/environment/surfaceMaterialModes.js +71 -0
  128. package/src/environment/toonLabEnvironmentMaterials.js +353 -0
  129. package/src/environment/toonLabMaterialPassCoupling.js +347 -0
  130. package/src/environment/toonLabNormalIntegration.js +171 -0
  131. package/src/environment/toonLabRockMaterialResolver.js +592 -0
  132. package/src/environment/toonLabSourceDefaultLit.js +444 -0
  133. package/src/environment/toonLabSourceLibrary.js +762 -0
  134. package/src/environment/toonLabSourceMaterials.js +3718 -0
  135. package/src/environment/toonLabSourceSubsurfaceLighting.js +415 -0
  136. package/src/environment/toonLabSourceTemporal.js +717 -0
  137. package/src/environment/toonLabSurfaceLighting.js +364 -0
  138. package/src/environment/toonLabTextureReadiness.js +105 -0
  139. package/src/environment/toonLabTreeMaterials.js +450 -0
  140. package/src/environment/transparentMaterialProfile.js +87 -0
  141. package/src/environment/urbanPropMaterial.js +2874 -0
  142. package/src/ground-shader/groundPrintLayer.js +375 -0
  143. package/src/ground-shader/groundShaderMaterial.js +851 -0
  144. package/src/ground-shader/groundShaderSettings.js +468 -0
  145. package/src/ground-shader/index.js +3 -0
  146. package/src/index.js +52 -22
  147. package/src/lighting/callMeSenseiLightingContract.js +163 -0
  148. package/src/lighting/index.js +14 -7
  149. package/src/lighting/lightingCapabilities.js +2 -2
  150. package/src/lighting/lightingPresets.js +6 -3
  151. package/src/lighting/lightingStyle.js +41 -6
  152. package/src/lighting/lightingSystem.js +140 -1
  153. package/src/lighting/{unrealExport.js → toonLabExport.js} +40 -41
  154. package/src/post/postProcessing.js +71 -12
  155. package/src/react/index.js +66 -0
  156. package/src/renderer/index.js +9 -0
  157. package/src/renderer/rendererConfiguration.js +250 -0
  158. package/src/rock-shader/index.js +3 -0
  159. package/src/rock-shader/rockMaterial.js +1843 -0
  160. package/src/rock-shader/rockShaderRuntime.js +494 -0
  161. package/src/rock-shader/rockShaderSettings.js +869 -0
  162. package/src/rockgen/export/glbExport.js +104 -14
  163. package/src/rockgen/index.js +4 -3
  164. package/src/rockgen/lod/index.js +6 -0
  165. package/src/rockgen/lod/rockLodMetrics.js +168 -0
  166. package/src/rockgen/lod/rockLodPlanner.js +372 -0
  167. package/src/rockgen/lod/rockLodPolicy.js +235 -0
  168. package/src/rockgen/lod/rockLodRuntime.js +124 -0
  169. package/src/rockgen/lod/rockLodSimplifier.js +173 -0
  170. package/src/rockgen/lod/rockLodValidation.js +113 -0
  171. package/src/rockgen/mesh/meshAttributes.js +17 -0
  172. package/src/rockgen/mesh/meshDocument.js +6 -0
  173. package/src/rockgen/rockDocument.js +352 -9
  174. package/src/rockgen/rockgenPresets.js +114 -13
  175. package/src/rockgen/rockgenSettings.js +62 -11
  176. package/src/runtime/index.js +14 -0
  177. package/src/runtime/sceneCollisionRuntime.js +317 -0
  178. package/src/runtime/sceneSurfaceRuntime.js +451 -0
  179. package/src/runtime/sceneUpdateScheduler.js +203 -0
  180. package/src/shaders-tsl/anime.js +9 -2
  181. package/src/shaders-tsl/chunks/environment-ground-field.js +174 -0
  182. package/src/shaders-tsl/chunks/environment-state.js +79 -0
  183. package/src/shaders-tsl/chunks/environment-sun-shadow.js +99 -32
  184. package/src/shaders-tsl/chunks/normalized-hue.js +41 -0
  185. package/src/shaders-tsl/chunks/pass-depth-color.js +4 -2
  186. package/src/shaders-tsl/chunks/scene-depth-color-pass.js +273 -0
  187. package/src/shaders-tsl/chunks/vegetation-style.js +116 -8
  188. package/src/shaders-tsl/chunks/water-color.js +19 -5
  189. package/src/shaders-tsl/chunks/water-shore-state.js +8 -1
  190. package/src/shaders-tsl/chunks/world-noise.js +30 -0
  191. package/src/shaders-tsl/environment.js +123 -17
  192. package/src/shaders-tsl/flower.js +51 -8
  193. package/src/shaders-tsl/grass.js +194 -29
  194. package/src/shaders-tsl/post-composite.js +83 -2
  195. package/src/shaders-tsl/tree-leaf.js +107 -16
  196. package/src/shaders-tsl/water-breaker.js +18 -4
  197. package/src/shaders-tsl/water.js +43 -3
  198. package/src/shaders-tsl/woody-surface.js +59 -7
  199. package/src/sky/atmosphereDome.js +193 -0
  200. package/src/sky/atmosphereParams.js +396 -0
  201. package/src/sky/atmosphereScattering.js +593 -0
  202. package/src/sky/atmosphereSky.js +371 -0
  203. package/src/sky/cloudShadow.js +355 -0
  204. package/src/sky/godRays.js +257 -0
  205. package/src/sky/index.js +55 -1
  206. package/src/sky/nightSky.js +1190 -0
  207. package/src/sky/renderLayers.js +120 -0
  208. package/src/sky/skyColor.js +582 -0
  209. package/src/sky/skyDayCycle.js +244 -0
  210. package/src/sky/skyParams.js +661 -0
  211. package/src/sky/skyPresets.js +772 -0
  212. package/src/sky/skyQualityTiers.js +383 -0
  213. package/src/sky/skyShaderSettings.js +699 -0
  214. package/src/sky/skyStyleSnapshots.js +211 -0
  215. package/src/sky/skySystem.js +1438 -0
  216. package/src/sky/skyTimeKeyframes.js +361 -0
  217. package/src/sky/stylizedSky.js +405 -116
  218. package/src/sky/sunDriver.js +499 -0
  219. package/src/sky/timeOfDay.js +335 -0
  220. package/src/styles/animeGameProfile.js +44 -0
  221. package/src/styles/index.js +134 -0
  222. package/src/styles/manufacturedStyleLabeling.js +204 -0
  223. package/src/styles/sceneLayerDocuments.js +185 -0
  224. package/src/styles/sceneLookComposition.js +156 -0
  225. package/src/styles/sceneQualityApplication.js +152 -0
  226. package/src/styles/sceneQualityProfiles.js +268 -0
  227. package/src/styles/sceneStyleAudit.js +512 -0
  228. package/src/styles/sceneStyleRuntime.js +876 -0
  229. package/src/styles/styleAdapters.js +166 -0
  230. package/src/styles/styleApplication.js +369 -0
  231. package/src/styles/styleBundle.js +444 -91
  232. package/src/styles/styleBundleProvider.js +83 -0
  233. package/src/styles/styleDomains.js +21 -0
  234. package/src/styles/styleInspector.js +262 -0
  235. package/src/styles/styleMaterialContract.js +375 -0
  236. package/src/styles/styleMetadata.js +73 -0
  237. package/src/styles/styleTargetDiscovery.js +162 -0
  238. package/src/styles/styleTargetLabels.js +206 -0
  239. package/src/styles/styleTargetMaterialCoverage.js +137 -0
  240. package/src/styles/styleTransaction.js +272 -0
  241. package/src/texgen/textureGenerators.js +21 -5
  242. package/src/toon/toonSettings.js +4 -0
  243. package/src/vegetation/branchTree.js +302 -0
  244. package/src/vegetation/callMeSenseiGrass.js +183 -0
  245. package/src/vegetation/compiledTree.js +506 -0
  246. package/src/vegetation/contactShadowField.js +107 -0
  247. package/src/vegetation/flowerSpecies.js +10 -2
  248. package/src/vegetation/grass.js +13 -0
  249. package/src/vegetation/grassClump.js +1179 -0
  250. package/src/vegetation/importedVegetationMaterial.js +183 -0
  251. package/src/vegetation/index.js +15 -1
  252. package/src/vegetation/legacyTreePresets.js +120 -0
  253. package/src/vegetation/scatter.js +322 -3
  254. package/src/vegetation/stylizedBush.js +14 -0
  255. package/src/vegetation/stylizedFlower.js +31 -0
  256. package/src/vegetation/stylizedFlowers.js +59 -7
  257. package/src/vegetation/stylizedForest.js +455 -147
  258. package/src/vegetation/stylizedGrass.js +188 -24
  259. package/src/vegetation/stylizedTree.js +378 -46
  260. package/src/vegetation/stylizedTreeFoliage.js +889 -38
  261. package/src/vegetation/stylizedUnderstory.js +230 -0
  262. package/src/vegetation/treeExport.js +262 -47
  263. package/src/vegetation/treeSurfaceTextures.js +337 -0
  264. package/src/vegetation/vegetationShaders.js +617 -28
  265. package/src/version.js +3 -0
  266. package/src/water/water.js +2 -0
  267. package/src/water/waterBreakerSystem.js +2 -0
  268. package/src/water/waterCurrentField.js +1 -0
  269. package/src/water/waterMaterial.js +3 -0
  270. package/src/water/waterRain.js +2 -0
  271. package/src/water/waterScenePasses.js +170 -7
  272. package/src/water/waterSettings.js +235 -43
  273. package/src/water/waterShoreMaterial.js +16 -2
  274. package/src/water/waterShoreStateField.js +1 -1
  275. package/src/water/waterSplashSystem.js +2 -0
  276. package/src/water/waterStageSettings.js +60 -0
  277. package/src/water/waterSurface.js +144 -4
  278. package/src/water/waterUnderwaterAtmosphere.js +288 -0
  279. package/src/water/waterVegetation.js +20 -4
  280. package/src/worldCollision.js +64 -9
  281. package/types/agents/index.d.ts +1 -0
  282. package/types/agents/sceneStyleOperations.d.ts +484 -0
  283. package/types/asset-policy/catalogLicenses.d.ts +5 -0
  284. package/types/asset-policy/index.d.ts +18 -0
  285. package/types/assetlib/ambientcg.d.ts +81 -0
  286. package/types/assetlib/assetRef.d.ts +26 -0
  287. package/types/assetlib/galleryMaterialFamily.d.ts +13 -0
  288. package/types/assetlib/importedEntry.d.ts +18 -0
  289. package/types/assetlib/index.d.ts +16 -0
  290. package/types/assetlib/kaykit.d.ts +112 -0
  291. package/types/assetlib/kaykitStaticIndex.d.ts +38 -0
  292. package/types/assetlib/loadImported.d.ts +54 -0
  293. package/types/assetlib/opensource3d.d.ts +55 -0
  294. package/types/assetlib/plateau.d.ts +67 -0
  295. package/types/assetlib/plateauLandmarks.d.ts +238 -0
  296. package/types/assetlib/plateauViewer.d.ts +3 -0
  297. package/types/assetlib/polyhaven.d.ts +90 -0
  298. package/types/assetlib/polypizza.d.ts +10 -0
  299. package/types/assetlib/smithsonian.d.ts +9 -0
  300. package/types/assetlib/sources.d.ts +22 -0
  301. package/types/assetlib/zip.d.ts +8 -0
  302. package/types/catalog/manifest.d.ts +26 -0
  303. package/types/catalog/officialCatalog.d.ts +4 -0
  304. package/types/catalog/officialCatalogAssetRuntime.d.ts +2 -0
  305. package/types/catalog/officialCatalogLod.d.ts +5 -0
  306. package/types/catalog/officialCatalogPlacement.d.ts +49 -0
  307. package/types/catalog/officialCatalogProvider.d.ts +7 -0
  308. package/types/character/animationRetarget.d.ts +20 -0
  309. package/types/character/characterRig.d.ts +28 -0
  310. package/types/character/characterRuntime.d.ts +4 -0
  311. package/types/character/freestyleSwimClip.d.ts +5 -0
  312. package/types/character/groundStabilizer.d.ts +55 -0
  313. package/types/character/index.d.ts +10 -0
  314. package/types/character/locomotionActions.d.ts +4 -0
  315. package/types/character/locomotionStateMachine.d.ts +62 -0
  316. package/types/character/mannequinAsset.d.ts +12 -0
  317. package/types/character/mannequinAssetUrl.node.d.ts +1 -0
  318. package/types/character/modelLoader.d.ts +7 -0
  319. package/types/character/walkableCharacterRuntime.d.ts +343 -0
  320. package/types/character/waterInteractionController.d.ts +114 -0
  321. package/types/cloud/ambientSkyBaker.d.ts +18 -0
  322. package/types/cloud/cloudLighting.d.ts +38 -0
  323. package/types/cloud/cloudParams.d.ts +18 -0
  324. package/types/cloud/cloudReprojection.d.ts +15 -0
  325. package/types/cloud/cloudStyle.d.ts +1380 -0
  326. package/types/cloud/cloudStyleSnapshots.d.ts +10 -0
  327. package/types/cloud/cloudVolume.d.ts +43 -0
  328. package/types/cloud/heroCloudRecipe.d.ts +167 -0
  329. package/types/cloud/index.d.ts +12 -0
  330. package/types/cloud/noise/baseShapeVolume.d.ts +86 -0
  331. package/types/cloud/noise/cirrusMap.d.ts +24 -0
  332. package/types/cloud/noise/curlNoise.d.ts +106 -0
  333. package/types/cloud/noise/erosionVolume.d.ts +58 -0
  334. package/types/cloud/noise/noiseVolume.d.ts +63 -0
  335. package/types/cloud/noise/periodicNoise3.d.ts +75 -0
  336. package/types/cloud/noise/weatherMap.d.ts +227 -0
  337. package/types/cloud/paramSchema.d.ts +142 -0
  338. package/types/collisionMetadata.d.ts +11 -0
  339. package/types/core/generation.d.ts +95 -0
  340. package/types/core/materialRoles.d.ts +102 -0
  341. package/types/core/presetDocuments.d.ts +25 -0
  342. package/types/core/systemStylePolicy.d.ts +4 -0
  343. package/types/environment/dayCurves.d.ts +47 -0
  344. package/types/environment/environmentAmbientProbe.d.ts +2 -0
  345. package/types/environment/environmentGroundFieldPass.d.ts +2 -0
  346. package/types/environment/environmentMaterialAdapter.d.ts +42 -0
  347. package/types/environment/environmentMaterialClassifier.d.ts +26 -0
  348. package/types/environment/environmentPlanarReflection.d.ts +3 -0
  349. package/types/environment/environmentPresets.d.ts +171 -0
  350. package/types/environment/environmentRigs.d.ts +13 -0
  351. package/types/environment/environmentSettings.d.ts +161 -0
  352. package/types/environment/environmentShaderMaterials.d.ts +14 -0
  353. package/types/environment/environmentState.d.ts +6 -0
  354. package/types/environment/environmentSunShadowPass.d.ts +2 -0
  355. package/types/environment/environmentTextureResolver.d.ts +30 -0
  356. package/types/environment/environmentTimeOfDay.d.ts +25 -0
  357. package/types/environment/environmentVertexAo.d.ts +18 -0
  358. package/types/environment/index.d.ts +27 -0
  359. package/types/environment/manufacturedMaterialContract.d.ts +129 -0
  360. package/types/environment/manufacturedReflectionProvider.d.ts +3 -0
  361. package/types/environment/scanAssetStylize.d.ts +43 -0
  362. package/types/environment/surfaceMaterialModes.d.ts +14 -0
  363. package/types/environment/toonLabEnvironmentMaterials.d.ts +139 -0
  364. package/types/environment/toonLabMaterialPassCoupling.d.ts +7 -0
  365. package/types/environment/toonLabNormalIntegration.d.ts +29 -0
  366. package/types/environment/toonLabRockMaterialResolver.d.ts +270 -0
  367. package/types/environment/toonLabSourceDefaultLit.d.ts +136 -0
  368. package/types/environment/toonLabSourceLibrary.d.ts +19 -0
  369. package/types/environment/toonLabSourceMaterials.d.ts +14 -0
  370. package/types/environment/toonLabSourceSubsurfaceLighting.d.ts +85 -0
  371. package/types/environment/toonLabSourceTemporal.d.ts +20 -0
  372. package/types/environment/toonLabSurfaceLighting.d.ts +136 -0
  373. package/types/environment/toonLabTextureReadiness.d.ts +8 -0
  374. package/types/environment/toonLabTreeMaterials.d.ts +7 -0
  375. package/types/environment/transparentMaterialProfile.d.ts +76 -0
  376. package/types/environment/urbanPropMaterial.d.ts +25 -0
  377. package/types/ground-shader/groundPrintLayer.d.ts +4 -0
  378. package/types/ground-shader/groundShaderMaterial.d.ts +11 -0
  379. package/types/ground-shader/groundShaderSettings.d.ts +90 -0
  380. package/types/ground-shader/index.d.ts +3 -0
  381. package/types/index.d.ts +1502 -0
  382. package/types/lighting/callMeSenseiLightingContract.d.ts +14 -0
  383. package/types/lighting/colorIntensity.d.ts +44 -0
  384. package/types/lighting/index.d.ts +12 -0
  385. package/types/lighting/lightDescriptors.d.ts +803 -0
  386. package/types/lighting/lightingCapabilities.d.ts +85 -0
  387. package/types/lighting/lightingDocuments.d.ts +140 -0
  388. package/types/lighting/lightingFixtures.d.ts +171 -0
  389. package/types/lighting/lightingGenerator.d.ts +403 -0
  390. package/types/lighting/lightingPresets.d.ts +264 -0
  391. package/types/lighting/lightingRuntime.d.ts +401 -0
  392. package/types/lighting/lightingStyle.d.ts +156 -0
  393. package/types/lighting/lightingSystem.d.ts +433 -0
  394. package/types/lighting/toonLabExport.d.ts +46 -0
  395. package/types/lighting/utils.d.ts +18 -0
  396. package/types/loaders/index.d.ts +1 -0
  397. package/types/post/index.d.ts +2 -0
  398. package/types/post/postGenerator.d.ts +282 -0
  399. package/types/post/postProcessing.d.ts +16 -0
  400. package/types/react/index.d.ts +1765 -0
  401. package/types/renderer/index.d.ts +1 -0
  402. package/types/renderer/rendererConfiguration.d.ts +8 -0
  403. package/types/rock-shader/index.d.ts +3 -0
  404. package/types/rock-shader/rockMaterial.d.ts +18 -0
  405. package/types/rock-shader/rockShaderRuntime.d.ts +8 -0
  406. package/types/rock-shader/rockShaderSettings.d.ts +170 -0
  407. package/types/rockgen/export/glbExport.d.ts +58 -0
  408. package/types/rockgen/heightfield/heightfieldErosion.d.ts +10 -0
  409. package/types/rockgen/heightfield/heightfieldPatch.d.ts +15 -0
  410. package/types/rockgen/heightfield/stylizedErosionSim.d.ts +41 -0
  411. package/types/rockgen/index.d.ts +11 -0
  412. package/types/rockgen/lod/index.d.ts +6 -0
  413. package/types/rockgen/lod/rockLodMetrics.d.ts +62 -0
  414. package/types/rockgen/lod/rockLodPlanner.d.ts +86 -0
  415. package/types/rockgen/lod/rockLodPolicy.d.ts +76 -0
  416. package/types/rockgen/lod/rockLodRuntime.d.ts +95 -0
  417. package/types/rockgen/lod/rockLodSimplifier.d.ts +15 -0
  418. package/types/rockgen/lod/rockLodValidation.d.ts +16 -0
  419. package/types/rockgen/mesh/meshAttributes.d.ts +32 -0
  420. package/types/rockgen/mesh/meshDocument.d.ts +40 -0
  421. package/types/rockgen/mesh/surfaceNets.d.ts +42 -0
  422. package/types/rockgen/noise/cellularNoise3.d.ts +24 -0
  423. package/types/rockgen/noise/prng.d.ts +16 -0
  424. package/types/rockgen/noise/simplexNoise3.d.ts +2 -0
  425. package/types/rockgen/noise/valueNoise3.d.ts +12 -0
  426. package/types/rockgen/rockDocument.d.ts +215 -0
  427. package/types/rockgen/rockHelpers.d.ts +2 -0
  428. package/types/rockgen/rockgenPresets.d.ts +10 -0
  429. package/types/rockgen/rockgenSettings.d.ts +531 -0
  430. package/types/rockgen/sdf/fieldCompiler.d.ts +20 -0
  431. package/types/rockgen/sdf/sculptEdits.d.ts +30 -0
  432. package/types/rockgen/sdf/sdfModifiers.d.ts +19 -0
  433. package/types/rockgen/sdf/sdfOps.d.ts +8 -0
  434. package/types/rockgen/sdf/sdfPrimitives.d.ts +22 -0
  435. package/types/runtime/index.d.ts +3 -0
  436. package/types/runtime/sceneCollisionRuntime.d.ts +94 -0
  437. package/types/runtime/sceneSurfaceRuntime.d.ts +90 -0
  438. package/types/runtime/sceneUpdateScheduler.d.ts +28 -0
  439. package/types/shaders-tsl/anime.d.ts +9 -0
  440. package/types/shaders-tsl/chunks/character-color.d.ts +6 -0
  441. package/types/shaders-tsl/chunks/character-highlights.d.ts +12 -0
  442. package/types/shaders-tsl/chunks/character-lighting.d.ts +20 -0
  443. package/types/shaders-tsl/chunks/character-material-maps.d.ts +18 -0
  444. package/types/shaders-tsl/chunks/character-roles.d.ts +21 -0
  445. package/types/shaders-tsl/chunks/character-scene-lights.d.ts +48 -0
  446. package/types/shaders-tsl/chunks/character-shadow-color.d.ts +5 -0
  447. package/types/shaders-tsl/chunks/character-skinning.d.ts +23 -0
  448. package/types/shaders-tsl/chunks/environment-color.d.ts +9 -0
  449. package/types/shaders-tsl/chunks/environment-debug.d.ts +24 -0
  450. package/types/shaders-tsl/chunks/environment-ground-field.d.ts +40 -0
  451. package/types/shaders-tsl/chunks/environment-lighting.d.ts +22 -0
  452. package/types/shaders-tsl/chunks/environment-state.d.ts +42 -0
  453. package/types/shaders-tsl/chunks/environment-sun-shadow.d.ts +19 -0
  454. package/types/shaders-tsl/chunks/foliage-fog.d.ts +21 -0
  455. package/types/shaders-tsl/chunks/normalized-hue.d.ts +1 -0
  456. package/types/shaders-tsl/chunks/pass-depth-color.d.ts +20 -0
  457. package/types/shaders-tsl/chunks/projected-water-caustics.d.ts +24 -0
  458. package/types/shaders-tsl/chunks/scene-depth-color-pass.d.ts +39 -0
  459. package/types/shaders-tsl/chunks/stylized-cloud-shadow.d.ts +9 -0
  460. package/types/shaders-tsl/chunks/vegetation-style.d.ts +60 -0
  461. package/types/shaders-tsl/chunks/water-color.d.ts +15 -0
  462. package/types/shaders-tsl/chunks/water-common.d.ts +9 -0
  463. package/types/shaders-tsl/chunks/water-foam.d.ts +8 -0
  464. package/types/shaders-tsl/chunks/water-lighting.d.ts +9 -0
  465. package/types/shaders-tsl/chunks/water-ripple.d.ts +8 -0
  466. package/types/shaders-tsl/chunks/water-shore-state.d.ts +7 -0
  467. package/types/shaders-tsl/chunks/water-waves.d.ts +18 -0
  468. package/types/shaders-tsl/chunks/world-noise.d.ts +4 -0
  469. package/types/shaders-tsl/environment-ao-overlay.d.ts +5 -0
  470. package/types/shaders-tsl/environment.d.ts +34 -0
  471. package/types/shaders-tsl/flower.d.ts +6 -0
  472. package/types/shaders-tsl/grass.d.ts +4 -0
  473. package/types/shaders-tsl/post-composite.d.ts +25 -0
  474. package/types/shaders-tsl/sky.d.ts +4 -0
  475. package/types/shaders-tsl/tree-leaf.d.ts +2 -0
  476. package/types/shaders-tsl/water-breaker.d.ts +15 -0
  477. package/types/shaders-tsl/water-kelp.d.ts +5 -0
  478. package/types/shaders-tsl/water-rain.d.ts +10 -0
  479. package/types/shaders-tsl/water-shore-state-simulation.d.ts +12 -0
  480. package/types/shaders-tsl/water-simulation.d.ts +5 -0
  481. package/types/shaders-tsl/water-splash.d.ts +12 -0
  482. package/types/shaders-tsl/water.d.ts +22 -0
  483. package/types/shaders-tsl/woody-surface.d.ts +3 -0
  484. package/types/sky/atmosphereDome.d.ts +2 -0
  485. package/types/sky/atmosphereParams.d.ts +185 -0
  486. package/types/sky/atmosphereScattering.d.ts +11 -0
  487. package/types/sky/atmosphereSky.d.ts +2 -0
  488. package/types/sky/cloudShadow.d.ts +68 -0
  489. package/types/sky/godRays.d.ts +5 -0
  490. package/types/sky/index.d.ts +18 -0
  491. package/types/sky/nightSky.d.ts +22 -0
  492. package/types/sky/renderLayers.d.ts +59 -0
  493. package/types/sky/sceneOverrideLayers.d.ts +10 -0
  494. package/types/sky/skyColor.d.ts +704 -0
  495. package/types/sky/skyDayCycle.d.ts +86 -0
  496. package/types/sky/skyParams.d.ts +3407 -0
  497. package/types/sky/skyPresets.d.ts +160 -0
  498. package/types/sky/skyQuality.d.ts +21 -0
  499. package/types/sky/skyQualityTiers.d.ts +223 -0
  500. package/types/sky/skyShaderSettings.d.ts +152 -0
  501. package/types/sky/skyStyleSnapshots.d.ts +11 -0
  502. package/types/sky/skySystem.d.ts +3 -0
  503. package/types/sky/skyTimeKeyframes.d.ts +230 -0
  504. package/types/sky/stylizedSky.d.ts +341 -0
  505. package/types/sky/sunDriver.d.ts +15 -0
  506. package/types/sky/timeOfDay.d.ts +145 -0
  507. package/types/styles/animeGameProfile.d.ts +27 -0
  508. package/types/styles/index.d.ts +17 -0
  509. package/types/styles/manufacturedStyleLabeling.d.ts +119 -0
  510. package/types/styles/sceneLayerDocuments.d.ts +145 -0
  511. package/types/styles/sceneLookComposition.d.ts +53 -0
  512. package/types/styles/sceneQualityApplication.d.ts +34 -0
  513. package/types/styles/sceneQualityProfiles.d.ts +13 -0
  514. package/types/styles/sceneStyleAudit.d.ts +80 -0
  515. package/types/styles/sceneStyleRuntime.d.ts +1782 -0
  516. package/types/styles/styleAdapters.d.ts +14 -0
  517. package/types/styles/styleApplication.d.ts +47 -0
  518. package/types/styles/styleBundle.d.ts +19 -0
  519. package/types/styles/styleBundleProvider.d.ts +44 -0
  520. package/types/styles/styleDomains.d.ts +18 -0
  521. package/types/styles/styleInspector.d.ts +59 -0
  522. package/types/styles/styleMaterialContract.d.ts +46 -0
  523. package/types/styles/styleMetadata.d.ts +11 -0
  524. package/types/styles/styleTargetDiscovery.d.ts +48 -0
  525. package/types/styles/styleTargetLabels.d.ts +32 -0
  526. package/types/styles/styleTargetMaterialCoverage.d.ts +20 -0
  527. package/types/styles/styleTransaction.d.ts +10 -0
  528. package/types/styles/styleTypes.d.ts +66 -0
  529. package/types/texgen/evaluateTexture.d.ts +40 -0
  530. package/types/texgen/index.d.ts +7 -0
  531. package/types/texgen/noise2.d.ts +46 -0
  532. package/types/texgen/textureAi.d.ts +6 -0
  533. package/types/texgen/textureGenerators.d.ts +261 -0
  534. package/types/texgen/texturePresets.d.ts +45 -0
  535. package/types/texgen/textureSettings.d.ts +121 -0
  536. package/types/texgen/textureThree.d.ts +13 -0
  537. package/types/toon/characterRenderPasses.d.ts +3 -0
  538. package/types/toon/index.d.ts +3 -0
  539. package/types/toon/settings/alphaSettings.d.ts +125 -0
  540. package/types/toon/settings/averageShadowSettings.d.ts +39 -0
  541. package/types/toon/settings/baseTextureSettings.d.ts +39 -0
  542. package/types/toon/settings/celShadeSettings.d.ts +37 -0
  543. package/types/toon/settings/contactShadowSettings.d.ts +30 -0
  544. package/types/toon/settings/eyeHighlightSettings.d.ts +55 -0
  545. package/types/toon/settings/faceLightingSettings.d.ts +32 -0
  546. package/types/toon/settings/furSettings.d.ts +23 -0
  547. package/types/toon/settings/glitterSettings.d.ts +43 -0
  548. package/types/toon/settings/hairHighlightSettings.d.ts +89 -0
  549. package/types/toon/settings/indirectLightSettings.d.ts +43 -0
  550. package/types/toon/settings/localLightSettings.d.ts +46 -0
  551. package/types/toon/settings/materialMapSettings.d.ts +86 -0
  552. package/types/toon/settings/outlineSettings.d.ts +125 -0
  553. package/types/toon/settings/perspectiveRemovalSettings.d.ts +14 -0
  554. package/types/toon/settings/rimLightSettings.d.ts +79 -0
  555. package/types/toon/settings/sceneShadowSettings.d.ts +32 -0
  556. package/types/toon/settings/selfShadowSettings.d.ts +44 -0
  557. package/types/toon/settings/shadowColorSettings.d.ts +77 -0
  558. package/types/toon/settings/skinToneSettings.d.ts +30 -0
  559. package/types/toon/settings/specularSettings.d.ts +96 -0
  560. package/types/toon/settings/stickerSettings.d.ts +40 -0
  561. package/types/toon/toonMaterialAdapter.d.ts +883 -0
  562. package/types/toon/toonSettings.d.ts +1182 -0
  563. package/types/vegetation/branchTree.d.ts +10 -0
  564. package/types/vegetation/callMeSenseiGrass.d.ts +8 -0
  565. package/types/vegetation/compiledTree.d.ts +75 -0
  566. package/types/vegetation/contactShadowField.d.ts +26 -0
  567. package/types/vegetation/flowerSpecies.d.ts +107 -0
  568. package/types/vegetation/grass.d.ts +4 -0
  569. package/types/vegetation/grassClump.d.ts +7 -0
  570. package/types/vegetation/grassPalettes.d.ts +29 -0
  571. package/types/vegetation/importedVegetationMaterial.d.ts +13 -0
  572. package/types/vegetation/index.d.ts +216 -0
  573. package/types/vegetation/legacyTreePresets.d.ts +22 -0
  574. package/types/vegetation/scatter.d.ts +12 -0
  575. package/types/vegetation/stylizedBush.d.ts +2 -0
  576. package/types/vegetation/stylizedFlower.d.ts +2 -0
  577. package/types/vegetation/stylizedFlowers.d.ts +8 -0
  578. package/types/vegetation/stylizedForest.d.ts +3 -0
  579. package/types/vegetation/stylizedGrass.d.ts +21 -0
  580. package/types/vegetation/stylizedTree.d.ts +19 -0
  581. package/types/vegetation/stylizedTreeFoliage.d.ts +18 -0
  582. package/types/vegetation/stylizedUnderstory.d.ts +50 -0
  583. package/types/vegetation/treeExport.d.ts +6 -0
  584. package/types/vegetation/treeSurfaceTextures.d.ts +72 -0
  585. package/types/vegetation/vegetationShaders.d.ts +74 -0
  586. package/types/version.d.ts +1 -0
  587. package/types/water/index.d.ts +1 -0
  588. package/types/water/sceneOverrideLayers.d.ts +16 -0
  589. package/types/water/water.d.ts +17 -0
  590. package/types/water/waterBreakerSystem.d.ts +46 -0
  591. package/types/water/waterCurrentField.d.ts +115 -0
  592. package/types/water/waterInteraction.d.ts +21 -0
  593. package/types/water/waterMaterial.d.ts +60 -0
  594. package/types/water/waterNearshorePhase.d.ts +5 -0
  595. package/types/water/waterRain.d.ts +17 -0
  596. package/types/water/waterRippleSimulation.d.ts +52 -0
  597. package/types/water/waterScenePasses.d.ts +70 -0
  598. package/types/water/waterSettings.d.ts +648 -0
  599. package/types/water/waterShoreMaterial.d.ts +3 -0
  600. package/types/water/waterShoreStateField.d.ts +2 -0
  601. package/types/water/waterSplashSystem.d.ts +2 -0
  602. package/types/water/waterStageSettings.d.ts +9 -0
  603. package/types/water/waterSurface.d.ts +2 -0
  604. package/types/water/waterUnderwaterAtmosphere.d.ts +103 -0
  605. package/types/water/waterVegetation.d.ts +16 -0
  606. package/types/worldCollision.d.ts +22 -0
  607. package/AGENTS.md +0 -254
  608. package/ATTRIBUTION.md +0 -78
  609. package/docs/characters.md +0 -144
  610. package/docs/debug-panel.md +0 -126
  611. package/docs/docs.css +0 -589
  612. package/docs/environment.md +0 -186
  613. package/docs/getting-started.md +0 -180
  614. package/docs/index.html +0 -14
  615. package/docs/lab-architecture.md +0 -100
  616. package/docs/lighting.md +0 -825
  617. package/docs/main.jsx +0 -739
  618. package/docs/mcp.md +0 -97
  619. package/docs/post-processing.md +0 -98
  620. package/docs/settings-reference.md +0 -1878
  621. package/docs/shader-constants.md +0 -77
  622. package/docs/sky.md +0 -182
  623. package/docs/style-labs.md +0 -309
  624. package/docs/texture-lab.md +0 -135
  625. package/docs/toon-shading.md +0 -183
  626. package/docs/tsl-conventions.md +0 -167
  627. package/docs/vegetation-sky.md +0 -275
  628. package/docs/water.md +0 -430
  629. package/docs/weather.md +0 -200
  630. package/docs/world-scale.md +0 -111
  631. package/mcp/style-lab-tools.mjs +0 -371
  632. package/src/ambientfx/INTEGRATION.md +0 -164
  633. package/src/ambientfx/ambientFxPresets.js +0 -83
  634. package/src/ambientfx/ambientFxSettings.js +0 -368
  635. package/src/ambientfx/emitters.js +0 -169
  636. package/src/ambientfx/index.js +0 -5
  637. package/src/ambientfx/particleBackbone.js +0 -493
  638. package/src/ambientfx/stylizedAmbientFx.js +0 -450
  639. package/src/biome/biomeGenerator.js +0 -385
  640. package/src/biome/biomeRuntime.js +0 -299
  641. package/src/biome/index.js +0 -2
  642. package/src/buildinggen/buildingAsset.js +0 -44
  643. package/src/buildinggen/buildingGrammar.js +0 -311
  644. package/src/buildinggen/buildingMesh.js +0 -451
  645. package/src/buildinggen/buildingPresets.js +0 -46
  646. package/src/buildinggen/buildingRecipe.js +0 -100
  647. package/src/buildinggen/buildingSettings.js +0 -238
  648. package/src/buildinggen/index.js +0 -6
  649. package/src/camera/cameraDirector.js +0 -157
  650. package/src/camera/cameraGenerator.js +0 -367
  651. package/src/camera/cameraRig.js +0 -570
  652. package/src/camera/cameraSettings.js +0 -236
  653. package/src/camera/index.js +0 -7
  654. package/src/catalog/builtinEntries.js +0 -245
  655. package/src/catalog/catalog.js +0 -210
  656. package/src/catalog/index.js +0 -3
  657. package/src/core/shaderBackend.js +0 -24
  658. package/src/debrisgen/debrisFields.js +0 -544
  659. package/src/debrisgen/debrisGenerator.js +0 -1929
  660. package/src/debrisgen/debrisPalettes.js +0 -71
  661. package/src/debrisgen/debrisPhysics.js +0 -198
  662. package/src/debrisgen/debrisPresets.js +0 -162
  663. package/src/debrisgen/debrisSettings.js +0 -333
  664. package/src/debrisgen/debrisTextures.js +0 -380
  665. package/src/debrisgen/index.js +0 -5
  666. package/src/debug/fieldValues.js +0 -95
  667. package/src/debug/index.js +0 -7
  668. package/src/debug/settingsPanel.js +0 -170
  669. package/src/fauna/INTEGRATION.md +0 -174
  670. package/src/fauna/boids.js +0 -861
  671. package/src/fauna/faunaBodies.js +0 -492
  672. package/src/fauna/faunaPresets.js +0 -52
  673. package/src/fauna/faunaSettings.js +0 -525
  674. package/src/fauna/index.js +0 -5
  675. package/src/fauna/stylizedFauna.js +0 -395
  676. package/src/game-feel/gameFeelGenerator.js +0 -402
  677. package/src/game-feel/gameFeelRuntime.js +0 -549
  678. package/src/game-feel/index.js +0 -2
  679. package/src/motion/index.js +0 -5
  680. package/src/motion/motionClip.js +0 -441
  681. package/src/motion/motionController.js +0 -628
  682. package/src/motion/motionDocuments.js +0 -225
  683. package/src/motion/motionGraph.js +0 -307
  684. package/src/motion/motionSettings.js +0 -222
  685. package/src/pathgen/index.js +0 -7
  686. package/src/pathgen/pathBridge.js +0 -232
  687. package/src/pathgen/pathPresets.js +0 -35
  688. package/src/pathgen/pathRibbon.js +0 -410
  689. package/src/pathgen/pathRouter.js +0 -380
  690. package/src/pathgen/pathSettings.js +0 -335
  691. package/src/pathgen/pathTextures.js +0 -123
  692. package/src/pathgen/stylizedPaths.js +0 -453
  693. package/src/propgen/generatorsWave1.js +0 -379
  694. package/src/propgen/generatorsWave2.js +0 -462
  695. package/src/propgen/index.js +0 -5
  696. package/src/propgen/propAsset.js +0 -323
  697. package/src/propgen/propParts.js +0 -170
  698. package/src/propgen/propPlacement.js +0 -459
  699. package/src/propgen/propPresets.js +0 -82
  700. package/src/propgen/propSettings.js +0 -395
  701. package/src/soundscape/index.js +0 -4
  702. package/src/soundscape/soundscapeGenerator.js +0 -179
  703. package/src/soundscape/soundscapeRuntime.js +0 -806
  704. package/src/soundscape/soundscapeSettings.js +0 -292
  705. package/src/stylizedTerrain.js +0 -631
  706. package/src/stylizedWorld.js +0 -903
  707. package/src/vegetation/treeRecipe.js +0 -647
  708. package/src/vfxgen/INTEGRATION.md +0 -145
  709. package/src/vfxgen/core/burstBackbone.js +0 -380
  710. package/src/vfxgen/core/projectileCore.js +0 -92
  711. package/src/vfxgen/core/spriteShapes.js +0 -98
  712. package/src/vfxgen/core/trailRibbon.js +0 -272
  713. package/src/vfxgen/core/vfxRandom.js +0 -29
  714. package/src/vfxgen/effects/emitHelpers.js +0 -37
  715. package/src/vfxgen/effects/magicEffects.js +0 -162
  716. package/src/vfxgen/effects/movementEffects.js +0 -87
  717. package/src/vfxgen/effects/weaponEffects.js +0 -118
  718. package/src/vfxgen/index.js +0 -18
  719. package/src/vfxgen/moves/moveController.js +0 -146
  720. package/src/vfxgen/moves/moveLibrary.js +0 -335
  721. package/src/vfxgen/vfxPresets.js +0 -98
  722. package/src/vfxgen/vfxSettings.js +0 -384
  723. package/src/vfxgen/vfxSystem.js +0 -449
  724. package/src/vfxgen/weapons/stylizedWeapons.js +0 -137
  725. package/src/villagegen/index.js +0 -4
  726. package/src/villagegen/stylizedVillage.js +0 -490
  727. package/src/villagegen/villageArchetypes.js +0 -160
  728. package/src/villagegen/villageNames.js +0 -40
  729. package/src/villagegen/villageSites.js +0 -105
  730. package/src/weather/index.js +0 -6
  731. package/src/weather/weatherPrecipitation.js +0 -221
  732. package/src/weather/weatherPresets.js +0 -258
  733. package/src/weather/weatherSettings.js +0 -269
  734. package/src/weather/weatherSystem.js +0 -871
  735. package/src/worldMinimap.js +0 -214
  736. package/src/worldPresets.js +0 -125
@@ -0,0 +1,3718 @@
1
+ // Family-specific WebGPU reconstructions of the licensed ToonLab source
2
+ // materials. These consume the exact exported material-instance profiles and
3
+ // remain separate from ToonLab's generic environment shader.
4
+
5
+ import * as THREE from 'three';
6
+ import {
7
+ MeshBasicNodeMaterial,
8
+ MeshPhysicalNodeMaterial,
9
+ MeshSSSNodeMaterial,
10
+ } from 'three/webgpu';
11
+ import {
12
+ abs,
13
+ cameraViewMatrix,
14
+ cameraPosition,
15
+ clamp,
16
+ cos,
17
+ cross,
18
+ dot,
19
+ faceDirection,
20
+ float,
21
+ fract,
22
+ luminance,
23
+ max,
24
+ mix,
25
+ mod,
26
+ normalMap as normalMapNode,
27
+ normalViewGeometry,
28
+ normalWorld,
29
+ normalWorldGeometry,
30
+ normalize,
31
+ positionLocal,
32
+ positionView,
33
+ positionWorld,
34
+ pow,
35
+ sign,
36
+ sin,
37
+ smoothstep,
38
+ step,
39
+ texture,
40
+ transformNormalByViewMatrix,
41
+ uniform,
42
+ uv,
43
+ vec2,
44
+ vec3,
45
+ vertexColor,
46
+ wgslFn,
47
+ } from 'three/tsl';
48
+
49
+ import {
50
+ loadToonLabMountainMaterial,
51
+ loadToonRockMaterial,
52
+ } from '../rock-shader/rockMaterial.js';
53
+ import {
54
+ sampleGroundColor,
55
+ sampleGroundHeight,
56
+ sampleGroundSurface,
57
+ } from '../shaders-tsl/chunks/environment-ground-field.js';
58
+ import {
59
+ DEFAULT_TOONLAB_SOURCE_BASE_URL,
60
+ TOONLAB_SHOWCASE_WEIGHTMAP_CONTRACT,
61
+ toonLabScalar as scalar,
62
+ toonLabSwitch as switchValue,
63
+ toonLabTexturePath as texturePath,
64
+ toonLabVector as vector,
65
+ } from './toonLabSourceLibrary.js';
66
+ import {
67
+ loadToonLabRockMaterialIndex,
68
+ resolveToonLabRockMaterial,
69
+ } from './toonLabRockMaterialResolver.js';
70
+ import {
71
+ buildToonLabGrassMaterial,
72
+ isToonLabGrassProfile,
73
+ toonLabGrassCastsShadow,
74
+ } from './toonLabEnvironmentMaterials.js';
75
+ import {
76
+ buildToonLabPineBarkMaterial,
77
+ buildToonLabPineLeavesMaterial,
78
+ isToonLabPineBarkProfile,
79
+ isToonLabPineLeavesProfile,
80
+ } from './toonLabTreeMaterials.js';
81
+ import {
82
+ installToonLabSurfaceLighting,
83
+ } from './toonLabSurfaceLighting.js';
84
+ import {
85
+ SURFACE_MATERIAL_MODE,
86
+ copySurfaceMaterialModes,
87
+ registerSurfaceMaterialMode,
88
+ resolveSurfaceMaterialMode,
89
+ } from './surfaceMaterialModes.js';
90
+ import { installToonLabSourceDefaultLitLighting } from './toonLabSourceDefaultLit.js';
91
+ import { installToonLabSourceSubsurfaceLighting } from './toonLabSourceSubsurfaceLighting.js';
92
+ import { toonLabSourceDitherTemporalAA } from './toonLabSourceTemporal.js';
93
+
94
+ const templateCaches = new WeakMap();
95
+ let toonRockMaterialIndexPromise = null;
96
+
97
+ const CURVE_ATLASES = Object.freeze({
98
+ clouds: 'Atlas_Clouds',
99
+ sky: 'Atlas_Sky',
100
+ grass: 'Curve_Grass_Atlas',
101
+ leaves: 'Curve_Leaves_Atlas',
102
+ });
103
+
104
+ const LANDSCAPE_FUNCTION_TEXTURES = Object.freeze({
105
+ autoCliffNoise: '/Game/ToonLab/Textures/Noise/T_NoiseStylized.T_NoiseStylized',
106
+ desertDirtNormal: '/Game/ToonLab/Environment/Landscape/Textures/T_DesertDirt_Rocks_N.T_DesertDirt_Rocks_N',
107
+ desertSandNormal: '/Game/ToonLab/Environment/Landscape/Textures/T_DesertSand_N.T_DesertSand_N',
108
+ desertSandRoughness: '/Game/ToonLab/Textures/Noise/T_ChromaNoise_Bilinear.T_ChromaNoise_Bilinear',
109
+ desertSandVariance: '/Game/ToonLab/Textures/Noise/T_NoiseRough_HighContrast.T_NoiseRough_HighContrast',
110
+ dirtNormal: '/Game/ToonLab/Environment/Landscape/Textures/T_Dirt1_N.T_Dirt1_N',
111
+ dirtRoughness: '/Game/ToonLab/Environment/Landscape/Textures/T_Dirt1_R.T_Dirt1_R',
112
+ grassVariance: '/Game/ToonLab/Textures/Noise/T_NoiseRough.T_NoiseRough',
113
+ sandNormal: '/Game/ToonLab/Environment/Landscape/Textures/T_Sand_N.T_Sand_N',
114
+ sandRoughness: '/Game/ToonLab/Environment/Landscape/Textures/T_Sand_R.T_Sand_R',
115
+ sparkleChroma: '/Game/ToonLab/Textures/Noise/T_ChromaNoise2x_Nearest.T_ChromaNoise2x_Nearest',
116
+ sparkleMask: '/Game/ToonLab/Textures/Masks/T_SphereMask.T_SphereMask',
117
+ snowSpecular: '/Game/ToonLab/Textures/Noise/T_ChromaNoise_Blurred.T_ChromaNoise_Blurred',
118
+ });
119
+
120
+ const CLOUD_LITE_TEXTURE =
121
+ '/Game/ToonLab/Environment/Sky/Textures/CloudLayers/T_CloudLayer03.T_CloudLayer03';
122
+
123
+ const TOONLAB_SHOWCASE_SOURCE_ASSET = 'Demonstration_ToonLabShowcase';
124
+ const TOONLAB_SHOWCASE_COLORMAP =
125
+ '/Game/ToonLab/Environment/Landscape/Textures/T_Grass_ColormapSnow.T_Grass_ColormapSnow';
126
+
127
+ /**
128
+ * Restore renderer adapters that Three's NodeMaterial.clone() cannot copy.
129
+ *
130
+ * `setupLightingModel` is installed as an instance function by each adapter.
131
+ * NodeMaterial.copy() enumerates the destination instance, so that source-only
132
+ * function is silently absent from every cached-template clone unless it is
133
+ * reinstalled here. Materials built through this module run in the ToonLab-authored
134
+ * source stage; ToonLab-derived graphs therefore require the ToonLab-to-TOONLAB Lambert
135
+ * energy / captured-SH boundary rather than the PI-premultiplied ToonLab-stage
136
+ * boundary.
137
+ */
138
+ export function rehydrateToonLabSourceMaterialLighting(material) {
139
+ if (!material?.isNodeMaterial) return material;
140
+ const defaultLitLighting = material.userData?.toonLabSourceDefaultLitLighting;
141
+ if (defaultLitLighting) {
142
+ installToonLabSourceDefaultLitLighting(material);
143
+ }
144
+ const toonLabLighting = material.userData?.toonLabSurfaceLighting;
145
+ if (toonLabLighting) {
146
+ installToonLabSurfaceLighting(material, {
147
+ inputAdapter: 'toonlab-captured-scene-sh',
148
+ workflow: toonLabLighting.workflow,
149
+ });
150
+ }
151
+ if (material.userData?.toonLabSourceSubsurfaceLighting) {
152
+ installToonLabSourceSubsurfaceLighting(material);
153
+ }
154
+ material.userData.toonLabSourceLightingClone = {
155
+ lightingModel: defaultLitLighting
156
+ ? 'toonlab-legacy-default-lit'
157
+ : toonLabLighting
158
+ ? 'toonlab-surface'
159
+ : material.userData?.toonLabSourceSubsurfaceLighting
160
+ ? 'toonlab-legacy-subsurface'
161
+ : null,
162
+ rehydrated: Boolean(
163
+ defaultLitLighting
164
+ || toonLabLighting
165
+ || material.userData?.toonLabSourceSubsurfaceLighting
166
+ ),
167
+ sourceStageInputAdapter: toonLabLighting ? 'toonlab-captured-scene-sh' : null,
168
+ };
169
+ return material;
170
+ }
171
+
172
+ // ToonLab materials use shared sampler sources extensively. The target WebGPU
173
+ // adapter exposes 48 sampled textures but only 16 samplers, while Three's
174
+ // ordinary TextureNode path assigns one sampler binding to every filterable
175
+ // texture. Keep every ToonLab texture and coordinate input, but reproduce bilinear
176
+ // and trilinear filtering with samplerless textureLoad calls. The private
177
+ // texture clones are flagged Nearest/Nearest only to stop Three from allocating
178
+ // unused sampler bindings; filtering still happens below from their original
179
+ // authored sampler state.
180
+ const sourceSamplerlessTextureState = new WeakMap();
181
+ const sourceTextureSampleSamplerless = wgslFn(`
182
+ fn sourceTextureSampleSamplerless(
183
+ sourceTexture: texture_2d<f32>,
184
+ sourceUv: vec2<f32>,
185
+ addressMode: vec2<f32>,
186
+ mipFilterMode: f32,
187
+ maxAnisotropy: f32
188
+ ) -> vec4<f32> {
189
+ let levelCount = textureNumLevels(sourceTexture);
190
+ let maxLevel = f32(levelCount - 1u);
191
+ var lod = 0.0;
192
+ var majorUv = vec2<f32>(0.0);
193
+ var tapCount = 1u;
194
+ if (mipFilterMode > 0.5 && levelCount > 1u) {
195
+ let size0 = vec2<f32>(textureDimensions(sourceTexture, 0u));
196
+ let dx = dpdx(sourceUv * size0);
197
+ let dy = dpdy(sourceUv * size0);
198
+ let dxLength = length(dx);
199
+ let dyLength = length(dy);
200
+ let major = select(dy, dx, dxLength >= dyLength);
201
+ let majorLength = max(dxLength, dyLength);
202
+ let authoredAnisotropy = clamp(maxAnisotropy, 1.0, 8.0);
203
+ let minorLength = max(
204
+ min(dxLength, dyLength),
205
+ majorLength / authoredAnisotropy
206
+ );
207
+ lod = clamp(log2(max(minorLength, 1e-4)), 0.0, maxLevel);
208
+ let anisotropicRatio = clamp(
209
+ majorLength / max(minorLength, 1e-4),
210
+ 1.0,
211
+ authoredAnisotropy
212
+ );
213
+ tapCount = min(8u, u32(ceil(anisotropicRatio)));
214
+ majorUv = major / size0;
215
+ }
216
+
217
+ if (tapCount == 1u) {
218
+ return sourceTextureAtLod(
219
+ sourceTexture,
220
+ sourceUv,
221
+ lod,
222
+ vec2<i32>(addressMode),
223
+ mipFilterMode
224
+ );
225
+ }
226
+
227
+ var accumulated = vec4<f32>(0.0);
228
+ for (var index = 0u; index < 8u; index = index + 1u) {
229
+ if (index < tapCount) {
230
+ let offset = (f32(index) + 0.5) / f32(tapCount) - 0.5;
231
+ accumulated = accumulated + sourceTextureAtLod(
232
+ sourceTexture,
233
+ sourceUv + majorUv * offset,
234
+ lod,
235
+ vec2<i32>(addressMode),
236
+ mipFilterMode
237
+ );
238
+ }
239
+ }
240
+ return accumulated / f32(tapCount);
241
+ }
242
+
243
+ fn sourceTextureAtLod(
244
+ sourceTexture: texture_2d<f32>,
245
+ sourceUv: vec2<f32>,
246
+ lod: f32,
247
+ addressMode: vec2<i32>,
248
+ mipFilterMode: f32
249
+ ) -> vec4<f32> {
250
+ let levelCount = textureNumLevels(sourceTexture);
251
+ if (mipFilterMode > 0.5 && mipFilterMode < 1.5) {
252
+ return sourceTextureBilinear(
253
+ sourceTexture,
254
+ sourceUv,
255
+ u32(round(lod)),
256
+ addressMode
257
+ );
258
+ }
259
+ let lowLevel = u32(floor(lod));
260
+ let highLevel = min(lowLevel + 1u, levelCount - 1u);
261
+ let lowSample = sourceTextureBilinear(
262
+ sourceTexture,
263
+ sourceUv,
264
+ lowLevel,
265
+ addressMode
266
+ );
267
+ if (highLevel == lowLevel) {
268
+ return lowSample;
269
+ }
270
+ let highSample = sourceTextureBilinear(
271
+ sourceTexture,
272
+ sourceUv,
273
+ highLevel,
274
+ addressMode
275
+ );
276
+ return mix(lowSample, highSample, fract(lod));
277
+ }
278
+
279
+ fn sourceTextureBilinear(
280
+ sourceTexture: texture_2d<f32>,
281
+ sourceUv: vec2<f32>,
282
+ mipLevel: u32,
283
+ addressMode: vec2<i32>
284
+ ) -> vec4<f32> {
285
+ let dimensions = vec2<i32>(textureDimensions(sourceTexture, mipLevel));
286
+ let texel = sourceUv * vec2<f32>(dimensions) - vec2<f32>(0.5);
287
+ let base = vec2<i32>(floor(texel));
288
+ let weight = fract(texel);
289
+ let x0 = sourceTextureAddressIndex(base.x, dimensions.x, addressMode.x);
290
+ let x1 = sourceTextureAddressIndex(base.x + 1, dimensions.x, addressMode.x);
291
+ let y0 = sourceTextureAddressIndex(base.y, dimensions.y, addressMode.y);
292
+ let y1 = sourceTextureAddressIndex(base.y + 1, dimensions.y, addressMode.y);
293
+ let a = textureLoad(sourceTexture, vec2<i32>(x0, y0), mipLevel);
294
+ let b = textureLoad(sourceTexture, vec2<i32>(x1, y0), mipLevel);
295
+ let c = textureLoad(sourceTexture, vec2<i32>(x0, y1), mipLevel);
296
+ let d = textureLoad(sourceTexture, vec2<i32>(x1, y1), mipLevel);
297
+ return mix(mix(a, b, weight.x), mix(c, d, weight.x), weight.y);
298
+ }
299
+
300
+ fn sourceTextureAddressIndex(index: i32, size: i32, mode: i32) -> i32 {
301
+ if (mode == 1) {
302
+ return ((index % size) + size) % size;
303
+ }
304
+ if (mode == 2) {
305
+ let period = size * 2;
306
+ let wrapped = ((index % period) + period) % period;
307
+ return select(wrapped, period - wrapped - 1, wrapped >= size);
308
+ }
309
+ return clamp(index, 0, size - 1);
310
+ }
311
+ `);
312
+
313
+ function sourceAddressMode(wrapping) {
314
+ if (wrapping === THREE.RepeatWrapping) return 1;
315
+ if (wrapping === THREE.MirroredRepeatWrapping) return 2;
316
+ return 0;
317
+ }
318
+
319
+ function sourceUsesMipmaps(map) {
320
+ return map.generateMipmaps !== false
321
+ && map.minFilter !== THREE.NearestFilter
322
+ && map.minFilter !== THREE.LinearFilter;
323
+ }
324
+
325
+ function sourceMipFilterMode(map) {
326
+ if (!sourceUsesMipmaps(map)) return 0;
327
+ if (map.minFilter === THREE.LinearMipmapNearestFilter
328
+ || map.minFilter === THREE.NearestMipmapNearestFilter) return 1;
329
+ return 2;
330
+ }
331
+
332
+ function createSamplerlessSourceTexture(map, cloneCache, prepared) {
333
+ if (!map?.isTexture) return map;
334
+ if (cloneCache.has(map)) return cloneCache.get(map);
335
+ const clone = map.clone();
336
+ clone.name = map.name;
337
+ const state = Object.freeze({
338
+ addressMode: Object.freeze([
339
+ sourceAddressMode(map.wrapS),
340
+ sourceAddressMode(map.wrapT),
341
+ ]),
342
+ anisotropy: map.anisotropy,
343
+ magFilter: map.magFilter,
344
+ minFilter: map.minFilter,
345
+ mipFilterMode: sourceMipFilterMode(map),
346
+ });
347
+ clone.minFilter = THREE.NearestFilter;
348
+ clone.magFilter = THREE.NearestFilter;
349
+ clone.anisotropy = 1;
350
+ clone.needsUpdate = true;
351
+ sourceSamplerlessTextureState.set(clone, state);
352
+ cloneCache.set(map, clone);
353
+ prepared.push(clone);
354
+ return clone;
355
+ }
356
+
357
+ function makeSourceTexturesSamplerless(maps, weightPackTextures = []) {
358
+ const cloneCache = new WeakMap();
359
+ const prepared = [];
360
+ for (const [name, map] of Object.entries(maps)) {
361
+ maps[name] = createSamplerlessSourceTexture(map, cloneCache, prepared);
362
+ }
363
+ const packs = weightPackTextures.map((map) =>
364
+ createSamplerlessSourceTexture(map, cloneCache, prepared));
365
+ return { count: prepared.length, packs };
366
+ }
367
+
368
+ function sourceTextureSample(map, coordinates, {
369
+ anisotropic = false,
370
+ } = {}) {
371
+ const samplerlessState = sourceSamplerlessTextureState.get(map);
372
+ if (!samplerlessState) return texture(map).sample(coordinates);
373
+ // WebGPU creates an sRGB texture format for exported ToonLab textures whose
374
+ // metadata says sRGB. Both textureSample and textureLoad therefore return
375
+ // working-linear values from the GPU. Applying colorSpaceToWorking here
376
+ // decoded those values a second time and made the Landscape grass/dirt
377
+ // several stops too dark. Linear mask/normal maps remain NoColorSpace and
378
+ // use the same path without any transfer conversion.
379
+ return sourceTextureSampleSamplerless(
380
+ texture(map),
381
+ coordinates,
382
+ vec2(...samplerlessState.addressMode),
383
+ float(samplerlessState.mipFilterMode),
384
+ float(anisotropic ? samplerlessState.anisotropy : 1),
385
+ );
386
+ }
387
+
388
+ function sourceSceneProfile(profile, sourceAssetName, sourceSceneVariant = null) {
389
+ if (sourceAssetName !== TOONLAB_SHOWCASE_SOURCE_ASSET || !profile) return profile;
390
+ // ToonLab's glTF exporter serializes the static-mesh slot name (`MI_Grass`),
391
+ // while the authored ToonLabShowcase level overrides that slot with the NoRVT
392
+ // instances. Reapply the level override before constructing the browser
393
+ // material so the port uses the same snow colormap and avoids a missing-RVT
394
+ // black fallback.
395
+ const isToonLabShowcaseGrass = profile.family === 'foliage'
396
+ && /MI_Grass(?:_NoRVT)?(?:_LOD[12])?\./.test(profile.path);
397
+ if (!isToonLabShowcaseGrass) return profile;
398
+ // Landscape AutoGrass is authored with MI_Grass itself and intentionally
399
+ // samples the Landscape RVT. Only the manually placed static-mesh foliage
400
+ // in the ToonLabShowcase level uses the NoRVT colormap override below.
401
+ if (sourceSceneVariant === 'landscape-auto-grass') return profile;
402
+ const next = structuredClone(profile);
403
+ next.parameters.texture['Color Map'] = TOONLAB_SHOWCASE_COLORMAP;
404
+ next.parameters.scalar['Grass Colormap Size'] = 50000;
405
+ next.parameters.static_switch['UseColorMap?'] = true;
406
+ next.parameters.static_switch['UseRVTColor?'] = false;
407
+ next.parameters.static_switch['BlendWithLandscape?'] = false;
408
+ next.parameters.static_switch['ShrinkOffgrassFoliage?'] = false;
409
+ return next;
410
+ }
411
+
412
+ function pathName(path) {
413
+ return String(path ?? '').split('.').at(-1)?.split('/').at(-1) ?? '';
414
+ }
415
+
416
+ function linearColor(values, fallback = [1, 1, 1]) {
417
+ const color = Array.isArray(values) ? values : fallback;
418
+ return vec3(color[0] ?? fallback[0], color[1] ?? fallback[1], color[2] ?? fallback[2]);
419
+ }
420
+
421
+ function cheapContrast(value, contrast) {
422
+ return clamp(value.sub(0.5).mul(Number(contrast) + 1).add(0.5), 0, 1);
423
+ }
424
+
425
+ function stableUnit(value) {
426
+ let hash = 2166136261;
427
+ const text = String(value ?? '');
428
+ for (let index = 0; index < text.length; index += 1) {
429
+ hash ^= text.charCodeAt(index);
430
+ hash = Math.imul(hash, 16777619);
431
+ }
432
+ return (hash >>> 0) / 4294967296;
433
+ }
434
+
435
+ function sourceUv(context, channel = 0) {
436
+ if (channel === 2 && context.hasUv2) return uv(2);
437
+ return uv();
438
+ }
439
+
440
+ function toonLabDirection(values, fallback = [0, 0, 1]) {
441
+ const value = Array.isArray(values) ? values : fallback;
442
+ // ToonLab (X,Y,Z) -> Three (X,Z,-Y).
443
+ return normalize(vec3(
444
+ value[0] ?? fallback[0],
445
+ value[2] ?? fallback[2],
446
+ -(value[1] ?? fallback[1]),
447
+ ));
448
+ }
449
+
450
+ function sourceInstanceIdentity(profile, object = null) {
451
+ // ToonLab's glTF export expands foliage instances into separate nodes and
452
+ // does not serialize PerInstanceRandom. Reconstruct it in the uniform's
453
+ // per-object update instead of putting object/instance nodes in a cached
454
+ // graph: those nodes have no bound Object3D on non-instanced glTF meshes
455
+ // during a material-template update and make the first rendered frame fail.
456
+ const world = new THREE.Vector3();
457
+ if (object?.isObject3D) object.getWorldPosition(world);
458
+ const toonLabX = world.x * 100;
459
+ const toonLabY = -world.z * 100;
460
+ const key = `${profile?.path ?? ''}|${object?.name ?? ''}|${toonLabX.toFixed(4)}|${toonLabY.toFixed(4)}`;
461
+ return {
462
+ actorToonLab: [toonLabX, toonLabY],
463
+ random: stableUnit(key),
464
+ };
465
+ }
466
+
467
+ function sourcePerInstanceRandom(profile) {
468
+ const fallback = sourceInstanceIdentity(profile).random;
469
+ return uniform(fallback).onObjectUpdate(
470
+ ({ object }) => sourceInstanceIdentity(profile, object).random,
471
+ );
472
+ }
473
+
474
+ function toonLabHueShift(colorNode, amountNode) {
475
+ // ToonLab's Engine HueShift material function is RotateAboutAxis around
476
+ // normalize(1,1,1), followed by adding the source color. RotateAboutAxis
477
+ // receives turns, not radians, and internally returns the position delta.
478
+ const axis = vec3(1 / Math.sqrt(3));
479
+ const angle = amountNode.mul(Math.PI * 2);
480
+ const cosine = cos(angle);
481
+ const sine = sin(angle);
482
+ return colorNode.mul(cosine)
483
+ .add(cross(axis, colorNode).mul(sine))
484
+ .add(axis.mul(dot(axis, colorNode)).mul(float(1).sub(cosine)));
485
+ }
486
+
487
+ function sourceDesaturate(colorNode, fractionNode) {
488
+ // ToonLabShowcase has r.LegacyLuminanceFactors=1, so ToonLab's Desaturation uses the
489
+ // legacy 0.30/0.59/0.11 luminance vector rather than Rec.709.
490
+ const grey = dot(colorNode, vec3(0.3, 0.59, 0.11));
491
+ return mix(colorNode, vec3(grey), fractionNode);
492
+ }
493
+
494
+ function sourceScreen(baseNode, blendNode) {
495
+ return vec3(1).sub(
496
+ vec3(1).sub(baseNode).mul(vec3(1).sub(blendNode)),
497
+ );
498
+ }
499
+
500
+ function sourceOverlay(baseNode, blendNode) {
501
+ const low = baseNode.mul(blendNode).mul(2);
502
+ const high = vec3(1).sub(
503
+ vec3(1).sub(baseNode).mul(vec3(1).sub(blendNode)).mul(2),
504
+ );
505
+ return mix(low, high, step(vec3(0.5), baseNode));
506
+ }
507
+
508
+ function linearRemap(valueNode, inputLow, inputHigh, outputLow = 0, outputHigh = 1) {
509
+ return valueNode
510
+ .sub(inputLow)
511
+ .div(Number(inputHigh) - Number(inputLow))
512
+ .mul(Number(outputHigh) - Number(outputLow))
513
+ .add(outputLow);
514
+ }
515
+
516
+ function rotateSourceUv(coordinates, turnsNode, center = vec2(0.5)) {
517
+ const angle = turnsNode.mul(Math.PI * 2);
518
+ const angleCos = cos(angle);
519
+ const angleSin = sin(angle);
520
+ const centered = coordinates.sub(center);
521
+ return vec2(
522
+ centered.x.mul(angleCos).sub(centered.y.mul(angleSin)),
523
+ centered.x.mul(angleSin).add(centered.y.mul(angleCos)),
524
+ ).add(center);
525
+ }
526
+
527
+ function sourcePixelDepthCm() {
528
+ return positionView.z.negate().mul(100);
529
+ }
530
+
531
+ function sourceHueShiftAmount(profile, object = null, sourceActorIdentity = null) {
532
+ const variation = scalar(profile, 'Hue Variation', 0);
533
+ const shift = scalar(profile, 'Hue Shift', 0);
534
+ const identity = sourceActorIdentity
535
+ ? {
536
+ actorToonLab: [
537
+ Number(sourceActorIdentity.locationCm?.[0]) || 0,
538
+ Number(sourceActorIdentity.locationCm?.[1]) || 0,
539
+ ],
540
+ random: Number(sourceActorIdentity.perInstanceRandom) || 0,
541
+ }
542
+ : sourceInstanceIdentity(profile, object);
543
+ const [toonLabX, toonLabY] = identity.actorToonLab;
544
+ const rawSeed = identity.random + toonLabX * 0.713145 + toonLabY * 0.713145;
545
+ const seed = ((rawSeed % 1) + 1) % 1;
546
+ const wave = Math.sin(seed * Math.PI * 2);
547
+ const signedCube = wave * Math.abs(wave) * Math.abs(wave);
548
+ return signedCube * variation + shift;
549
+ }
550
+
551
+ function sourceHueVariance(colorNode, profile, sourceActorIdentity = null) {
552
+ const variation = scalar(profile, 'Hue Variation', 0);
553
+ const shift = scalar(profile, 'Hue Shift', 0);
554
+ if (variation === 0 && shift === 0) return colorNode;
555
+ const hueAmount = uniform(sourceHueShiftAmount(
556
+ profile,
557
+ null,
558
+ sourceActorIdentity,
559
+ )).onObjectUpdate(
560
+ ({ object }) => sourceHueShiftAmount(profile, object, sourceActorIdentity),
561
+ );
562
+ return toonLabHueShift(colorNode, hueAmount);
563
+ }
564
+
565
+ function lerpFive(a, b, c, d, e, timeNode) {
566
+ const x = fract(timeNode).mul(4);
567
+ let result = mix(a, b, clamp(x, 0, 1));
568
+ result = mix(result, c, clamp(x.sub(1), 0, 1));
569
+ result = mix(result, d, clamp(x.sub(2), 0, 1));
570
+ return mix(result, e, clamp(x.sub(3), 0, 1));
571
+ }
572
+
573
+ function applyDayCycleEmission(inputNode, profile, state) {
574
+ if (!switchValue(profile, 'UseDayCycleEmission?', true)) return inputNode;
575
+ const day = scalar(profile, 'Day Emission Multiplier', 1);
576
+ const cycle = lerpFive(
577
+ day,
578
+ scalar(profile, 'Sunset Emission Multiplier', 0.1),
579
+ scalar(profile, 'Night Emission Multiplier', 0),
580
+ scalar(profile, 'Sunrise Emission Multiplier', 0.1),
581
+ day,
582
+ state.uniforms.dayCycleProgress,
583
+ );
584
+ if (!switchValue(profile, 'UseWeather?', true)) return inputNode.mul(cycle);
585
+ return inputNode.mul(mix(
586
+ cycle,
587
+ scalar(profile, 'Overcast Emission Multiplier', 0.25),
588
+ clamp(state.uniforms.overcast, 0, 1),
589
+ ));
590
+ }
591
+
592
+ function sourceEmission(colorNode, profile, state, emissiveMapNode = null) {
593
+ let inputNode = colorNode.mul(scalar(profile, 'Emissive Strength', 0));
594
+ const useEmissiveMap = switchValue(
595
+ profile,
596
+ 'Emissive Map?',
597
+ switchValue(profile, 'EmissiveMap?', false),
598
+ );
599
+ if (emissiveMapNode && useEmissiveMap) {
600
+ inputNode = inputNode.mul(emissiveMapNode.rgb);
601
+ }
602
+ return applyDayCycleEmission(inputNode, profile, state);
603
+ }
604
+
605
+ function sourceTemporalDither(amountNode, state) {
606
+ return toonLabSourceDitherTemporalAA(clamp(amountNode, 0, 1), state);
607
+ }
608
+
609
+ function sourceToonLabWorldXY(worldOffsetToonLabMeters = null) {
610
+ if (worldOffsetToonLabMeters) {
611
+ // The parity contract uses canonical metres (x,y,z), which Three renders
612
+ // as (x,y,-z). ToonLab receives the canonical basis as (z,x,y), so the
613
+ // retained Landscape horizontal basis is ToonLab X/Y = (-Three Z, Three X).
614
+ return vec2(positionWorld.z.negate(), positionWorld.x).add(vec2(
615
+ Number(worldOffsetToonLabMeters[0]) || 0,
616
+ Number(worldOffsetToonLabMeters[1]) || 0,
617
+ ));
618
+ }
619
+ // Ordinary glTF source meshes retain ToonLab (X,Y) -> Three (X,-Z).
620
+ return vec2(positionWorld.x, positionWorld.z.negate());
621
+ }
622
+
623
+ function planarAtToonLabWorldXY(map, sourceWorld, scaleMeters, offset = null) {
624
+ const scale = max(float(Math.max(Number(scaleMeters) || 1, 0.001)), 0.001);
625
+ let coordinates = sourceWorld.div(scale);
626
+ if (offset) coordinates = coordinates.add(vec2(offset[0] ?? 0, offset[1] ?? 0));
627
+ return sourceTextureSample(map, coordinates);
628
+ }
629
+
630
+ function planar(map, scaleMeters, offset = null) {
631
+ return planarAtToonLabWorldXY(map, sourceToonLabWorldXY(), scaleMeters, offset);
632
+ }
633
+
634
+ function planarCentered(
635
+ map,
636
+ scaleXMeters,
637
+ scaleYMeters,
638
+ offsetX = 0,
639
+ offsetY = 0,
640
+ worldOffsetToonLabMeters = null,
641
+ ) {
642
+ const scale = vec2(
643
+ Math.max(Number(scaleXMeters) || 1, 0.001),
644
+ Math.max(Number(scaleYMeters) || 1, 0.001),
645
+ );
646
+ const sourceWorld = sourceToonLabWorldXY(worldOffsetToonLabMeters);
647
+ const coordinates = sourceWorld.div(scale).add(
648
+ vec2(0.5 + Number(offsetX || 0), 0.5 + Number(offsetY || 0)),
649
+ );
650
+ return sourceTextureSample(map, coordinates);
651
+ }
652
+
653
+ function landscapeLayerCoordinates(
654
+ sourceAssetName,
655
+ record = null,
656
+ worldOffsetToonLabMeters = null,
657
+ ) {
658
+ const sourceContract = sourceAssetName === TOONLAB_SHOWCASE_SOURCE_ASSET
659
+ ? TOONLAB_SHOWCASE_WEIGHTMAP_CONTRACT
660
+ : null;
661
+ const originCm = record?.originCm ?? sourceContract?.originCm ?? [0, 0];
662
+ const quadScaleCm = record?.quadScaleCm ?? sourceContract?.quadScaleCm ?? [100, 100];
663
+ // Canonical metres map to ToonLab centimetres as (z,x,y). Three renders
664
+ // canonical Z with the opposite sign, therefore the retained Landscape
665
+ // horizontal basis is ToonLab X/Y = (-Three Z, Three X).
666
+ const toonLabWorldMeters = sourceToonLabWorldXY(worldOffsetToonLabMeters);
667
+ const toonLabWorldCm = toonLabWorldMeters.mul(100);
668
+ return toonLabWorldCm
669
+ .sub(vec2(originCm[0], originCm[1]))
670
+ .div(vec2(quadScaleCm[0], quadScaleCm[1]));
671
+ }
672
+
673
+ function landscapeWindColor(profile, state, maps, sourceWorld = sourceToonLabWorldXY()) {
674
+ if (!switchValue(profile, 'UseWindColor?', false)
675
+ || !maps['Wind Color Noise']
676
+ || !maps['Wind Color Mask']) {
677
+ return float(0);
678
+ }
679
+ const windSize = Math.max(scalar(profile, 'Wind Size', 8000) / 100, 0.001);
680
+ const worldUv = sourceWorld.div(windSize);
681
+ const rotated = rotateSourceUv(worldUv, state.uniforms.windAngle);
682
+ const speed = state.uniforms.windSpeed;
683
+ const noiseUv = rotated.add(vec2(
684
+ state.uniforms.time.mul(speed).mul(0.04),
685
+ 0,
686
+ ));
687
+ const maskSize = scalar(profile, 'Mask Size', 1.5);
688
+ const maskUv = rotated
689
+ .mul(vec2(maskSize, maskSize * 0.6))
690
+ .add(vec2(
691
+ state.uniforms.time.mul(speed).mul(0.06),
692
+ state.uniforms.time.mul(speed).mul(0.02),
693
+ ));
694
+ return sourceTextureSample(maps['Wind Color Noise'], noiseUv).r
695
+ .mul(sourceTextureSample(maps['Wind Color Mask'], maskUv).r)
696
+ .mul(scalar(profile, 'Wind Mask Multiply', 3))
697
+ .mul(clamp(state.uniforms.time, 0, 1));
698
+ }
699
+
700
+ function snowDayWeatherFactor(profile, state) {
701
+ if (!switchValue(profile, 'SnowDayAndWeather?', true)) return float(1);
702
+ const day = lerpFive(1, 0.4, 0.1, 0.4, 1, state.uniforms.dayCycleProgress);
703
+ return mix(day, 0, clamp(state.uniforms.overcast, 0, 1));
704
+ }
705
+
706
+ function snowSparkleLayer(profile, state, maps, {
707
+ brightnessName,
708
+ rotationName,
709
+ scaleName,
710
+ }) {
711
+ if (!maps.sparkleChroma || !maps.sparkleMask) return vec3(0);
712
+ const scaleCm = Math.max(scalar(profile, scaleName, 1600), 0.001);
713
+ const scaleMeters = scaleCm / 100;
714
+ const rotation = float(scalar(profile, rotationName, 0));
715
+ const worldXY = vec2(positionWorld.x, positionWorld.z.negate());
716
+ const rotated = switchValue(profile, 'NeedWorldRotation?', true)
717
+ ? rotateSourceUv(worldXY, rotation, vec2(0))
718
+ : worldXY;
719
+
720
+ const chroma = sourceTextureSample(maps.sparkleChroma, rotated.div(scaleMeters)).rgb;
721
+ const sparkleDirection = normalize(chroma.sub(0.5));
722
+ const cameraVector = normalize(cameraPosition.sub(positionWorld));
723
+ const facing = dot(cameraVector, sparkleDirection);
724
+ let sparkleSignal = abs(facing);
725
+ if (!switchValue(profile, 'SimpleSparkle?', false)) {
726
+ const speed = Math.max(scalar(profile, 'Snow Twinkle Speed', 1), 0.001);
727
+ const period = 1 / speed;
728
+ const wave = mod(
729
+ facing.add(9999).sub(period / 4),
730
+ period,
731
+ ).sub(period);
732
+ // This is the exported non-simple triangle-wave branch: the final
733
+ // Subtract node is (4 / period * abs(wave)) - 1, before tolerance remap.
734
+ sparkleSignal = abs(wave).mul(4 / period).sub(1);
735
+ }
736
+ const tolerance = scalar(profile, 'Snow Twinkle Tolerance', 0.95);
737
+ const angleMask = clamp(linearRemap(sparkleSignal, tolerance, 1), 0, 1);
738
+
739
+ const sphere = sourceTextureSample(
740
+ maps.sparkleMask,
741
+ rotated.div(scaleMeters / 256),
742
+ ).r;
743
+ let sphereMask = sphere;
744
+ if (switchValue(profile, 'SparklShrinkNear?', true)) {
745
+ const shrinkAmount = scalar(profile, 'Snow Sparkle Shrink Amount', 0.3);
746
+ const shrinkThreshold = clamp(linearRemap(
747
+ sourcePixelDepthCm(),
748
+ scalar(profile, 'Snow Sparkle Shrink Near Distance', 500),
749
+ scalar(profile, 'Snow Shrink Far Distance', 1500),
750
+ shrinkAmount,
751
+ 0,
752
+ ), 0, shrinkAmount);
753
+ sphereMask = clamp(
754
+ sphere.sub(shrinkThreshold).div(max(float(1).sub(shrinkThreshold), 0.0001)),
755
+ 0,
756
+ 1,
757
+ );
758
+ }
759
+
760
+ // The active source branch uses a volume-noise texture for additional
761
+ // intensity variance. That VolumeTexture is not present in the supplied
762
+ // browser manifest, so the only non-invented fallback is neutral variance.
763
+ const topFacing = switchValue(profile, 'SparkleProject3D?', false)
764
+ ? float(1)
765
+ : clamp(linearRemap(normalWorldGeometry.y, 0.2, 0.5), 0, 1);
766
+ let intensity = angleMask
767
+ .mul(sphereMask)
768
+ .mul(topFacing)
769
+ .mul(scalar(profile, brightnessName, 20));
770
+
771
+ if (switchValue(profile, 'SparkleDayAndWeather?', true)) {
772
+ const day = lerpFive(1, 0.3, 0.3, 0.3, 1, state.uniforms.dayCycleProgress);
773
+ const weather = mix(1, 0.75, clamp(state.uniforms.overcast, 0, 1));
774
+ intensity = intensity.mul(day).mul(weather);
775
+ }
776
+ const distanceFade = clamp(linearRemap(
777
+ sourcePixelDepthCm(),
778
+ scalar(profile, 'Snow Sparkle Fade Start', 200),
779
+ scalar(profile, 'Snow Sparkle Fade End', 2500),
780
+ 1,
781
+ 0,
782
+ ), 0, 1);
783
+ return linearColor(vector(profile, 'Snow Sparkle Color', [0.627031, 0.663767, 1]))
784
+ .mul(intensity)
785
+ .mul(distanceFade);
786
+ }
787
+
788
+ function snowSparkle(profile, state, maps) {
789
+ if (!switchValue(profile, 'SnowSparkle?', true)) return vec3(0);
790
+ let result = snowSparkleLayer(profile, state, maps, {
791
+ brightnessName: 'Snow Sparkle Brightness',
792
+ rotationName: 'Snow Sparkle Rotation',
793
+ scaleName: 'Snow Sparkle Scale',
794
+ });
795
+ if (switchValue(profile, 'SnowSparkleDualLayer?', true)) {
796
+ result = result.add(snowSparkleLayer(profile, state, maps, {
797
+ brightnessName: 'Snow Sparkle 2 Brightness',
798
+ rotationName: 'Snow Sparkle 2 Rotation',
799
+ scaleName: 'Snow Sparkle 2 Scale',
800
+ }));
801
+ }
802
+ return result;
803
+ }
804
+
805
+ function buildSnowNodes(profile, state, maps) {
806
+ const colorNode = planar(
807
+ maps['Snow Texture'],
808
+ scalar(profile, 'Snow Scale', 5000) / 100,
809
+ ).rgb;
810
+ const specularNoise = maps.snowSpecular
811
+ ? planar(
812
+ maps.snowSpecular,
813
+ scalar(profile, 'Snow Specular Scale', 75) / 100,
814
+ ).r
815
+ : float(0.5);
816
+ const specularNode = mix(
817
+ scalar(profile, 'Snow Spec Min', 0.1),
818
+ scalar(profile, 'Snow Spec Max', 0.3),
819
+ specularNoise,
820
+ );
821
+ const emissiveNode = colorNode
822
+ .mul(scalar(profile, 'Snow Emission', 0.05))
823
+ .mul(snowDayWeatherFactor(profile, state))
824
+ .add(snowSparkle(profile, state, maps));
825
+ return {
826
+ colorNode,
827
+ emissiveNode,
828
+ metalnessNode: float(0),
829
+ roughnessNode: float(scalar(profile, 'Snow Rough', 0.5)),
830
+ specularNode,
831
+ };
832
+ }
833
+
834
+ function sourceProfileCastsShadow(profile) {
835
+ // ToonLab's grass prefabs explicitly disable cast shadows on every LOD. Other
836
+ // families retain their scene/component shadow metadata.
837
+ return toonLabGrassCastsShadow(profile);
838
+ }
839
+
840
+ function triplanar(map, scaleMeters, {
841
+ contrast = 4,
842
+ normalNode = normalWorld,
843
+ sideOnly = false,
844
+ } = {}) {
845
+ const scale = max(float(Math.max(Number(scaleMeters) || 1, 0.001)), 0.001);
846
+ const projectionPower = Math.max(Number(contrast) || 0, 0.0001);
847
+ const weights = pow(abs(normalNode), vec3(projectionPower));
848
+ const weightX = weights.x;
849
+ const weightY = sideOnly ? float(0) : weights.y;
850
+ const weightZ = weights.z;
851
+ const weightSum = max(weightX.add(weightY).add(weightZ), 0.0001);
852
+ return sourceTextureSample(
853
+ map,
854
+ vec2(positionWorld.z.negate(), positionWorld.y).div(scale),
855
+ ).mul(weightX)
856
+ .add(sourceTextureSample(
857
+ map,
858
+ vec2(positionWorld.x, positionWorld.z.negate()).div(scale),
859
+ ).mul(weightY))
860
+ .add(sourceTextureSample(map, positionWorld.xy.div(scale)).mul(weightZ))
861
+ .div(weightSum);
862
+ }
863
+
864
+ function unpackSourceNormal(sampleNode) {
865
+ // ToonLab normal textures use the DirectX (+Y) convention. Source PNGs are
866
+ // loaded without a vertical flip, so invert green before basis conversion.
867
+ return vec3(
868
+ sampleNode.r.mul(2).sub(1),
869
+ float(1).sub(sampleNode.g.mul(2)),
870
+ sampleNode.b.mul(2).sub(1),
871
+ );
872
+ }
873
+
874
+ function sourceWorldAlignedNormal(map, scaleMeters, {
875
+ contrast = 3,
876
+ flatTop = false,
877
+ sideOnly = false,
878
+ } = {}) {
879
+ const scale = max(float(Math.max(Number(scaleMeters) || 1, 0.001)), 0.001);
880
+ const projectionPower = Math.max(Number(contrast) || 0, 0.0001);
881
+ const weights = pow(abs(normalWorldGeometry), vec3(projectionPower));
882
+ const weightX = weights.x;
883
+ const weightY = sideOnly ? float(0) : weights.y;
884
+ const weightZ = weights.z;
885
+ const weightSum = max(weightX.add(weightY).add(weightZ), 0.0001);
886
+
887
+ const sampleX = unpackSourceNormal(
888
+ sourceTextureSample(
889
+ map,
890
+ vec2(positionWorld.z.negate(), positionWorld.y).div(scale),
891
+ ).rgb,
892
+ );
893
+ const sampleY = unpackSourceNormal(
894
+ sourceTextureSample(
895
+ map,
896
+ vec2(positionWorld.x, positionWorld.z.negate()).div(scale),
897
+ ).rgb,
898
+ );
899
+ const sampleZ = unpackSourceNormal(
900
+ sourceTextureSample(map, positionWorld.xy.div(scale)).rgb,
901
+ );
902
+ const signX = sign(normalWorldGeometry.x);
903
+ const signY = sign(normalWorldGeometry.y);
904
+ const signZ = sign(normalWorldGeometry.z);
905
+ const normalX = vec3(
906
+ sampleX.z.mul(signX),
907
+ sampleX.y,
908
+ sampleX.x.negate().mul(signX),
909
+ );
910
+ const projectedY = vec3(
911
+ sampleY.x.mul(signY),
912
+ sampleY.z.mul(signY),
913
+ sampleY.y.negate(),
914
+ );
915
+ const normalY = flatTop ? vec3(0, signY, 0) : projectedY;
916
+ const normalZ = vec3(
917
+ sampleZ.x.mul(signZ),
918
+ sampleZ.y,
919
+ sampleZ.z.mul(signZ),
920
+ );
921
+ return normalize(
922
+ normalX.mul(weightX)
923
+ .add(normalY.mul(weightY))
924
+ .add(normalZ.mul(weightZ))
925
+ .div(weightSum),
926
+ );
927
+ }
928
+
929
+ function wetSurface(colorNode, roughnessNode, profile, state) {
930
+ if (!switchValue(profile, 'UseWeather?', true)
931
+ || !switchValue(profile, 'RainWetness?', true)) {
932
+ return { colorNode, roughnessNode };
933
+ }
934
+ const wet = clamp(state.uniforms.rainWetness, 0, 1);
935
+ const darkening = scalar(profile, 'Puddle Darkening', 0.18);
936
+ const desaturation = scalar(profile, 'Puddle Desaturation', 0);
937
+ const wetColor = sourceDesaturate(
938
+ colorNode,
939
+ wet.mul(desaturation),
940
+ ).mul(float(1).sub(wet.mul(Math.min(darkening, 0.85))));
941
+ return {
942
+ colorNode: wetColor,
943
+ roughnessNode: mix(
944
+ roughnessNode,
945
+ scalar(profile, 'Wet Roughness', 0.3),
946
+ wet,
947
+ ),
948
+ };
949
+ }
950
+
951
+ function configureSourceSubsurface(material, colorNode, opacityNode, {
952
+ thinCardTransmissionFallback = false,
953
+ } = {}) {
954
+ // Keep the ToonLab graph inputs exact and isolate renderer translation here.
955
+ // The thickness fields remain populated for graph inspection/backward
956
+ // compatibility, but the installed lighting model evaluates ToonLab's
957
+ // MSM_SUBSURFACE direct and front/back SkyLight equations instead of Three's
958
+ // unrelated experimental half-vector thickness lobe.
959
+ material.thicknessColorNode = colorNode;
960
+ material.thicknessAttenuationNode = clamp(opacityNode, 0, 1);
961
+ material.thicknessDistortionNode = float(0.1);
962
+ material.thicknessAmbientNode = float(0);
963
+ material.thicknessPowerNode = float(2);
964
+ material.thicknessScaleNode = float(10);
965
+ return installToonLabSourceSubsurfaceLighting(material, {
966
+ subsurfaceColorNode: colorNode,
967
+ subsurfaceOpacityNode: clamp(opacityNode, 0, 1),
968
+ thinCardTransmissionFallback,
969
+ });
970
+ }
971
+
972
+ function configureLeafSubsurface(
973
+ material,
974
+ colorNode,
975
+ profile,
976
+ state,
977
+ textureColorNode = vec3(1),
978
+ { thinCardTransmissionFallback = false } = {},
979
+ ) {
980
+ const colorCycle = lerpFive(1, 0.5, 0.4, 0.5, 1, state.uniforms.dayCycleProgress);
981
+ const opacityCycle = lerpFive(1, 2, 3, 2, 1, state.uniforms.dayCycleProgress);
982
+ return configureSourceSubsurface(
983
+ material,
984
+ colorNode
985
+ .mul(textureColorNode)
986
+ .mul(scalar(profile, 'SS Strength', 0.3))
987
+ .mul(colorCycle),
988
+ float(scalar(profile, 'SS Opacity', 0.08)).mul(opacityCycle),
989
+ { thinCardTransmissionFallback },
990
+ );
991
+ }
992
+
993
+ function configureFoliageSubsurface(
994
+ material,
995
+ colorNode,
996
+ profile,
997
+ { thinCardTransmissionFallback = false } = {},
998
+ ) {
999
+ return configureSourceSubsurface(
1000
+ material,
1001
+ colorNode.mul(scalar(profile, 'SS Strength', 0.3)),
1002
+ float(scalar(profile, 'SS Opacity', 0.08)),
1003
+ { thinCardTransmissionFallback },
1004
+ );
1005
+ }
1006
+
1007
+ function windOffset(profile, state, {
1008
+ sway = false,
1009
+ weight = uv().y,
1010
+ } = {}) {
1011
+ const enabled = switchValue(profile, 'UseWind?', false)
1012
+ || (sway && switchValue(profile, 'Tree Sway?', false));
1013
+ if (!enabled) return vec3(0);
1014
+ const direction = vec2(
1015
+ cos(state.uniforms.windAngle.mul(Math.PI * 2)),
1016
+ sin(state.uniforms.windAngle.mul(Math.PI * 2)),
1017
+ );
1018
+ const localPhase = positionLocal.x.mul(0.17).add(positionLocal.z.mul(0.13));
1019
+ const phase = state.uniforms.time
1020
+ .mul(state.uniforms.windSpeed)
1021
+ .mul(scalar(profile, 'Wind Speed', 0.5))
1022
+ .mul(Math.PI * 2)
1023
+ .add(localPhase);
1024
+ const flutter = sin(phase).mul(0.7).add(sin(phase.mul(1.71).add(1.3)).mul(0.3));
1025
+ const amplitude = scalar(profile, 'Wind Intensity', 0.8)
1026
+ * scalar(profile, 'Wind Weight', 0.25)
1027
+ / 100;
1028
+ let offset = vec3(direction.x, 0, direction.y)
1029
+ .mul(flutter)
1030
+ .mul(state.uniforms.windIntensity)
1031
+ .mul(amplitude)
1032
+ .mul(clamp(weight, 0, 1));
1033
+ if (sway && switchValue(profile, 'Tree Sway?', false)) {
1034
+ const swayPhase = state.uniforms.time.mul(state.uniforms.swaySpeed).add(localPhase.mul(0.35));
1035
+ const swayAmount = state.uniforms.swayLean
1036
+ .mul(scalar(profile, 'Sway Intensity Multiplier', 1))
1037
+ .div(100);
1038
+ offset = offset.add(
1039
+ vec3(direction.x, 0, direction.y)
1040
+ .mul(sin(swayPhase))
1041
+ .mul(swayAmount)
1042
+ .mul(clamp(weight, 0, 1)),
1043
+ );
1044
+ }
1045
+ return offset;
1046
+ }
1047
+
1048
+ function foliageWindColor(profile, state, maps) {
1049
+ if (!switchValue(profile, 'UseWindColor?', false)
1050
+ || !maps['Wind Color Noise']
1051
+ || !maps['Wind Color Mask']) {
1052
+ return float(0);
1053
+ }
1054
+ const windSize = Math.max(scalar(profile, 'Wind Size', 8000) / 100, 0.001);
1055
+ const world = sourceToonLabWorldXY(state.userData?.worldOffsetToonLabMeters).div(windSize);
1056
+ const angle = state.uniforms.windAngle.mul(Math.PI * 2);
1057
+ const angleCos = cos(angle);
1058
+ const angleSin = sin(angle);
1059
+ const rotated = vec2(
1060
+ world.x.mul(angleCos).sub(world.y.mul(angleSin)),
1061
+ world.x.mul(angleSin).add(world.y.mul(angleCos)),
1062
+ );
1063
+ const speed = state.uniforms.windSpeed;
1064
+ const noiseUv = rotated.add(vec2(
1065
+ state.uniforms.time.mul(speed).mul(0.04),
1066
+ state.uniforms.time.mul(speed).mul(0.04),
1067
+ ));
1068
+ const maskSize = scalar(profile, 'Mask Size', 1.5);
1069
+ const maskUv = rotated
1070
+ .mul(vec2(maskSize, maskSize * 0.6))
1071
+ .add(vec2(
1072
+ state.uniforms.time.mul(speed).mul(0.06),
1073
+ state.uniforms.time.mul(speed).mul(0.02),
1074
+ ));
1075
+ const noise = sourceTextureSample(maps['Wind Color Noise'], noiseUv).r;
1076
+ const mask = sourceTextureSample(maps['Wind Color Mask'], maskUv).r;
1077
+ return noise
1078
+ .mul(mask)
1079
+ .mul(scalar(profile, 'Wind Mask Multiply', 3))
1080
+ .mul(clamp(state.uniforms.time, 0, 1));
1081
+ }
1082
+
1083
+ function finalizeMaterial(material, profile, family) {
1084
+ material.name = `Source::${pathName(profile.path)}`;
1085
+ // The supplied sky and cloud domes are ordinary ToonLab surfaces with
1086
+ // IsSky=false. They participate in the level's exponential-height fog just
1087
+ // like the other source materials.
1088
+ material.fog = true;
1089
+ material.userData.environmentShaderExclude = true;
1090
+ material.userData.toonLabSource = {
1091
+ family,
1092
+ materialPath: profile.path,
1093
+ reconstruction: 'source-profile',
1094
+ };
1095
+ return material;
1096
+ }
1097
+
1098
+ function setShaderSwipeBaseline(material, {
1099
+ alphaTestNode = null,
1100
+ colorNode = null,
1101
+ opacityNode = null,
1102
+ } = {}) {
1103
+ // Keep comparison-only nodes out of NodeMaterial properties. Three/WebGPU
1104
+ // discovers arbitrary `*Node` fields while compiling a material; attaching
1105
+ // the raw baseline there makes the active P17 graph compile those extra
1106
+ // texture bindings too. A WeakMap keeps the diagnostic completely inert
1107
+ // until Live Preview explicitly asks for it.
1108
+ registerSurfaceMaterialMode(material, SURFACE_MATERIAL_MODE.neutralLit, {
1109
+ alphaTestNode,
1110
+ colorNode,
1111
+ keepsLighting: true,
1112
+ keepsTextures: true,
1113
+ opacityNode,
1114
+ vertexDeformation: false,
1115
+ });
1116
+ registerSurfaceMaterialMode(material, SURFACE_MATERIAL_MODE.rawTexture, {
1117
+ alphaTestNode,
1118
+ colorNode,
1119
+ keepsLighting: false,
1120
+ keepsTextures: true,
1121
+ opacityNode,
1122
+ vertexDeformation: false,
1123
+ });
1124
+ material.userData.shaderSwipeBaseline = {
1125
+ alpha: Boolean(opacityNode),
1126
+ mode: 'neutral-standard-lit-texture',
1127
+ vertexDeformation: false,
1128
+ };
1129
+ return material;
1130
+ }
1131
+
1132
+ export function resolveToonLabShaderSwipeBaseline(material) {
1133
+ return resolveSurfaceMaterialMode(
1134
+ material,
1135
+ SURFACE_MATERIAL_MODE.neutralLit,
1136
+ );
1137
+ }
1138
+
1139
+ function recordSourceContract(material, contract) {
1140
+ material.userData.toonLabSource.contract = contract;
1141
+ return material;
1142
+ }
1143
+
1144
+ function createStateUniforms(snapshot) {
1145
+ const scalarValue = (name, fallback) => Number.isFinite(snapshot.scalars[name])
1146
+ ? snapshot.scalars[name] : fallback;
1147
+ const vectorValue = (name, fallback) => snapshot.vectors[name] ?? fallback;
1148
+ const sun = vectorValue('Sun Light Direction', [0.35, 0.8, 0.4, 1]);
1149
+ const moon = vectorValue('Moon Light Direction', [-0.35, 0.6, -0.5, 1]);
1150
+ return {
1151
+ currentTime: uniform(scalarValue('Current Time', 0)),
1152
+ dayCycleProgress: uniform(scalarValue('Day Cycle Progress', 0)),
1153
+ dayLength: uniform(scalarValue('Day Length', 500)),
1154
+ moonDirection: uniform(new THREE.Vector3(moon[0], moon[2], -moon[1]).normalize()),
1155
+ nightLength: uniform(scalarValue('Night Length', 500)),
1156
+ overcast: uniform(scalarValue('Overcast', 0)),
1157
+ rainPuddles: uniform(scalarValue('Rain Puddles', 0)),
1158
+ rainStrength: uniform(scalarValue('Rain Strength', 0)),
1159
+ rainWetness: uniform(scalarValue('Rain Wetness', 0)),
1160
+ skyColor: uniform(new THREE.Color(0.45, 0.62, 0.9)),
1161
+ snowCover: uniform(0),
1162
+ sunDirection: uniform(new THREE.Vector3(sun[0], sun[1], sun[2]).normalize()),
1163
+ sunColor: uniform(new THREE.Color(1, 0.9, 0.72)),
1164
+ swayDamping: uniform(scalarValue('Global Sway Damping', 0.5)),
1165
+ swayLean: uniform(scalarValue('Global Sway Lean', 3)),
1166
+ swaySpeed: uniform(scalarValue('Global Sway Speed', 0.25)),
1167
+ time: uniform(scalarValue('Current Time', 0)),
1168
+ weatherAtmosphereMix: uniform(scalarValue('Weather Atmosphere Mix', 0)),
1169
+ windAngle: uniform(scalarValue('Global Wind Angle', 0.2)),
1170
+ windIntensity: uniform(scalarValue('Global Wind Intensity', 1.2)),
1171
+ windSpeed: uniform(scalarValue('Global Wind Speed', 1)),
1172
+ };
1173
+ }
1174
+
1175
+ export function createToonLabSourceEnvironmentState(library, overrides = {}) {
1176
+ const snapshot = library.createGlobalParameterSnapshot(overrides);
1177
+ const uniforms = createStateUniforms(snapshot);
1178
+ uniforms.temporalSampleIndex = uniform(
1179
+ Number.isFinite(overrides.temporalSampleIndex)
1180
+ ? Math.max(0, Math.trunc(overrides.temporalSampleIndex))
1181
+ : 0,
1182
+ );
1183
+ return {
1184
+ snapshot,
1185
+ temporal: {
1186
+ ditherNoiseTexture: overrides.temporalDitherNoiseTexture ?? null,
1187
+ },
1188
+ uniforms,
1189
+ };
1190
+ }
1191
+
1192
+ export function updateToonLabSourceEnvironmentState(state, values = {}) {
1193
+ const u = state?.uniforms;
1194
+ if (!u) return state;
1195
+ const numbers = {
1196
+ currentTime: 'currentTime',
1197
+ dayCycleProgress: 'dayCycleProgress',
1198
+ dayLength: 'dayLength',
1199
+ nightLength: 'nightLength',
1200
+ overcast: 'overcast',
1201
+ rainPuddles: 'rainPuddles',
1202
+ rainStrength: 'rainStrength',
1203
+ rainWetness: 'rainWetness',
1204
+ snowCover: 'snowCover',
1205
+ swayDamping: 'swayDamping',
1206
+ swayLean: 'swayLean',
1207
+ swaySpeed: 'swaySpeed',
1208
+ temporalSampleIndex: 'temporalSampleIndex',
1209
+ time: 'time',
1210
+ weatherAtmosphereMix: 'weatherAtmosphereMix',
1211
+ windAngle: 'windAngle',
1212
+ windIntensity: 'windIntensity',
1213
+ windSpeed: 'windSpeed',
1214
+ };
1215
+ for (const [input, slot] of Object.entries(numbers)) {
1216
+ if (Number.isFinite(values[input])) u[slot].value = values[input];
1217
+ }
1218
+ if (values.sunDirection) {
1219
+ const direction = values.sunDirection;
1220
+ u.sunDirection.value.set(
1221
+ direction.x ?? direction[0] ?? 0,
1222
+ direction.y ?? direction[1] ?? 1,
1223
+ direction.z ?? direction[2] ?? 0,
1224
+ ).normalize();
1225
+ }
1226
+ if (values.sunColor) u.sunColor.value.copy(values.sunColor);
1227
+ if (values.skyColor) u.skyColor.value.copy(values.skyColor);
1228
+ if (values.moonDirection) {
1229
+ const direction = values.moonDirection;
1230
+ u.moonDirection.value.set(
1231
+ direction.x ?? direction[0] ?? 0,
1232
+ direction.y ?? direction[1] ?? 1,
1233
+ direction.z ?? direction[2] ?? 0,
1234
+ ).normalize();
1235
+ }
1236
+ return state;
1237
+ }
1238
+
1239
+ export function advanceToonLabSourceEnvironmentState(state, delta = 0) {
1240
+ if (state?.uniforms?.time && Number.isFinite(delta)) {
1241
+ state.uniforms.time.value += Math.max(0, Math.min(delta, 0.1));
1242
+ }
1243
+ return state;
1244
+ }
1245
+
1246
+ async function loadProfileTextures(library, profile, names, options = {}) {
1247
+ const entries = names.map((name) => [name, texturePath(profile, name)]);
1248
+ const loaded = await Promise.all(entries.map(([, path]) =>
1249
+ path ? library.loadTexture(path, options).catch(() => null) : null));
1250
+ return Object.fromEntries(entries.map(([name], index) => [name, loaded[index]]));
1251
+ }
1252
+
1253
+ async function buildLeaves(profile, context) {
1254
+ const { library, state, hasVertexColors } = context;
1255
+ const maps = await loadProfileTextures(library, profile, [
1256
+ 'Basic Color Texture',
1257
+ 'Emissive Map',
1258
+ 'LeafTexture',
1259
+ 'Roughness Map',
1260
+ 'Subsurface Texture',
1261
+ ], { flipY: false });
1262
+ const leafMap = maps.LeafTexture;
1263
+ if (!leafMap) throw new Error(`${profile.path} has no exported LeafTexture.`);
1264
+ const retainedPineLeafMask = profile.path.endsWith(
1265
+ '/MI_PineLeaves.MI_PineLeaves',
1266
+ );
1267
+ if (retainedPineLeafMask) {
1268
+ // T_Leaf_Pine inherits TEXTUREGROUP_World. ToonLab's active device
1269
+ // profile specifies MinMagFilter=aniso, MipFilter=point and
1270
+ // TMGS_SimpleAverage. Three's generic trilinear mip blend thins the pine
1271
+ // needles between adjacent mip levels, so select the nearest generated
1272
+ // mip while preserving linear/aniso filtering inside that mip.
1273
+ leafMap.minFilter = THREE.LinearMipmapNearestFilter;
1274
+ leafMap.needsUpdate = true;
1275
+ }
1276
+ const baseUv = uv();
1277
+ const gradientUv = sourceUv(context, 2);
1278
+ const leaf = texture(leafMap).sample(baseUv);
1279
+
1280
+ let mainColor = linearColor(vector(profile, 'Main Color', [0.02, 0.18, 0.04]));
1281
+ let gradientColor = linearColor(vector(profile, 'Gradient Color', [0.4, 0.8, 0.12]));
1282
+ if (switchValue(profile, 'UseCurveColor?', false)) {
1283
+ const atlas = library.resolveCurve(CURVE_ATLASES.leaves);
1284
+ const mainCurve = library.createCurveTexture(library.resolveCurveAtlasRow(
1285
+ atlas,
1286
+ scalar(profile, 'Main Color Curve', 0),
1287
+ ));
1288
+ const gradientCurve = library.createCurveTexture(library.resolveCurveAtlasRow(
1289
+ atlas,
1290
+ scalar(profile, 'Gradient Color Curve', 1),
1291
+ ));
1292
+ const curveTime = vec2(fract(state.uniforms.dayCycleProgress), 0.5);
1293
+ if (mainCurve) mainColor = texture(mainCurve).sample(curveTime).rgb;
1294
+ if (gradientCurve) gradientColor = texture(gradientCurve).sample(curveTime).rgb;
1295
+ }
1296
+
1297
+ let colorNode = mainColor;
1298
+ if (switchValue(profile, 'UseGradient?', true)) {
1299
+ const gradientInput = gradientUv.y.add(scalar(profile, 'Gradient Offset', 0));
1300
+ const gradient = cheapContrast(gradientInput, scalar(profile, 'Gradient Contrast', 0));
1301
+ // M_Leaves.LinearInterpolate_0: A = Gradient Color, B = Main Color.
1302
+ // ToonLab's Lerp is A * (1 - Alpha) + B * Alpha, so preserving the authored
1303
+ // pin order matters: reversing these inputs inverts the UV2 foliage ramp.
1304
+ colorNode = mix(gradientColor, colorNode, gradient);
1305
+ }
1306
+ if (switchValue(profile, 'UseColorTexture?', false) && maps['Basic Color Texture']) {
1307
+ colorNode = texture(maps['Basic Color Texture']).sample(baseUv).rgb;
1308
+ }
1309
+ colorNode = sourceHueVariance(colorNode, profile, context.sourceActorIdentity);
1310
+
1311
+ let roughnessNode = float(scalar(profile, 'Roughness', 0.75));
1312
+ if (switchValue(profile, 'UseRoughnessMap?', false) && maps['Roughness Map']) {
1313
+ roughnessNode = texture(maps['Roughness Map'])
1314
+ .sample(baseUv)
1315
+ .r
1316
+ .mul(scalar(profile, 'Roughness', 0.75));
1317
+ }
1318
+ const material = new MeshSSSNodeMaterial();
1319
+ material.side = THREE.DoubleSide;
1320
+ material.forceSinglePass = true;
1321
+ material.colorNode = colorNode;
1322
+ material.roughnessNode = clamp(roughnessNode, 0.02, 1);
1323
+ material.metalnessNode = float(0);
1324
+ material.specularIntensityNode = clamp(float(scalar(profile, 'Specular', 0.1)), 0, 1);
1325
+ // M_Leaves writes tangent-space +Z * TwoSidedSign when TwoSidedNormals? is
1326
+ // enabled. ToonLab then multiplies the transformed world normal by
1327
+ // TwoSidedSign again in MaterialTemplate.ush. The two signs cancel, so the
1328
+ // final normal is the authored geometric normal on both sides. When the
1329
+ // graph switch is disabled only the engine-boundary sign remains.
1330
+ material.normalNode = switchValue(profile, 'TwoSidedNormals?', true)
1331
+ ? normalViewGeometry
1332
+ : normalViewGeometry.mul(faceDirection);
1333
+
1334
+ const opacityMultiply = scalar(profile, 'Opacity Multiply', 1);
1335
+ // The retained P16 actor is a fully visible, non-fading StaticMeshActor:
1336
+ // PerInstanceFadeAmount=1 and MI_PineLeaves Opacity Multiply=1. ToonLab displays
1337
+ // DitherTemporalAA through an already-warmed temporal resolve. Showing one
1338
+ // raw dither frame in this non-temporal parity viewport turns the averaged
1339
+ // pine-mask mip texels into the screen-door stripes seen on oblique cards.
1340
+ // Specialize the known full-visibility result to one; preserve the literal
1341
+ // source dither for profiles that can actually fade.
1342
+ const analyticallyResolvedFullVisibility = retainedPineLeafMask
1343
+ && opacityMultiply >= 1;
1344
+ const dither = analyticallyResolvedFullVisibility
1345
+ ? float(1)
1346
+ : sourceTemporalDither(float(opacityMultiply), state);
1347
+ let visibleMask = leaf.r;
1348
+ if (switchValue(profile, 'CullPerpendiculars?', false)) {
1349
+ const cameraVector = normalize(cameraPosition.sub(positionWorld));
1350
+ visibleMask = visibleMask.mul(clamp(
1351
+ dot(normalWorld, cameraVector).add(scalar(profile, 'Perpendicular Trim', 0.1)),
1352
+ 0,
1353
+ 1,
1354
+ ));
1355
+ }
1356
+ visibleMask = visibleMask.mul(dither);
1357
+ const shadowMask = leaf.r.mul(dither);
1358
+ material.opacityNode = visibleMask;
1359
+ material.alphaTestNode = float(1 / 3);
1360
+ // MF_Occlusion and perpendicular camera trimming are visible-pass only.
1361
+ // ToonLab ShadowReplace keeps the source alpha silhouette for shadow maps.
1362
+ material.maskShadowNode = shadowMask.greaterThan(float(1 / 3));
1363
+ material.alphaToCoverage = false;
1364
+
1365
+ let subsurfaceColor = vec3(1);
1366
+ if (switchValue(profile, 'UseTexturedSS?', false) && maps['Subsurface Texture']) {
1367
+ subsurfaceColor = texture(maps['Subsurface Texture']).sample(baseUv).rgb;
1368
+ }
1369
+ const emissiveMap = maps['Emissive Map']
1370
+ ? texture(maps['Emissive Map']).sample(baseUv)
1371
+ : null;
1372
+ material.emissiveNode = sourceEmission(colorNode, profile, state, emissiveMap);
1373
+ configureLeafSubsurface(material, colorNode, profile, state, subsurfaceColor, {
1374
+ thinCardTransmissionFallback: retainedPineLeafMask,
1375
+ });
1376
+
1377
+ const windWeight = hasVertexColors ? vertexColor().r : gradientUv.y;
1378
+ material.positionNode = positionLocal.add(windOffset(profile, state, {
1379
+ sway: true,
1380
+ weight: windWeight,
1381
+ }));
1382
+ setShaderSwipeBaseline(material, {
1383
+ colorNode: maps['Basic Color Texture']
1384
+ ? texture(maps['Basic Color Texture']).sample(baseUv).rgb
1385
+ : leaf.rgb,
1386
+ opacityNode: leaf.r,
1387
+ alphaTestNode: float(1 / 3),
1388
+ });
1389
+ return recordSourceContract(finalizeMaterial(material, profile, 'leaves'), {
1390
+ alpha: 'LeafTexture.r',
1391
+ alphaClip: 1 / 3,
1392
+ gradientUv: context.hasUv2 ? 2 : 0,
1393
+ hueVariance: context.sourceActorIdentity
1394
+ ? 'retained-ToonLab-StaticMeshActor-position-plus-zero-PerInstanceRandom'
1395
+ : 'runtime-object-position-plus-reconstructed-PerInstanceRandom',
1396
+ shadowMask: 'source-alpha-without-camera-occlusion-or-perpendicular-trim',
1397
+ shadingModel: 'MSM_SUBSURFACE',
1398
+ subsurfaceLighting: 'ToonLab direct transmission + front/back captured-SkyLight SH',
1399
+ transmissionShadow: retainedPineLeafMask
1400
+ ? 'authored SS Opacity separates thin-card transmission from opaque surface visibility'
1401
+ : 'surface visibility fallback',
1402
+ textureMipFilter: retainedPineLeafMask
1403
+ ? 'TEXTUREGROUP_World MinMagFilter=aniso, MipFilter=point, TMGS_SimpleAverage'
1404
+ : 'source texture metadata default',
1405
+ temporalDither: analyticallyResolvedFullVisibility
1406
+ ? 'analytic warmed-TAA full-visibility result; PerInstanceFadeAmount=1 and Opacity Multiply=1'
1407
+ : 'ToonLab DitherTemporalAA(Opacity Multiply); PerInstanceFadeAmount fixed to 1',
1408
+ twoSidedNormal: switchValue(profile, 'TwoSidedNormals?', true)
1409
+ ? 'M_Leaves +Z * TwoSidedSign, then ToonLab material-boundary TwoSidedSign; net authored geometric normal'
1410
+ : 'M_Leaves +Z, then ToonLab material-boundary TwoSidedSign; net face-corrected geometric normal',
1411
+ toonLabMaterialBoundaryNormal: 'MaterialTemplate.ush: Parameters.WorldNormal *= Parameters.TwoSidedSign',
1412
+ toonLabMaterialTemplateSha256: '2d237cc8c53a024341a6a3828a251a655fbc9a266c0a2d7ed7e244be90bf292d',
1413
+ vertexColor: hasVertexColors ? 'r:wpo-weight' : 'absent',
1414
+ });
1415
+ }
1416
+
1417
+ async function buildFoliage(profile, context) {
1418
+ if (isToonLabGrassProfile(profile)
1419
+ && context.sourceAssetName !== TOONLAB_SHOWCASE_SOURCE_ASSET) {
1420
+ const material = await buildToonLabGrassMaterial(profile, {
1421
+ ...context,
1422
+ baseUrl: context.library?.environmentBaseUrl,
1423
+ });
1424
+ finalizeMaterial(material, profile, 'foliage');
1425
+ Object.assign(material.userData.toonLabSource, {
1426
+ reconstruction: 'toonlab-s-foliage',
1427
+ sourceEngine: 'ToonLab reference renderer',
1428
+ sourceMaterial: material.userData.toonLabGrass?.sourceMaterial ?? 'MV_Grass',
1429
+ sourceToonLabGraph: 'S_FoliageShader',
1430
+ });
1431
+ return recordSourceContract(material, {
1432
+ alpha: 'ToonLab ordered 4x4 dither * radial 80-100m fade',
1433
+ alphaClip: 0.9,
1434
+ baseColor: 'lerp(MV_Grass.Bottom, noise-gradient/tip-distance, UV0.y)',
1435
+ castShadow: false,
1436
+ emission: 'BaseColor * 0.03',
1437
+ gradientUv: 0,
1438
+ lighting: 'TOONLAB Lit specular-workflow adapter',
1439
+ roughness: '1 - ToonLab Smoothness(.05) = .95',
1440
+ source: `${material.userData.toonLabGrass?.sourceMaterial ?? 'MV_Grass'} `
1441
+ + '+ MV_Grass + M_Foliage + compiled S_FoliageShader',
1442
+ specular: '[.17273237,.511,.057577446]',
1443
+ vertex: 'deterministic ToonLab GradientNoise wind + .2m world-Y vertex-color lift',
1444
+ vertexColor: context.hasVertexColors ? 'rgb:wpo-mask' : 'absent/fallback-one',
1445
+ });
1446
+ }
1447
+ const { library, state, hasVertexColors } = context;
1448
+ const retainedDaisyMask = context.sourceAssetName === TOONLAB_SHOWCASE_SOURCE_ASSET
1449
+ && context.sourceSceneVariant === 'retained-instanced-daisies'
1450
+ && profile.path.endsWith('/MI_Daisy.MI_Daisy');
1451
+ const maps = await loadProfileTextures(library, profile, [
1452
+ 'Color Map',
1453
+ 'Emissive Map',
1454
+ 'Foliage Texture',
1455
+ 'Height Texture',
1456
+ 'Hue Texture',
1457
+ 'Wind Color Mask',
1458
+ 'Wind Color Noise',
1459
+ ], { flipY: false });
1460
+ const useTexture = Boolean(
1461
+ switchValue(profile, 'UseTexture?', false) && maps['Foliage Texture'],
1462
+ );
1463
+ const baseUv = uv();
1464
+ const gradientUv = sourceUv(context, 2);
1465
+ const foliageSample = useTexture ? texture(maps['Foliage Texture']).sample(uv()) : null;
1466
+ const windColor = foliageWindColor(profile, state, maps);
1467
+ const windBoost = scalar(profile, 'Wind Color Boost', 2.5);
1468
+ let colorNode;
1469
+ if (useTexture) {
1470
+ const base = foliageSample.rgb
1471
+ .mul(linearColor(vector(profile, 'TextureTint', [1, 1, 1])));
1472
+ colorNode = mix(base, base.mul(windBoost), windColor);
1473
+ } else {
1474
+ const ground = sampleGroundColor(positionWorld);
1475
+ let rootColor = linearColor(vector(profile, 'Base Color', [0.15, 0.33, 0.07]));
1476
+ if (switchValue(profile, 'UseRVTColor?', false)) {
1477
+ // ToonLab's RVT sample is only authoritative where the landscape writer has
1478
+ // coverage and valid color data. Preserve MI_Grass's authored Base
1479
+ // Color outside that coverage instead of multiplying the blade down to
1480
+ // black when a renderer target exposes coverage before its color data.
1481
+ const validRvt = ground.a.mul(step(
1482
+ 1 / 255,
1483
+ max(max(ground.r, ground.g), ground.b),
1484
+ ));
1485
+ rootColor = mix(rootColor, ground.rgb, validRvt);
1486
+ } else if (switchValue(profile, 'UseBinaryColor?', false)) {
1487
+ rootColor = mix(
1488
+ linearColor(vector(profile, 'Offgrass Color', [0.4, 0.35, 0.16])),
1489
+ rootColor,
1490
+ ground.a,
1491
+ );
1492
+ } else if (switchValue(profile, 'UseColorMap?', false) && maps['Color Map']) {
1493
+ const mapSize = scalar(profile, 'Grass Colormap Size', 100000) / 100;
1494
+ rootColor = planarCentered(
1495
+ maps['Color Map'],
1496
+ mapSize,
1497
+ mapSize,
1498
+ 0,
1499
+ 0,
1500
+ state.userData?.worldOffsetToonLabMeters,
1501
+ )
1502
+ .rgb
1503
+ .mul(scalar(profile, 'Colormap Multiply', 1));
1504
+ }
1505
+
1506
+ let tipColor;
1507
+ if (switchValue(profile, 'CurveColoredTips?', false) && maps['Hue Texture']) {
1508
+ const atlas = library.resolveCurve(CURVE_ATLASES.grass);
1509
+ const curveTexture = library.createCurveTexture(library.resolveCurveAtlasRow(
1510
+ atlas,
1511
+ scalar(profile, 'Grass Color Curve', 0),
1512
+ ));
1513
+ if (curveTexture) {
1514
+ const hueScale = scalar(profile, 'Hue Variance Scale', 4000) / 100;
1515
+ const hueNoise = planar(maps['Hue Texture'], hueScale).r;
1516
+ tipColor = texture(curveTexture).sample(vec2(hueNoise, 0.5)).rgb;
1517
+ }
1518
+ }
1519
+ if (!tipColor) {
1520
+ tipColor = rootColor.add(scalar(profile, 'Tip Brightness', 0.1));
1521
+ const grey = dot(tipColor, vec3(0.3, 0.59, 0.11));
1522
+ tipColor = mix(
1523
+ tipColor,
1524
+ vec3(grey),
1525
+ scalar(profile, 'Tip Desaturation', -0.5),
1526
+ );
1527
+ tipColor = toonLabHueShift(tipColor, float(scalar(profile, 'Tip Hue Shift', -0.06)));
1528
+ }
1529
+ rootColor = mix(rootColor, rootColor.mul(windBoost), windColor);
1530
+ tipColor = mix(tipColor, tipColor.mul(windBoost), windColor);
1531
+ colorNode = mix(tipColor, rootColor, gradientUv.y);
1532
+ }
1533
+ colorNode = sourceHueVariance(colorNode, profile);
1534
+
1535
+ const roughness = scalar(profile, 'Roughness', 0.5);
1536
+ const roughnessNode = mix(
1537
+ roughness,
1538
+ roughness * scalar(profile, 'Random Roughness', 1),
1539
+ sourcePerInstanceRandom(profile),
1540
+ );
1541
+ const localSpecularNode = mix(
1542
+ scalar(profile, 'Specular', 0.05),
1543
+ scalar(profile, 'Specular', 0.05) * 3,
1544
+ windColor,
1545
+ );
1546
+ let specularNode = localSpecularNode;
1547
+ if (switchValue(profile, 'UseRVTColor?', false)) {
1548
+ const groundSurface = sampleGroundSurface(positionWorld);
1549
+ specularNode = mix(
1550
+ localSpecularNode,
1551
+ groundSurface.g,
1552
+ gradientUv.y.mul(groundSurface.a),
1553
+ );
1554
+ }
1555
+ const material = new MeshSSSNodeMaterial();
1556
+ material.side = THREE.DoubleSide;
1557
+ material.forceSinglePass = true;
1558
+ // COLOR_0 is authored exclusively as a WPO mask in M_Foliage. Letting the
1559
+ // renderer's generic vertex-color path consume it would multiply those
1560
+ // black-to-white deformation weights into Base Color.
1561
+ material.vertexColors = false;
1562
+ material.colorNode = colorNode;
1563
+ material.roughnessNode = clamp(roughnessNode, 0.02, 1);
1564
+ material.metalnessNode = float(scalar(profile, 'Metallic', 0));
1565
+ material.specularIntensityNode = clamp(specularNode, 0, 1);
1566
+ // M_Foliage's TwoSidedNormals branch resolves both sides to the authored
1567
+ // interpolated grass normal. Three's default DoubleSide path negates the
1568
+ // reverse face a second time, turning half of each clump into a downward
1569
+ // normal and therefore a near-black skylight response.
1570
+ material.normalNode = normalViewGeometry;
1571
+ const emissiveMap = maps['Emissive Map']
1572
+ ? texture(maps['Emissive Map']).sample(baseUv)
1573
+ : null;
1574
+ material.emissiveNode = sourceEmission(colorNode, profile, state, emissiveMap);
1575
+ configureFoliageSubsurface(material, colorNode, profile, {
1576
+ thinCardTransmissionFallback: retainedDaisyMask,
1577
+ });
1578
+
1579
+ const baseMask = foliageSample ? foliageSample.a : float(1);
1580
+ // The retained FoliageInstancedStaticMeshComponent has no cull distance
1581
+ // and its source graph receives PerInstanceFadeAmount=1. Resolve the
1582
+ // warmed-TAA full-visibility result analytically for P17 instead of showing
1583
+ // one temporal-dither frame in deterministic comparisons.
1584
+ const dither = retainedDaisyMask
1585
+ ? float(1)
1586
+ : sourceTemporalDither(float(1), state);
1587
+ const visibleMask = baseMask.mul(dither);
1588
+ const shadowMask = baseMask.mul(dither);
1589
+ material.opacityNode = visibleMask;
1590
+ material.alphaTestNode = float(1 / 3);
1591
+ material.maskShadowNode = shadowMask.greaterThan(float(1 / 3));
1592
+ material.alphaToCoverage = false;
1593
+
1594
+ let wpo = windOffset(profile, state, { weight: float(1) });
1595
+ if (maps['Height Texture']) {
1596
+ const heightNoise = planarAtToonLabWorldXY(
1597
+ maps['Height Texture'],
1598
+ sourceToonLabWorldXY(state.userData?.worldOffsetToonLabMeters),
1599
+ scalar(profile, 'Height Texture Scale', 2500) / 100,
1600
+ ).r;
1601
+ const heightCm = mix(
1602
+ scalar(profile, 'Height Min', 5),
1603
+ scalar(profile, 'Height Max', 20),
1604
+ heightNoise,
1605
+ );
1606
+ wpo = wpo.add(vec3(0, heightCm.div(100), 0));
1607
+ }
1608
+ wpo = wpo.add(vec3(
1609
+ scalar(profile, 'AdditionalX', 0) / 100,
1610
+ scalar(profile, 'AdditionalZ', 0) / 100,
1611
+ -scalar(profile, 'AdditionalY', 0) / 100,
1612
+ ));
1613
+ wpo = wpo.add(vec3(
1614
+ 0,
1615
+ windColor.mul(scalar(profile, 'Wind Color WPO', 0) / 100),
1616
+ 0,
1617
+ ));
1618
+ if (switchValue(profile, 'ShrinkOffgrassFoliage?', false)) {
1619
+ const grassMask = sampleGroundColor(positionWorld).a;
1620
+ wpo = wpo.mul(mix(
1621
+ scalar(profile, 'Offgrass Height', 1),
1622
+ 1,
1623
+ pow(grassMask, 3),
1624
+ ));
1625
+ }
1626
+ wpo = vec3(
1627
+ wpo.x,
1628
+ wpo.y.mul(scalar(profile, 'Final Z Multiply', 1)),
1629
+ wpo.z,
1630
+ );
1631
+ if (hasVertexColors) {
1632
+ // ToonLab multiplies XYZ WPO by COLOR_0.rgb before coordinate conversion.
1633
+ wpo = wpo.mul(vec3(vertexColor().r, vertexColor().b, vertexColor().g));
1634
+ }
1635
+ material.positionNode = positionLocal.add(wpo);
1636
+ setShaderSwipeBaseline(material, {
1637
+ colorNode: foliageSample?.rgb ?? colorNode,
1638
+ opacityNode: baseMask,
1639
+ alphaTestNode: float(1 / 3),
1640
+ });
1641
+ return recordSourceContract(finalizeMaterial(material, profile, 'foliage'), {
1642
+ alpha: useTexture ? 'FoliageTexture.a' : '1',
1643
+ alphaClip: 1 / 3,
1644
+ colormap: 'worldXY*ColormapMultiply',
1645
+ gradientUv: context.hasUv2 ? 2 : 0,
1646
+ shadowMask: 'source-alpha-without-camera-occlusion',
1647
+ shadingModel: 'MSM_SUBSURFACE',
1648
+ subsurfaceLighting: 'ToonLab direct transmission + front/back captured-SkyLight SH',
1649
+ temporalDither: retainedDaisyMask
1650
+ ? 'analytic warmed-TAA full-visibility result; PerInstanceFadeAmount=1'
1651
+ : 'ToonLab DitherTemporalAA(PerInstanceFadeAmount); input fixed to 1',
1652
+ transmissionShadow: retainedDaisyMask
1653
+ ? 'authored SS Opacity separates thin-card transmission from masked surface visibility'
1654
+ : 'surface visibility fallback',
1655
+ twoSidedNormal: switchValue(profile, 'TwoSidedNormals?', true)
1656
+ ? 'flat tangent normal * TwoSidedSign'
1657
+ : 'flat tangent normal',
1658
+ vertexColor: hasVertexColors ? 'rgb:wpo-mask' : 'absent',
1659
+ });
1660
+ }
1661
+
1662
+ async function buildBark(profile, context) {
1663
+ const { library, state, hasVertexColors } = context;
1664
+ const maps = await loadProfileTextures(library, profile, [
1665
+ 'Diffuse Texture',
1666
+ 'Emissive Map',
1667
+ 'MossTexture',
1668
+ 'Normal Texture',
1669
+ 'Rough Texture',
1670
+ 'Snow Texture',
1671
+ ], { flipY: false });
1672
+ maps.snowSpecular = await library.loadTexture(
1673
+ LANDSCAPE_FUNCTION_TEXTURES.snowSpecular,
1674
+ ).catch(() => null);
1675
+ const diffuse = maps['Diffuse Texture'];
1676
+ if (!diffuse) throw new Error(`${profile.path} has no exported Diffuse Texture.`);
1677
+ const barkUv = uv().mul(vec2(
1678
+ scalar(profile, 'XScale', 1),
1679
+ scalar(profile, 'YScale', 1),
1680
+ ));
1681
+ const barkSample = texture(diffuse).sample(barkUv);
1682
+ const tint = linearColor(vector(profile, 'TintColor', [1, 1, 1]));
1683
+ let colorNode = mix(barkSample.rgb, tint, scalar(profile, 'TintMix', 0));
1684
+ if (switchValue(profile, 'HueVariance?', false)) {
1685
+ colorNode = sourceHueVariance(colorNode, profile);
1686
+ }
1687
+
1688
+ let roughnessNode = maps['Rough Texture']
1689
+ ? texture(maps['Rough Texture']).sample(barkUv).r.mul(scalar(profile, 'RoughMult', 1))
1690
+ : float(scalar(profile, 'RoughMult', 0.8));
1691
+ let specularNode = float(scalar(profile, 'Specular', 0.2));
1692
+ let mossMask = float(0);
1693
+ let mossColor = vec3(0);
1694
+
1695
+ if (switchValue(profile, 'Moss?', false) && maps.MossTexture) {
1696
+ const mossNoise = clamp(triplanar(
1697
+ maps.MossTexture,
1698
+ scalar(profile, 'MossSize', 1200) / 100,
1699
+ ).r, 0, 1);
1700
+ const directionMask = switchValue(profile, 'WorldAligned?', true)
1701
+ ? clamp(
1702
+ dot(
1703
+ normalWorld,
1704
+ toonLabDirection(vector(profile, 'MossDirection', [0, 0, 1])),
1705
+ )
1706
+ .mul(scalar(profile, 'MossSharpness', 1))
1707
+ .sub(scalar(profile, 'MossOffset', 0.3)),
1708
+ 0,
1709
+ 1,
1710
+ )
1711
+ : (hasVertexColors ? vertexColor().g : float(0));
1712
+ mossMask = clamp(pow(
1713
+ mossNoise
1714
+ .mul(scalar(profile, 'Moss Multiply', 5))
1715
+ .mul(directionMask),
1716
+ 2,
1717
+ ), 0, 1);
1718
+ mossColor = mix(
1719
+ linearColor(vector(profile, 'Moss Color 2', [0.05, 0.35, 0])),
1720
+ linearColor(vector(profile, 'Moss Color', [0.18, 0.43, 0.06])),
1721
+ pow(mossNoise, 2),
1722
+ );
1723
+ colorNode = mix(colorNode, mossColor, mossMask);
1724
+ roughnessNode = mix(
1725
+ roughnessNode,
1726
+ clamp(mossNoise.mul(scalar(profile, 'Moss Roughness', 1.3)), 0, 1),
1727
+ mossMask,
1728
+ );
1729
+ specularNode = mix(
1730
+ specularNode,
1731
+ scalar(profile, 'Moss Specular', 0.5),
1732
+ mossMask,
1733
+ );
1734
+ }
1735
+
1736
+ let snowMask = float(0);
1737
+ let snowColor = vec3(0);
1738
+ if (switchValue(profile, 'Snow?', false) && maps['Snow Texture']) {
1739
+ snowColor = planar(
1740
+ maps['Snow Texture'],
1741
+ scalar(profile, 'Snow Scale', 5000) / 100,
1742
+ ).rgb;
1743
+ snowMask = switchValue(profile, 'SnowWorldAligned?', true)
1744
+ ? clamp(
1745
+ dot(
1746
+ normalWorld,
1747
+ toonLabDirection(vector(profile, 'Snow Direction', [0, 0, 1])),
1748
+ )
1749
+ .mul(scalar(profile, 'Snow Sharpness', 8))
1750
+ .sub(scalar(profile, 'Snow Offset', 0.3)),
1751
+ 0,
1752
+ 1,
1753
+ )
1754
+ : (hasVertexColors ? vertexColor().g : float(0));
1755
+ colorNode = mix(colorNode, snowColor, snowMask);
1756
+ roughnessNode = mix(
1757
+ roughnessNode,
1758
+ scalar(profile, 'Snow Rough', 0.5),
1759
+ snowMask,
1760
+ );
1761
+ const snowSpecularNoise = maps.snowSpecular
1762
+ ? planar(
1763
+ maps.snowSpecular,
1764
+ scalar(profile, 'Snow Specular Scale', 75) / 100,
1765
+ ).r
1766
+ : float(0.5);
1767
+ const snowSpecular = mix(
1768
+ scalar(profile, 'Snow Spec Min', 0.1),
1769
+ scalar(profile, 'Snow Spec Max', 0.3),
1770
+ snowSpecularNoise,
1771
+ );
1772
+ specularNode = mix(specularNode, snowSpecular, snowMask);
1773
+ }
1774
+
1775
+ const wet = wetSurface(colorNode, roughnessNode, profile, state);
1776
+ const material = new MeshPhysicalNodeMaterial();
1777
+ material.side = THREE.FrontSide;
1778
+ material.colorNode = wet.colorNode;
1779
+ material.roughnessNode = clamp(wet.roughnessNode, 0.02, 1);
1780
+ material.metalnessNode = float(0);
1781
+ material.specularIntensityNode = clamp(specularNode, 0, 1);
1782
+ if (maps['Normal Texture']) {
1783
+ const normalStrength = 1 - THREE.MathUtils.clamp(
1784
+ scalar(profile, 'NormalFlatness', 0), 0, 1,
1785
+ );
1786
+ material.normalNode = normalMapNode(
1787
+ texture(maps['Normal Texture']).sample(barkUv).rgb,
1788
+ vec2(normalStrength, -normalStrength),
1789
+ );
1790
+ }
1791
+
1792
+ let emissiveInput = wet.colorNode.mul(scalar(profile, 'Emissive Strength', 0));
1793
+ if (switchValue(profile, 'Moss?', false)) {
1794
+ let mossEmission = mossColor.mul(scalar(profile, 'Moss Emissive Strength', 0));
1795
+ if (switchValue(profile, 'MossEmissiveMap?', false) && maps['Emissive Map']) {
1796
+ mossEmission = mossEmission.mul(triplanar(
1797
+ maps['Emissive Map'],
1798
+ Math.max(scalar(profile, 'Moss Emissive Map Scale', 1), 0.001),
1799
+ ).rgb).mul(linearColor(vector(profile, 'Emissive Tint', [1, 1, 1])));
1800
+ }
1801
+ emissiveInput = mix(emissiveInput, mossEmission, mossMask);
1802
+ }
1803
+ if (switchValue(profile, 'Snow?', false)) {
1804
+ const snowEmission = snowColor.mul(scalar(profile, 'Snow Emission', 0.05));
1805
+ emissiveInput = mix(emissiveInput, snowEmission, snowMask);
1806
+ }
1807
+ material.emissiveNode = applyDayCycleEmission(emissiveInput, profile, state);
1808
+ material.positionNode = positionLocal.add(windOffset(profile, state, {
1809
+ sway: true,
1810
+ weight: uv().y,
1811
+ }));
1812
+ setShaderSwipeBaseline(material, {
1813
+ colorNode: barkSample.rgb,
1814
+ });
1815
+ installToonLabSourceDefaultLitLighting(material);
1816
+ return recordSourceContract(finalizeMaterial(material, profile, 'bark'), {
1817
+ lighting:
1818
+ 'ToonLab legacy Default Lit Lambert + punctual GGX + captured-SkyLight boundary',
1819
+ mossProjection: 'world-aligned-triplanar-or-vertex-g',
1820
+ shadingModel: 'MSM_DEFAULT_LIT',
1821
+ snowProjection: 'worldXY-planar',
1822
+ tint: 'lerp(diffuse,TintColor,TintMix)',
1823
+ vertexColor: hasVertexColors ? 'g:moss-or-snow-mask' : 'absent',
1824
+ });
1825
+ }
1826
+
1827
+ async function buildTreeLod(profile, context) {
1828
+ const { library, state, hasVertexColors } = context;
1829
+ const maps = await loadProfileTextures(library, profile, [
1830
+ 'Filled Leaf Texture',
1831
+ 'Leaf Texture',
1832
+ 'SS Texture',
1833
+ ], { flipY: false });
1834
+ const baseUv = uv();
1835
+ const gradientUv = sourceUv(context, 2);
1836
+ let leafColor = linearColor(vector(profile, 'Leaf Color', [0.08, 0.28, 0.03]));
1837
+ let gradientColor = linearColor(
1838
+ vector(profile, 'Leaf Gradient Color', [0.35, 0.65, 0.08]),
1839
+ );
1840
+ if (switchValue(profile, 'UseCurveColor?', false)) {
1841
+ const atlas = library.resolveCurve(CURVE_ATLASES.leaves);
1842
+ const leafCurve = library.createCurveTexture(
1843
+ library.resolveCurveAtlasRow(atlas, scalar(profile, 'Main Color Curve', 0)),
1844
+ );
1845
+ const gradientCurve = library.createCurveTexture(
1846
+ library.resolveCurveAtlasRow(atlas, scalar(profile, 'Gradient Color Curve', 1)),
1847
+ );
1848
+ const curveTime = vec2(fract(state.uniforms.dayCycleProgress), 0.5);
1849
+ if (leafCurve) leafColor = texture(leafCurve).sample(curveTime).rgb;
1850
+ if (gradientCurve) gradientColor = texture(gradientCurve).sample(curveTime).rgb;
1851
+ }
1852
+ const leafGradient = cheapContrast(
1853
+ gradientUv.y.add(scalar(profile, 'Gradient Offset', 0)),
1854
+ scalar(profile, 'Gradient Contrast', 0),
1855
+ );
1856
+ let leaves = switchValue(profile, 'UseGradient?', true)
1857
+ ? mix(leafColor, gradientColor, leafGradient)
1858
+ : leafColor;
1859
+ leaves = sourceHueVariance(leaves, profile);
1860
+ if (switchValue(profile, 'UseTexture?', false) && maps['Leaf Texture']) {
1861
+ leaves = texture(maps['Leaf Texture']).sample(baseUv).rgb;
1862
+ }
1863
+
1864
+ let bark = linearColor(vector(profile, 'Bark Color', [0.3, 0.2, 0.12]));
1865
+ if (switchValue(profile, 'Snow?', false)) {
1866
+ const snowMask = clamp(
1867
+ normalWorld.y.mul(scalar(profile, 'Snow Sharpness', 3)),
1868
+ 0,
1869
+ 1,
1870
+ );
1871
+ bark = mix(
1872
+ bark,
1873
+ linearColor(vector(profile, 'Snow Color', [0.9, 0.9, 0.9])),
1874
+ snowMask,
1875
+ );
1876
+ }
1877
+
1878
+ const leafSelector = hasVertexColors
1879
+ ? vertexColor().r
1880
+ : smoothstep(0.3, 0.7, gradientUv.y);
1881
+ const colorNode = mix(bark, leaves, leafSelector);
1882
+ const filledLeaf = maps['Filled Leaf Texture']
1883
+ ? texture(maps['Filled Leaf Texture']).sample(baseUv).r
1884
+ : float(1);
1885
+ const opacityMask = mix(1, filledLeaf, leafSelector);
1886
+
1887
+ const material = new MeshSSSNodeMaterial();
1888
+ material.side = THREE.DoubleSide;
1889
+ material.forceSinglePass = true;
1890
+ material.colorNode = colorNode;
1891
+ material.roughnessNode = clamp(float(scalar(profile, 'Roughness', 0.75)), 0.02, 1);
1892
+ material.metalnessNode = float(0);
1893
+ material.specularIntensityNode = clamp(float(scalar(profile, 'Specular', 0.1)), 0, 1);
1894
+ material.opacityNode = opacityMask;
1895
+ material.alphaTestNode = float(1 / 3);
1896
+ material.maskShadowNode = opacityMask.greaterThan(float(1 / 3));
1897
+ material.alphaToCoverage = false;
1898
+ material.emissiveNode = sourceEmission(colorNode, profile, state);
1899
+
1900
+ let ssColor = colorNode.mul(scalar(profile, 'SS Strength', 0.3));
1901
+ if (switchValue(profile, 'SubsurfaceTexture?', false) && maps['SS Texture']) {
1902
+ ssColor = ssColor.mul(texture(maps['SS Texture']).sample(baseUv).rgb);
1903
+ }
1904
+ configureSourceSubsurface(
1905
+ material,
1906
+ ssColor.mul(leafSelector),
1907
+ mix(1, scalar(profile, 'SS Opacity', 0.08), leafSelector),
1908
+ );
1909
+ setShaderSwipeBaseline(material, {
1910
+ colorNode: switchValue(profile, 'UseTexture?', false) && maps['Leaf Texture']
1911
+ ? mix(bark, texture(maps['Leaf Texture']).sample(baseUv).rgb, leafSelector)
1912
+ : colorNode,
1913
+ opacityNode: opacityMask,
1914
+ alphaTestNode: float(1 / 3),
1915
+ });
1916
+ return recordSourceContract(finalizeMaterial(material, profile, 'treeLod'), {
1917
+ alpha: 'lerp(1,FilledLeafTexture.r,VertexColor.r)',
1918
+ gradientUv: context.hasUv2 ? 2 : 0,
1919
+ leafSelector: hasVertexColors ? 'color.r' : 'uv-fallback',
1920
+ shadingModel: 'MSM_SUBSURFACE',
1921
+ snow: 'bark-only-normal-z',
1922
+ subsurfaceLighting: 'ToonLab direct transmission + front/back captured-SkyLight SH',
1923
+ twoSidedNormal: switchValue(profile, 'TwoSidedNormals?', true)
1924
+ ? 'flat tangent normal * TwoSidedSign'
1925
+ : 'flat tangent normal',
1926
+ });
1927
+ }
1928
+
1929
+ async function buildSnow(profile, context) {
1930
+ const { library, state } = context;
1931
+ const maps = await loadProfileTextures(library, profile, ['Snow Texture'], { flipY: false });
1932
+ if (!maps['Snow Texture']) {
1933
+ throw new Error(`${profile.path} has no exported Snow Texture.`);
1934
+ }
1935
+ const embedded = await Promise.all([
1936
+ library.loadTexture(LANDSCAPE_FUNCTION_TEXTURES.snowSpecular, { flipY: false })
1937
+ .catch(() => null),
1938
+ library.loadTexture(LANDSCAPE_FUNCTION_TEXTURES.sparkleChroma, { flipY: false })
1939
+ .catch(() => null),
1940
+ library.loadTexture(LANDSCAPE_FUNCTION_TEXTURES.sparkleMask, { flipY: false })
1941
+ .catch(() => null),
1942
+ ]);
1943
+ [maps.snowSpecular, maps.sparkleChroma, maps.sparkleMask] = embedded;
1944
+ const nodes = buildSnowNodes(profile, state, maps);
1945
+ const material = new MeshPhysicalNodeMaterial();
1946
+ material.side = THREE.FrontSide;
1947
+ material.depthTest = true;
1948
+ material.depthWrite = true;
1949
+ material.colorNode = nodes.colorNode;
1950
+ material.roughnessNode = clamp(nodes.roughnessNode, 0.02, 1);
1951
+ material.metalnessNode = nodes.metalnessNode;
1952
+ material.specularIntensityNode = clamp(nodes.specularNode, 0, 1);
1953
+ material.emissiveNode = nodes.emissiveNode;
1954
+ installToonLabSourceDefaultLitLighting(material);
1955
+ return recordSourceContract(finalizeMaterial(material, profile, 'snow'), {
1956
+ colorProjection: 'absolute-toonlab-world-xy',
1957
+ dayWeather: 'snow-five-point-day-curve-and-overcast',
1958
+ intensityVariance: 'neutral-until-source-T_3DNoise-volume-is-exported',
1959
+ normal: 'flat-tangent-space',
1960
+ lighting:
1961
+ 'ToonLab legacy Default Lit Lambert + punctual GGX + captured-SkyLight boundary',
1962
+ shadingModel: 'MSM_DEFAULT_LIT',
1963
+ sparkle: switchValue(profile, 'SnowSparkleDualLayer?', true)
1964
+ ? 'dual-layer-source-2d-projection'
1965
+ : 'single-layer-source-2d-projection',
1966
+ specular: 'T_ChromaNoise_Blurred.r',
1967
+ });
1968
+ }
1969
+
1970
+ export async function buildToonLabLandscapeMaterial(profile, context) {
1971
+ const { library, state } = context;
1972
+ const maps = await loadProfileTextures(library, profile, [
1973
+ 'Color Map',
1974
+ 'Desert Dirt Roughness',
1975
+ 'Desert Dirt Texture',
1976
+ 'Desert Sand Texture',
1977
+ 'DirtTexture',
1978
+ 'Grass Color Texture',
1979
+ 'Grass Roughness Texture',
1980
+ 'Hue Texture',
1981
+ 'Rock Normal Texture',
1982
+ 'Rock Texture',
1983
+ 'Roughness Map',
1984
+ 'SandTexture',
1985
+ 'Snow Texture',
1986
+ 'Wind Color Mask',
1987
+ 'Wind Color Noise',
1988
+ ], { flipY: false });
1989
+ const embeddedTextureEntries = await Promise.all(
1990
+ Object.entries(LANDSCAPE_FUNCTION_TEXTURES).map(async ([name, path]) => [
1991
+ name,
1992
+ await library.loadTexture(path, { flipY: false }).catch(() => null),
1993
+ ]),
1994
+ );
1995
+ Object.assign(maps, Object.fromEntries(embeddedTextureEntries));
1996
+
1997
+ const isToonLabShowcase = context.sourceAssetName === TOONLAB_SHOWCASE_SOURCE_ASSET;
1998
+ // ToonLabShowcase is an ToonLab-authored Landscape with ten painted weight layers,
1999
+ // AutoCliff, height blending, rain wetness, and scene-specific textures.
2000
+ // ToonLab Terrain/Lit belongs to EnvironmentReferenceScene and cannot be combined
2001
+ // with these masks for an apple-to-apple scene comparison.
2002
+ const toonLabTerrainLayers = null;
2003
+ if (toonLabTerrainLayers) {
2004
+ for (const [layerName, layer] of Object.entries(toonLabTerrainLayers)) {
2005
+ maps[`toonLabTerrain${layerName}Diffuse`] = layer.diffuseMap;
2006
+ if (layer.normalMap) maps[`toonLabTerrain${layerName}Normal`] = layer.normalMap;
2007
+ }
2008
+ }
2009
+ let landscapeWeightSet = null;
2010
+ if (isToonLabShowcase) {
2011
+ if (typeof library.loadLandscapeWeightmapTextures !== 'function') {
2012
+ throw new Error('ToonLabShowcase requires the authoritative Landscape weightmap loader.');
2013
+ }
2014
+ landscapeWeightSet = await library.loadLandscapeWeightmapTextures(
2015
+ context.sourceAssetName,
2016
+ TOONLAB_SHOWCASE_WEIGHTMAP_CONTRACT,
2017
+ );
2018
+ }
2019
+ const weightInspection = landscapeWeightSet?.inspection
2020
+ ?? library.inspectLandscapeWeightmapSet?.(
2021
+ context.sourceAssetName,
2022
+ TOONLAB_SHOWCASE_WEIGHTMAP_CONTRACT,
2023
+ )
2024
+ ?? {
2025
+ errors: ['source library has no Landscape weightmap resolver'],
2026
+ record: null,
2027
+ status: 'missing',
2028
+ };
2029
+ let weightBindings = landscapeWeightSet?.bindings ?? null;
2030
+ let weightPackTextures = landscapeWeightSet?.textures ?? null;
2031
+ const samplerlessTextures = makeSourceTexturesSamplerless(
2032
+ maps,
2033
+ weightPackTextures ?? [],
2034
+ );
2035
+ if (weightPackTextures) {
2036
+ weightPackTextures = samplerlessTextures.packs;
2037
+ weightBindings = Object.fromEntries(Object.entries(weightBindings).map(
2038
+ ([layerName, binding]) => [layerName, Object.freeze({
2039
+ ...binding,
2040
+ texture: weightPackTextures[binding.packIndex],
2041
+ })],
2042
+ ));
2043
+ }
2044
+ const landscapeCoord = landscapeLayerCoordinates(
2045
+ context.sourceAssetName,
2046
+ weightInspection.record,
2047
+ state.userData?.worldOffsetToonLabMeters,
2048
+ );
2049
+ const sourceWorldXY = sourceToonLabWorldXY(state.userData?.worldOffsetToonLabMeters);
2050
+
2051
+ const grassScale = scalar(profile, 'Global Scale', 1600) / 100;
2052
+ const rockScale = scalar(profile, 'Rock Scale', 2500) / 100;
2053
+ const grassPrimary = planarAtToonLabWorldXY(
2054
+ maps['Grass Color Texture'],
2055
+ sourceWorldXY,
2056
+ grassScale,
2057
+ ).rgb;
2058
+ const grassSecondary = planarAtToonLabWorldXY(
2059
+ maps['Grass Color Texture'],
2060
+ sourceWorldXY,
2061
+ grassScale * 1.75,
2062
+ ).rgb;
2063
+ let grassVariance = float(0);
2064
+ if (maps.grassVariance) {
2065
+ grassVariance = clamp(planarAtToonLabWorldXY(
2066
+ maps.grassVariance,
2067
+ sourceWorldXY,
2068
+ scalar(profile, 'Grass Variance Scale', 8417.2) / 100,
2069
+ ).r.mul(scalar(profile, 'Grass Variance Multiply', 2)), 0, 1);
2070
+ }
2071
+ const grassSample = mix(grassPrimary, grassSecondary, grassVariance);
2072
+ const grassTint = linearColor(vector(profile, 'Grass Tint', [0.42, 0.6, 0.433]));
2073
+ let grassColor = grassSample.mul(grassTint);
2074
+ if (switchValue(profile, 'UseColorMap?', false) && maps['Color Map']) {
2075
+ const colormap = planarCentered(
2076
+ maps['Color Map'],
2077
+ scalar(profile, 'Grass Colormap ScaleX', 100000) / 100,
2078
+ scalar(profile, 'Grass Colormap ScaleY', 100000) / 100,
2079
+ scalar(profile, 'Grass Colormap OffsetX', 0),
2080
+ scalar(profile, 'Grass Colormap OffsetY', 0),
2081
+ state.userData?.worldOffsetToonLabMeters,
2082
+ ).rgb;
2083
+ const grey = sourceDesaturate(grassSample, 1).r;
2084
+ const low = colormap.mul(grey.mul(2));
2085
+ const high = vec3(1).sub(vec3(1).sub(colormap).mul(grey.oneMinus().mul(2)));
2086
+ grassColor = mix(low, high, step(0.5, grey));
2087
+ }
2088
+
2089
+ if (maps['Hue Texture']) {
2090
+ const hueNoise = planarAtToonLabWorldXY(
2091
+ maps['Hue Texture'],
2092
+ sourceWorldXY,
2093
+ scalar(profile, 'Hue Variance Scale', 8000) / 100,
2094
+ ).rgb;
2095
+ const hueAmount = hueNoise
2096
+ .add(scalar(profile, 'Hue Pre-Offset', -0.05))
2097
+ .mul(scalar(profile, 'Hue Variance Strength', -0.1))
2098
+ .add(scalar(profile, 'Hue Post Offset', -0.01));
2099
+ grassColor = toonLabHueShift(grassColor, hueAmount);
2100
+ }
2101
+
2102
+ const windColor = landscapeWindColor(profile, state, maps, sourceWorldXY);
2103
+ const windColorBoostAmount = scalar(profile, 'Wind Color Boost', 1.2);
2104
+ const windColorBoost = lerpFive(
2105
+ windColorBoostAmount,
2106
+ 1,
2107
+ 1,
2108
+ 1,
2109
+ windColorBoostAmount,
2110
+ state.uniforms.dayCycleProgress,
2111
+ );
2112
+ grassColor = mix(grassColor, grassColor.mul(windColorBoost), windColor);
2113
+ const grassSpecular = mix(
2114
+ 0.1,
2115
+ lerpFive(1, 0.4, 0.2, 0.4, 1, state.uniforms.dayCycleProgress),
2116
+ windColor,
2117
+ );
2118
+ const grassRoughness = maps['Grass Roughness Texture']
2119
+ ? mix(
2120
+ planarAtToonLabWorldXY(
2121
+ maps['Grass Roughness Texture'],
2122
+ sourceWorldXY,
2123
+ grassScale,
2124
+ ).r,
2125
+ planarAtToonLabWorldXY(
2126
+ maps['Grass Roughness Texture'],
2127
+ sourceWorldXY,
2128
+ grassScale * 1.75,
2129
+ ).r,
2130
+ grassVariance,
2131
+ )
2132
+ : float(0.9);
2133
+ const grassEmission = grassColor.mul(scalar(profile, 'Grass Emissive', 0.03));
2134
+
2135
+ const rockSample = triplanar(
2136
+ maps['Rock Texture'],
2137
+ rockScale,
2138
+ {
2139
+ contrast: scalar(profile, 'Projection Contrast', 0.5),
2140
+ normalNode: normalWorldGeometry,
2141
+ sideOnly: switchValue(profile, 'SideProjectOnly?', false),
2142
+ },
2143
+ );
2144
+ const rockNear = rockSample.rgb
2145
+ .mul(linearColor(vector(profile, 'Rock Tint', [0.893, 0.922, 0.83])));
2146
+ const rockDistance = clamp(linearRemap(
2147
+ sourcePixelDepthCm(),
2148
+ scalar(profile, 'Close Tint Blend Distance', 500),
2149
+ scalar(profile, 'Far Tint Blend Distance', 15000),
2150
+ ), 0, 1);
2151
+ const rockFar = mix(
2152
+ rockNear,
2153
+ linearColor(vector(profile, 'Distant Tint Blend', [0.59375, 0.59375, 0.59375])),
2154
+ scalar(profile, 'Distant Tint Blend Lerp Alpha Mix', 0.5),
2155
+ );
2156
+ const rockColor = mix(rockNear, rockFar, rockDistance);
2157
+ const rockRoughness = switchValue(profile, 'RoughnessMap?', false)
2158
+ && maps['Roughness Map']
2159
+ ? triplanar(maps['Roughness Map'], rockScale, {
2160
+ contrast: scalar(profile, 'Projection Contrast', 0.5),
2161
+ normalNode: normalWorldGeometry,
2162
+ sideOnly: switchValue(profile, 'SideProjectOnly?', false),
2163
+ }).r
2164
+ .mul(scalar(profile, 'Roughness', 1.2))
2165
+ : cheapContrast(rockSample.r, 0.3).mul(scalar(profile, 'Roughness', 1.2));
2166
+
2167
+ let rockNormalView = normalViewGeometry;
2168
+ if (maps['Rock Normal Texture']) {
2169
+ let rockNormalWorld = sourceWorldAlignedNormal(
2170
+ maps['Rock Normal Texture'],
2171
+ rockScale,
2172
+ {
2173
+ contrast: scalar(profile, 'Projection Contrast', 0.5),
2174
+ flatTop: switchValue(profile, 'FlatTopCrackNormals?', false),
2175
+ sideOnly: switchValue(profile, 'SideProjectOnly?', false),
2176
+ },
2177
+ );
2178
+ const closeFlatness = THREE.MathUtils.clamp(
2179
+ scalar(profile, 'Rock Normal Flatten', 0), 0, 1,
2180
+ );
2181
+ const farFlatness = switchValue(profile, 'FlattenDistantCracks?', true)
2182
+ ? THREE.MathUtils.clamp(
2183
+ scalar(profile, 'Distant Rock Normal Flatten', 1), 0, 1,
2184
+ )
2185
+ : closeFlatness;
2186
+ const normalFade = clamp(
2187
+ sourcePixelDepthCm().div(Math.max(
2188
+ scalar(profile, 'Rock Normal Distance', 20000),
2189
+ 0.001,
2190
+ )),
2191
+ 0,
2192
+ 1,
2193
+ );
2194
+ rockNormalWorld = normalize(mix(
2195
+ rockNormalWorld,
2196
+ normalWorldGeometry,
2197
+ mix(closeFlatness, farFlatness, normalFade),
2198
+ ));
2199
+ rockNormalView = transformNormalByViewMatrix(rockNormalWorld, cameraViewMatrix);
2200
+ }
2201
+
2202
+ const slope = linearRemap(
2203
+ normalWorldGeometry.y,
2204
+ scalar(profile, 'Auto Cliff Start', 0.85),
2205
+ scalar(profile, 'Auto Cliff Fade', 0.8),
2206
+ );
2207
+ const cliffNoise = maps.autoCliffNoise
2208
+ ? sourceTextureSample(maps.autoCliffNoise,
2209
+ landscapeCoord.div(Math.max(scalar(profile, 'Auto Cliff Noise Scale', 80), 0.001)),
2210
+ ).r.mul(scalar(profile, 'Auto Cliff Noise Strength', 2))
2211
+ : float(0);
2212
+ let cliffMask = switchValue(profile, 'AutoCliff?', true)
2213
+ ? clamp(slope.sub(cliffNoise), 0, 1)
2214
+ : float(0);
2215
+ // AutoGrass drives the procedural grass/RVT output in ToonLab. It does not
2216
+ // alter the visible AutoCliff material blend.
2217
+
2218
+ const rockSurface = {
2219
+ color: rockColor,
2220
+ emissive: sourceEmission(rockColor, profile, state),
2221
+ metalness: float(scalar(profile, 'Metallic', 0.1)),
2222
+ normal: rockNormalView,
2223
+ roughness: rockRoughness,
2224
+ specular: float(scalar(profile, 'Specular', 0.2)),
2225
+ };
2226
+ const grassSurface = {
2227
+ color: grassColor,
2228
+ emissive: grassEmission,
2229
+ metalness: float(0),
2230
+ normal: normalViewGeometry,
2231
+ roughness: grassRoughness,
2232
+ specular: grassSpecular,
2233
+ };
2234
+ // Raw color-only input used by Live Preview. Use the primary source albedo,
2235
+ // not M_Landscape's secondary-scale variance branch.
2236
+ let shaderSwipeColorNode = grassPrimary;
2237
+
2238
+ let paintedSurface = grassSurface;
2239
+ let paintedWeights = null;
2240
+ if (weightBindings) {
2241
+ const dirtUv = landscapeCoord.div(Math.max(scalar(profile, 'Dirt Scale', 13), 0.001));
2242
+ const dirtSample = sourceTextureSample(
2243
+ maps.DirtTexture,
2244
+ dirtUv,
2245
+ { anisotropic: true },
2246
+ ).rgb;
2247
+ const dirtColor = dirtSample.mul(
2248
+ linearColor(vector(profile, 'Dirt Tint', [0.5, 0.529, 0.552])),
2249
+ );
2250
+ const dirtNormalStrength = 1 - THREE.MathUtils.clamp(
2251
+ scalar(profile, 'Dirt Flatten', 0.5), 0, 1,
2252
+ );
2253
+ const dirtSurface = {
2254
+ color: dirtColor,
2255
+ emissive: vec3(0),
2256
+ metalness: float(0),
2257
+ normal: maps.dirtNormal
2258
+ ? normalMapNode(
2259
+ sourceTextureSample(
2260
+ maps.dirtNormal,
2261
+ dirtUv,
2262
+ { anisotropic: true },
2263
+ ).rgb,
2264
+ vec2(dirtNormalStrength, -dirtNormalStrength),
2265
+ )
2266
+ : normalViewGeometry,
2267
+ roughness: maps.dirtRoughness
2268
+ ? sourceTextureSample(
2269
+ maps.dirtRoughness,
2270
+ dirtUv,
2271
+ { anisotropic: true },
2272
+ ).r
2273
+ : float(1),
2274
+ specular: float(scalar(profile, 'Dirt Specular', 0.1)),
2275
+ };
2276
+
2277
+ const sandUv = landscapeCoord.div(Math.max(scalar(profile, 'Sand Scale', 10), 0.001));
2278
+ const sandSample = sourceTextureSample(maps.SandTexture, sandUv).rgb;
2279
+ const sandBase = sandSample.mul(
2280
+ linearColor(vector(profile, 'Sand Tint', [0.831, 0.811, 0.623])),
2281
+ );
2282
+ const waterline = clamp(
2283
+ positionWorld.y.mul(100)
2284
+ .sub(scalar(profile, 'Waterline Height', 20))
2285
+ .div(Math.max(scalar(profile, 'Waterline Distance', 75), 0.001)),
2286
+ 0,
2287
+ 1,
2288
+ );
2289
+ const sandNormalStrength = 1 - THREE.MathUtils.clamp(
2290
+ scalar(profile, 'Sand Flatten', 0.3), 0, 1,
2291
+ );
2292
+ const sandSurface = {
2293
+ color: mix(sandBase.mul(scalar(profile, 'Water Darken', 0.7)), sandBase, waterline),
2294
+ emissive: vec3(0),
2295
+ metalness: float(0),
2296
+ normal: maps.sandNormal
2297
+ ? normalMapNode(
2298
+ sourceTextureSample(maps.sandNormal, sandUv).rgb,
2299
+ vec2(sandNormalStrength, -sandNormalStrength),
2300
+ )
2301
+ : normalViewGeometry,
2302
+ roughness: maps.sandRoughness
2303
+ ? sourceTextureSample(maps.sandRoughness, sandUv).r
2304
+ : float(1),
2305
+ specular: float(scalar(profile, 'Sand Specular', 0.15)),
2306
+ };
2307
+
2308
+ const snowNodes = buildSnowNodes(profile, state, maps);
2309
+ const snowSurface = {
2310
+ color: snowNodes.colorNode,
2311
+ emissive: snowNodes.emissiveNode,
2312
+ metalness: snowNodes.metalnessNode,
2313
+ normal: normalViewGeometry,
2314
+ roughness: snowNodes.roughnessNode,
2315
+ specular: snowNodes.specularNode,
2316
+ };
2317
+ const snowGrassBlueSurface = {
2318
+ ...snowSurface,
2319
+ color: snowSurface.color.mul(linearColor(
2320
+ vector(profile, 'SnowGrassBlue Color', [0.373, 0.47, 0.896]),
2321
+ )),
2322
+ };
2323
+
2324
+ const desertGrassUv = sourceWorldXY.div(Math.max(
2325
+ scalar(profile, 'Desert Grass Scale', 1024) / 100,
2326
+ 0.001,
2327
+ ));
2328
+ const desertGrassSample = sourceTextureSample(
2329
+ maps['Grass Color Texture'],
2330
+ desertGrassUv,
2331
+ ).rgb;
2332
+ const desertGrassBase = sourceOverlay(
2333
+ sourceDesaturate(desertGrassSample, 1),
2334
+ linearColor(vector(profile, 'Desert Grass Tint', [0.604, 0.214, 0.099])),
2335
+ );
2336
+ const cameraVector = normalize(cameraPosition.sub(positionWorld));
2337
+ const desertFresnel = pow(
2338
+ clamp(float(1).sub(dot(normalWorldGeometry, cameraVector)), 0, 1),
2339
+ scalar(profile, 'Desert Sand Fresnel Falloff', 4),
2340
+ );
2341
+ const desertGrassColor = mix(
2342
+ desertGrassBase,
2343
+ desertGrassBase.mul(scalar(profile, 'Desert Sand Fresnel Multiply', 2)),
2344
+ desertFresnel,
2345
+ );
2346
+ const desertGrassSurface = {
2347
+ color: desertGrassColor,
2348
+ emissive: desertGrassColor.mul(
2349
+ scalar(profile, 'Desert Grass Emission', 0.2),
2350
+ ),
2351
+ metalness: float(0),
2352
+ normal: normalViewGeometry,
2353
+ roughness: float(scalar(profile, 'Desert Grass Roughness', 0.4)),
2354
+ specular: float(scalar(profile, 'Desert Grass Specular', 0.5)),
2355
+ };
2356
+
2357
+ const desertDirtUv = sourceWorldXY.div(Math.max(
2358
+ scalar(profile, 'Desert Dirt Scale', 1024) / 100,
2359
+ 0.001,
2360
+ ));
2361
+ const desertDirtBase = sourceTextureSample(
2362
+ maps['Desert Dirt Texture'],
2363
+ desertDirtUv,
2364
+ ).rgb;
2365
+ const desertDirtTint = linearColor(
2366
+ vector(profile, 'Desert Dirt Tint', [0.604, 0.214, 0.099]),
2367
+ );
2368
+ const desertDirtColor = desertDirtBase.mul(mix(
2369
+ desertDirtTint,
2370
+ desertDirtTint.mul(2),
2371
+ desertFresnel,
2372
+ ));
2373
+ const desertDirtNormalStrength = 1 - THREE.MathUtils.clamp(
2374
+ scalar(profile, 'Desert Dirt Normal Flatness', 0.5), 0, 1,
2375
+ );
2376
+ const desertDirtSurface = {
2377
+ color: desertDirtColor,
2378
+ emissive: desertDirtColor.mul(
2379
+ scalar(profile, 'Desert Dirt Emissive', 0.1),
2380
+ ),
2381
+ metalness: float(0),
2382
+ normal: maps.desertDirtNormal
2383
+ ? normalMapNode(
2384
+ sourceTextureSample(maps.desertDirtNormal, desertDirtUv).rgb,
2385
+ vec2(desertDirtNormalStrength, -desertDirtNormalStrength),
2386
+ )
2387
+ : normalViewGeometry,
2388
+ roughness: maps['Desert Dirt Roughness']
2389
+ ? sourceTextureSample(maps['Desert Dirt Roughness'], desertDirtUv).r
2390
+ .mul(scalar(profile, 'Desert Dirt Roughness Multiplier', 1))
2391
+ : float(1),
2392
+ specular: float(scalar(profile, 'Desert Dirt Specular', 0.2)),
2393
+ };
2394
+
2395
+ const desertSandUv = sourceWorldXY.div(Math.max(
2396
+ scalar(profile, 'Desert Sand Scale', 1024) / 100,
2397
+ 0.001,
2398
+ ));
2399
+ const desertSandSample = sourceTextureSample(
2400
+ maps['Desert Sand Texture'],
2401
+ desertSandUv,
2402
+ ).rgb;
2403
+ const desertSandBase = sourceDesaturate(desertSandSample, 1);
2404
+ const desertSandVariance = maps.desertSandVariance
2405
+ ? sourceTextureSample(maps.desertSandVariance, sourceWorldXY.div(Math.max(
2406
+ scalar(profile, 'Desert Sand Color Variance Scale', 50000) / 100,
2407
+ 0.001,
2408
+ ))).r
2409
+ : float(0);
2410
+ const desertSandColorBase = mix(
2411
+ sourceOverlay(
2412
+ desertSandBase,
2413
+ linearColor(vector(profile, 'Desert Sand Tint', [0.597, 0.292, 0.156])),
2414
+ ),
2415
+ sourceOverlay(
2416
+ desertSandBase,
2417
+ linearColor(vector(profile, 'Desert Sand Tint 2', [0.597, 0.246, 0.114])),
2418
+ ),
2419
+ desertSandVariance,
2420
+ );
2421
+ const desertSandColor = mix(
2422
+ desertSandColorBase,
2423
+ desertSandColorBase.mul(scalar(profile, 'Desert Sand Fresnel Multiply', 2)),
2424
+ desertFresnel,
2425
+ );
2426
+ const desertSandRoughnessNoise = maps.desertSandRoughness
2427
+ ? sourceTextureSample(maps.desertSandRoughness, sourceWorldXY.div(5)).r
2428
+ : float(0.5);
2429
+ let desertSandNormalView = normalViewGeometry;
2430
+ if (maps.desertSandNormal) {
2431
+ let desertSandNormalWorld = sourceWorldAlignedNormal(
2432
+ maps.desertSandNormal,
2433
+ scalar(profile, 'Desert Sand Normal Texture Scale', 2400) / 100,
2434
+ );
2435
+ const desertNormalFade = clamp(
2436
+ sourcePixelDepthCm().div(Math.max(
2437
+ scalar(profile, 'Desert Sand Normal Far Distance', 3000),
2438
+ 0.001,
2439
+ )),
2440
+ 0,
2441
+ 1,
2442
+ );
2443
+ desertSandNormalWorld = normalize(mix(
2444
+ desertSandNormalWorld,
2445
+ normalWorldGeometry,
2446
+ mix(
2447
+ scalar(profile, 'Desert Sand Normal Near Flatness', 0),
2448
+ scalar(profile, 'Desert Sand Normal Far Flatness', 1),
2449
+ desertNormalFade,
2450
+ ),
2451
+ ));
2452
+ desertSandNormalView = transformNormalByViewMatrix(
2453
+ desertSandNormalWorld,
2454
+ cameraViewMatrix,
2455
+ );
2456
+ }
2457
+ const desertSandSurface = {
2458
+ color: desertSandColor,
2459
+ emissive: desertSandColor.mul(scalar(profile, 'Desert Sand Emissive', 0.1)),
2460
+ metalness: float(0),
2461
+ normal: desertSandNormalView,
2462
+ roughness: mix(
2463
+ scalar(profile, 'Desert Sand Roughness Min', 0.5),
2464
+ scalar(profile, 'Desert Sand Roughness Max', 0.7),
2465
+ desertSandRoughnessNoise,
2466
+ ),
2467
+ specular: float(scalar(profile, 'Desert Sand Specular', 0.2)),
2468
+ };
2469
+
2470
+ const sourceSurfaces = {
2471
+ DesertDirt: desertDirtSurface,
2472
+ DesertGrass: desertGrassSurface,
2473
+ DesertSand: desertSandSurface,
2474
+ Dirt: dirtSurface,
2475
+ Grass: grassSurface,
2476
+ Rock: rockSurface,
2477
+ Sand: sandSurface,
2478
+ Snow: snowSurface,
2479
+ SnowGrass: snowSurface,
2480
+ SnowGrassBlue: snowGrassBlueSurface,
2481
+ };
2482
+ const sourceRawColors = {
2483
+ DesertDirt: desertDirtBase,
2484
+ DesertGrass: desertGrassSample,
2485
+ DesertSand: desertSandSample,
2486
+ Dirt: dirtSample,
2487
+ Grass: grassPrimary,
2488
+ Rock: rockSample.rgb,
2489
+ Sand: sandSample,
2490
+ // Texture projection is retained, while snow response, sparkle,
2491
+ // weather, tint, and emission remain authored-mode responsibilities.
2492
+ Snow: planar(
2493
+ maps['Snow Texture'],
2494
+ scalar(profile, 'Snow Scale', 5000) / 100,
2495
+ ).rgb,
2496
+ SnowGrass: planar(
2497
+ maps['Snow Texture'],
2498
+ scalar(profile, 'Snow Scale', 5000) / 100,
2499
+ ).rgb,
2500
+ SnowGrassBlue: planar(
2501
+ maps['Snow Texture'],
2502
+ scalar(profile, 'Snow Scale', 5000) / 100,
2503
+ ).rgb,
2504
+ };
2505
+ let surfaces = sourceSurfaces;
2506
+ if (toonLabTerrainLayers) {
2507
+ const toonLabSurface = (layerName) => {
2508
+ const layer = toonLabTerrainLayers[layerName];
2509
+ const layerUv = sourceWorldXY.div(Math.max(layer.tileSize, 0.001));
2510
+ const diffuseMap = maps[`toonLabTerrain${layerName}Diffuse`];
2511
+ const normalMap = maps[`toonLabTerrain${layerName}Normal`];
2512
+ return {
2513
+ color: sourceTextureSample(diffuseMap, layerUv).rgb,
2514
+ emissive: vec3(0),
2515
+ metalness: float(layer.metallic),
2516
+ normal: normalMap
2517
+ ? normalMapNode(
2518
+ sourceTextureSample(normalMap, layerUv).rgb,
2519
+ vec2(layer.normalScale, layer.normalScale),
2520
+ )
2521
+ : normalViewGeometry,
2522
+ roughness: float(1 - layer.smoothness),
2523
+ // TOONLAB Terrain/Lit uses the standard dielectric F0 before its metallic
2524
+ // blend; Three's physical material reaches that with intensity 1.
2525
+ specular: float(1),
2526
+ };
2527
+ };
2528
+ const exact = Object.fromEntries(
2529
+ Object.keys(toonLabTerrainLayers).map((layerName) => [
2530
+ layerName,
2531
+ toonLabSurface(layerName),
2532
+ ]),
2533
+ );
2534
+ surfaces = {
2535
+ ...exact,
2536
+ SnowGrass: exact.Snow,
2537
+ SnowGrassBlue: exact.Snow,
2538
+ };
2539
+ }
2540
+
2541
+ const weightSize = vec2(
2542
+ TOONLAB_SHOWCASE_WEIGHTMAP_CONTRACT.width,
2543
+ TOONLAB_SHOWCASE_WEIGHTMAP_CONTRACT.height,
2544
+ );
2545
+ const weightUv = clamp(
2546
+ landscapeCoord.add(0.5).div(weightSize),
2547
+ vec2(
2548
+ 0.5 / TOONLAB_SHOWCASE_WEIGHTMAP_CONTRACT.width,
2549
+ 0.5 / TOONLAB_SHOWCASE_WEIGHTMAP_CONTRACT.height,
2550
+ ),
2551
+ vec2(
2552
+ (TOONLAB_SHOWCASE_WEIGHTMAP_CONTRACT.width - 0.5)
2553
+ / TOONLAB_SHOWCASE_WEIGHTMAP_CONTRACT.width,
2554
+ (TOONLAB_SHOWCASE_WEIGHTMAP_CONTRACT.height - 0.5)
2555
+ / TOONLAB_SHOWCASE_WEIGHTMAP_CONTRACT.height,
2556
+ ),
2557
+ );
2558
+ const heightSignal = maps.autoCliffNoise
2559
+ ? sourceTextureSample(maps.autoCliffNoise,
2560
+ landscapeCoord.div(Math.max(scalar(profile, 'Height Noise Scale', 30), 0.001)),
2561
+ ).r.mul(scalar(profile, 'Height Noise Strength', 1.1))
2562
+ : float(0);
2563
+ const sourceWeights = {};
2564
+ const modifiedWeights = {};
2565
+ for (const layerName of TOONLAB_SHOWCASE_WEIGHTMAP_CONTRACT.layers) {
2566
+ const binding = weightBindings[layerName];
2567
+ const rawWeight = sourceTextureSample(
2568
+ binding.texture,
2569
+ weightUv,
2570
+ )[binding.channel];
2571
+ sourceWeights[layerName] = rawWeight;
2572
+ modifiedWeights[layerName] = !toonLabTerrainLayers
2573
+ && TOONLAB_SHOWCASE_WEIGHTMAP_CONTRACT.heightBlendLayers.includes(layerName)
2574
+ ? clamp(rawWeight.mul(2).sub(1).add(heightSignal), 0.0001, 1)
2575
+ : rawWeight;
2576
+ }
2577
+ let weightSum = float(0);
2578
+ for (const layerName of TOONLAB_SHOWCASE_WEIGHTMAP_CONTRACT.layers) {
2579
+ weightSum = weightSum.add(modifiedWeights[layerName]);
2580
+ }
2581
+ const normalizedWeightDenominator = max(weightSum, 1e-8);
2582
+ paintedWeights = Object.fromEntries(
2583
+ TOONLAB_SHOWCASE_WEIGHTMAP_CONTRACT.layers.map((layerName) => [
2584
+ layerName,
2585
+ modifiedWeights[layerName].div(normalizedWeightDenominator),
2586
+ ]),
2587
+ );
2588
+ let sourceWeightSum = float(0);
2589
+ for (const layerName of TOONLAB_SHOWCASE_WEIGHTMAP_CONTRACT.layers) {
2590
+ sourceWeightSum = sourceWeightSum.add(sourceWeights[layerName]);
2591
+ }
2592
+ const sourceWeightDenominator = max(sourceWeightSum, 1e-8);
2593
+ const sourcePlacementWeights = Object.fromEntries(
2594
+ TOONLAB_SHOWCASE_WEIGHTMAP_CONTRACT.layers.map((layerName) => [
2595
+ layerName,
2596
+ sourceWeights[layerName].div(sourceWeightDenominator),
2597
+ ]),
2598
+ );
2599
+ const blendField = (field, initial) => {
2600
+ let result = initial;
2601
+ for (const layerName of TOONLAB_SHOWCASE_WEIGHTMAP_CONTRACT.layers) {
2602
+ result = result.add(surfaces[layerName][field].mul(paintedWeights[layerName]));
2603
+ }
2604
+ return result;
2605
+ };
2606
+ paintedSurface = {
2607
+ color: blendField('color', vec3(0)),
2608
+ emissive: blendField('emissive', vec3(0)),
2609
+ metalness: blendField('metalness', float(0)),
2610
+ normal: normalize(blendField('normal', vec3(0))),
2611
+ roughness: blendField('roughness', float(0)),
2612
+ specular: blendField('specular', float(0)),
2613
+ };
2614
+ let rawColorBlend = vec3(0);
2615
+ for (const layerName of TOONLAB_SHOWCASE_WEIGHTMAP_CONTRACT.layers) {
2616
+ rawColorBlend = rawColorBlend.add(
2617
+ sourceRawColors[layerName].mul(sourcePlacementWeights[layerName]),
2618
+ );
2619
+ }
2620
+ shaderSwipeColorNode = rawColorBlend;
2621
+ }
2622
+
2623
+ let colorNode;
2624
+ let roughnessNode;
2625
+ let specularNode;
2626
+ let metalnessNode;
2627
+ let emissiveNode;
2628
+ let normalNode;
2629
+ if (toonLabTerrainLayers) {
2630
+ // ToonLab's supplied landscape is stock TOONLAB Terrain/Lit. It has no ToonLab
2631
+ // AutoCliff, height-blend, day-cycle emission, or rain-wetness stage.
2632
+ colorNode = paintedSurface.color;
2633
+ roughnessNode = paintedSurface.roughness;
2634
+ specularNode = paintedSurface.specular;
2635
+ metalnessNode = paintedSurface.metalness;
2636
+ emissiveNode = paintedSurface.emissive;
2637
+ normalNode = normalize(paintedSurface.normal);
2638
+ cliffMask = float(0);
2639
+ } else {
2640
+ // M_Landscape normalizes the painted layers, replaces them with MF_Rock on
2641
+ // AutoCliff slopes, then applies MF_RainWetness.
2642
+ colorNode = mix(paintedSurface.color, rockSurface.color, cliffMask);
2643
+ roughnessNode = mix(paintedSurface.roughness, rockSurface.roughness, cliffMask);
2644
+ specularNode = mix(paintedSurface.specular, rockSurface.specular, cliffMask);
2645
+ metalnessNode = mix(paintedSurface.metalness, rockSurface.metalness, cliffMask);
2646
+ emissiveNode = mix(paintedSurface.emissive, rockSurface.emissive, cliffMask);
2647
+ normalNode = normalize(mix(paintedSurface.normal, rockSurface.normal, cliffMask));
2648
+ const wet = wetSurface(colorNode, roughnessNode, profile, state);
2649
+ colorNode = wet.colorNode;
2650
+ roughnessNode = wet.roughnessNode;
2651
+ if (switchValue(profile, 'UseWeather?', true)
2652
+ && switchValue(profile, 'RainWetness?', true)) {
2653
+ const wetness = clamp(state.uniforms.rainWetness, 0, 1);
2654
+ specularNode = mix(
2655
+ specularNode,
2656
+ clamp(specularNode.mul(scalar(profile, 'Wet Specular', 1)), 0, 1),
2657
+ wetness,
2658
+ );
2659
+ }
2660
+ }
2661
+
2662
+ const material = new MeshPhysicalNodeMaterial();
2663
+ material.side = THREE.FrontSide;
2664
+ material.colorNode = colorNode;
2665
+ material.roughnessNode = clamp(roughnessNode, 0.02, 1);
2666
+ material.metalnessNode = clamp(metalnessNode, 0, 1);
2667
+ material.specularIntensityNode = clamp(specularNode, 0, 1);
2668
+ material.emissiveNode = emissiveNode;
2669
+ material.normalNode = normalNode;
2670
+ setShaderSwipeBaseline(material, {
2671
+ colorNode: shaderSwipeColorNode,
2672
+ });
2673
+ installToonLabSourceDefaultLitLighting(material);
2674
+ return recordSourceContract(finalizeMaterial(material, profile, 'landscape'), {
2675
+ autoCliff: toonLabTerrainLayers
2676
+ ? 'disabled; absent from ToonLab Terrain/Lit'
2677
+ : 'saturate(remap(VertexNormalWS.z,.85,.8)-noise)',
2678
+ autoGrassAffectsSurface: false,
2679
+ inferredSnow: false,
2680
+ layerBlendOrder: toonLabTerrainLayers
2681
+ ? 'ToonLab Terrain/Lit normalized splat weights'
2682
+ : 'painted-layers-then-auto-cliff-then-rain-wetness',
2683
+ landscapeCoordinates: 'actor-local-quad-units',
2684
+ lighting:
2685
+ 'ToonLab legacy Default Lit Lambert + punctual GGX + captured-SkyLight boundary',
2686
+ rockNormal: 'world-aligned-projection-with-pixel-depth-flattening',
2687
+ weightmaps: {
2688
+ binding: weightBindings
2689
+ ? 'authoritative-ten-mask-three-rgba-packs'
2690
+ : 'diagnostic-grass-fallback',
2691
+ blend: weightBindings
2692
+ ? (toonLabTerrainLayers
2693
+ ? 'ToonLab Terrain/Lit normalized splat weights; no mask/height maps'
2694
+ : 'height:clamp(2*w-1+T_NoiseStylized.r*1.1,.0001,1); '
2695
+ + 'weight:w; normalize-all-ten-together')
2696
+ : null,
2697
+ errors: [...weightInspection.errors],
2698
+ fallback: weightBindings
2699
+ ? null
2700
+ : 'Grass plus source AutoCliff; no inferred painted layers',
2701
+ heightBlendLayers: [...TOONLAB_SHOWCASE_WEIGHTMAP_CONTRACT.heightBlendLayers],
2702
+ requiredLayers: [...TOONLAB_SHOWCASE_WEIGHTMAP_CONTRACT.layers],
2703
+ samplerlessFiltering:
2704
+ 'manual-bilinear-trilinear-textureLoad; authored-address-modes; '
2705
+ + 'P14 dirt base/normal/roughness authored 8x anisotropy',
2706
+ samplerlessColorTransfer:
2707
+ 'WebGPU sRGB texture formats decode on textureLoad; no second shader decode',
2708
+ samplerlessTextureCount: samplerlessTextures.count,
2709
+ status: weightInspection.status,
2710
+ textureNames: weightPackTextures
2711
+ ? weightPackTextures.map((weightTexture) => weightTexture.name)
2712
+ : [],
2713
+ weightBlendLayers: [...TOONLAB_SHOWCASE_WEIGHTMAP_CONTRACT.weightBlendLayers],
2714
+ weightsConnected: Boolean(paintedWeights),
2715
+ },
2716
+ });
2717
+ }
2718
+
2719
+ async function buildWater(profile, context) {
2720
+ const { library, state } = context;
2721
+ const maps = await loadProfileTextures(library, profile, [
2722
+ 'Detail Normal Texture',
2723
+ 'Stylized Texture',
2724
+ 'Waves Displacement Texture',
2725
+ 'Waves Normal Texture',
2726
+ ], { flipY: false });
2727
+ const waterScale = scalar(profile, 'Waves Scale', 8000) / 100;
2728
+ const waveSpeed = scalar(profile, 'Wave Speed', 0.2);
2729
+ const waveUv = positionWorld.xz.div(Math.max(waterScale, 0.001))
2730
+ .add(vec2(state.uniforms.time.mul(waveSpeed * 0.015), state.uniforms.time.mul(waveSpeed * -0.011)));
2731
+ const wave = maps['Waves Displacement Texture']
2732
+ ? texture(maps['Waves Displacement Texture']).sample(waveUv)
2733
+ : null;
2734
+ const scattering = linearColor(vector(profile, 'Scattering Color', [0.02, 0.12, 0.63]));
2735
+ const absorption = linearColor(vector(profile, 'Absorption Color', [1, 0.17, 0]));
2736
+ const facing = pow(clamp(dot(normalize(normalWorld), vec3(0, 1, 0)), 0, 1), 2);
2737
+ const colorNode = mix(scattering, scattering.add(absorption.mul(0.08)), facing);
2738
+ const material = new MeshPhysicalNodeMaterial();
2739
+ material.side = THREE.DoubleSide;
2740
+ material.transparent = true;
2741
+ material.depthWrite = false;
2742
+ material.opacity = 0.78;
2743
+ material.colorNode = colorNode;
2744
+ material.roughnessNode = clamp(float(scalar(profile, 'Roughness', 0.12)), 0.02, 1);
2745
+ material.metalnessNode = clamp(float(scalar(profile, 'Metallic', 0)), 0, 1);
2746
+ material.specularIntensityNode = clamp(float(scalar(profile, 'Specular 2', 0.2)), 0, 1);
2747
+ if (maps['Waves Normal Texture']) {
2748
+ material.normalNode = normalMapNode(
2749
+ texture(maps['Waves Normal Texture']).sample(waveUv).rgb,
2750
+ vec2(1, -1),
2751
+ );
2752
+ }
2753
+ if (wave && switchValue(profile, 'WaterDisplacement?', true)) {
2754
+ const height = scalar(profile, 'Main Wave Displace Height', 80) / 100;
2755
+ material.positionNode = positionLocal.add(vec3(0, wave.r.sub(0.5).mul(height), 0));
2756
+ }
2757
+ return finalizeMaterial(material, profile, 'water');
2758
+ }
2759
+
2760
+ async function buildSky(profile, context) {
2761
+ const { library } = context;
2762
+ const maps = await loadProfileTextures(library, profile, [
2763
+ 'BG Cloud Texture',
2764
+ 'Nebula Texture',
2765
+ 'Star Texture',
2766
+ ], { flipY: false });
2767
+ const atlas = library.resolveCurve(CURVE_ATLASES.sky);
2768
+ const dayCurve = library.resolveCurveAtlasRow(atlas, scalar(profile, 'Day Curve', 0));
2769
+ const dayTexture = library.createCurveTexture(dayCurve);
2770
+ let skyColor = dayTexture
2771
+ ? texture(dayTexture).sample(vec2(clamp(float(1).sub(uv().y), 0, 1), 0.5)).rgb
2772
+ : vec3(0.12, 0.45, 0.9);
2773
+ skyColor = skyColor.mul(scalar(profile, 'Sky Brightness', 1));
2774
+ if (switchValue(profile, 'BackgroundClouds?', true) && maps['BG Cloud Texture']) {
2775
+ const verticalStretch = Math.max(
2776
+ scalar(profile, 'BG Clouds Vertical Stretch', 1),
2777
+ 0.001,
2778
+ );
2779
+ const cloudUv = uv()
2780
+ .sub(0.5)
2781
+ .div(vec2(1, verticalStretch))
2782
+ .add(0.5)
2783
+ .add(vec2(0, scalar(profile, 'BG Clouds Vertical Offset', 0)));
2784
+ const cloud = texture(maps['BG Cloud Texture'])
2785
+ .sample(cloudUv)
2786
+ .rgb
2787
+ .mul(linearColor(vector(profile, 'BG Clouds Tint', [0.529, 0.747966, 1])));
2788
+ const screened = sourceScreen(skyColor, cloud);
2789
+ skyColor = mix(
2790
+ skyColor,
2791
+ screened,
2792
+ scalar(profile, 'BG Clouds Strength', 0.3),
2793
+ );
2794
+ }
2795
+ skyColor = sourceDesaturate(
2796
+ skyColor,
2797
+ 1 - scalar(profile, 'Saturation', 1),
2798
+ );
2799
+ const material = new MeshBasicNodeMaterial();
2800
+ material.side = THREE.FrontSide;
2801
+ material.depthWrite = true;
2802
+ material.depthTest = true;
2803
+ material.fog = true;
2804
+ material.colorNode = skyColor;
2805
+ return recordSourceContract(finalizeMaterial(material, profile, 'sky'), {
2806
+ backgroundClouds: 'static-tinted-texture-screen-blend',
2807
+ blendMode: 'opaque',
2808
+ curveTime: '1-uv0.y',
2809
+ depthTest: true,
2810
+ depthWrite: true,
2811
+ fog: true,
2812
+ shadingModel: 'unlit',
2813
+ sidedness: 'front',
2814
+ temporalDither: 'ToonLab exact graph, Good64x64TilingNoiseHighFreq, Random=1',
2815
+ });
2816
+ }
2817
+
2818
+ async function buildClouds(profile, context) {
2819
+ const { library, state } = context;
2820
+ // M_StylizedClouds_Lite embeds this texture sample directly in its parent
2821
+ // graph, so it does not appear as an overridable instance parameter. It is
2822
+ // nevertheless part of the supplied source material and texture inventory.
2823
+ const cloudMap = await library.loadTexture(CLOUD_LITE_TEXTURE, { flipY: false });
2824
+ const atlas = library.resolveCurve(CURVE_ATLASES.clouds);
2825
+ const curve = library.resolveCurveAtlasRow(
2826
+ atlas,
2827
+ scalar(profile, 'CloudColor', 0),
2828
+ );
2829
+ const curveTexture = library.createCurveTexture(curve);
2830
+ const rotation = scalar(profile, 'Rotation Speed', -0.0005);
2831
+ const verticalStretch = scalar(profile, 'Vertical Stretch', 1);
2832
+ const panned = vec2(
2833
+ uv().x.add(state.uniforms.time.mul(rotation)),
2834
+ uv().y.add(scalar(profile, 'Vertical Offset', 0)),
2835
+ );
2836
+ // Engine/ScaleUVsByCenter divides the centered coordinate by Texture
2837
+ // Scale. Its optional 0-1 mask output is not connected in the source graph.
2838
+ const coordinates = panned.sub(0.5).div(vec2(1, verticalStretch)).add(0.5);
2839
+ const cloudSample = texture(cloudMap).sample(coordinates);
2840
+ // In the source graph the cloud texture's R channel is the CurveTime input
2841
+ // of the CloudColor CurveAtlasRowParameter. Alpha is the silhouette mask;
2842
+ // Strength multiplies the evaluated cloud color, not the mask.
2843
+ const cloudColor = curveTexture
2844
+ ? texture(curveTexture).sample(vec2(clamp(cloudSample.r, 0, 1), 0.5)).rgb
2845
+ : vec3(0.92, 0.96, 1);
2846
+ const cloudMask = sourceTemporalDither(cloudSample.a, state);
2847
+ const cloudStrength = scalar(profile, 'Strength', 1);
2848
+ const material = new MeshBasicNodeMaterial();
2849
+ material.side = THREE.FrontSide;
2850
+ material.transparent = false;
2851
+ material.depthTest = true;
2852
+ material.depthWrite = true;
2853
+ material.fog = true;
2854
+ material.colorNode = cloudColor.mul(cloudStrength);
2855
+ material.opacityNode = cloudMask;
2856
+ material.alphaTestNode = float(1 / 3);
2857
+ material.maskShadowNode = cloudMask.greaterThan(float(1 / 3));
2858
+ material.alphaToCoverage = false;
2859
+ return recordSourceContract(finalizeMaterial(material, profile, 'clouds'), {
2860
+ alpha: 'DitherTemporalAA(T_CloudLayer03.a)',
2861
+ alphaClip: 1 / 3,
2862
+ blendMode: 'masked',
2863
+ color: 'Curve_Clouds_Classic_Day(T_CloudLayer03.r)*Strength',
2864
+ coordinateMaskConnected: false,
2865
+ depthTest: true,
2866
+ depthWrite: true,
2867
+ fog: true,
2868
+ shadingModel: 'unlit',
2869
+ sidedness: 'front',
2870
+ });
2871
+ }
2872
+
2873
+ async function buildFallback(profile, context) {
2874
+ const { library, state } = context;
2875
+ const textureEntries = Object.entries(profile.parameters?.texture ?? {});
2876
+ const colorTexture = textureEntries.find(([name]) =>
2877
+ /(?:base|color|diffuse|texture)/i.test(name)
2878
+ && !/(?:normal|rough|mask|height|displace)/i.test(name));
2879
+ const map = colorTexture
2880
+ ? await library.loadTexture(colorTexture[1]).catch(() => null)
2881
+ : null;
2882
+ const firstVector = Object.values(profile.parameters?.vector ?? {})[0];
2883
+ let colorNode = linearColor(firstVector, [0.65, 0.65, 0.65]);
2884
+ if (map) colorNode = texture(map).sample(uv()).rgb;
2885
+ const material = new MeshPhysicalNodeMaterial();
2886
+ material.side = THREE.DoubleSide;
2887
+ material.colorNode = colorNode;
2888
+ material.roughnessNode = clamp(float(scalar(profile, 'Roughness', 0.7)), 0.02, 1);
2889
+ material.metalnessNode = clamp(float(scalar(profile, 'Metallic', 0)), 0, 1);
2890
+ material.specularIntensityNode = clamp(float(scalar(profile, 'Specular', 0.2)), 0, 1);
2891
+ material.emissiveNode = sourceEmission(colorNode, profile, state);
2892
+ return finalizeMaterial(material, profile, profile.family ?? 'misc');
2893
+ }
2894
+
2895
+ function isStylizedBasicProfile(profile) {
2896
+ return Boolean(profile?.chain?.includes(
2897
+ '/Game/ToonLab/Materials/M_StylizedBasic.M_StylizedBasic',
2898
+ ));
2899
+ }
2900
+
2901
+ /**
2902
+ * Exact active M_StylizedBasic graph used by the supplied cactus and beach
2903
+ * shell instances.
2904
+ *
2905
+ * Unlike ToonLab's S_StylizedBasic counterpart, ToonLab consumes the roughness
2906
+ * texture directly. The optional VT branch follows MF_VTBlend's authored
2907
+ * world-height formulas; no shipped instance enables both landscape blending
2908
+ * and normal blending, so the active source set needs no inferred ground
2909
+ * normal.
2910
+ */
2911
+ async function buildStylizedBasic(profile, context) {
2912
+ const {
2913
+ importedPbr = null,
2914
+ library,
2915
+ sourceActorIdentity,
2916
+ state,
2917
+ } = context;
2918
+ const maps = await loadProfileTextures(library, profile, [
2919
+ 'Base Color Texture',
2920
+ 'Emissive Texture',
2921
+ 'Metallic Texture',
2922
+ 'Normal Texture',
2923
+ 'Roughness Texture',
2924
+ 'Specular Texture',
2925
+ ], { flipY: false });
2926
+ const coordinates = uv();
2927
+ const baseTextureSample = importedPbr?.map
2928
+ ? texture(importedPbr.map).sample(coordinates)
2929
+ : maps['Base Color Texture']
2930
+ ? sourceTextureSample(maps['Base Color Texture'], coordinates)
2931
+ : null;
2932
+ const baseColorFactor = linearColor(
2933
+ importedPbr?.color
2934
+ ? [importedPbr.color.r, importedPbr.color.g, importedPbr.color.b]
2935
+ : vector(profile, 'Base Color', [0.541667, 0.541667, 0.541667]),
2936
+ );
2937
+ let colorNode = baseTextureSample
2938
+ ? baseTextureSample.rgb.mul(baseColorFactor)
2939
+ : baseColorFactor;
2940
+ colorNode = sourceHueVariance(colorNode, profile, sourceActorIdentity);
2941
+
2942
+ const metallicTextureSample = importedPbr?.metalnessMap
2943
+ ? texture(importedPbr.metalnessMap).sample(coordinates)
2944
+ : maps['Metallic Texture']
2945
+ ? sourceTextureSample(maps['Metallic Texture'], coordinates)
2946
+ : null;
2947
+ let metalnessNode = importedPbr
2948
+ ? metallicTextureSample
2949
+ ? metallicTextureSample.b.mul(importedPbr.metalness)
2950
+ : float(importedPbr.metalness)
2951
+ : switchValue(profile, 'MetallicMap?', false) && metallicTextureSample
2952
+ ? metallicTextureSample.r
2953
+ : float(scalar(profile, 'Metallic', 0));
2954
+
2955
+ const roughnessTextureSample = importedPbr?.roughnessMap
2956
+ ? texture(importedPbr.roughnessMap).sample(coordinates)
2957
+ : maps['Roughness Texture']
2958
+ ? sourceTextureSample(maps['Roughness Texture'], coordinates)
2959
+ : null;
2960
+ let roughnessNode = importedPbr
2961
+ ? roughnessTextureSample
2962
+ ? roughnessTextureSample.g.mul(importedPbr.roughness)
2963
+ : float(importedPbr.roughness)
2964
+ : switchValue(profile, 'RoughnessMap?', false) && roughnessTextureSample
2965
+ ? roughnessTextureSample.r
2966
+ : float(scalar(profile, 'Roughness', 0.5));
2967
+
2968
+ const specularTextureSample = maps['Specular Texture']
2969
+ ? sourceTextureSample(maps['Specular Texture'], coordinates)
2970
+ : null;
2971
+ let specularNode = switchValue(profile, 'SpecularMap?', false)
2972
+ && specularTextureSample
2973
+ ? specularTextureSample.r
2974
+ : float(scalar(profile, 'Specular', 0.5));
2975
+
2976
+ let normalNode = normalViewGeometry;
2977
+ const normalTextureSample = importedPbr?.normalMap
2978
+ ? texture(importedPbr.normalMap).sample(coordinates)
2979
+ : maps['Normal Texture']
2980
+ ? sourceTextureSample(maps['Normal Texture'], coordinates)
2981
+ : null;
2982
+ if (importedPbr?.normalMap && normalTextureSample) {
2983
+ normalNode = normalMapNode(
2984
+ normalTextureSample.rgb,
2985
+ vec2(
2986
+ importedPbr.normalScale?.x ?? 1,
2987
+ importedPbr.normalScale?.y ?? 1,
2988
+ ),
2989
+ );
2990
+ } else if (switchValue(profile, 'NormalMap?', false) && normalTextureSample) {
2991
+ const strength = scalar(profile, 'Normal Strength', 1);
2992
+ normalNode = normalMapNode(
2993
+ normalTextureSample.rgb,
2994
+ vec2(strength, -strength),
2995
+ );
2996
+ }
2997
+
2998
+ const blendWithLandscape = switchValue(profile, 'BlendWithLandscape?', false);
2999
+ if (blendWithLandscape) {
3000
+ const groundColor = sampleGroundColor(positionWorld);
3001
+ const groundSurface = sampleGroundSurface(positionWorld);
3002
+ const heightDeltaCm = positionWorld.y
3003
+ .sub(sampleGroundHeight(positionWorld))
3004
+ .mul(100);
3005
+ const distanceCm = Math.max(
3006
+ scalar(profile, 'VT Blend - Distance', 100),
3007
+ 0.001,
3008
+ );
3009
+ const offsetCm = scalar(profile, 'VT Blend - Offset', 0);
3010
+ const falloff = Math.max(scalar(profile, 'VT Blend - Falloff', 2), 0.001);
3011
+ const colorAlpha = pow(
3012
+ float(1).sub(clamp(
3013
+ heightDeltaCm.add(offsetCm).div(distanceCm),
3014
+ 0,
3015
+ 1,
3016
+ )),
3017
+ falloff,
3018
+ ).mul(groundColor.a);
3019
+ const surfaceAlpha = float(1).sub(clamp(
3020
+ heightDeltaCm.div(distanceCm / 6),
3021
+ 0,
3022
+ 1,
3023
+ )).mul(groundSurface.a);
3024
+ colorNode = mix(colorNode, groundColor.rgb, colorAlpha);
3025
+ specularNode = mix(specularNode, groundSurface.g, surfaceAlpha);
3026
+ // The only supplied instance with BlendWithLandscape? enabled has
3027
+ // BlendNormals? disabled. Preserve its authored local normal exactly.
3028
+ }
3029
+
3030
+ const emissiveTextureSample = importedPbr?.emissiveMap
3031
+ ? texture(importedPbr.emissiveMap).sample(coordinates)
3032
+ : maps['Emissive Texture']
3033
+ ? sourceTextureSample(maps['Emissive Texture'], coordinates)
3034
+ : null;
3035
+ const importedEmissive = importedPbr
3036
+ ? linearColor([
3037
+ importedPbr.emissive.r,
3038
+ importedPbr.emissive.g,
3039
+ importedPbr.emissive.b,
3040
+ ]).mul(importedPbr.emissiveIntensity)
3041
+ : null;
3042
+ const emissiveInput = importedPbr
3043
+ ? emissiveTextureSample
3044
+ ? emissiveTextureSample.rgb.mul(importedEmissive)
3045
+ : importedEmissive
3046
+ : switchValue(profile, 'EmissiveMap?', false) && emissiveTextureSample
3047
+ ? emissiveTextureSample.rgb
3048
+ : colorNode;
3049
+ const emissiveNode = applyDayCycleEmission(
3050
+ importedPbr
3051
+ ? emissiveInput
3052
+ : emissiveInput.mul(scalar(profile, 'Emissive Strength', 0)),
3053
+ profile,
3054
+ state,
3055
+ );
3056
+
3057
+ const material = new MeshPhysicalNodeMaterial();
3058
+ material.side = THREE.FrontSide;
3059
+ material.colorNode = colorNode;
3060
+ material.metalnessNode = clamp(metalnessNode, 0, 1);
3061
+ // M_StylizedBasic outputs ToonLab roughness directly. Do not apply the
3062
+ // smoothness inversion used by ToonLab's S_StylizedBasic port.
3063
+ material.roughnessNode = clamp(roughnessNode, 0, 1);
3064
+ material.specularIntensityNode = clamp(specularNode, 0, 1);
3065
+ material.normalNode = normalNode;
3066
+ material.emissiveNode = emissiveNode;
3067
+ setShaderSwipeBaseline(material, {
3068
+ colorNode: baseTextureSample
3069
+ ? baseTextureSample.rgb.mul(baseColorFactor)
3070
+ : baseColorFactor,
3071
+ });
3072
+ installToonLabSourceDefaultLitLighting(material);
3073
+ return recordSourceContract(finalizeMaterial(
3074
+ material,
3075
+ profile,
3076
+ 'stylizedBasic',
3077
+ ), {
3078
+ baseColor: 'UseColorTexture? Base Color Texture : Base Color; MF_HueVariance',
3079
+ blendNormals: blendWithLandscape
3080
+ ? 'authored disabled on every active VT-blended source instance'
3081
+ : 'inactive because BlendWithLandscape? is false',
3082
+ emissive: 'EmissiveMap? texture : post-hue base; strength; MF_DayCycleEmission',
3083
+ landscapeBlend: blendWithLandscape
3084
+ ? 'MF_VTBlend world-height color and specular branches'
3085
+ : 'inactive',
3086
+ lighting: 'ToonLab Default Lit',
3087
+ metallic: 'MetallicMap? texture.r : Metallic',
3088
+ normal: switchValue(profile, 'NormalMap?', false)
3089
+ ? 'FlattenNormal(Normal Texture, 1-Normal Strength)'
3090
+ : 'tangent-space +Z / authored geometry normal',
3091
+ roughness: 'RoughnessMap? texture.r : Roughness; direct ToonLab roughness',
3092
+ shadingModel: 'MSM_DEFAULT_LIT',
3093
+ sidedness: 'front',
3094
+ specular: 'SpecularMap? texture.r : Specular',
3095
+ sourceGraph: '/Game/ToonLab/Materials/M_StylizedBasic',
3096
+ vtBlend: blendWithLandscape
3097
+ ? {
3098
+ baseAlpha: 'pow(1-saturate((WorldZ-GroundZ+Offset)/Distance),Falloff)',
3099
+ normalBlend: switchValue(profile, 'BlendNormals?', false),
3100
+ surfaceAlpha: '1-saturate((WorldZ-GroundZ)/(Distance/6))',
3101
+ }
3102
+ : null,
3103
+ });
3104
+ }
3105
+
3106
+ /**
3107
+ * Route an ordinary imported PBR material through the Call Me Sensei
3108
+ * manufactured-surface implementation without changing the imported mesh.
3109
+ *
3110
+ * This is intentionally narrow: it preserves the authored PBR factors, maps,
3111
+ * normal strength, emission, and sidedness present in the supplied GLB.
3112
+ */
3113
+ export async function createToonLabBasicMaterialFromPbr(
3114
+ sourceMaterial,
3115
+ {
3116
+ library,
3117
+ sourceActorIdentity = null,
3118
+ sourceAssetName = 'imported-solid-prop',
3119
+ state = null,
3120
+ } = {},
3121
+ ) {
3122
+ if (!library) {
3123
+ throw new Error('createToonLabBasicMaterialFromPbr requires a source library.');
3124
+ }
3125
+ const color = sourceMaterial?.color ?? new THREE.Color(1, 1, 1);
3126
+ const profileName = String(sourceMaterial?.name || 'ImportedSolid')
3127
+ .replace(/[^A-Za-z0-9_-]+/g, '_');
3128
+ const profile = {
3129
+ path: `/ToonLab/CallMeSensei/${sourceAssetName}/${profileName}.${profileName}`,
3130
+ family: 'misc',
3131
+ chain: [
3132
+ `/ToonLab/CallMeSensei/${sourceAssetName}/${profileName}.${profileName}`,
3133
+ '/Game/ToonLab/Materials/M_StylizedBasic.M_StylizedBasic',
3134
+ ],
3135
+ parameters: {
3136
+ scalar: {
3137
+ 'Day Emission Multiplier': 1,
3138
+ 'Emissive Strength': 0,
3139
+ 'Hue Shift': 0,
3140
+ 'Hue Variation': 0,
3141
+ Metallic: Number(sourceMaterial?.metalness) || 0,
3142
+ 'Night Emission Multiplier': 0,
3143
+ 'Normal Strength': 0,
3144
+ 'Overcast Emission Multiplier': 0.25,
3145
+ Roughness: Number.isFinite(sourceMaterial?.roughness)
3146
+ ? sourceMaterial.roughness
3147
+ : 0.5,
3148
+ Specular: Number.isFinite(sourceMaterial?.specularIntensity)
3149
+ ? sourceMaterial.specularIntensity
3150
+ : 0.5,
3151
+ 'Sunrise Emission Multiplier': 0.1,
3152
+ 'Sunset Emission Multiplier': 0.1,
3153
+ },
3154
+ vector: {
3155
+ 'Base Color': [color.r, color.g, color.b, 1],
3156
+ },
3157
+ texture: {},
3158
+ static_switch: {
3159
+ 'BlendNormals?': false,
3160
+ 'BlendWithLandscape?': false,
3161
+ 'EmissiveMap?': false,
3162
+ 'MetallicMap?': false,
3163
+ 'NormalMap?': false,
3164
+ 'RoughnessMap?': false,
3165
+ 'SpecularMap?': false,
3166
+ 'UseColorTexture?': false,
3167
+ // Call Me Sensei owns the general solid-surface response only. Imported
3168
+ // emission is preserved verbatim; time/weather modulation remains
3169
+ // frozen until its declared checkpoint.
3170
+ 'UseDayCycleEmission?': false,
3171
+ 'UseWeather?': false,
3172
+ },
3173
+ },
3174
+ };
3175
+ const material = await buildStylizedBasic(profile, {
3176
+ hasUv2: false,
3177
+ hasVertexColors: false,
3178
+ importedPbr: {
3179
+ color,
3180
+ emissive: sourceMaterial?.emissive ?? new THREE.Color(0, 0, 0),
3181
+ emissiveIntensity: Number.isFinite(sourceMaterial?.emissiveIntensity)
3182
+ ? sourceMaterial.emissiveIntensity
3183
+ : 1,
3184
+ emissiveMap: sourceMaterial?.emissiveMap ?? null,
3185
+ map: sourceMaterial?.map ?? null,
3186
+ metalness: Number.isFinite(sourceMaterial?.metalness)
3187
+ ? sourceMaterial.metalness
3188
+ : 0,
3189
+ metalnessMap: sourceMaterial?.metalnessMap ?? null,
3190
+ normalMap: sourceMaterial?.normalMap ?? null,
3191
+ normalScale: sourceMaterial?.normalScale ?? new THREE.Vector2(1, 1),
3192
+ roughness: Number.isFinite(sourceMaterial?.roughness)
3193
+ ? sourceMaterial.roughness
3194
+ : 0.5,
3195
+ roughnessMap: sourceMaterial?.roughnessMap ?? null,
3196
+ },
3197
+ library,
3198
+ sourceActorIdentity,
3199
+ sourceAssetName,
3200
+ sourceSceneVariant: 'call-me-sensei-imported-solid-prop',
3201
+ state: state ?? createToonLabSourceEnvironmentState(library),
3202
+ });
3203
+ material.name = `CallMeSensei::${sourceAssetName}::${profileName}`;
3204
+ // Fab/Sketchfab GLBs commonly author foliage-like thin pieces, slats, and
3205
+ // lamp housings as double-sided. M_StylizedBasic's native beach fixtures
3206
+ // remain front-sided, while the imported adapter preserves the GLB's
3207
+ // explicit surface contract.
3208
+ material.side = sourceMaterial?.side ?? THREE.FrontSide;
3209
+ material.userData.toonLabSource.reconstruction =
3210
+ 'imported-pbr-input-through-M_StylizedBasic';
3211
+ material.userData.toonLabSource.contract.inputAuthority = {
3212
+ baseColor: sourceMaterial?.map
3213
+ ? 'GLB pbrMetallicRoughness.baseColorTexture * baseColorFactor'
3214
+ : 'GLB pbrMetallicRoughness.baseColorFactor',
3215
+ emission: sourceMaterial?.emissiveMap
3216
+ ? 'GLB emissiveTexture * emissiveFactor * KHR_materials_emissive_strength'
3217
+ : 'GLB emissiveFactor * KHR_materials_emissive_strength',
3218
+ metallic: sourceMaterial?.metalnessMap
3219
+ ? 'GLB metallicRoughnessTexture.b * metallicFactor'
3220
+ : 'GLB pbrMetallicRoughness.metallicFactor',
3221
+ normal: sourceMaterial?.normalMap
3222
+ ? 'GLB normalTexture with authored normalScale'
3223
+ : 'authored geometry normal',
3224
+ roughness: sourceMaterial?.roughnessMap
3225
+ ? 'GLB metallicRoughnessTexture.g * roughnessFactor'
3226
+ : 'GLB pbrMetallicRoughness.roughnessFactor',
3227
+ sidedness: material.side === THREE.DoubleSide
3228
+ ? 'GLB doubleSided'
3229
+ : 'GLB front-sided',
3230
+ texture: sourceMaterial?.map
3231
+ || sourceMaterial?.metalnessMap
3232
+ || sourceMaterial?.roughnessMap
3233
+ || sourceMaterial?.normalMap
3234
+ || sourceMaterial?.emissiveMap
3235
+ ? 'embedded GLB PBR maps decoded by GLTFLoader with authored color spaces'
3236
+ : 'none authored in supplied GLB',
3237
+ };
3238
+ return material;
3239
+ }
3240
+
3241
+ async function buildToonLabRock(profile, context) {
3242
+ if (!toonRockMaterialIndexPromise) {
3243
+ toonRockMaterialIndexPromise = loadToonLabRockMaterialIndex()
3244
+ .catch((error) => {
3245
+ toonRockMaterialIndexPromise = null;
3246
+ throw error;
3247
+ });
3248
+ }
3249
+ const index = await toonRockMaterialIndexPromise;
3250
+ const resolution = resolveToonLabRockMaterial(profile, {
3251
+ allowFallback: true,
3252
+ index,
3253
+ sourceAssetName: context.sourceAssetName,
3254
+ });
3255
+ if (!resolution?.materialRecord) {
3256
+ throw new Error(`No ToonLab S_Rock profile matches ${profile.path}.`);
3257
+ }
3258
+ const material = await loadToonRockMaterial({
3259
+ manifest: index.manifest,
3260
+ material: resolution.materialRecord,
3261
+ coordinates: {
3262
+ zSign: 1,
3263
+ // Both the ToonLab material parameters and the glTF/Three scene are in
3264
+ // metres. These values are intentionally not converted from ToonLab units:
3265
+ // ToonLab's authored 500/15000/20000 distance thresholds must remain
3266
+ // 500/15000/20000 world metres.
3267
+ distanceScale: 1,
3268
+ },
3269
+ });
3270
+ finalizeMaterial(material, profile, 'rock');
3271
+ Object.assign(material.userData.toonLabSource, {
3272
+ reconstruction: 'toonlab-s-rock',
3273
+ toonLabMaterial: resolution.toonLabMaterialName,
3274
+ toonLabProfileId: resolution.profileId,
3275
+ toonLabMatchKind: resolution.matchKind,
3276
+ toonLabExactProfile: resolution.isExact,
3277
+ sourceDistanceScale: 1,
3278
+ });
3279
+ return recordSourceContract(material, {
3280
+ alpha: 'opaque',
3281
+ baseColor: 'ToonLab S_Rock ToonLab graph',
3282
+ distance: 'radial world distance; ToonLab metres preserved 1:1',
3283
+ layers: 'Grass -> Snow -> Sand sequential SG_SubLayer chain',
3284
+ lighting: 'TOONLAB Lit metallic-workflow adapter',
3285
+ normal: 'ToonLabGraph triplanar + distance flatten + NormalBlend',
3286
+ sourceEngine: 'ToonLab reference renderer',
3287
+ sourceMaterial: resolution.toonLabMaterialName,
3288
+ sourceProfileExact: resolution.isExact,
3289
+ });
3290
+ }
3291
+
3292
+ async function buildToonLabMountain(profile, context) {
3293
+ if (!toonRockMaterialIndexPromise) {
3294
+ toonRockMaterialIndexPromise = loadToonLabRockMaterialIndex()
3295
+ .catch((error) => {
3296
+ toonRockMaterialIndexPromise = null;
3297
+ throw error;
3298
+ });
3299
+ }
3300
+ const index = await toonRockMaterialIndexPromise;
3301
+ const resolution = resolveToonLabRockMaterial(profile, {
3302
+ allowFallback: true,
3303
+ index,
3304
+ sourceAssetName: context.sourceAssetName,
3305
+ });
3306
+ if (!resolution?.materialRecord) {
3307
+ throw new Error(`No ToonLab S_Mountain profile matches ${profile.path}.`);
3308
+ }
3309
+ const material = await loadToonLabMountainMaterial({
3310
+ manifest: index.manifest,
3311
+ material: resolution.materialRecord,
3312
+ coordinates: {
3313
+ zSign: 1,
3314
+ // This showcase geometry came through ToonLab's glTF exporter. Its UV V is
3315
+ // the inverse of the supplied ToonLab FBX, which matters only where the
3316
+ // graph treats UV.y as scalar height rather than as texture coordinates.
3317
+ flipProceduralUvY: true,
3318
+ },
3319
+ });
3320
+ finalizeMaterial(material, profile, 'mountain');
3321
+ Object.assign(material.userData.toonLabSource, {
3322
+ reconstruction: 'toonlab-s-mountain',
3323
+ toonLabMaterial: resolution.toonLabMaterialName,
3324
+ toonLabProfileId: resolution.profileId,
3325
+ toonLabMatchKind: resolution.matchKind,
3326
+ toonLabExactProfile: resolution.isExact,
3327
+ });
3328
+ return recordSourceContract(material, {
3329
+ baseColor: 'ToonLab S_Mountain ToonLab graph',
3330
+ grass: 'world-XZ sample + geometry slope + procedural UV0 height fade',
3331
+ lighting: 'TOONLAB Lit metallic-workflow adapter',
3332
+ normal: 'authored geometry normal (S_Mountain has no connected normal map)',
3333
+ snow: 'world-XZ sample + reversed UV0 height gradient + noise threshold',
3334
+ sourceEngine: 'ToonLab reference renderer',
3335
+ sourceMaterial: resolution.toonLabMaterialName,
3336
+ sourceProfileExact: resolution.isExact,
3337
+ });
3338
+ }
3339
+
3340
+ async function buildToonLabPineLeaves(profile, context) {
3341
+ const result = await buildToonLabPineLeavesMaterial(profile, context);
3342
+ finalizeMaterial(result.material, profile, 'leaves');
3343
+ Object.assign(result.material.userData.toonLabSource, {
3344
+ reconstruction: result.reconstruction,
3345
+ toonLabExactProfile: true,
3346
+ toonLabSourceGraph: result.sourceGraph,
3347
+ toonLabSourceMaterial: result.sourceMaterial,
3348
+ });
3349
+ return recordSourceContract(result.material, result.contract);
3350
+ }
3351
+
3352
+ async function buildToonLabPineBark(profile, context) {
3353
+ const result = await buildToonLabPineBarkMaterial(profile, context);
3354
+ finalizeMaterial(result.material, profile, 'bark');
3355
+ Object.assign(result.material.userData.toonLabSource, {
3356
+ reconstruction: result.reconstruction,
3357
+ toonLabExactProfile: true,
3358
+ toonLabSourceGraph: result.sourceGraph,
3359
+ toonLabSourceMaterial: result.sourceMaterial,
3360
+ });
3361
+ return recordSourceContract(result.material, result.contract);
3362
+ }
3363
+
3364
+ async function buildTemplate(profile, context) {
3365
+ if (isStylizedBasicProfile(profile)) {
3366
+ return buildStylizedBasic(profile, context);
3367
+ }
3368
+ switch (profile.family) {
3369
+ case 'rock':
3370
+ // ToonLab is the portable shader authority for the rock family. Resolve
3371
+ // the exact MV_* counterpart of every imported MI_* slot and execute the
3372
+ // supplied S_Rock graph/property chain. The literal ToonLab reconstruction
3373
+ // remains available in Rock Lab for forensic A/B checks, but is not the
3374
+ // production showcase binding.
3375
+ return buildToonLabRock(profile, context);
3376
+ case 'mountain':
3377
+ return buildToonLabMountain(profile, context);
3378
+ case 'leaves':
3379
+ return isToonLabPineLeavesProfile(profile)
3380
+ && context.sourceAssetName !== TOONLAB_SHOWCASE_SOURCE_ASSET
3381
+ ? buildToonLabPineLeaves(profile, context)
3382
+ : buildLeaves(profile, context);
3383
+ case 'foliage': return buildFoliage(profile, context);
3384
+ case 'bark':
3385
+ return isToonLabPineBarkProfile(profile)
3386
+ && context.sourceAssetName !== TOONLAB_SHOWCASE_SOURCE_ASSET
3387
+ ? buildToonLabPineBark(profile, context)
3388
+ : buildBark(profile, context);
3389
+ case 'treeLod': return buildTreeLod(profile, context);
3390
+ case 'landscape': return buildToonLabLandscapeMaterial(profile, context);
3391
+ case 'snow': return buildSnow(profile, context);
3392
+ case 'water':
3393
+ case 'waterLegacy': return buildWater(profile, context);
3394
+ case 'sky': return buildSky(profile, context);
3395
+ case 'clouds': return buildClouds(profile, context);
3396
+ default: return buildFallback(profile, context);
3397
+ }
3398
+ }
3399
+
3400
+ /**
3401
+ * Builds one uncached material from an already-resolved source profile.
3402
+ *
3403
+ * Shader-profile adapters use this path when editor settings deliberately
3404
+ * create a new parameterized profile with the same source material path.
3405
+ * The ordinary `createToonLabSourceMaterial()` cache is path-based and is
3406
+ * therefore correct for immutable source profiles but not for live authoring.
3407
+ */
3408
+ export async function createToonLabSourceMaterialFromProfile(profileReference, {
3409
+ hasUv2 = false,
3410
+ hasVertexColors = false,
3411
+ library,
3412
+ sourceActorIdentity = null,
3413
+ sourceAssetName = null,
3414
+ sourceSceneVariant = null,
3415
+ state = null,
3416
+ } = {}) {
3417
+ if (!library) {
3418
+ throw new Error('createToonLabSourceMaterialFromProfile requires a source library.');
3419
+ }
3420
+ const resolved = library.resolveMaterial(profileReference);
3421
+ if (!resolved) {
3422
+ throw new Error(`Unknown ToonLab material profile: ${profileReference}`);
3423
+ }
3424
+ const profile = sourceSceneProfile(
3425
+ resolved,
3426
+ sourceAssetName,
3427
+ sourceSceneVariant,
3428
+ );
3429
+ const environmentState = state ?? createToonLabSourceEnvironmentState(library);
3430
+ const material = await buildTemplate(profile, {
3431
+ hasUv2,
3432
+ hasVertexColors,
3433
+ library,
3434
+ sourceActorIdentity,
3435
+ sourceAssetName,
3436
+ sourceSceneVariant,
3437
+ state: environmentState,
3438
+ });
3439
+ return rehydrateToonLabSourceMaterialLighting(material);
3440
+ }
3441
+
3442
+ export async function createToonLabSourceMaterial(profileReference, {
3443
+ hasUv2 = false,
3444
+ hasVertexColors = false,
3445
+ library,
3446
+ sourceActorIdentity = null,
3447
+ sourceAssetName = null,
3448
+ sourceSceneVariant = null,
3449
+ state = null,
3450
+ } = {}) {
3451
+ if (!library) throw new Error('createToonLabSourceMaterial requires a source library.');
3452
+ const profile = sourceSceneProfile(
3453
+ library.resolveMaterial(profileReference),
3454
+ sourceAssetName,
3455
+ sourceSceneVariant,
3456
+ );
3457
+ if (!profile) throw new Error(`Unknown ToonLab material profile: ${profileReference}`);
3458
+ const environmentState = state ?? createToonLabSourceEnvironmentState(library);
3459
+ if (!templateCaches.has(library)) templateCaches.set(library, new Map());
3460
+ const cache = templateCaches.get(library);
3461
+ const sourceActorIdentityKey = sourceActorIdentity
3462
+ ? [
3463
+ ...(sourceActorIdentity.locationCm ?? [0, 0, 0]),
3464
+ Number(sourceActorIdentity.perInstanceRandom) || 0,
3465
+ ].join(',')
3466
+ : '';
3467
+ const key = `${profile.path}|uv2:${hasUv2 ? 1 : 0}|vc:${hasVertexColors ? 1 : 0}`
3468
+ + `|asset:${sourceAssetName ?? ''}|variant:${sourceSceneVariant ?? ''}`
3469
+ + `|actor:${sourceActorIdentityKey}`;
3470
+ if (!cache.has(key)) {
3471
+ cache.set(key, buildTemplate(profile, {
3472
+ hasUv2,
3473
+ hasVertexColors,
3474
+ library,
3475
+ sourceActorIdentity,
3476
+ sourceAssetName,
3477
+ sourceSceneVariant,
3478
+ state: environmentState,
3479
+ }).catch((error) => {
3480
+ cache.delete(key);
3481
+ throw error;
3482
+ }));
3483
+ }
3484
+ const template = await cache.get(key);
3485
+ const material = template.clone();
3486
+ material.name = template.name;
3487
+ material.userData = JSON.parse(JSON.stringify(template.userData ?? {}));
3488
+ copySurfaceMaterialModes(template, material);
3489
+ return rehydrateToonLabSourceMaterialLighting(material);
3490
+ }
3491
+
3492
+ export async function applyToonLabSourceMaterials(root, {
3493
+ library,
3494
+ sourceActorIdentity = null,
3495
+ sourceAssetName,
3496
+ sourceSceneVariant = null,
3497
+ state = null,
3498
+ } = {}) {
3499
+ if (!library) throw new Error('applyToonLabSourceMaterials requires a source library.');
3500
+ if (!sourceAssetName) throw new Error('applyToonLabSourceMaterials requires sourceAssetName.');
3501
+ const environmentState = state ?? createToonLabSourceEnvironmentState(library);
3502
+ const jobs = [];
3503
+ const unresolved = [];
3504
+ let materialCount = 0;
3505
+ let meshCount = 0;
3506
+ root.traverse((object) => {
3507
+ if (!object.isMesh || !object.material) return;
3508
+ meshCount += 1;
3509
+ if (!object.geometry.attributes.normal) object.geometry.computeVertexNormals();
3510
+ const originals = Array.isArray(object.material) ? object.material : [object.material];
3511
+ const replacements = new Array(originals.length);
3512
+ const shadowSlots = new Array(originals.length).fill(true);
3513
+ const materialJobs = originals.map((original, materialIndex) => {
3514
+ const resolved = library.resolveMeshSlot(
3515
+ sourceAssetName,
3516
+ original?.name,
3517
+ materialIndex,
3518
+ );
3519
+ if (!resolved?.profile) {
3520
+ unresolved.push({
3521
+ material: original?.name ?? '',
3522
+ materialIndex,
3523
+ object: object.name ?? '',
3524
+ });
3525
+ replacements[materialIndex] = original;
3526
+ return Promise.resolve();
3527
+ }
3528
+ materialCount += 1;
3529
+ shadowSlots[materialIndex] = sourceProfileCastsShadow(resolved.profile);
3530
+ return createToonLabSourceMaterial(resolved.profile, {
3531
+ hasUv2: Boolean(object.geometry.attributes.uv2),
3532
+ hasVertexColors: Boolean(object.geometry.attributes.color),
3533
+ library,
3534
+ sourceActorIdentity,
3535
+ sourceAssetName,
3536
+ sourceSceneVariant,
3537
+ state: environmentState,
3538
+ }).then((material) => {
3539
+ replacements[materialIndex] = material;
3540
+ });
3541
+ });
3542
+ jobs.push(Promise.all(materialJobs).then(() => {
3543
+ object.material = Array.isArray(object.material) ? replacements : replacements[0];
3544
+ object.castShadow = shadowSlots.some(Boolean);
3545
+ object.receiveShadow = true;
3546
+ object.userData.toonLabSourceAsset = sourceAssetName;
3547
+ }));
3548
+ });
3549
+ await Promise.all(jobs);
3550
+ return {
3551
+ materialCount,
3552
+ meshCount,
3553
+ sourceAssetName,
3554
+ state: environmentState,
3555
+ unresolved,
3556
+ };
3557
+ }
3558
+
3559
+ export async function applyToonLabNamedSourceMaterials(root, {
3560
+ library,
3561
+ sourceActorIdentity = null,
3562
+ sourceAssetName = 'authored-scene',
3563
+ sourceSceneVariant = null,
3564
+ state = null,
3565
+ } = {}) {
3566
+ if (!library) throw new Error('applyToonLabNamedSourceMaterials requires a source library.');
3567
+ const environmentState = state ?? createToonLabSourceEnvironmentState(library);
3568
+ const materials = new Map();
3569
+ const importedMaterials = new Set();
3570
+ const unresolved = [];
3571
+ let meshCount = 0;
3572
+
3573
+ const jobs = [];
3574
+ root.traverse((object) => {
3575
+ if (!object.isMesh || !object.material) return;
3576
+ meshCount += 1;
3577
+ if (!object.geometry.attributes.normal) object.geometry.computeVertexNormals();
3578
+ const originals = Array.isArray(object.material) ? object.material : [object.material];
3579
+ originals.forEach((material) => importedMaterials.add(material));
3580
+ const shadowSlots = new Array(originals.length).fill(true);
3581
+ jobs.push(Promise.all(originals.map(async (original, materialIndex) => {
3582
+ const profile = library.resolveMaterial(original?.name);
3583
+ if (!profile) {
3584
+ unresolved.push({
3585
+ material: original?.name ?? '',
3586
+ materialIndex,
3587
+ object: object.name ?? '',
3588
+ });
3589
+ return original;
3590
+ }
3591
+ const hasVertexColors = Boolean(object.geometry.attributes.color);
3592
+ const hasUv2 = Boolean(object.geometry.attributes.uv2);
3593
+ shadowSlots[materialIndex] = sourceProfileCastsShadow(profile);
3594
+ const key = `${profile.path}|uv2:${hasUv2 ? 1 : 0}|vc:${hasVertexColors ? 1 : 0}`
3595
+ + `|variant:${sourceSceneVariant ?? ''}`
3596
+ + `|actor:${sourceActorIdentity
3597
+ ? [
3598
+ ...(sourceActorIdentity.locationCm ?? [0, 0, 0]),
3599
+ Number(sourceActorIdentity.perInstanceRandom) || 0,
3600
+ ].join(',')
3601
+ : ''}`;
3602
+ if (!materials.has(key)) {
3603
+ materials.set(key, createToonLabSourceMaterial(profile, {
3604
+ hasUv2,
3605
+ hasVertexColors,
3606
+ library,
3607
+ sourceActorIdentity,
3608
+ sourceAssetName,
3609
+ sourceSceneVariant,
3610
+ state: environmentState,
3611
+ }));
3612
+ }
3613
+ return materials.get(key);
3614
+ })).then((replacements) => {
3615
+ object.material = Array.isArray(object.material) ? replacements : replacements[0];
3616
+ object.castShadow = shadowSlots.some(Boolean);
3617
+ object.receiveShadow = true;
3618
+ object.userData.toonLabSourceAsset = sourceAssetName;
3619
+ }));
3620
+ });
3621
+ await Promise.all(jobs);
3622
+ for (const imported of importedMaterials) imported?.dispose?.();
3623
+ return {
3624
+ materialCount: materials.size,
3625
+ meshCount,
3626
+ sourceAssetName,
3627
+ state: environmentState,
3628
+ unresolved,
3629
+ };
3630
+ }
3631
+
3632
+ function isFailedAuthoredBakeMaterial(material) {
3633
+ if (!material || material.map) return false;
3634
+ const color = material.color;
3635
+ return Boolean(
3636
+ color
3637
+ && color.r >= 0.95
3638
+ && color.g <= 0.05
3639
+ && color.b >= 0.95,
3640
+ );
3641
+ }
3642
+
3643
+ /**
3644
+ * Repairs only the explicit magenta failure sentinels emitted by ToonLab's
3645
+ * glTF material baker. Successful per-mesh native bakes remain untouched;
3646
+ * failed slots fall back to the audited live reconstruction of the same
3647
+ * source material instance.
3648
+ */
3649
+ export async function repairToonLabAuthoredBakeMaterials(root, {
3650
+ library,
3651
+ sourceAssetName = 'authored-scene',
3652
+ state = null,
3653
+ } = {}) {
3654
+ if (!library) throw new Error('repairToonLabAuthoredBakeMaterials requires a source library.');
3655
+ const environmentState = state ?? createToonLabSourceEnvironmentState(library);
3656
+ const liveMaterials = new Map();
3657
+ const importedMaterials = new Set();
3658
+ const replacedMaterials = new Set();
3659
+ const unresolved = [];
3660
+ let fallbackSlotCount = 0;
3661
+ let meshCount = 0;
3662
+
3663
+ const jobs = [];
3664
+ root.traverse((object) => {
3665
+ if (!object.isMesh || !object.material) return;
3666
+ meshCount += 1;
3667
+ if (!object.geometry.attributes.normal) object.geometry.computeVertexNormals();
3668
+ const originals = Array.isArray(object.material) ? object.material : [object.material];
3669
+ originals.forEach((material) => importedMaterials.add(material));
3670
+ jobs.push(Promise.all(originals.map(async (original, materialIndex) => {
3671
+ if (!isFailedAuthoredBakeMaterial(original)) return original;
3672
+ const profile = library.resolveAuthoredBakeMaterial(original?.name);
3673
+ if (!profile) {
3674
+ unresolved.push({
3675
+ material: original?.name ?? '',
3676
+ materialIndex,
3677
+ object: object.name ?? '',
3678
+ });
3679
+ return original;
3680
+ }
3681
+ const hasVertexColors = Boolean(object.geometry.attributes.color);
3682
+ const hasUv2 = Boolean(object.geometry.attributes.uv2);
3683
+ const key = `${profile.path}|uv2:${hasUv2 ? 1 : 0}|vc:${hasVertexColors ? 1 : 0}`;
3684
+ if (!liveMaterials.has(key)) {
3685
+ liveMaterials.set(key, createToonLabSourceMaterial(profile, {
3686
+ hasUv2,
3687
+ hasVertexColors,
3688
+ library,
3689
+ sourceAssetName,
3690
+ state: environmentState,
3691
+ }));
3692
+ }
3693
+ fallbackSlotCount += 1;
3694
+ replacedMaterials.add(original);
3695
+ return liveMaterials.get(key);
3696
+ })).then((replacements) => {
3697
+ object.material = Array.isArray(object.material) ? replacements : replacements[0];
3698
+ object.castShadow = true;
3699
+ object.receiveShadow = true;
3700
+ object.userData.toonLabSourceAsset = sourceAssetName;
3701
+ }));
3702
+ });
3703
+ await Promise.all(jobs);
3704
+ for (const material of replacedMaterials) {
3705
+ if (importedMaterials.has(material)) material.dispose?.();
3706
+ }
3707
+ return {
3708
+ fallbackMaterialCount: liveMaterials.size,
3709
+ fallbackSlotCount,
3710
+ meshCount,
3711
+ sourceAssetName,
3712
+ state: environmentState,
3713
+ unresolved,
3714
+ };
3715
+ }
3716
+
3717
+ export const TOONLAB_SOURCE_MATERIAL_BASE_URL =
3718
+ DEFAULT_TOONLAB_SOURCE_BASE_URL;