threedog 0.1.0 → 0.2.1

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 (244) hide show
  1. package/README.md +4 -4
  2. package/core/Animator.js +1 -0
  3. package/core/Assets.js +28 -0
  4. package/core/DebugOverrides.js +143 -0
  5. package/core/Describe.js +14 -3
  6. package/core/Engine.js +44 -72
  7. package/core/Events.js +59 -1
  8. package/core/I18n.js +2 -2
  9. package/core/Inspect.js +12 -32
  10. package/core/InspectScene.js +7 -3
  11. package/core/MaterialInfo.js +32 -0
  12. package/core/Ops.js +43 -59
  13. package/core/Saves.js +5 -4
  14. package/core/UrlState.js +3 -2
  15. package/core/Vars.js +1 -0
  16. package/core/Views.js +49 -0
  17. package/core/actor.js +2 -2
  18. package/core/assetReport.js +83 -0
  19. package/core/catalog.js +169 -0
  20. package/core/checks.js +67 -0
  21. package/core/claims.js +51 -0
  22. package/core/debugView.js +76 -0
  23. package/core/describeRender.js +51 -0
  24. package/core/describeText.js +11 -4
  25. package/core/errorCodes.js +33 -0
  26. package/core/errorHints.js +6 -1
  27. package/core/grid.js +127 -0
  28. package/core/gridLoad.js +19 -0
  29. package/core/holds.js +106 -0
  30. package/core/lifecycle.js +1 -0
  31. package/core/lightWatch.js +23 -3
  32. package/core/look/coreParts.js +112 -0
  33. package/core/look/layers.js +136 -0
  34. package/core/look/part.js +173 -0
  35. package/core/look/report.js +79 -0
  36. package/core/look/write.js +86 -0
  37. package/core/loop.js +22 -16
  38. package/core/modules.js +19 -5
  39. package/core/opsAtomic.js +31 -0
  40. package/core/opsCheck.js +25 -14
  41. package/core/opsFail.js +20 -0
  42. package/core/opsHistory.js +6 -6
  43. package/core/opsRun.js +77 -0
  44. package/core/params.js +132 -0
  45. package/core/renamed.js +22 -0
  46. package/core/saveApply.js +2 -2
  47. package/core/sceneMethods.js +9 -34
  48. package/core/services.js +73 -0
  49. package/core/startup.js +3 -1
  50. package/core/styleParts.js +11 -9
  51. package/core/thingExplain.js +68 -0
  52. package/core/thingOps.js +35 -24
  53. package/core/things.js +15 -1
  54. package/core/util.js +11 -0
  55. package/core/validate.js +23 -7
  56. package/docs/AI.md +93 -114
  57. package/docs/API.md +8 -9
  58. package/docs/CODEMAP.md +67 -53
  59. package/docs/COMMANDS.md +21 -7
  60. package/docs/CONVENTIONS.md +22 -11
  61. package/docs/THREE.md +3 -3
  62. package/docs/api/assets.md +3 -0
  63. package/docs/api/characters.md +5 -2
  64. package/docs/api/collision.md +4 -0
  65. package/docs/api/content.md +1 -0
  66. package/docs/api/engine.md +23 -14
  67. package/docs/api/events.md +5 -1
  68. package/docs/api/post.md +5 -4
  69. package/docs/api/saves.md +2 -1
  70. package/docs/api/sky.md +3 -3
  71. package/docs/api/style.md +8 -8
  72. package/docs/api/tools.md +5 -2
  73. package/docs/api/vegetation.md +1 -0
  74. package/docs/api/weather.md +1 -1
  75. package/docs/recipes/01-new-game.md +41 -43
  76. package/docs/recipes/02-npc.md +38 -22
  77. package/docs/recipes/03-items-pickups.md +4 -4
  78. package/docs/recipes/04-quests.md +23 -23
  79. package/docs/recipes/05-props-bake.md +5 -5
  80. package/docs/recipes/06-clock-events.md +13 -0
  81. package/docs/recipes/07-flow-scenes-pause.md +6 -2
  82. package/docs/recipes/08-weather-sky.md +6 -6
  83. package/docs/recipes/09-style-pack.md +35 -100
  84. package/docs/recipes/12-navmesh.md +22 -0
  85. package/docs/recipes/13-animation.md +25 -6
  86. package/docs/recipes/14-custom-module.md +6 -7
  87. package/docs/recipes/15-perf.md +9 -1
  88. package/docs/recipes/16-dev-bridge.md +52 -18
  89. package/docs/recipes/18-world.md +5 -2
  90. package/docs/recipes/19-shooting-picking.md +9 -8
  91. package/docs/recipes/20-content-actions-save.md +10 -10
  92. package/docs/recipes/21-camera.md +51 -2
  93. package/docs/recipes/22-shop-gold.md +16 -16
  94. package/docs/recipes/23-ops.md +46 -10
  95. package/docs/recipes/27-net.md +3 -3
  96. package/docs/recipes/28-terrain.md +2 -2
  97. package/docs/recipes/29-grid.md +47 -27
  98. package/docs/recipes/34-environment-lighting.md +11 -10
  99. package/docs/recipes/35-style-from-reference.md +41 -46
  100. package/docs/recipes/36-sky-ground-plant-looks.md +22 -20
  101. package/docs/recipes/37-terrain-look-hooks.md +34 -13
  102. package/docs/recipes/38-environment-look-hooks.md +49 -42
  103. package/docs/recipes/40-scene.md +29 -0
  104. package/docs/recipes/41-thing-registry.md +29 -0
  105. package/docs/recipes/42-terrain-shape.md +1 -1
  106. package/docs/recipes/43-shader-patches-surface-looks.md +37 -20
  107. package/docs/recipes/44-water-weather-look-hooks.md +11 -9
  108. package/docs/recipes/45-cascaded-shadows.md +2 -2
  109. package/docs/recipes/46-blender-art-route.md +26 -4
  110. package/docs/recipes/47-island-snow-backdrop.md +4 -3
  111. package/docs/recipes/48-make-material.md +70 -0
  112. package/docs/recipes/49-game-module-contract.md +71 -0
  113. package/docs/recipes/50-own-renderer.md +12 -0
  114. package/docs/recipes/51-capability-catalog.md +63 -0
  115. package/docs/recipes/52-look.md +146 -0
  116. package/docs/recipes/53-ground-up-close.md +58 -0
  117. package/examples/action/GAMEMAP.md +7 -7
  118. package/examples/action/content/index.js +2 -1
  119. package/examples/action/content/views.js +6 -0
  120. package/examples/action/main.js +3 -2
  121. package/examples/sheepisland/GAMEMAP.md +3 -4
  122. package/examples/styletest/GAMEMAP.md +3 -3
  123. package/examples/styletest/content/npcs.js +1 -1
  124. package/examples/styletest/main.js +2 -2
  125. package/examples/styletest/panel.js +3 -3
  126. package/examples/world/GAMEMAP.md +3 -3
  127. package/examples/world/content/npcs.js +1 -1
  128. package/examples/world/main.js +1 -1
  129. package/index.d.ts +35 -2
  130. package/index.js +6 -3
  131. package/llms.txt +13 -7
  132. package/modules/ambience/Ambience.js +5 -2
  133. package/modules/camera/FirstPersonCamera.js +3 -5
  134. package/modules/camera/FixedCamera.js +19 -12
  135. package/modules/camera/FollowCamera.js +14 -8
  136. package/modules/camera/RtsCamera.js +3 -5
  137. package/modules/camera/common.js +40 -10
  138. package/modules/camera/index.js +1 -1
  139. package/modules/camera/projection.js +34 -0
  140. package/modules/characters/Character.js +45 -31
  141. package/modules/characters/assetModel.js +35 -7
  142. package/modules/characters/astar.js +14 -7
  143. package/modules/characters/index.js +6 -3
  144. package/modules/characters/movers/simple.js +6 -1
  145. package/modules/characters/npcSim.js +8 -2
  146. package/modules/characters/pathAsync.js +12 -6
  147. package/modules/characters/pathJob.js +2 -1
  148. package/modules/characters/proceduralRig.js +50 -11
  149. package/modules/characters/useModel.js +22 -0
  150. package/modules/characters/walkTo.js +58 -0
  151. package/modules/collision/Collision.js +102 -4
  152. package/modules/content/explain.js +13 -0
  153. package/modules/content/index.js +3 -1
  154. package/modules/content/loader.js +3 -0
  155. package/modules/content/rules.js +1 -0
  156. package/modules/debug/DebugPanel.js +11 -5
  157. package/modules/entities/Entities.js +6 -2
  158. package/modules/flow/index.js +5 -2
  159. package/modules/gameplay/Dialogue.js +5 -2
  160. package/modules/gameplay/Interactions.js +12 -2
  161. package/modules/gameplay/Inventory.js +21 -11
  162. package/modules/gameplay/Quests.js +13 -3
  163. package/modules/gameplay/pickups.js +6 -4
  164. package/modules/grid/Layer.js +1 -1
  165. package/modules/grid/index.js +1 -1
  166. package/modules/grid/tiles.js +9 -5
  167. package/modules/hlod/index.js +5 -2
  168. package/modules/hud/index.js +5 -2
  169. package/modules/level/index.js +5 -3
  170. package/modules/lights/index.js +5 -2
  171. package/modules/music/Music.js +6 -2
  172. package/modules/nav/index.js +5 -3
  173. package/modules/net/Client.js +4 -3
  174. package/modules/net/Host.js +2 -2
  175. package/modules/net/index.js +5 -3
  176. package/modules/particles/Particles.js +1 -1
  177. package/modules/photo/Photo.js +10 -7
  178. package/modules/rigid/RigidBodies.js +5 -2
  179. package/modules/settings/Settings.js +6 -3
  180. package/modules/settings/apply.js +2 -1
  181. package/modules/sky/Sky.js +21 -19
  182. package/modules/sky/cascades.js +6 -6
  183. package/modules/sky/domeLayers.js +1 -1
  184. package/modules/sky/environment.js +39 -13
  185. package/modules/sky/fog.js +9 -6
  186. package/modules/sky/frame.js +4 -3
  187. package/modules/sky/look.js +3 -2
  188. package/modules/sky/lookFog.js +80 -0
  189. package/modules/sky/lookShadow.js +50 -0
  190. package/modules/sky/lookSky.js +108 -0
  191. package/modules/sky/shader.js +2 -2
  192. package/modules/sky/shadow.js +4 -10
  193. package/modules/sky/skyModule.js +4 -3
  194. package/modules/terrain/ChunkManager.js +2 -33
  195. package/modules/terrain/chunkLevels.js +40 -0
  196. package/modules/terrain/index.js +10 -2
  197. package/modules/terrain/lookGround.js +61 -0
  198. package/modules/timeline/Timeline.js +7 -3
  199. package/modules/timeline/Tween.js +3 -7
  200. package/modules/timeline/shots.js +6 -4
  201. package/modules/triggers/index.js +9 -2
  202. package/modules/vegetation/Vegetation.js +17 -4
  203. package/modules/vegetation/index.js +7 -4
  204. package/modules/vegetation/lookWind.js +37 -0
  205. package/modules/vegetation/nearFade.js +39 -0
  206. package/modules/water/Water.js +19 -3
  207. package/modules/water/look.js +80 -0
  208. package/modules/weather/Weather.js +22 -31
  209. package/modules/weather/look.js +75 -0
  210. package/modules/weather/particles.js +1 -1
  211. package/modules/weather/strings.js +15 -0
  212. package/modules/world/explain.js +11 -0
  213. package/modules/world/index.js +11 -4
  214. package/modules/world/thingSource.js +44 -0
  215. package/package.json +2 -1
  216. package/render/PostFX.js +48 -51
  217. package/render/detail.js +39 -15
  218. package/render/effects.js +4 -2
  219. package/render/fuse.js +12 -0
  220. package/render/lights.js +4 -2
  221. package/render/lookSurface.js +161 -0
  222. package/render/materials.js +27 -10
  223. package/render/postLook.js +86 -0
  224. package/render/surface.js +3 -1
  225. package/types/core.d.ts +223 -29
  226. package/types/gameplay.d.ts +22 -6
  227. package/types/generated/core/DebugOverrides.d.ts +52 -0
  228. package/types/generated/core/Events.d.ts +43 -0
  229. package/types/generated/core/Ops.d.ts +62 -21
  230. package/types/generated/core/Saves.d.ts +1 -0
  231. package/types/generated/core/Views.d.ts +33 -0
  232. package/types/generated/modules/debug/DebugPanel.d.ts +2 -2
  233. package/types/generated/modules/grid/Layer.d.ts +1 -0
  234. package/types/generated/modules/sky/Sky.d.ts +10 -17
  235. package/types/generated/modules/weather/Weather.d.ts +5 -15
  236. package/types/generated/render/PostFX.d.ts +20 -23
  237. package/types/generated/render/materials.d.ts +10 -0
  238. package/types/physics.d.ts +8 -0
  239. package/types/style.d.ts +35 -20
  240. package/types/world.d.ts +7 -1
  241. package/ui/Parts.js +6 -2
  242. package/ui/UI.js +1 -1
  243. package/ui/defaults.js +1 -1
  244. package/docs/api/debug.md +0 -10
package/render/detail.js CHANGED
@@ -7,12 +7,12 @@ import { placeholderTexture, hashText } from './effects.js';
7
7
  import { declareUniforms } from './uniformDecl.js';
8
8
 
9
9
  /**
10
- * @typedef {{ texture?: string | import('three').Texture, noise?: 'grain' | 'paper' | 'stroke', glsl?: string, uniforms?: Record<string, any>,
10
+ * @typedef {{ texture?: string | import('three').Texture, noise?: 'grain' | 'paper' | 'stroke' | 'dabs', glsl?: string, uniforms?: Record<string, any>,
11
11
  * projection?: 'world' | 'triplanar', scale?: number, strength?: number, mode?: 'multiply' | 'add' | 'mix', tint?: import('../types/common').ColorLike,
12
- * direction?: number, stretch?: number, octaves?: number, normal?: number, roughness?: number }} DetailOptions
12
+ * direction?: number, stretch?: number, octaves?: number, normal?: number, roughness?: number, fade?: boolean }} DetailOptions
13
13
  */
14
- const KEYS = ['texture', 'noise', 'glsl', 'uniforms', 'projection', 'scale', 'strength', 'mode', 'tint', 'direction', 'stretch', 'octaves', 'normal', 'roughness'];
15
- const NOISES = ['grain', 'paper', 'stroke'];
14
+ const KEYS = ['texture', 'noise', 'glsl', 'uniforms', 'projection', 'scale', 'strength', 'mode', 'tint', 'direction', 'stretch', 'octaves', 'normal', 'roughness', 'fade'];
15
+ const NOISES = ['grain', 'paper', 'stroke', 'dabs'];
16
16
  const MODES = ['multiply', 'add', 'mix'];
17
17
 
18
18
  const NOISE = `float threedogDHash(vec2 p){ return fract(sin(dot(p, vec2(127.1, 311.7))) * 43758.5453); }
@@ -20,28 +20,52 @@ float threedogDNoise(vec2 p){ vec2 i = floor(p), f = fract(p); f = f*f*(3.0-2.0*
20
20
  return mix(mix(threedogDHash(i), threedogDHash(i+vec2(1,0)), f.x), mix(threedogDHash(i+vec2(0,1)), threedogDHash(i+vec2(1,1)), f.x), f.y); }
21
21
  float threedogDFbm(vec2 p){ float s = 0.0, a = 0.5, n = 0.0;
22
22
  for (int i = 0; i < 4; i++) { if (float(i) >= uDetailOctaves) break; s += a * threedogDNoise(p); n += a; p = p * 2.03 + 17.0; a *= 0.5; }
23
- return s / n; }`;
23
+ return s / n; }
24
+ // Soft oval brush dabs: one random dab per cell (random size, rotation, tone), no preferred direction. 3x3 cells cover a dab that reaches into a neighbor.
25
+ float threedogDDabs(vec2 p){ float s = 0.5, w = 0.85;
26
+ for (int o = 0; o < 3; o++) { if (float(o) >= uDetailOctaves) break;
27
+ vec2 ip = floor(p); float fo = float(o);
28
+ for (int j = -1; j <= 1; j++) for (int i = -1; i <= 1; i++) {
29
+ vec2 c = ip + vec2(float(i), float(j));
30
+ vec2 h = vec2(threedogDHash(c + fo * 13.1), threedogDHash(c.yx + 7.7 + fo * 5.3));
31
+ float ang = 6.2832 * threedogDHash(c * 1.7 + 3.1 + fo), r = 0.35 + 0.3 * threedogDHash(c * 2.3 + 11.9 + fo), tone = threedogDHash(c + vec2(5.5, 1.3) + fo);
32
+ vec2 d = p - (c + 0.15 + 0.7 * h); float ca = cos(ang), sa = sin(ang);
33
+ d = vec2(ca * d.x + sa * d.y, -sa * d.x + ca * d.y) / vec2(r * 1.3, r * 0.75);
34
+ s = mix(s, tone, (1.0 - smoothstep(0.3, 1.0, length(d))) * w); }
35
+ p = p * 2.03 + 17.0; w *= 0.6; }
36
+ return s; }
37
+ // Size of one pixel in pattern units (1 = one pattern cell): the fade-out and \`glsl\` samples read it
38
+ float threedogDetailFootprint = 0.0;
39
+ float threedogDFp(vec2 p){ return max(length(dFdx(p)), length(dFdy(p))); }
40
+ float threedogDFade = 1.0;
41
+ float threedogDFadeOf(float fp){ return mix(1.0, 1.0 - smoothstep(0.5, 1.0, fp), uDetailFade); }`;
24
42
 
25
43
  // Built-in sources: p is already scaled, turned by direction and stretched along it; returns (color, height)
26
44
  const SOURCES = {
27
45
  tex: 'vec4 threedogDetailSample(vec2 p){ vec3 c = texture2D(uDetail, p).rgb; return vec4(c, dot(c, vec3(0.299, 0.587, 0.114))); }',
28
46
  grain: 'vec4 threedogDetailSample(vec2 p){ float s = threedogDFbm(p); return vec4(vec3(s), s); }',
29
47
  paper: 'vec4 threedogDetailSample(vec2 p){ float s = 0.65 * threedogDFbm(p) + 0.35 * threedogDNoise(vec2(p.x * 7.0, p.y * 0.9)); return vec4(vec3(s), s); }',
48
+ dabs: 'vec4 threedogDetailSample(vec2 p){ float s = threedogDDabs(p); return vec4(vec3(s), s); }',
30
49
  stroke: 'vec4 threedogDetailSample(vec2 p){ float s = smoothstep(0.15, 0.85, threedogDFbm(vec2(p.x, p.y * 1.7))); return vec4(vec3(s), s); }',
31
50
  };
32
51
 
33
52
  // p (world position) -> sample; 'world' looks straight down (xz), 'triplanar' blends the three axis planes by the surface normal
34
53
  const PROJECT = {
35
- world: 'vec4 threedogDetail(vec3 w){ return threedogDetailSample(threedogDetailUV(w.xz)); }',
54
+ world: `vec4 threedogDetail(vec3 w){ vec2 p = threedogDetailUV(w.xz); threedogDetailFootprint = threedogDFp(p); threedogDFade = threedogDFadeOf(threedogDetailFootprint);
55
+ return threedogDetailSample(p); }`,
36
56
  triplanar: `vec4 threedogDetail(vec3 w){
37
57
  vec3 n = abs(normalize(cross(dFdx(w), dFdy(w)))); n /= n.x + n.y + n.z;
38
- return threedogDetailSample(threedogDetailUV(w.zy)) * n.x + threedogDetailSample(threedogDetailUV(w.xz)) * n.y + threedogDetailSample(threedogDetailUV(w.xy)) * n.z; }`,
58
+ vec2 a = threedogDetailUV(w.zy), b = threedogDetailUV(w.xz), c = threedogDetailUV(w.xy);
59
+ float fa = threedogDFp(a), fb = threedogDFp(b), fc = threedogDFp(c);
60
+ threedogDFade = threedogDFadeOf(fa) * n.x + threedogDFadeOf(fb) * n.y + threedogDFadeOf(fc) * n.z;
61
+ threedogDetailFootprint = fa; vec4 sa = threedogDetailSample(a); threedogDetailFootprint = fb; vec4 sb = threedogDetailSample(b); threedogDetailFootprint = fc; vec4 sc = threedogDetailSample(c);
62
+ return sa * n.x + sb * n.y + sc * n.z; }`,
39
63
  };
40
64
 
41
65
  const COLOR = `{ vec3 tdc = threedogDS.rgb * uDetailTint;
42
- if (uDetailMode < 0.5) diffuseColor.rgb *= mix(vec3(1.0), tdc * 2.0, uDetailStrength);
43
- else if (uDetailMode < 1.5) diffuseColor.rgb += (tdc - 0.5) * uDetailStrength;
44
- else diffuseColor.rgb = mix(diffuseColor.rgb, tdc, uDetailStrength); }`;
66
+ if (uDetailMode < 0.5) diffuseColor.rgb *= mix(vec3(1.0), tdc * 2.0, uDetailStrength * threedogDFade);
67
+ else if (uDetailMode < 1.5) diffuseColor.rgb += (tdc - 0.5) * uDetailStrength * threedogDFade;
68
+ else diffuseColor.rgb = mix(diffuseColor.rgb, tdc, uDetailStrength * threedogDFade); }`;
45
69
  // Screen-space bump (the same maths as three's bump map): uDetailBump is the relief height in meters per unit of height
46
70
  const BUMP = `vec3 threedogDetailBump(vec3 surfPos, vec3 surfNorm, float h, float k, float faceDir){
47
71
  vec3 sx = dFdx(surfPos), sy = dFdy(surfPos), r1 = cross(sy, surfNorm), r2 = cross(surfNorm, sx);
@@ -62,7 +86,7 @@ export function detailPatch(o, engine, label = 'detail') {
62
86
  if (o.noise !== undefined && !NOISES.includes(o.noise)) throw new Error(`${label}.noise '${o.noise}' is not a built-in noise; use ${NOISES.join(' | ')}, or write your own with glsl: 'vec4 threedogDetailSample(vec2 p){ ... }'`);
63
87
  const proj = o.projection ?? 'world';
64
88
  if (!PROJECT[proj]) throw new Error(`${label}.projection '${proj}' must be 'world' (top-down) or 'triplanar'`);
65
- if (o.glsl && !/vec4\s+threedogDetailSample\s*\(\s*vec2/.test(o.glsl)) throw new Error(`${label}.glsl must define \`vec4 threedogDetailSample(vec2 p)\`: p is the scaled, turned, stretched position; return vec4(color rgb, height 0-1). uDetailOctaves and the uniforms you list are in scope`);
89
+ if (o.glsl && !/vec4\s+threedogDetailSample\s*\(\s*vec2/.test(o.glsl)) throw new Error(`${label}.glsl must define \`vec4 threedogDetailSample(vec2 p)\`: p is the scaled, turned, stretched position; return vec4(color rgb, height 0-1). uDetailOctaves, threedogDetailFootprint (one pixel in pattern units; fade yourself or leave it to detail.fade) and the uniforms you list are in scope`);
66
90
  const src = o.glsl ? 'glsl:' + hashText(o.glsl) : o.texture ? 'tex' : o.noise ?? 'grain';
67
91
  const isStroke = o.noise === 'stroke', ang = (o.direction ?? 0) * Math.PI / 180;
68
92
  const colorOn = o.strength !== 0 && (o.strength !== undefined || !(o.normal || o.roughness)), bump = !!o.normal, rough = !!o.roughness;
@@ -70,7 +94,7 @@ export function detailPatch(o, engine, label = 'detail') {
70
94
  uDetailScale: { value: o.scale ?? 0.25 }, uDetailStrength: { value: o.strength ?? 0.35 }, uDetailMode: { value: Math.max(0, MODES.indexOf(o.mode ?? 'multiply')) },
71
95
  uDetailTint: { value: new THREE.Color(o.tint ?? 0xffffff) }, uDetailDir: { value: new THREE.Vector2(Math.cos(ang), Math.sin(ang)) },
72
96
  uDetailStretch: { value: o.stretch ?? (isStroke ? 6 : 1) }, uDetailOctaves: { value: o.octaves ?? 2 },
73
- uDetailBump: { value: o.normal ?? 0 }, uDetailRough: { value: o.roughness ?? 0 },
97
+ uDetailBump: { value: o.normal ?? 0 }, uDetailRough: { value: o.roughness ?? 0 }, uDetailFade: { value: o.fade === false ? 0 : 1 },
74
98
  });
75
99
  let decl = '';
76
100
  if (o.texture || o.glsl) {
@@ -91,7 +115,7 @@ export function detailPatch(o, engine, label = 'detail') {
91
115
  }
92
116
  const own = declareUniforms(label + '.uniforms', o.uniforms);
93
117
  Object.assign(u, own.uniforms); decl += '\n' + own.decl;
94
- const pars = `uniform float uDetailScale, uDetailStrength, uDetailMode, uDetailStretch, uDetailOctaves, uDetailBump, uDetailRough;
118
+ const pars = `uniform float uDetailScale, uDetailStrength, uDetailMode, uDetailStretch, uDetailOctaves, uDetailBump, uDetailRough, uDetailFade;
95
119
  uniform vec3 uDetailTint; uniform vec2 uDetailDir; ${decl}
96
120
  ${NOISE}
97
121
  vec2 threedogDetailUV(vec2 w){ vec2 p = w * uDetailScale; p = vec2(uDetailDir.x * p.x + uDetailDir.y * p.y, -uDetailDir.y * p.x + uDetailDir.x * p.y); p.x /= uDetailStretch; return p; }
@@ -99,7 +123,7 @@ ${o.glsl ?? SOURCES[o.texture ? 'tex' : o.noise ?? 'grain']}
99
123
  ${PROJECT[proj]}
100
124
  ${BUMP}`;
101
125
  const fragment = /** @type {Record<string, string>} */ ({ pars, color_fragment: `vec4 threedogDS = threedogDetail(vThreedogWorld);\n${colorOn ? COLOR : ''}` });
102
- if (bump) fragment.normal_fragment_maps = 'normal = threedogDetailBump(-vViewPosition, normal, threedogDS.a, uDetailBump, faceDirection);';
103
- if (rough) fragment.roughnessmap_fragment = 'roughnessFactor = clamp(roughnessFactor + (threedogDS.a - 0.5) * uDetailRough, 0.04, 1.0);';
126
+ if (bump) fragment.normal_fragment_maps = 'normal = threedogDetailBump(-vViewPosition, normal, threedogDS.a, uDetailBump * threedogDFade, faceDirection);';
127
+ if (rough) fragment.roughnessmap_fragment = 'roughnessFactor = clamp(roughnessFactor + (threedogDS.a - 0.5) * uDetailRough * threedogDFade, 0.04, 1.0);';
104
128
  return { name: 'detail', cacheKey: `${src}|${proj}|${colorOn ? 'c' : ''}${bump ? 'n' : ''}${rough ? 'r' : ''}`, needs: { patches: ['world'] }, uniforms: u, glsl: { fragment } };
105
129
  }
package/render/effects.js CHANGED
@@ -14,6 +14,7 @@ const UNIFORM_DEFAULTS = {
14
14
  uCloudScale: 0.006, // cloud size (smaller = bigger clouds)
15
15
  uCloudSpeed: () => new THREE.Vector2(0.012, 0.006), // cloud drift direction and speed
16
16
  uWindFreq: 1, // sway frequency multiplier
17
+ uWindAmp: 1, // sway amplitude multiplier (look.wind.amplitude); every wind patch's amplitude is scaled by it
17
18
  uFoliageTint: () => new THREE.Color(1, 1, 1), // season: foliage tint (driven by the sky module's calendar)
18
19
  uGroundTint: () => new THREE.Color(1, 1, 1), // season: ground tint
19
20
  uFoliageMix: 0, uGroundMix: 0, // season mode 'mix': how far the surface moves to the tint (0 = multiply, the default)
@@ -111,8 +112,9 @@ export const EFFECTS = {
111
112
  'reflectedLight.directDiffuse *= threedogCloudLight(vThreedogWorld.xz);\n reflectedLight.directSpecular *= threedogCloudLight(vThreedogWorld.xz);' } } }),
112
113
  // wind(amplitude) or wind(amplitude, { glsl, uniforms, decl }): a style's own sway function replaces the default one (see StyleWind in types/style.d.ts)
113
114
  wind: (amplitude, custom) => ({ name: 'wind', cacheKey: custom ? `${amplitude}|${hashText(custom.glsl)}` : amplitude, shadow: true,
114
- uniforms: { ...pick('uTime', 'uWind', 'uWindFreq'), ...custom?.uniforms }, glsl: {
115
- vertex: { pars: `#define THREEDOG_WIND_AMP ${(+amplitude).toFixed(4)}
115
+ uniforms: { ...pick('uTime', 'uWind', 'uWindFreq', 'uWindAmp'), ...custom?.uniforms }, glsl: {
116
+ vertex: { pars: `uniform float uWindAmp;
117
+ #define THREEDOG_WIND_AMP (${(+amplitude).toFixed(4)} * uWindAmp)
116
118
  #include <threedog_wind_pars_vertex>` + (custom
117
119
  ? `
118
120
  #define THREEDOG_WIND_CUSTOM
package/render/fuse.js CHANGED
@@ -70,3 +70,15 @@ export function groupFuse(on) {
70
70
  }
71
71
  return out;
72
72
  }
73
+
74
+ // Only the buffer the scene render wrote holds scene depth: after a pass that swaps buffers, readBuffer.depthTexture is another
75
+ // target's (a fullscreen quad's, or stale). A depth reader behind such a pass would silently find nothing, so the chain refuses it.
76
+ export function checkDepthOrder(chain) {
77
+ let swapped = null;
78
+ for (const e of chain) {
79
+ if (e._def?.needsDepth && swapped)
80
+ throw new Error(`post effect '${e.name}' reads scene depth (needsDepth) but runs after '${swapped}', which swaps buffers, so the depth it would read is not the scene's; ` +
81
+ `give '${e.name}' a lower order or an earlier slot than '${swapped}', or turn one of them off`);
82
+ if (e._impl.needsSwap && !e._impl.keepsDepth) swapped ??= e.name;
83
+ }
84
+ }
package/render/lights.js CHANGED
@@ -6,11 +6,13 @@
6
6
  import * as THREE from 'three';
7
7
 
8
8
  /** @param {any} engine @returns {{ sun: THREE.DirectionalLight, hemi: THREE.HemisphereLight }} */
9
- export function createDefaultLights(engine) {
9
+ export function createDefaultLights(engine, { add = true } = {}) {
10
10
  const hemi = new THREE.HemisphereLight(0xffffff, 0x555555, 1.2);
11
11
  const sun = new THREE.DirectionalLight(0xffffff, 2);
12
12
  sun.position.set(40, 80, 30); // above and to the side, so faces read with some shading
13
13
  sun.castShadow = false; // placeholder lighting casts no shadows; an installed sky module turns them on (sizes from style.sky.shadow)
14
- engine.scene.add(hemi, sun, sun.target);
14
+ // add: false (createEngine({ lights: false })): the objects still exist so engine.lights.sun / hemi and the sky module never hit undefined, but they
15
+ // are not in the scene, so nothing is lit by them and they cost no shader light slots; the game brings all its own lights
16
+ if (add) engine.scene.add(hemi, sun, sun.target);
15
17
  return { sun, hemi };
16
18
  }
@@ -0,0 +1,161 @@
1
+ // look.materials and look.surface (render/materials.js reads them when it makes a material).
2
+ // Why a file of its own: materials.js is near the size cap, and the two parts share one rule: a verb changes what makeMaterial does NEXT time
3
+ // (a Material already handed out is not touched, catalog / describe say appliesTo; rebuilding made materials from the spec costs a recompile each, so it is not done).
4
+ // Exception: plain numeric / color properties (LIVE_KEYS below) are written to the already-made materials of that role at once; they need no recompile.
5
+ // look.materials set({ wool: { roughness: 0.4 } }) merge into the role's spec (style.materials[role] stays below as the style layer)
6
+ // patch(name, shaderPatch, { roles }) add a named ShaderPatch (render/patches.js) to materials made for those roles
7
+ // replace(role, Material | fn) a role is this Material (cloned) / this (params, purpose, engine) => Material
8
+ // look.surface set({ lighting: { wrap, shadowTint, rim }, detail: {...}, ramp: [...], soften }) defaults for every spec-made material
9
+ // patch('lighting' | 'detail', glsl) the shared threedogLighting / threedogDetailSample function
10
+ import { defineLookPart } from '../core/look/part.js';
11
+ import * as THREE from 'three';
12
+ import { codedError } from '../core/errorHints.js';
13
+ import { isPlainObject as isPlain } from '../core/util.js';
14
+ import { rampTexture } from './lighting.js';
15
+
16
+ const asGlsl = v => (typeof v === 'string' ? { glsl: v } : v); // a hook value is a GLSL string or { glsl, uniforms }
17
+
18
+ /** A material spec key makeMaterial understands: its own keys (materials.js SPEC_KEYS + type) or a property of one of the three.js types it makes */
19
+ const probes = []; // one probe Material per three.js type, made on first use; page-wide on purpose (they are never rendered)
20
+ function knownSpecKey(k) {
21
+ if (['type', 'steps', 'ramp', 'soften', 'repeat', 'wrap', 'detail', 'lighting'].includes(k)) return true;
22
+ if (!probes.length) probes.push(...[THREE.MeshPhysicalMaterial, THREE.MeshLambertMaterial, THREE.MeshPhongMaterial, THREE.MeshToonMaterial, THREE.MeshBasicMaterial].map(C => new C()));
23
+ return probes.some(m => k in m);
24
+ }
25
+ /** Plain material properties that change at once on materials already made for the role (no shader change, so no recompile); every other key is for new materials only */
26
+ export const LIVE_KEYS = ['color', 'emissive', 'emissiveIntensity', 'roughness', 'metalness', 'opacity', 'envMapIntensity', 'shininess', 'specular'];
27
+ const COLOR_KEYS = new Set(['color', 'emissive', 'specular']);
28
+ /** Every Material made per role, per engine, as weak refs (a disposed material that nobody holds drops out) */
29
+ const LIVE = new WeakMap();
30
+ const liveOf = e => LIVE.get(e) ?? LIVE.set(e, new Map()).get(e);
31
+ /** The last Material made per role, per engine (look.materials.object(role)); kept here so materials.js never touches the part's fields */
32
+ const MADE = new WeakMap();
33
+ const madeOf = e => MADE.get(e) ?? MADE.set(e, new Map()).get(e);
34
+
35
+ /** Materials: role names are open, so the part grows `<role>.<specKey>` params as the style or a game mentions them */
36
+ export function defineMaterialsLook(e, purposes) {
37
+ const M = e.style.materials ?? {};
38
+ const params = {}, style = {};
39
+ const grow = (into, key) => { into[key] = { type: 'any', default: null, neutral: true, desc: 'a spec key of this role (type, color, roughness, steps, ramp, detail, lighting ...); null = not overridden' }; };
40
+ for (const [role, spec] of Object.entries(M)) if (isPlain(spec)) for (const [k, v] of Object.entries(spec)) { grow(params, `${role}.${k}`); style[`${role}.${k}`] = v; }
41
+ const made = madeOf(e);
42
+ const part = defineLookPart(e, {
43
+ id: 'materials', group: 'surface', module: 'core', docs: ['recipes/52-look.md'], params, style: () => style, appliesTo: `materials made after the change, except the live keys (${LIVE_KEYS.join(', ')}), which also change the materials already made for that role; type, steps, ramp, soften, repeat, wrap, detail, lighting, patch and replace are for new materials only`,
44
+ applyAtStart: false,
45
+ apply(v, changed) { // live keys: write them to the already-made materials of the role (a cleared key goes back to the style value, or stays when the style gave none)
46
+ for (const k of changed) {
47
+ const i = k.indexOf('.'), role = k.slice(0, i), prop = k.slice(i + 1);
48
+ if (i < 0 || !LIVE_KEYS.includes(prop)) continue;
49
+ const val = v[k] ?? style[k];
50
+ if (val == null) continue;
51
+ for (const ref of liveOf(e).get(role) ?? []) {
52
+ const m = ref.deref();
53
+ if (!m) { liveOf(e).get(role).delete(ref); continue; }
54
+ if (!(prop in m)) continue;
55
+ if (COLOR_KEYS.has(prop)) m[prop].set(val); else m[prop] = val;
56
+ }
57
+ }
58
+ },
59
+ // a function, not a map: look.materials.object('wool') is the last Material made for that role, object() all of them
60
+ object: () => role => (role === undefined ? Object.fromEntries(made) : made.get(role)),
61
+ // set({ wool: { roughnes: 1 } }) used to add the typo as a new key; now a role key must be one makeMaterial reads (review M7).
62
+ // normalize runs for set() and engine.debug.override alike, before the values are checked
63
+ normalize(p) {
64
+ const grown = {};
65
+ for (const [role, spec] of Object.entries(p)) if (isPlain(spec)) for (const k of Object.keys(spec)) if (!part.has(`${role}.${k}`)) {
66
+ if (!knownSpecKey(k)) throw codedError('look-param', `look.materials.set(): ${role}.${k} is not a material spec key (type, color, roughness, steps, ramp, detail, lighting or a three.js material property)`);
67
+ grow(grown, `${role}.${k}`);
68
+ }
69
+ if (Object.keys(grown).length) part.extend(grown);
70
+ return p;
71
+ },
72
+ hooks: { '<name>': { signature: 'a ShaderPatch { name, glsl, uniforms, needs } (render/patches.js); patch(name, spec, { roles: ["wool"] }) adds it to materials made for those roles (none = all)', scope: ['fragment', 'vertex'] } },
73
+ replace: { accepts: "replace('wool', Material | (params, purpose, engine) => Material); replace('wool', null) gives the role back to the style", loses: ['the role spec: type, steps, ramp, detail, lighting ... and look.materials.set keys for that role'] },
74
+ verbs: {
75
+ patch: { signature: 'patch(name, shaderPatch | null, { roles, owner })',
76
+ take(bad, name, spec, { roles, owner } = {}) {
77
+ if (typeof name !== 'string' || !name) bad("name is the patch's name, e.g. patch('snap', { glsl: {...} }, { roles: ['wool'] })");
78
+ if (spec != null && !isPlain(spec)) bad(`the patch is a ShaderPatch object { glsl: { vertex|fragment: {...} }, uniforms, needs } (render/patches.js); got ${typeof spec}`);
79
+ return [{ [`hook:${name}`]: spec == null ? null : { patch: { name, ...spec }, roles: roles ?? null } }, owner];
80
+ } },
81
+ replace: { signature: 'replace(role, Material | (params, purpose, engine) => Material | null, { owner })',
82
+ take(bad, role, impl, { owner } = {}) {
83
+ if (typeof role !== 'string') bad("the first argument is the role name, e.g. replace('wool', new THREE.MeshMatcapMaterial(...))");
84
+ if (impl != null && !impl.isMaterial && typeof impl !== 'function') bad(`give a three.js Material or a function (params, purpose, engine) => Material; got ${typeof impl}`);
85
+ return [{ [`replace:${role}`]: impl ?? null }, owner];
86
+ } },
87
+ },
88
+ });
89
+ return part;
90
+ }
91
+
92
+ /** What the games and debug layers changed for a role: { key: value } to lay over the role's spec (makeMaterial) */
93
+ export function materialOverrides(eng, role) {
94
+ const p = eng?.look?.materials, out = {};
95
+ if (!p) return out;
96
+ for (const [k] of p.resolved(role + '.')) { const v = p.top(k); if (v != null) out[k.slice(role.length + 1)] = v; }
97
+ return out;
98
+ }
99
+ /** replace(role, ...) from a game / debug layer, else undefined */
100
+ export const materialReplace = (eng, role) => eng?.look?.materials?.top(`replace:${role}`) ?? undefined;
101
+ /** Patches added with look.materials.patch for this role */
102
+ export function materialPatches(eng, role) {
103
+ const p = eng?.look?.materials, out = [];
104
+ if (p) for (const [, v] of p.resolved('hook:')) if (v && (!v.roles || v.roles.includes(role))) out.push(v.patch);
105
+ return out;
106
+ }
107
+ /** Remember the last Material made for a role (look.materials.object(role)) */
108
+ export function materialMade(eng, role, m) {
109
+ if (!eng) return;
110
+ madeOf(eng).set(role, m);
111
+ (liveOf(eng).get(role) ?? liveOf(eng).set(role, new Set()).get(role)).add(new WeakRef(m));
112
+ }
113
+
114
+ const needColor = name => v => (isPlain(v) && v.color !== undefined ? null : `needs a color, e.g. { color: '#334', strength: 0.5 } (${name})`);
115
+ /** Surface: the pack-wide lighting / detail / toon ramp every spec-made material starts from */
116
+ export function defineSurfaceLook(e) {
117
+ const L = e.style.lighting ?? {};
118
+ const keep = o => Object.fromEntries(Object.entries(o).filter(([, v]) => v != null));
119
+ const num = v => (typeof v === 'number' ? null : 'must be a number');
120
+ defineLookPart(e, {
121
+ id: 'surface', appliesTo: 'materials made after the change', group: 'surface', module: 'core', docs: ['recipes/52-look.md'],
122
+ params: {
123
+ 'lighting.wrap': { type: 'any', default: null, neutral: true, check: num, desc: 'half-lambert wrap 0-1: how far light bends past the terminator (softer shade edge); null = off' },
124
+ 'lighting.shadowTint': { type: 'any', default: null, neutral: true, check: needColor('shadowTint'), desc: '{ color, strength?, soft? } hue of the shaded side; null = off' },
125
+ 'lighting.rim': { type: 'any', default: null, neutral: true, check: needColor('rim'), desc: '{ color, strength?, power?, shadowSide? } edge light; null = off' },
126
+ detail: { type: 'any', default: null, neutral: true, check: v => (isPlain(v) ? null : 'must be a detail object, e.g. { noise: "grain", strength: 0.2 } (render/detail.js)'), desc: 'detail layer added to every spec-made material (a spec\'s own detail wins; detail: false in a spec opts out); null = none' },
127
+ ramp: { type: 'any', default: null, neutral: true, check: v => { try { rampTexture(v); return null; } catch (err) { return err.message; } }, desc: 'toon ramp for every toon material, grays or colors dark to light; null = each spec\'s own steps / ramp' },
128
+ soften: { type: 'any', default: null, neutral: true, check: num, desc: 'how much the toon bands melt into each other 0-1; used with ramp' },
129
+ },
130
+ style: () => keep({ 'lighting.wrap': L.wrap, 'lighting.shadowTint': L.shadowTint, 'lighting.rim': L.rim, 'hook:lighting': L.glsl ? { glsl: L.glsl, uniforms: L.uniforms } : null }),
131
+ hooks: {
132
+ lighting: { signature: 'void threedogLighting(inout ReflectedLight light, vec3 normal, vec3 viewDir, vec3 sunDir, float sunShadow, vec3 albedo)', scope: ['fragment'], example: 'engine.look.surface.patch("lighting", glslString)' },
133
+ detail: { signature: 'vec4 threedogDetailSample(vec2 p) // rgb + height 0-1', scope: ['fragment'], example: 'engine.look.surface.patch("detail", glslString)' },
134
+ },
135
+ noReplace: 'to swap a whole material, use engine.look.materials.replace(role, ...)',
136
+ });
137
+ }
138
+
139
+ /** The pack-wide lighting options for makeMaterial: style.lighting under any look.surface change (undefined without the part) */
140
+ export function surfaceLighting(eng) {
141
+ const p = eng?.look?.surface;
142
+ if (!p) return eng?.style?.lighting;
143
+ const o = keep3({ wrap: p.value('lighting.wrap'), shadowTint: p.value('lighting.shadowTint'), rim: p.value('lighting.rim'), ...asGlsl(p.value('hook:lighting')) });
144
+ return Object.keys(o).length ? o : undefined;
145
+ }
146
+ /** The pack-wide detail options (with the detail hook's glsl), or undefined */
147
+ export function surfaceDetail(eng) {
148
+ const p = eng?.look?.surface, d = p?.value('detail');
149
+ return d ? { ...asGlsl(p.value('hook:detail')), ...d } : undefined;
150
+ }
151
+ /** The pack-wide toon ramp { ramp, soften }, or undefined */
152
+ export function surfaceRamp(eng) {
153
+ const p = eng?.look?.surface, r = p?.value('ramp');
154
+ return r ? { ramp: r, soften: p.value('soften') ?? 0 } : undefined;
155
+ }
156
+ function keep3(o) { return Object.fromEntries(Object.entries(o).filter(([, v]) => v != null)); }
157
+ /** The ground's detail options: look.ground (style.terrain.detail under any change, plus its detail glsl hook), or style.terrain.detail without the part */
158
+ export function groundDetail(eng) {
159
+ const p = eng?.look?.ground, d = p ? p.value('detail') : eng?.style?.terrain?.detail;
160
+ return d ? { ...asGlsl(p?.value('hook:detail')), ...d } : undefined;
161
+ }
@@ -13,13 +13,14 @@
13
13
  // }
14
14
  // Role names are open: a game can add its own and fetch it with makeMaterial('furniture', { color: 0x8a5a36 }).
15
15
  import * as THREE from 'three';
16
- import { closest, warnMissing, warnOnce } from '../core/validate.js';
16
+ import { closest, warnMissing, warnOnce, checkOptions } from '../core/validate.js';
17
17
  import { patchMaterial, copyPatches } from './patches.js';
18
18
  import { declareUniforms } from './uniformDecl.js';
19
19
  import { EFFECTS } from './effects.js';
20
20
  import { detailPatch } from './detail.js';
21
21
  import { applySurface } from './surface.js';
22
22
  import { lightingPatch, rampTexture } from './lighting.js';
23
+ import { groundDetail, materialOverrides, materialReplace, materialPatches, materialMade, surfaceLighting, surfaceRamp } from './lookSurface.js';
23
24
  /** @import { ColorLike, Material, BufferGeometry } from '../types/common' */
24
25
 
25
26
  // ---------- style pack per engine ----------
@@ -64,6 +65,8 @@ export const MATERIAL_PURPOSES = ['default', 'terrain', 'vegetation', 'character
64
65
 
65
66
  // The style pack's materials[role] (or materials.default) decides the material; params are this call's specifics (color, vertex colors, double-sided...).
66
67
  // Only properties the material has are set, so one params object works for any material, built-in or custom.
68
+ // Spec keys handled by makeMaterial / applySurface rather than copied onto the material
69
+ const SPEC_KEYS = ['steps', 'ramp', 'soften', 'repeat', 'wrap', 'detail', 'lighting'];
67
70
  const isSpec = e => e && !e.isMaterial && typeof e !== 'function';
68
71
  /**
69
72
  * Create a material by role: makeMaterial('furniture', { color: 0x8a5a36 }); the look comes from the style pack's materials[role] (unlisted roles use materials.default).
@@ -91,7 +94,8 @@ export function makeMaterial(purpose = 'default', params = {}, engine = undefine
91
94
  const known = [...new Set([...MATERIAL_PURPOSES, ...Object.keys(M)])];
92
95
  if (closest(purpose, known)) warnMissing('material', purpose, known);
93
96
  }
94
- const entry = M[purpose] ?? M.default, key = purpose in M ? purpose : 'default', eng = owner(engine);
97
+ const eng = owner(engine), rep = materialReplace(eng, purpose); // look.materials.replace(role, ...) beats the style's entry
98
+ const entry = rep ?? M[purpose] ?? M.default, key = purpose in M ? purpose : 'default';
95
99
  let m, props = params;
96
100
  if (entry?.isMaterial) m = copyPatches(entry, entry.clone());
97
101
  else if (typeof entry === 'function') {
@@ -99,30 +103,43 @@ export function makeMaterial(purpose = 'default', params = {}, engine = undefine
99
103
  if (!m?.isMaterial) throw new Error(`style.materials.${key} returned ${m}; the function must return a three.js Material`);
100
104
  } else {
101
105
  // A spec layers on top of materials.default when that is a spec too
102
- const { type = 'lambert', steps = 3, ramp, soften, ...rest } = { ...(isSpec(M.default) ? M.default : {}), ...entry, ...params };
106
+ // look.materials.set layers (game / debug) lie over the style's spec; look.surface.ramp over a toon material's own ramp
107
+ const merged = { ...(isSpec(M.default) ? M.default : {}), ...entry, ...materialOverrides(eng, 'default'), ...(purpose === 'default' ? {} : materialOverrides(eng, purpose)), ...params };
108
+ if ((merged.type ?? 'lambert') === 'toon') Object.assign(merged, surfaceRamp(eng)); // the pack-wide ramp wins over the spec's own
109
+ const { type = 'lambert', steps = 3, ramp, soften, ...rest } = merged;
103
110
  const Ctor = TYPES[type];
104
111
  if (!Ctor) throw new Error(`style.materials.${key}: unknown type '${type}'; use ${Object.keys(TYPES).join(' | ')}, or give a Material instance or a function (params, purpose) => Material`);
105
112
  m = new Ctor();
106
113
  if (type === 'toon') m.gradientMap = ramp ? rampTexture(ramp, soften) : toonRamp(steps);
107
114
  else if (ramp || soften !== undefined) throw new Error(`style.materials.${key}: ramp / soften belong to type 'toon' (this is '${type}')`);
108
- props = applySurface(m, rest, `style.materials.${key}`, eng, eng?.style?.lighting);
115
+ props = applySurface(m, rest, `style.materials.${key}`, eng, surfaceLighting(eng));
109
116
  }
110
117
  // the pack's style.lighting also shapes pack Materials and function results that are plain three.js lit materials (specs got it above)
111
- if (props === params && eng?.style?.lighting && (m.isMeshStandardMaterial || m.isMeshLambertMaterial || m.isMeshPhongMaterial || m.isMeshToonMaterial))
112
- patchMaterial(m, [lightingPatch(eng.style.lighting, 'style.lighting')]);
118
+ if (props === params && surfaceLighting(eng) && (m.isMeshStandardMaterial || m.isMeshLambertMaterial || m.isMeshPhongMaterial || m.isMeshToonMaterial))
119
+ patchMaterial(m, [lightingPatch(surfaceLighting(eng), 'style.lighting')]);
113
120
  for (const k in props) {
114
121
  if (k === 'type' || !(k in m)) continue;
115
122
  const v = props[k];
116
123
  if (m[k]?.isColor) m[k].set(v); else if (m[k]?.isVector2 && Array.isArray(v)) m[k].set(...v); else m[k] = v;
117
124
  }
125
+ // A key this material lacks is skipped on purpose (one params object works for any material type), but a key that looks like a typo of a real
126
+ // property ('roughnes') warns once with the suggestion. loose: keys with no close match (a spec shared across types) stay silent.
127
+ // `k in m` also finds accessor properties on the prototype (MeshPhysicalMaterial clearcoat, sheen, ...), which Object.keys does not list
128
+ const unknown = Object.fromEntries(Object.entries(params).filter(([k]) => !(k in m)));
129
+ checkOptions(`makeMaterial('${purpose}')`, unknown, [...Object.keys(m), ...SPEC_KEYS, 'type'], { loose: true });
118
130
  m.userData.purpose = purpose;
131
+ // Minimal provenance for inspect.scene (diagnostic only, one small object per material): which layer supplied the spec
132
+ m.userData.materialSource = { role: purpose, from: !entry ? (Object.keys(params).length ? 'call-params' : 'default') : entry.isMaterial ? 'pack-instance' : typeof entry === 'function' ? 'pack-function' : 'pack-spec', keys: Object.keys(params) };
133
+ const added = materialPatches(eng, purpose); // look.materials.patch(name, patch, { roles })
134
+ if (added.length) patchMaterial(m, added);
135
+ materialMade(eng, purpose, m);
119
136
  m.needsUpdate = true;
120
137
  return m;
121
138
  }
122
139
 
123
140
  // ---------- shader effects (named patches, see patches.js; the built-in ones are in effects.js) ----------
124
141
  // A style's own sway function (style.wind.glsl): must define threedogWind(); its uniforms are declared for it
125
- function windCustom({ glsl, uniforms }) {
142
+ export function windCustom({ glsl, uniforms }) {
126
143
  if (!/void\s+threedogWind\s*\(/.test(glsl || '')) throw new Error('style.wind.glsl must define `void threedogWind(inout vec3 transformed, vec3 ip, vec3 position)`: move the vertex (object space) by the sway; ip = world position of this instance, uTime / uWind / uWindFreq / THREEDOG_WIND_AMP are in scope');
127
144
  return { glsl, ...declareUniforms('style.wind.uniforms', uniforms) };
128
145
  }
@@ -164,10 +181,10 @@ export function applyEffects(material, { wind, clouds = true, season, detail, en
164
181
  */
165
182
  export function terrainMaterial(base = null, engine = undefined) {
166
183
  const e = owner(engine);
167
- // style.terrain.detail is the `detail` patch with its texture-only options (top-down world projection, multiply)
168
- const det = e?.style?.terrain?.detail, tex = det?.texture && e?.assets;
184
+ // look.ground.detail (style.terrain.detail) is the `detail` patch with its options (texture, or noise / glsl; top-down world projection, multiply)
185
+ const det = groundDetail(e), on = det && ((det.texture && e?.assets) || det.noise || det.glsl);
169
186
  return applyEffects(base || makeMaterial('terrain', { vertexColors: true }, e ?? undefined),
170
- { season: 'ground', engine: e ?? undefined, ...(tex && { detail: { texture: det.texture, scale: det.scale ?? 0.25, strength: det.strength ?? 0.35 } }) });
187
+ { season: 'ground', engine: e ?? undefined, ...(on && { detail: { scale: 0.25, strength: 0.35, ...det } }) });
171
188
  }
172
189
 
173
190
  /**
@@ -0,0 +1,86 @@
1
+ // look.post: the post-processing chain as a look part (recipes/52-look.md).
2
+ // set({ bloom: { strength: 0.6 }, vignette: false }) keys are '<effect>.<param>' and '<effect>.enabled'; false / true is the same as enabled
3
+ // patch('grain', glsl | { glsl, slot, order, uniforms, values }) generates a fuse effect named 'grain' (PostFuse in PostFX.js); patch('grain', null) removes it
4
+ // add(effect, { owner }) adds ONE custom pass (name, create | fuse, slot, order, params) without replacing the chain; returns { remove() }
5
+ // replace([effect, ...]) swaps the whole chain for these effects; replace(null) gives the style's chain back
6
+ // The old engine.post.add / enable and handle set / enable / remove were removed in 0.2 (they throw renamed-api): this part is the one way to change the chain, so describe().look
7
+ // and describe().render say who changed what. Style-pack effects (bloom, ao, outline ...) are the style layer; the keys come and go with the
8
+ // effects, so the part adds and removes its params as the chain changes (core/look/dynamic.js).
9
+ // Why '<effect>.<param>' keys and not one object per effect: layering and owners are per key, so a game can change bloom.strength and leave
10
+ // the style's bloom.threshold alone.
11
+ import { defineLookPart } from '../core/look/part.js';
12
+ import { codedError } from '../core/errorHints.js';
13
+
14
+ /** @param {any} post PostFX @param {any[]} styleDefs the style pack's effects */
15
+ export function definePostLook(post, styleDefs) {
16
+ const e = post.engine, low = e.tier === 'low', generated = new Map(), source = new Map();
17
+ const defaultOn = d => (d.enabled ?? true) && !(d.costly && low); // a costly effect starts off on low-tier devices unless the game said otherwise
18
+ const decl = h => {
19
+ const d = h._def, n = h.name;
20
+ return { [`${n}.enabled`]: { type: 'bool', default: !!defaultOn(d), cost: d.costly ? 'gpu' : 'uniform',
21
+ why: low && d.costly ? (post._offWhy[n] ?? `costly effect: off on low-tier devices`) : `post effect '${n}'${styleDefs.includes(d) ? ' of the style pack' : ''}`,
22
+ off: `look.post.set({ ${n}: ${defaultOn(d) ? 'false' : 'true'} })` },
23
+ ...Object.fromEntries(Object.entries(d.params ?? {}).map(([k, v]) => [`${n}.${k}`, { type: 'any', default: v, neutral: true, cost: d.fuse ? 'uniform' : 'recompile' }])) };
24
+ };
25
+ const styleValues = () => Object.fromEntries(post._list.filter(h => styleDefs.includes(h._def)).flatMap(h => Object.entries(h.params).map(([k, v]) => [`${h.name}.${k}`, v])));
26
+ /** The game layer records what differs from the default (createEngine({ post }), or an effect the game added) */
27
+ const record = h => { if (!styleDefs.includes(h._def) || h.enabled !== !!defaultOn(h._def)) part.write('game', { [`${h.name}.enabled`]: h.enabled }); };
28
+ const split = k => { const i = k.indexOf('.'); return [k.slice(0, i), k.slice(i + 1)]; };
29
+ const part = defineLookPart(e, {
30
+ id: 'post', group: 'screen', module: 'core', object: () => post.composer, docs: ['recipes/52-look.md'], applyAtStart: false,
31
+ params: Object.assign({}, ...post._list.map(decl)), style: styleValues,
32
+ read: () => ({}),
33
+ normalize(p) { // post.set({ vignette: false }) -> { 'vignette.enabled': false }
34
+ return Object.fromEntries(Object.entries(p).map(([k, v]) => (typeof v === 'boolean' && part.has(`${k}.enabled`) ? [`${k}.enabled`, v] : [k, v])));
35
+ },
36
+ apply(v, changed) {
37
+ const sets = new Map();
38
+ for (const k of changed) {
39
+ const [n, p] = split(k), h = post.get(n);
40
+ if (!h) continue;
41
+ if (p === 'enabled') { if (h.enabled !== !!v[k]) h._enable(!!v[k]); } else if (h.params[p] !== v[k]) (sets.get(h) ?? sets.set(h, {}).get(h))[p] = v[k];
42
+ }
43
+ for (const [h, p] of sets) h._set(p);
44
+ },
45
+ hooks: { '*': { signature: 'GLSL statements that edit `vec4 color` (see PostFuse in render/PostFX.js); spec { glsl, slot: "ldr", order, uniforms, values }', scope: ['vUv', 'tDiffuse', 'uTime', 'uResolution', 'fxHash(vec2)'] } },
46
+ extraSignatures: { add: 'add(effect, { owner })' },
47
+ applyHook(name, impl) {
48
+ if (impl != null && generated.has(name) && source.get(name) === impl) return; // the same spec again (a rolled-back write re-applies every hook): keep the built effect
49
+ generated.get(name)?._remove();
50
+ source.delete(name);
51
+ if (generated.delete(name)) part.retract(name + '.');
52
+ if (impl == null) return;
53
+ if (post.get(name)) throw new Error(`look.post.patch/add('${name}'): an effect named '${name}' already exists; pick another name, or change it with look.post.set({ '${name}.<param>': value })`);
54
+ const s = typeof impl === 'string' ? { glsl: impl } : impl, { slot, order, params, ...fuse } = s;
55
+ // add(effect) passes a whole effect (create | fuse): it keeps its own slot / order / enabled; patch(name, spec) is a fuse snippet in 'ldr'
56
+ const h = s.create || s.fuse ? post._add({ ...s, name }) : post._add({ name, fuse, slot: slot ?? 'ldr', order, params });
57
+ generated.set(name, h); source.set(name, impl); part.extend(decl(h));
58
+ },
59
+ replace: { accepts: 'an array of post effects ({ name, create | fuse, slot, order, params }); null gives the style\'s chain back',
60
+ loses: ['every effect the style, patch() or a replaced chain brought (their look.post values go with them)'] },
61
+ // checked before the record is written, so a wrong replace never reaches applyReplace (review H1)
62
+ validate: (k, v) => (k === '@replace' && !Array.isArray(v) ? 'is an array of effects like [bloom({ strength: 0.4 }), myGrain]; null gives the style chain back' : null),
63
+ applyReplace(impl) {
64
+ if (impl != null && !Array.isArray(impl)) throw new Error('look.post.replace(effects): effects is an array like [bloom({ strength: 0.4 }), myGrain]; null gives the style chain back');
65
+ post._building = true;
66
+ try {
67
+ for (const h of [...post._list]) { h._remove(); part.retract(h.name + '.'); }
68
+ generated.clear(); source.clear();
69
+ for (const d of impl ?? styleDefs) { const lowOff = impl == null && d.costly && low; const h = post._add(d, { enabled: lowOff ? false : undefined }); part.extend(decl(h)); }
70
+ part.restyle(impl ? {} : styleValues());
71
+ } finally { post._building = false; post._sync(); }
72
+ },
73
+ });
74
+ /** Add one custom pass; it is a patch under the effect's name, so owner layers, describe, remove and rollback work like every look verb */
75
+ part.add = (effect, o) => {
76
+ if (!effect || typeof effect.name !== 'string' || (typeof effect.create !== 'function' && !effect.fuse))
77
+ throw codedError('look-verb', "look.post.add(effect): needs { name: 'myEffect', create: (ctx) => pass } (or a fuse snippet { name, fuse: { glsl } }, see PostEffect)");
78
+ // checked here, before any write: the hook key is the effect name, so a second write under it would replace (and tear down) the first effect
79
+ if (post.get(effect.name)) throw codedError('look-verb', `look.post.add: post effect '${effect.name}' is already added; change it with look.post.set({ '${effect.name}.<param>': value }), or drop it with its handle.remove() / look.post.replace([...])`);
80
+ part.patch(effect.name, effect, o);
81
+ // patch's handle would drop the owner's WHOLE post layer (every other effect this owner added); remove only this effect's hook
82
+ return { remove: () => { part.patch(effect.name, null, o); } };
83
+ };
84
+ for (const h of post._list) record(h);
85
+ return { part };
86
+ }
package/render/surface.js CHANGED
@@ -6,6 +6,7 @@ import { placeholderTexture, EFFECTS } from './effects.js';
6
6
  import { detailPatch } from './detail.js';
7
7
  import { lightingPatch } from './lighting.js';
8
8
  import { patchMaterial } from './patches.js';
9
+ import { surfaceDetail } from './lookSurface.js';
9
10
 
10
11
  // Color textures are sRGB; the rest hold data and stay linear (three would otherwise gamma-decode normals and roughness)
11
12
  const COLOR_SLOTS = ['map', 'emissiveMap', 'lightMap', 'sheenColorMap', 'specularColorMap'];
@@ -60,7 +61,8 @@ export function applySurface(m, props, where, engine, lit) {
60
61
  loadSlot(m, k, v, tex, where, engine);
61
62
  } else rest[k] = v;
62
63
  }
63
- if (props.detail) patchMaterial(m, [EFFECTS.world(), detailPatch(props.detail, engine, `${where}.detail`)]);
64
+ const det = props.detail === false ? null : props.detail ?? surfaceDetail(engine); // look.surface.detail is the pack-wide default
65
+ if (det) patchMaterial(m, [EFFECTS.world(), detailPatch(det, engine, `${where}.detail`)]);
64
66
  const l = props.lighting === false ? null : { ...lit, ...props.lighting };
65
67
  if (l && Object.keys(l).length) patchMaterial(m, [lightingPatch(l, `${where}.lighting`)]);
66
68
  return rest;