@casmo/tree.js 0.3.0 → 0.5.0

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 (154) hide show
  1. package/README.md +775 -4
  2. package/dist/effects/custom.d.ts +62 -0
  3. package/dist/effects/custom.d.ts.map +1 -0
  4. package/dist/effects/effects.d.ts +92 -6
  5. package/dist/effects/effects.d.ts.map +1 -1
  6. package/dist/effects/glow.d.ts +5 -0
  7. package/dist/effects/glow.d.ts.map +1 -1
  8. package/dist/effects/grade.d.ts +3 -0
  9. package/dist/effects/grade.d.ts.map +1 -1
  10. package/dist/effects/highlight.d.ts +35 -0
  11. package/dist/effects/highlight.d.ts.map +1 -0
  12. package/dist/effects/index.d.ts +7 -1
  13. package/dist/effects/index.d.ts.map +1 -1
  14. package/dist/effects/inner-lines.d.ts +39 -0
  15. package/dist/effects/inner-lines.d.ts.map +1 -0
  16. package/dist/effects/live.d.ts +12 -0
  17. package/dist/effects/live.d.ts.map +1 -0
  18. package/dist/effects/mask.d.ts +32 -12
  19. package/dist/effects/mask.d.ts.map +1 -1
  20. package/dist/effects/outline.d.ts +12 -0
  21. package/dist/effects/outline.d.ts.map +1 -1
  22. package/dist/effects/pass.d.ts +27 -0
  23. package/dist/effects/pass.d.ts.map +1 -0
  24. package/dist/effects/screen.d.ts +31 -0
  25. package/dist/effects/screen.d.ts.map +1 -0
  26. package/dist/effects/suggested.d.ts +5 -0
  27. package/dist/effects/suggested.d.ts.map +1 -1
  28. package/dist/effects/tree-id.d.ts +50 -0
  29. package/dist/effects/tree-id.d.ts.map +1 -0
  30. package/dist/effects-qHx_8Dlk.js +1052 -0
  31. package/dist/effects-qHx_8Dlk.js.map +1 -0
  32. package/dist/effects.js +3 -249
  33. package/dist/forest/Forest.d.ts +82 -4
  34. package/dist/forest/Forest.d.ts.map +1 -1
  35. package/dist/forest/forest-lod.d.ts +70 -0
  36. package/dist/forest/forest-lod.d.ts.map +1 -0
  37. package/dist/forest/impostor-material.d.ts +106 -0
  38. package/dist/forest/impostor-material.d.ts.map +1 -0
  39. package/dist/forest/impostor-season.d.ts +13 -0
  40. package/dist/forest/impostor-season.d.ts.map +1 -0
  41. package/dist/forest/impostor.d.ts +105 -0
  42. package/dist/forest/impostor.d.ts.map +1 -0
  43. package/dist/forest/index.d.ts +1 -0
  44. package/dist/forest/index.d.ts.map +1 -1
  45. package/dist/forest/levels.d.ts +144 -0
  46. package/dist/forest/levels.d.ts.map +1 -0
  47. package/dist/forest/lod.d.ts +106 -0
  48. package/dist/forest/lod.d.ts.map +1 -0
  49. package/dist/forest/nodes.d.ts +42 -1
  50. package/dist/forest/nodes.d.ts.map +1 -1
  51. package/dist/forest/octahedral.d.ts +33 -0
  52. package/dist/forest/octahedral.d.ts.map +1 -0
  53. package/dist/{forest-ChEaWJrf.js → forest-CM5DrklM.js} +1727 -340
  54. package/dist/forest-CM5DrklM.js.map +1 -0
  55. package/dist/generator/fruit.d.ts +2 -0
  56. package/dist/generator/fruit.d.ts.map +1 -1
  57. package/dist/generator/index.d.ts +1 -0
  58. package/dist/generator/index.d.ts.map +1 -1
  59. package/dist/generator/light.d.ts +36 -0
  60. package/dist/generator/light.d.ts.map +1 -0
  61. package/dist/index.d.ts +3 -2
  62. package/dist/index.d.ts.map +1 -1
  63. package/dist/index.js +5 -2
  64. package/dist/index.js.map +1 -1
  65. package/dist/materials/crown-nodes.d.ts +5 -0
  66. package/dist/materials/crown-nodes.d.ts.map +1 -1
  67. package/dist/materials/leaf-translucency-model.d.ts +6 -1
  68. package/dist/materials/leaf-translucency-model.d.ts.map +1 -1
  69. package/dist/materials/material-features.d.ts +12 -0
  70. package/dist/materials/material-features.d.ts.map +1 -1
  71. package/dist/materials/shader-hooks.d.ts +155 -0
  72. package/dist/materials/shader-hooks.d.ts.map +1 -0
  73. package/dist/motion-Qd7xjeZM.js +276 -0
  74. package/dist/motion-Qd7xjeZM.js.map +1 -0
  75. package/dist/nodes-DxgTyF9B.js +436 -0
  76. package/dist/nodes-DxgTyF9B.js.map +1 -0
  77. package/dist/react/Forest.d.ts +17 -3
  78. package/dist/react/Forest.d.ts.map +1 -1
  79. package/dist/react/ScenePipeline.d.ts +63 -0
  80. package/dist/react/ScenePipeline.d.ts.map +1 -0
  81. package/dist/react/SceneShaderHooks.d.ts +25 -0
  82. package/dist/react/SceneShaderHooks.d.ts.map +1 -0
  83. package/dist/react/Tree.d.ts +9 -2
  84. package/dist/react/Tree.d.ts.map +1 -1
  85. package/dist/react/Weather.d.ts +45 -0
  86. package/dist/react/Weather.d.ts.map +1 -0
  87. package/dist/react/Wind.d.ts +12 -1
  88. package/dist/react/Wind.d.ts.map +1 -1
  89. package/dist/react/index.d.ts +7 -1
  90. package/dist/react/index.d.ts.map +1 -1
  91. package/dist/react.js +347 -10
  92. package/dist/react.js.map +1 -1
  93. package/dist/renderer/index.d.ts +6 -0
  94. package/dist/renderer/index.d.ts.map +1 -1
  95. package/dist/scene/antialias.d.ts +35 -0
  96. package/dist/scene/antialias.d.ts.map +1 -0
  97. package/dist/scene/ao.d.ts +46 -0
  98. package/dist/scene/ao.d.ts.map +1 -0
  99. package/dist/scene/bloom.d.ts +19 -0
  100. package/dist/scene/bloom.d.ts.map +1 -0
  101. package/dist/scene/fog.d.ts +49 -0
  102. package/dist/scene/fog.d.ts.map +1 -0
  103. package/dist/scene/godrays.d.ts +37 -0
  104. package/dist/scene/godrays.d.ts.map +1 -0
  105. package/dist/scene/index.d.ts +14 -0
  106. package/dist/scene/index.d.ts.map +1 -0
  107. package/dist/scene/motion-blur.d.ts +23 -0
  108. package/dist/scene/motion-blur.d.ts.map +1 -0
  109. package/dist/scene/pipeline.d.ts +109 -0
  110. package/dist/scene/pipeline.d.ts.map +1 -0
  111. package/dist/scene/settings.d.ts +36 -0
  112. package/dist/scene/settings.d.ts.map +1 -0
  113. package/dist/scene/stack.d.ts +25 -0
  114. package/dist/scene/stack.d.ts.map +1 -0
  115. package/dist/scene/stage.d.ts +52 -0
  116. package/dist/scene/stage.d.ts.map +1 -0
  117. package/dist/scene/suggested.d.ts +12 -0
  118. package/dist/scene/suggested.d.ts.map +1 -0
  119. package/dist/scene/tone-mapping.d.ts +20 -0
  120. package/dist/scene/tone-mapping.d.ts.map +1 -0
  121. package/dist/scene/velocity.d.ts +34 -0
  122. package/dist/scene/velocity.d.ts.map +1 -0
  123. package/dist/scene.js +889 -0
  124. package/dist/scene.js.map +1 -0
  125. package/dist/season/nodes.d.ts +13 -0
  126. package/dist/season/nodes.d.ts.map +1 -1
  127. package/dist/shader-hooks-BFRtlWGI.js +275 -0
  128. package/dist/shader-hooks-BFRtlWGI.js.map +1 -0
  129. package/dist/tree/Tree.d.ts +8 -3
  130. package/dist/tree/Tree.d.ts.map +1 -1
  131. package/dist/tree/index.d.ts.map +1 -1
  132. package/dist/weather/index.d.ts +3 -0
  133. package/dist/weather/index.d.ts.map +1 -0
  134. package/dist/weather/shared.d.ts +43 -0
  135. package/dist/weather/shared.d.ts.map +1 -0
  136. package/dist/weather/snow.d.ts +87 -0
  137. package/dist/weather/snow.d.ts.map +1 -0
  138. package/dist/weather/wetness.d.ts +75 -0
  139. package/dist/weather/wetness.d.ts.map +1 -0
  140. package/dist/weather.js +288 -0
  141. package/dist/weather.js.map +1 -0
  142. package/dist/wind/Wind.d.ts +100 -5
  143. package/dist/wind/Wind.d.ts.map +1 -1
  144. package/dist/wind/burst.d.ts +28 -0
  145. package/dist/wind/burst.d.ts.map +1 -0
  146. package/dist/wind/index.d.ts +3 -2
  147. package/dist/wind/index.d.ts.map +1 -1
  148. package/dist/wind/motion.d.ts +30 -0
  149. package/dist/wind/motion.d.ts.map +1 -0
  150. package/dist/wind/node.d.ts +17 -3
  151. package/dist/wind/node.d.ts.map +1 -1
  152. package/package.json +9 -1
  153. package/dist/effects.js.map +0 -1
  154. package/dist/forest-ChEaWJrf.js.map +0 -1
package/README.md CHANGED
@@ -18,6 +18,7 @@ thousands at once as an instanced Forest, add opt-in Tree Effects, or design you
18
18
  - [Wind](#wind)
19
19
  - [Forests](#forests)
20
20
  - [Material Features](#material-features)
21
+ - [Tree Shader Hook](#tree-shader-hook)
21
22
  - [Tree Effects](#tree-effects)
22
23
  - [React Three Fiber](#react-three-fiber)
23
24
  - [Without a bundler: import map (CDN)](#without-a-bundler-import-map-cdn)
@@ -42,7 +43,9 @@ npm install @casmo/tree.js three
42
43
  | `@casmo/tree.js/styles/low-poly` (`stylized`, `realistic`) | a built-in Style: one Tree Definition per Form (a few kB of data) |
43
44
  | `@casmo/tree.js/species` | the 28 Species (`oak`, `douglasFir`, ...), `loadSpecies`, `SPECIES_NAMES`; JSON files |
44
45
  | `@casmo/tree.js/effects` | Tree Effects (post-processing) |
45
- | `@casmo/tree.js/react` | `<Tree>`, `<Forest>`, `<Wind>`, `useTreeStyle` for React Three Fiber |
46
+ | `@casmo/tree.js/scene` | Scene Pipeline: the Style's suggested Tree Effects and Scene Effects (tone mapping, SMAA/FXAA, fog, ...) in one opt-in pipeline |
47
+ | `@casmo/tree.js/weather` | ready-made weather Tree Shader Hooks: [Snow Cover](#snow-cover), [Wetness](#wetness) |
48
+ | `@casmo/tree.js/react` | `<Tree>`, `<Forest>`, `<Wind>`, `useTreeStyle`, `<ScenePipeline>` for React Three Fiber |
46
49
 
47
50
  ## Quick start
48
51
 
@@ -384,6 +387,55 @@ scene.add(swaying, sheltered);
384
387
 
385
388
  A swaying tree needs a render loop (`renderer.setAnimationLoop`).
386
389
 
390
+ ### Wind Burst
391
+
392
+ A Wind Burst is a short, local push of air from a point on the ground, e.g. where the player places a
393
+ building: trees within its radius bend away from it, the front rolls outward at 30 m/s, and the push
394
+ springs back once and fades out within 1.2 s of Wind time. It adds to the Wind on trunk, branches and
395
+ leaves, scaled by each tree's Wind response, also when the Wind is calm:
396
+
397
+ ```ts
398
+ import { createTree, sceneWind } from '@casmo/tree.js';
399
+
400
+ const tree = createTree({ schemaVersion: 3 }, { seed: 1 });
401
+ tree.position.set(3, 0, 0);
402
+
403
+ sceneWind.burst({ x: 1, z: 0, strength: 1, radius: 6 }); // radius defaults to 8 m per unit of strength
404
+ sceneWind.burst({ x: 1, z: 0, strength: -0.5 }); // reduced motion: lean away and settle, no swing
405
+ console.log(sceneWind.bursts.length); // the bursts running now
406
+ ```
407
+
408
+ A negative strength is the reduced-motion mode, for players who turn motion down: trees within reach
409
+ lean away from the point all at once and settle, with no front travelling outward and no swing back; the
410
+ size of the value is the strength (and sets the default radius). A weaker positive strength simply
411
+ pushes less.
412
+
413
+ Up to 8 bursts (`MAX_WIND_BURSTS`) run at once per Wind; another one replaces the oldest. A burst starts
414
+ at the Wind's current time (its pinned `time`, or the renderer clock), so a pinned clock holds it still.
415
+ The Wind-aware velocity channel (TRAA, motion blur) includes burst motion.
416
+
417
+ Wind Bursts are opt-in at the material level: until a Wind has had its first `burst()`, the trees swaying
418
+ with it have no burst nodes at all, and their materials are exactly as without Wind Bursts. The first
419
+ burst on a Wind (or binding a tree or Forest to a Wind that has had one) rebuilds the node graphs of
420
+ those trees once, on Trees, every Forest Detail Level, Impostors and the velocity channel, so expect one
421
+ shader compile then; the geometry is never rebuilt. Call `burst()` once during loading (e.g. with a
422
+ small radius far away) to have that compile happen up front. After that a burst only writes uniforms,
423
+ and with no burst running the shader loop runs zero times.
424
+
425
+ Forests take the bursts of their Wind too: every Forest tree bends away from the burst point from its
426
+ own position and rotation, at every Detail Level, and Impostors sway with it, so the whole park reacts:
427
+
428
+ ```ts
429
+ import { createForest, sceneWind } from '@casmo/tree.js';
430
+
431
+ const forest = createForest({ schemaVersion: 3 }, [{ position: [0, 0, 0] }, { position: [20, 0, 0] }], { lod: true });
432
+ scene.add(forest);
433
+
434
+ sceneWind.burst({ x: 2, z: 0, strength: 1, radius: 6 }); // the first tree bends, the second does not
435
+ ```
436
+
437
+ Impostors also include their sway, bursts and all, in the Wind-aware velocity channel.
438
+
387
439
  ## Forests
388
440
 
389
441
  ![A 400-tree instanced Forest whose trees turn to autumn towards the right](docs/images/forest.png)
@@ -422,6 +474,70 @@ if (hit) console.log(forest.treeAt(hit)?.key);
422
474
 
423
475
  `forest.dispose()` frees everything. `forest.ready` resolves once its textures have loaded.
424
476
 
477
+ ### Detail Levels
478
+
479
+ Far trees cover a few pixels but still cost their full mesh. With `lod` a Forest draws each tree at a
480
+ **Detail Level** for its distance from the camera: **Full** up close, **Light** (the same Variant
481
+ regenerated with fewer faces and larger leaves, every branch in place) in the middle distance, and an
482
+ **Impostor** far away: one camera-facing card per tree, lit by your lights from baked normals, that still
483
+ follows Season (leaf colour, leaf drop down to bare branches, blossom) and sways in the Wind. Neighbouring
484
+ levels cross-fade with an ordered dither, so trees never pop. A compute pass picks the levels on the GPU
485
+ every frame and fills indirect draws, so there is no per-tree work on the CPU. A tree that is not fully
486
+ grown is never an Impostor.
487
+
488
+ ```ts
489
+ import { createForest, type ForestPlacement } from '@casmo/tree.js';
490
+ import lowPoly from '@casmo/tree.js/styles/low-poly';
491
+
492
+ declare const placements: ForestPlacement[]; // thousands of trees
493
+
494
+ // Light from 30 m, Impostor from 90 m (distances are divided by a tree's placement scale),
495
+ // cross-fading over 10% of the switch distance. `lod: true` uses 6 and 20 trunk heights.
496
+ const forest = createForest(lowPoly.broadleaf, placements, { variants: 4, lod: { light: 30, impostor: 90, fade: 0.1 } });
497
+ scene.add(forest);
498
+ renderer.render(scene, camera); // the first frame finds the backend and draws every tree in full
499
+ await forest.lodReady; // Detail Levels drawn, Impostors baked (far trees draw Light until then)
500
+
501
+ forest.lod = { impostor: 120 }; // distances, fade and the camera that picks the levels are live: no rebuild
502
+ ```
503
+
504
+ - Detail Levels need WebGPU (compute and indirect draws). On WebGPURenderer's WebGL2 fallback a `lod`
505
+ Forest draws every tree in full, exactly as without `lod`, with one console warning. Without `lod` nothing
506
+ changes: no extra meshes, buffers or bake.
507
+ - The backend is only known when the Forest is first drawn: three.js hands it the renderer during that
508
+ render, after the frame's draw list is made. So on WebGPU the **first frame draws every tree in full**
509
+ (one full-cost frame), the Detail Levels take over from the next frame, and far trees switch from Light
510
+ to Impostor once the bake is done; on the WebGL2 fallback `lodReady` resolves on that first render, not
511
+ at once. To show neither switch, render once and `await forest.lodReady` before the forest is seen.
512
+ - One camera picks every tree's level: the first non-shadow camera that draws the Forest in a frame, or
513
+ `lod.camera`. Shadow passes and other cameras reuse its levels.
514
+ - Raycasting, `forest.treeAt`, `addTree`/`removeTree`, live Material Features and Tree Effects work as
515
+ without `lod`, at every Detail Level.
516
+ - **Memory**: the Impostors are baked into atlases of `impostorAtlas.size`² pixels (default 2048, with
517
+ `frames` 12 × 12 directions from the horizon to straight above), in two render targets per Variant: the
518
+ tree (colour, normals, Season data, and Material Feature inputs when the Definition sets them) and the
519
+ wood alone (colour, normals: shown where leaves have dropped). Each atlas is RGBA8 with mipmaps, about
520
+ 21 MiB at 2048, and each render target has a depth buffer of the same size (16 MiB). That is about
521
+ 139 MiB of GPU memory per Variant (five atlases), 160 MiB with Material Features (six), so 555 MiB or
522
+ 640 MiB for 4 Variants. Halving `size` quarters it (`impostorAtlas: { size: 1024 }`: about 35 MiB per
523
+ Variant); fewer `frames` keep the memory and give each direction more pixels. `forest.dispose()` frees them.
524
+
525
+ [`examples/large-forest`](examples/large-forest/main.ts) draws 10,000 trees under an orbiting camera and
526
+ rebuilds the Forest with Detail Levels on or off, measuring both runs side by side. One example run
527
+ (not a guarantee; measure on your own hardware):
528
+
529
+ | 10,000 trees, 4 Variants | Detail Levels off | Detail Levels on (`lod: true`) |
530
+ | --- | --- | --- |
531
+ | frame time, average / p95 | 2,988 / 6,207 ms | 264 / 441 ms |
532
+ | draw calls | 10 | 22 |
533
+ | triangles drawn | 12,520,003 | 450,869 |
534
+ | trees Full / Light / Impostor | 10,000 / 0 / 0 | 40 / 1,639 / 8,630 |
535
+
536
+ *Measured with `?orbit=30` (camera pinned), 120 frames at 640 × 480, in headless Chromium (Playwright 1.65)
537
+ whose WebGPU runs on SwiftShader, a CPU rasterizer, on an AMD Ryzen 9 7900 that was also running other jobs.
538
+ That is why a frame takes seconds; on a GPU the frames are far faster and the ratio differs. The extra draw
539
+ calls are the indirect draws of every Variant and level, issued even when a level is empty.*
540
+
425
541
  ## Material Features
426
542
 
427
543
  ![The same stylized tree without (left) and with (right) the suggested Material Features: the crown is lit as one rounded shape, glows at its edge against the low sun and is darker inside](docs/images/material-features.png)
@@ -513,6 +629,185 @@ Material Features are a different thing from [Tree Effects](#tree-effects): thos
513
629
  (the "leaf glow" effect is a screen-space bloom, not Leaf Translucency). See them side by side per Style in
514
630
  [`examples/material-features`](examples/material-features/main.ts).
515
631
 
632
+ ## Tree Shader Hook
633
+
634
+ A Tree Shader Hook is the one supported way to change how a tree's surface is shaded (snow, rain, drought
635
+ colour, a painterly foliage look) without touching its materials. You hand the library a
636
+ [TSL](https://threejs.org/docs/#api/en/nodes/TSL) function per tree part (`bark`, `leaves` or `fruit`),
637
+ and it applies it inside that part's node materials, which it keeps building and rewiring itself for
638
+ Growth, Season and Wind. Don't patch `tree.leaves.material` yourself; set a hook instead.
639
+
640
+ The hook gets TSL nodes for the fragment it shades and returns a colour (lit as before), or a colour and a
641
+ roughness:
642
+
643
+ | Input | What it is |
644
+ | --- | --- |
645
+ | `color` | The base colour (linear rgb): after Season, Ground Tint, textures and the Seed's tint, before lighting |
646
+ | `roughness` | The part's roughness before the hook |
647
+ | `normal` | The world-space normal the fragment is lit with, after Wind and Growth (and Crown Normals, the bark normal map) |
648
+ | `position`, `treePosition` | The fragment's world position, and the tree's own (the foot of its trunk) |
649
+ | `season`, `growth` | The tree's Season and Growth (0..1) |
650
+ | `part`, `shading` | The tree part, and the Style's shading (`'flat'`, `'toon'` or `'standard'`) |
651
+
652
+ ```ts
653
+ import { createTree, type TreeShaderHook } from '@casmo/tree.js';
654
+ import stylized from '@casmo/tree.js/styles/stylized';
655
+ import { mix, smoothstep, uniform, vec3 } from 'three/tsl';
656
+
657
+ const frost = uniform(0.5); // animate the hook with uniforms: no rebuild
658
+ const frosty: TreeShaderHook = ({ color, normal, roughness }) => ({
659
+ color: mix(color, vec3(0.9, 0.95, 1), smoothstep(0.3, 0.8, normal.y).mul(frost)),
660
+ roughness: roughness.mul(0.8),
661
+ });
662
+
663
+ const tree = createTree(stylized.broadleaf, { seed: 3, shaderHooks: { leaves: frosty } });
664
+ tree.shaderHooks = { leaves: frosty, bark: frosty }; // set or change at runtime
665
+ tree.shaderHooks = {}; // remove: the tree is drawn exactly as before
666
+ ```
667
+
668
+ `tree.shaderHooks` holds the hooks per part of a `Tree`; a part whose hooks didn't change is left alone. A
669
+ hook is called once when it is set, to build the node graph, not per frame. Setting, changing or removing it
670
+ rebuilds the node graph of that part's material once (a shader recompile) and never the geometry. With no
671
+ hook nothing changes: same geometry, attributes and materials as before. It works on WebGPU and on the
672
+ WebGL2 fallback.
673
+
674
+ ### On Forests, Detail Levels and Impostors
675
+
676
+ A `Forest` takes hooks the same way, for every tree in it, near and far:
677
+
678
+ ```ts
679
+ import { createForest } from '@casmo/tree.js';
680
+ import stylized from '@casmo/tree.js/styles/stylized';
681
+ import { mix, vec3 } from 'three/tsl';
682
+
683
+ const forest = createForest(stylized.broadleaf, [{ position: [0, 0, 0] }, { position: [6, 0, 2] }], {
684
+ lod: true,
685
+ shaderHooks: { leaves: ({ color }) => mix(color, vec3(0.9, 0.6, 0.2), 0.5) },
686
+ });
687
+ forest.shaderHooks = {}; // set, change or remove at runtime, as on a Tree
688
+ ```
689
+
690
+ The hook runs at every [Detail Level](#detail-levels): Full and Light trees share the Variant's materials,
691
+ and Impostors apply it while they are drawn, to their baked colour, normals and Season data, with
692
+ `part` set per texel (bark or leaves; Impostors have no Fruit). So far trees follow a hook, and its
693
+ uniforms, live: changing a hook never rebakes an Impostor. `season`, `growth` and `treePosition` are each
694
+ tree's own.
695
+
696
+ ### Scene-wide default and stacking
697
+
698
+ `setSceneShaderHooks` sets hooks every Tree and Forest runs, now and when created later, the way
699
+ `sceneWind` is shared:
700
+
701
+ ```ts
702
+ import { createTree, setSceneShaderHooks, stackShaderHooks, type TreeShaderHook } from '@casmo/tree.js';
703
+ import stylized from '@casmo/tree.js/styles/stylized';
704
+ import { vec3 } from 'three/tsl';
705
+
706
+ const dusk: TreeShaderHook = ({ color }) => color.mul(vec3(1, 0.85, 0.7));
707
+ const pale: TreeShaderHook = ({ color }) => color.mul(1.2);
708
+ setSceneShaderHooks({ bark: dusk, leaves: dusk });
709
+
710
+ const tree = createTree(stylized.broadleaf, {
711
+ shaderHooks: {
712
+ leaves: pale, // stacks: dusk, then pale
713
+ bark: null, // overrides: no hook on this tree's bark, not even the scene-wide one
714
+ },
715
+ });
716
+ tree.shaderHooks = stackShaderHooks({ leaves: pale }, { leaves: dusk }); // several sets of hooks, joined per part
717
+ setSceneShaderHooks({}); // remove the scene-wide default
718
+ ```
719
+
720
+ Per part, a Tree's or Forest's hooks work like this:
721
+
722
+ - **left out** (or `undefined`): only the scene-wide default's hooks run;
723
+ - **a hook or a list of hooks**: they stack after the scene-wide default's;
724
+ - **`null`**: no hook at all on that part, the scene-wide default is overridden.
725
+
726
+ Stacked hooks run in a fixed order: first the ready-made hooks the library ships (such as Snow Cover and
727
+ Wetness), then the app's own; within each group the scene-wide default's before the Tree's or Forest's,
728
+ each list in the order given. Each hook gets the colour and roughness the one before it returned. A hook
729
+ that is listed twice runs once.
730
+
731
+ ### The normal after Wind
732
+
733
+ `normal` is the normal after Wind on every Style. three only moves a flat-shaded (low-poly) facet with the
734
+ swayed vertices; on smooth shading the library turns the lit normal by how the Wind turned the surface
735
+ (the facet of the unswayed positions to the swayed one, from screen-space derivatives). That costs one
736
+ varying and a few instructions, and only in a hook that reads `normal`. On an Impostor the baked normal is
737
+ turned with the card's sway the same way.
738
+
739
+ ### Snow Cover
740
+
741
+ Snow Cover is a ready-made Tree Shader Hook that whitens the surfaces of trees that face up, by a
742
+ scene-wide snow amount from 0 (none) to 1 (full cover). The amount is shared the way `sceneWind` is:
743
+ `sceneSnow`, or a `Snow` of your own. It lives in its own entry point, `@casmo/tree.js/weather`, which
744
+ nothing else in the library imports, so a game without weather never loads it:
745
+
746
+ ```ts
747
+ import { setSceneShaderHooks } from '@casmo/tree.js';
748
+ import { sceneSnow, snowCoverHooks } from '@casmo/tree.js/weather';
749
+
750
+ const snow = snowCoverHooks();
751
+ setSceneShaderHooks(snow); // every Tree and Forest, near and far (Impostors too); or `tree.shaderHooks = snow`
752
+ sceneSnow.amount = 0.8; // driven by your weather: a uniform, no rebuild
753
+
754
+ // Settings are live too (uniform writes):
755
+ snow.set({
756
+ color: '#f4f8ff', // sRGB, like any three.js colour
757
+ slope: 60, // the steepest surface (degrees from level, 0..90) that still holds snow
758
+ softness: 25, // degrees below `slope` over which the snow thins out to none (0: a hard edge)
759
+ strength: { bark: 1, leaves: 1, fruit: 0.5 }, // how much snow each part takes
760
+ });
761
+ ```
762
+
763
+ It draws to suit the Style: hard flat caps on low-poly, toon bands on stylized, soft lit snow with a slight
764
+ sparkle on realistic. Snow is read from the `normal` after Wind, so it sways with the branches, lies on bare
765
+ winter branches when the leaves are gone, and undersides stay bare. It stacks like any hooks and always runs
766
+ before your own. At amount 0, or without the hooks set, trees look exactly as before.
767
+ `snowCoverHooks({ snow })` follows another `Snow` than `sceneSnow`. For snow of your own, start from
768
+ `snowCoverShading`, the body of the ready-made hook, which only uses the hook's inputs and the settings you
769
+ give it.
770
+
771
+ ### Wetness
772
+
773
+ Wetness is a ready-made Tree Shader Hook for rain: trees get darker and get a sheen (a lower roughness),
774
+ most on surfaces that face up, by a scene-wide wetness amount from 0 (dry) to 1 (soaked). The amount is
775
+ shared the way `sceneWind` is: `sceneWetness`, or a `Wetness` of your own. It lives in its own entry
776
+ point, `@casmo/tree.js/weather`, so a game without weather never loads it:
777
+
778
+ ```ts
779
+ import { createTree, setSceneShaderHooks, stackShaderHooks, type TreeShaderHook } from '@casmo/tree.js';
780
+ import stylized from '@casmo/tree.js/styles/stylized';
781
+ import { sceneWetness, wetnessHooks } from '@casmo/tree.js/weather';
782
+
783
+ const wet = wetnessHooks({ darkening: 0.5, sheen: 0.7 });
784
+ setSceneShaderHooks(wet); // every Tree and Forest, near and far (Impostors too)
785
+ sceneWetness.amount = 0.8; // driven by your weather: a uniform, no rebuild
786
+
787
+ // Settings are live too (uniform writes):
788
+ wet.set({
789
+ color: '#d8e0ea', // the tint wet surfaces take on
790
+ slope: 140, // the steepest surface (degrees from level, 0..180: facing down) that still gets wet
791
+ softness: 60, // degrees below `slope` over which it dries out to none (0: a hard edge)
792
+ strength: { bark: 1, leaves: 0.8, fruit: 0.5 }, // how much each part takes
793
+ darkening: 0.4, // how much darker a soaked surface gets
794
+ sheen: 0.6, // how much its roughness drops
795
+ });
796
+
797
+ // Stacks with your own hooks: the ready-made ones always run first.
798
+ const mine: TreeShaderHook = ({ color }) => color.mul(1.1);
799
+ const tree = createTree(stylized.broadleaf, { shaderHooks: stackShaderHooks({ leaves: mine }, wet) });
800
+ ```
801
+
802
+ `slope` and `softness` mean the same as Snow Cover's: the angle of a surface from level (its normal from
803
+ straight up), fully wet up to `slope - softness` and dry from `slope` on. Unlike snow, rain also wets
804
+ sides and undersides, so Wetness's `slope` goes up to 180 (Snow Cover's to 90).
805
+
806
+ It draws to suit the Style: smooth on realistic, whole facets on low-poly, and toon bands with a light
807
+ glint band on top on stylized (toon lighting has no highlights for the sheen to show in). At amount 0, or
808
+ without the hooks set, trees look exactly as before. `wetnessHooks({ wetness })` follows another `Wetness`
809
+ than `sceneWetness`. For a look of your own, write your own hook instead, using this one as a model.
810
+
516
811
  ## Tree Effects
517
812
 
518
813
  ![A stylized tree, a rock and a crate without (left) and with (right) the stylized Tree Effects: only the tree gets an outline and colour grading](docs/images/effects.png)
@@ -532,6 +827,19 @@ renderer.setAnimationLoop(() => effects.render()); // instead of renderer.render
532
827
  effects.set({ outline: { color: '#203018', thickness: 2 }, grade: { saturation: 1.1 } }); // or null = none
533
828
  ```
534
829
 
830
+ Each Style has a suggested combination (`SUGGESTED_TREE_EFFECTS`): `low-poly` has a colour grade, ink
831
+ [Inner Lines](#inner-lines) and a dark outline that is also drawn [between overlapping trees](#outline-between-overlapping-trees);
832
+ `stylized` has a warm grade, a leaf glow, soft Inner Lines and a soft outline; `realistic` only a gentle
833
+ grade and a faint leaf glow (no ink).
834
+
835
+ > **Changed in this release:** the `low-poly` and `stylized` suggestions now include Inner Lines, and
836
+ > `low-poly` also `outline.betweenTrees`. Apps that use either suggestion get a changed look (ink lines
837
+ > inside the crown, and for low-poly between overlapping trees) and extra channels in the scene pass:
838
+ > the `normal` channel for both, and for low-poly also the [Tree ID](#tree-id) channel (a scene pass with
839
+ > the Tree ID renders without MSAA). In your own pipeline, request those channels from `treeEffectsPass`
840
+ > (see below). Use your own settings, e.g. `{ ...SUGGESTED_TREE_EFFECTS.stylized, innerLines: undefined }`,
841
+ > to keep the old look.
842
+
535
843
  Pass `selection: [tree]` to outline only some trees. In your own pipeline, the effects are nodes that
536
844
  compose with your other effects:
537
845
 
@@ -541,7 +849,8 @@ import { float, screenUV, vec4 } from 'three/tsl';
541
849
  import { applyTreeEffects, SUGGESTED_TREE_EFFECTS, treeEffectsPass } from '@casmo/tree.js/effects';
542
850
 
543
851
  const pipeline = new THREE.RenderPipeline(renderer);
544
- const input = treeEffectsPass(scene, camera); // { pass, color, mask }
852
+ // The low-poly suggestion's Inner Lines need the normal channel, its betweenTrees outline the Tree ID.
853
+ const input = treeEffectsPass(scene, camera, null, { normal: true, treeId: true }); // { pass, color, mask, ... }
545
854
  const trees = applyTreeEffects(input, SUGGESTED_TREE_EFFECTS['low-poly']); // or treeOutline / leafGlow / treeColorGrade
546
855
  const vignette = float(1).sub(screenUV.sub(0.5).length().mul(0.9).pow(2)); // your own effect on top
547
856
  pipeline.outputNode = vec4(trees.rgb.mul(vignette), 1);
@@ -551,11 +860,372 @@ renderer.setAnimationLoop(() => pipeline.render());
551
860
  To add the tree mask to a scene pass you already have, merge `treeMaskMRT()` into its MRT and read the
552
861
  mask with `scenePass.getTextureNode(TREE_MASK)`.
553
862
 
863
+ ### Tree ID
864
+
865
+ To tell trees apart on screen (GPU picking, your own per-tree effects), add the opt-in **Tree ID**
866
+ channel: an extra MRT target in which every tree writes its own number. Each Tree has one ID for all
867
+ its parts (wood, leaves, Fruit), and each tree of a Forest has its own. Nothing else changes: the tree
868
+ mask, its format and the `treeEffectsPass` default stay as they are.
869
+
870
+ ```ts
871
+ import { mrt, output, pass } from 'three/tsl';
872
+ import { readTreeId, TREE_ID, treeFromId, treeIdMRT, treeIdTexture, treeMaskMRT } from '@casmo/tree.js/effects';
873
+
874
+ const scenePass = pass(scene, camera);
875
+ scenePass.setMRT(mrt({ output }).merge(treeMaskMRT()).merge(treeIdMRT()));
876
+ treeIdTexture(scenePass); // makes the target one 32-bit unsigned integer per pixel
877
+ const ids = scenePass.getTextureNode(TREE_ID); // read it with exact texel loads (ids.load(...)), never filtered
878
+
879
+ renderer.domElement.addEventListener('click', async (event) => {
880
+ const id = await readTreeId(renderer, scenePass, event.offsetX, event.offsetY); // CSS pixels
881
+ const tree = treeFromId(id); // the Tree or ForestTree, or undefined (0 = no tree)
882
+ });
883
+ ```
884
+
885
+ - **Encoding:** `r32uint`, 0 = not a tree. A Forest Variant reserves a block of IDs the size of its
886
+ capacity, and its trees write block start + slot, at every Detail Level (Impostors included). The
887
+ tree mask, outline, Inner Lines and Highlight work on far trees too; raycasting and `forest.treeAt`
888
+ keep hitting the full meshes.
889
+ - **No MSAA:** an integer target cannot be multisampled, so turning on the Tree ID turns MSAA off on
890
+ that scene pass: `treeIdTexture` sets `samples: 0`, also with an `antialias: true` renderer. This
891
+ applies wherever the ID channel is on: `treeIdTexture`, `treeEffectsPass(..., { treeId: true })`,
892
+ and in `TreeEffects` the `treeId: true` option, `outline.betweenTrees`, `highlight` and the
893
+ `low-poly` suggestion (which uses `betweenTrees`). Add FXAA or SMAA after the pass if you need
894
+ smooth edges there.
895
+ - **Limits:** IDs are handed out by one registry for the whole page on first use: the first time a
896
+ tree is drawn with the channel or asked for with `treeIdOf(tree)`, whichever comes first. They are
897
+ never reused: about 4.29 billion per session. The registry keeps no tree alive. The ID ignores the
898
+ outline's `selection`.
899
+ - **Frame-relative:** a Forest tree's ID follows its instance slot. Removing a tree (the last tree
900
+ moves into its slot) or a Variant growing past its capacity can change the IDs of other trees. So
901
+ resolve an ID with `treeFromId` in the frame it was read, and ask `treeIdOf(tree)` for a tree's
902
+ current ID; a removed tree resolves to `undefined`.
903
+ - `readTreeId` reads the pixel under a point of the canvas from the last render of the pass (it
904
+ handles the target's index, the y flip and the device pixel ratio). It works on WebGPU and on the
905
+ WebGL2 fallback.
906
+ - **WebGL2 fallback:** three clears every target there as floats, which is invalid for an integer
907
+ target, so `treeIdTexture` makes the pass clear the ID target itself right before every render (a
908
+ frame with nothing drawn reads 0). three's own clear still logs a GL warning
909
+ (a `GL_INVALID_OPERATION` from `clearBufferfv`) in the console each frame; it is harmless.
910
+
911
+ #### Picking with `TreeEffects` and the opt-in channels
912
+
913
+ The ready-made pipeline only renders the channels its settings need. Without them (`effects: null`,
914
+ or grade, glow and outline without `betweenTrees`) the scene pass is exactly `{ output, treeMask }` with the 8-bit mask, as
915
+ always. Pass `treeId: true` to keep the Tree ID channel on without any effect needing it, then pick
916
+ with one call:
917
+
918
+ ```ts
919
+ import { createTreeEffects } from '@casmo/tree.js/effects';
920
+
921
+ const effects = createTreeEffects(renderer, scene, camera, { effects: 'stylized', treeId: true });
922
+ renderer.domElement.addEventListener('pointermove', async (event) => {
923
+ const tree = await effects.pick(event.offsetX, event.offsetY); // Tree, ForestTree or undefined
924
+ });
925
+ ```
926
+
927
+ `pick` reads the ID from the last render and resolves it right away (IDs are frame-relative). Without
928
+ the Tree ID channel it throws an error that names the `treeId` option. The scene pass's MRT (and with
929
+ it the compiled materials of your scene) only changes when `set()` needs a different set of channels;
930
+ switching between settings that need the same channels keeps it. When the channels do change,
931
+ `effects.scenePass` is a new pass (three cannot remove a target from a pass, nor turn MSAA back on
932
+ for it), so read `effects.scenePass` again after such a `set()` instead of keeping the old one. In your own pipeline,
933
+ `treeEffectsPass(scene, camera, selection, { treeId: true })` adds the channel and fills in the
934
+ effects' `treeId` input.
935
+
936
+ #### Outline between overlapping trees
937
+
938
+ By default the outline goes around all trees together, so trees that overlap on screen merge into one
939
+ shape. With `betweenTrees` the outline is also drawn where a tree lies in front of another one, for a
940
+ Tree and a Tree, two Forest trees, or a Tree and a Forest tree:
941
+
942
+ ```ts
943
+ import { createTreeEffects } from '@casmo/tree.js/effects';
944
+
945
+ const effects = createTreeEffects(renderer, scene, camera, {
946
+ effects: { outline: { color: '#18230f', thickness: 2, betweenTrees: true } },
947
+ });
948
+ ```
949
+
950
+ The line is drawn on a selected tree pixel when the pixel `thickness` px away is another tree (a
951
+ different Tree ID) that is further away, so it lies on the front tree's side, with the outline's own
952
+ colour, thickness and strength (with a standard, reversed or logarithmic depth buffer). It is off by
953
+ default (the outline stays as it was). It needs the Tree
954
+ ID: `TreeEffects` turns the channel on for it, and switching `betweenTrees` on or off builds a new
955
+ graph. In your own pipeline, use `treeEffectsPass(scene, camera, selection, { treeId: true })`, which
956
+ also fills in the `depth` input; `treeOutline` throws when the `treeId` or `depth` input is missing.
957
+
958
+ ### Inner Lines
959
+
960
+ **Inner Lines** are ink lines inside the trees where the surface folds or steps away from the viewer,
961
+ such as around each leaf clump, on top of the outline around the tree. They come from depth edges
962
+ (a relative step `|Δz| / z`, so they look the same near and far) and normal edges (`1 − dot`), are
963
+ only drawn on tree pixels of every tree (whatever the `selection`) and only from neighbours that are
964
+ tree pixels too: the silhouette is left to the outline. They work with a standard, reversed
965
+ (`reversedDepthBuffer`) or logarithmic (`logarithmicDepthBuffer`) depth buffer.
966
+
967
+ ```ts
968
+ import { createTreeEffects } from '@casmo/tree.js/effects';
969
+
970
+ const effects = createTreeEffects(renderer, scene, camera, {
971
+ effects: { outline: {}, innerLines: { color: '#1d2a14', thickness: 1, strength: 1, normalThreshold: 0.4, depthThreshold: 0.02 } },
972
+ });
973
+ ```
974
+
975
+ Inner Lines need view normals, so with `innerLines` the ready-made pipeline adds a `normal` channel
976
+ (RGBA8) to its scene pass; without it the pass stays `{ output, treeMask }`. Order of the effects:
977
+ grade, glow, inner lines, outline. In your own pipeline, `treeEffectsPass(scene, camera, selection, { normal: true })`
978
+ fills in the `normal`, `depth` and `camera` inputs, or merge `treeNormalMRT()` into your scene pass.
979
+ `innerLines()` throws an error naming the missing input when `normal`, `depth` or `camera` is missing.
980
+
981
+ If your pipeline already renders normals (for GTAO, SSR and the like), pass that texture instead of
982
+ rendering them twice, with its encoding: `'color'` (default, `directionToColor(normalView)` in an
983
+ RGBA8 target) or `'direction'` (the normal itself, e.g. in a float target):
984
+
985
+ ```ts
986
+ import * as THREE from 'three/webgpu';
987
+ import { mrt, normalView, output, pass } from 'three/tsl';
988
+ import { innerLines, TREE_MASK, treeMaskMRT, treeOutline } from '@casmo/tree.js/effects';
989
+
990
+ const scenePass = pass(scene, camera);
991
+ scenePass.setMRT(mrt({ output, normal: normalView }).merge(treeMaskMRT())); // your MRT, plus the tree mask
992
+ scenePass.getTexture(TREE_MASK).type = THREE.UnsignedByteType;
993
+ const normal = scenePass.getTextureNode('normal'); // also feeds your GTAO / SSR
994
+ const input = {
995
+ color: scenePass.getTextureNode('output'),
996
+ mask: scenePass.getTextureNode(TREE_MASK),
997
+ depth: scenePass.getTextureNode('depth'),
998
+ camera,
999
+ normal,
1000
+ normalEncoding: 'direction' as const,
1001
+ };
1002
+ const lined = innerLines(input, { strength: 0.8 });
1003
+ const pipeline = new THREE.RenderPipeline(renderer);
1004
+ pipeline.outputNode = treeOutline({ ...input, color: lined });
1005
+ ```
1006
+
1007
+ ### Highlight
1008
+
1009
+ **Highlight** marks the trees you point out, such as the one under the cursor: it brightens and tints
1010
+ them and draws a ring just outside them, optionally pulsing. It is the one Tree Effect that also
1011
+ changes pixels next to a tree (its ring). It is never on by default and in no suggestion. It needs
1012
+ the Tree ID, so `highlight` turns that channel on (and with it `pick`):
1013
+
1014
+ ```ts
1015
+ import { createTreeEffects } from '@casmo/tree.js/effects';
1016
+
1017
+ const effects = createTreeEffects(renderer, scene, camera, {
1018
+ effects: { outline: {}, highlight: { color: '#ffe066', tint: 0.25, brightness: 1.25, outlineColor: '#ffd23f', thickness: 2, pulse: 0 } },
1019
+ });
1020
+ renderer.domElement.addEventListener('pointermove', async (event) => {
1021
+ const tree = await effects.pick(event.offsetX, event.offsetY);
1022
+ effects.highlighted.splice(0, effects.highlighted.length, ...(tree ? [tree] : [])); // read every frame, no recompile
1023
+ });
1024
+ ```
1025
+
1026
+ - `highlighted` (an option, or the `effects.highlighted` list) holds Trees and Forest trees, not a
1027
+ Forest or a group. Change it in place; it is read every frame. At most 64 trees are highlighted at
1028
+ once (one console warning beyond that). Removed, disposed and undrawn trees are skipped.
1029
+ - Options: `color` and `tint` (0..1) of the tint, `brightness` (a multiplier), `outlineColor` and
1030
+ `thickness` (px) of the ring, `strength` (0..1) and `pulse` (Hz, 0 = off): tint and brightness swing
1031
+ between their value and half of it, the ring stays solid.
1032
+ - It is applied last (grade, glow, inner lines, outline, then highlight), so it is always on top. In your own
1033
+ pipeline: `treeHighlight(input, highlighted, options)`, with the `treeId` input of
1034
+ `treeEffectsPass(scene, camera, null, { treeId: true })`, or `applyTreeEffects(input, settings, highlighted)`.
1035
+
1036
+ ### Custom Tree Effects
1037
+
1038
+ Add a Tree Effect of your own to `TreeEffects`, such as a brush look on the foliage only. It is built
1039
+ the way the built-in ones are: from the colour so far and the tree mask, returning a colour node and an
1040
+ `update()` that changes its uniforms live. The tree mask's `r` is 1 on any tree pixel, `g` on leaf
1041
+ pixels only and `b` on the selected trees'.
1042
+
1043
+ ```ts
1044
+ import { mix, uniform, vec4 } from 'three/tsl';
1045
+ import { createTreeEffects, type CustomTreeEffect } from '@casmo/tree.js/effects';
1046
+
1047
+ const foliage: CustomTreeEffect<{ strength: number }> = {
1048
+ before: 'outline', // where it runs among the built-in effects (default: last, under the Highlight; 'end': over it)
1049
+ // channels: { treeId: true, normal: true }, // only if it reads them: the scene pass adds them
1050
+ build(input, options) {
1051
+ const strength = uniform(options.strength);
1052
+ const look = input.color.rgb; // your look here (this is the bare pass-through)
1053
+ const node = vec4(mix(input.color.rgb, look, input.mask.g.mul(strength)), input.color.a);
1054
+ return { node, update: (next) => (strength.value = next.strength) };
1055
+ },
1056
+ };
1057
+
1058
+ const effects = createTreeEffects(renderer, scene, camera, { effects: 'stylized' });
1059
+ effects.addEffect(foliage, { strength: 1 });
1060
+ effects.updateEffect(foliage, { strength: 0.5 }); // live: no new graph, no recompile
1061
+ effects.removeEffect(foliage);
1062
+ ```
1063
+
1064
+ - `before` names a built-in effect (`'grade'`, `'glow'`, `'innerLines'`, `'outline'` or `'highlight'`);
1065
+ the custom effect runs right before it, whether that one is on or not. `'end'` runs it after every
1066
+ built-in Tree Effect, the Highlight too (so it also changes the Highlight's tint and ring). Custom
1067
+ effects at the same place run in the order they were added. The default, `'highlight'`, runs it after
1068
+ every other built-in effect and under the Highlight.
1069
+ - The input has the colour so far (`color`), the tree mask (`mask`), `depth` and `camera`, plus the
1070
+ optional channels it declares in `channels` (`treeId`, `normal` with `normalEncoding`), which the scene
1071
+ pass then adds (a new scene pass, as for the built-in effects). Undeclared channels are never in its
1072
+ input, even when a built-in effect has them on.
1073
+ - Custom effects stay through `effects.set()`, which rebuilds them with their latest options when it
1074
+ builds a new graph. `effects.customEffects` lists them. Adding or removing one builds a new graph.
1075
+ - With no custom effect nothing changes: no channel, no pass. A custom effect itself adds no pass; it
1076
+ is part of the pipeline's output node.
1077
+ - The [Scene Pipeline](#scene-pipeline) takes the same custom effects, with the same `addEffect`,
1078
+ `updateEffect`, `removeEffect` and `customEffects`: see [Custom Tree Effects in the Scene
1079
+ Pipeline](#custom-tree-effects-in-the-scene-pipeline).
1080
+ - In your own pipeline, call `effect.build(input, options)` on the output of `applyTreeEffects` (or any
1081
+ colour) yourself. See [`examples/custom-effect`](examples/custom-effect/main.ts) for the bare setup of a
1082
+ foliage-only effect.
1083
+
1084
+ ## Scene Pipeline
1085
+
1086
+ ![A stylized tree in front of a small Forest without (left) and with (right) the Scene Pipeline's stylized suggestion: AgX tone mapping, ground-contact AO, a soft bloom, distance fog and a low mist](docs/images/scene-pipeline.png)
1087
+
1088
+ *Without (left) and with (right) `createScenePipeline(renderer, scene, camera, { style: 'stylized' })`.*
1089
+
1090
+ Tree Effects only change tree pixels. `@casmo/tree.js/scene` adds the whole-scene part around them,
1091
+ the **Scene Effects**: tone mapping, anti-aliasing, ground-contact ambient occlusion (GTAO), bloom, fog
1092
+ and god rays, plus TRAA and motion blur that see Wind. The **Scene Pipeline** renders a Style's
1093
+ suggested Tree Effects and Scene Effects in one `RenderPipeline`. It is opt-in: nothing changes until
1094
+ you create one. It never changes your renderer (tone mapping and the output colour space are applied
1095
+ inside the pipeline; shadows and lights are yours). Its only scene change is fog (`scene.fogNode`),
1096
+ and it gives your own value back.
1097
+
1098
+ ```ts
1099
+ import * as THREE from 'three/webgpu';
1100
+ import { createScenePipeline } from '@casmo/tree.js/scene';
1101
+
1102
+ const sun = new THREE.DirectionalLight('#fff4e0', 3.5); // your own light; for god rays it casts shadows
1103
+ sun.castShadow = true;
1104
+ scene.add(sun);
1105
+ const pipeline = createScenePipeline(renderer, scene, camera, { style: 'stylized', sun });
1106
+ renderer.setAnimationLoop(() => pipeline.render()); // instead of renderer.render(scene, camera)
1107
+ pipeline.set({ style: 'realistic' }); // same parts on: only uniforms change, no recompile
1108
+ pipeline.dispose(); // also restores your scene.fogNode
1109
+ ```
1110
+
1111
+ `ScenePipeline` replaces `TreeEffects` (use one or the other): the same options (`selection`, `treeId`,
1112
+ `highlighted`) and the same `set`, `pick`, `highlighted`, `scenePass`, `settings`, `render` and `dispose`,
1113
+ plus `pipeline` (the `RenderPipeline`).
1114
+ With no `style` and no overrides it adds nothing and renders exactly like `renderer.render()`.
1115
+
1116
+ The suggestion per Style (`SUGGESTED_SCENE_EFFECTS`, plain data). Fog is in metres, tuned for a small
1117
+ forest (trees 10-30 m away); scale it up for large worlds:
1118
+
1119
+ | Style | Tone mapping | AA | AO | Bloom | Fog | God rays |
1120
+ | --- | --- | --- | --- | --- | --- | --- |
1121
+ | `low-poly` | Neutral | SMAA | light | - | distance | - |
1122
+ | `stylized` | AgX | SMAA | yes | soft | distance + low mist | - |
1123
+ | `realistic` | AgX | SMAA | yes | subtle | distance + mist + far haze | yes (needs `sun`) |
1124
+
1125
+ SMAA is in every suggestion because the [Tree ID](#tree-id) channel turns MSAA off. TRAA and motion
1126
+ blur are never suggested. Override a whole group with `treeEffects` or `sceneEffects` (a Style name,
1127
+ settings or `null`; no deep merge, so spread the suggestion to change a part):
1128
+
1129
+ ```ts
1130
+ import type { DirectionalLight } from 'three/webgpu';
1131
+ import { createScenePipeline, SUGGESTED_SCENE_EFFECTS } from '@casmo/tree.js/scene';
1132
+
1133
+ const sun = scene.getObjectByName('sun') as DirectionalLight;
1134
+ createScenePipeline(renderer, scene, camera, {
1135
+ treeEffects: 'low-poly', // or null: no Tree Effects
1136
+ sceneEffects: { ...SUGGESTED_SCENE_EFFECTS.realistic, antialias: 'traa', fog: { near: 60, far: 600 } },
1137
+ sun, // a DirectionalLight or PointLight that already casts shadows
1138
+ });
1139
+ ```
1140
+
1141
+ - **God rays** need a `sun` that already casts shadows (with `renderer.shadowMap.enabled` and casting
1142
+ objects). Without one they are skipped with one console warning; the pipeline never turns shadows on.
1143
+ In the open they read as a faint warm haze, under a dense canopy as light shafts.
1144
+ - **Fog** takes its colour from `scene.background` when that is a plain `Color`, so far trees fade into
1145
+ the sky. `fog: { near, far, color?, mist?: { height, strength, near?, far?, farLayer? } }`.
1146
+ - **TRAA** (`antialias: 'traa'`) and **motion blur** (`motionBlur: { strength?, samples? }`) turn on a
1147
+ Wind-aware velocity channel in the scene pass: swaying leaves don't ghost under TRAA, and blur with
1148
+ the sway. Without them tree materials are unchanged. Pass `velocity: true` to keep the channel on for
1149
+ your own temporal effects (`pipeline.scenePass.velocity`).
1150
+ - The order is fixed: scene pass (fog in the materials, AO in the ambient light) -> Tree Effects -> god
1151
+ rays -> motion blur -> bloom -> TRAA -> tone mapping and output colour space -> SMAA / FXAA.
1152
+
1153
+ ### Custom Tree Effects in the Scene Pipeline
1154
+
1155
+ A [custom Tree Effect](#custom-tree-effects) goes into the Scene Pipeline the same way as into
1156
+ `TreeEffects`. It runs among the Tree Effects, at the place its `before` names (`'end'`: after the
1157
+ Highlight), so on tree pixels and before every Scene Effect (god rays, bloom, tone mapping and anti-aliasing see its result):
1158
+
1159
+ ```ts
1160
+ import { vec4 } from 'three/tsl';
1161
+ import type { CustomTreeEffect } from '@casmo/tree.js/effects';
1162
+ import { createScenePipeline } from '@casmo/tree.js/scene';
1163
+
1164
+ // The bare foliage-only setup of Custom Tree Effects above (put your look in place of `input.color.rgb`).
1165
+ const foliage: CustomTreeEffect<{ strength: number }> = {
1166
+ before: 'outline',
1167
+ build: (input) => ({ node: vec4(input.color.rgb, input.color.a), update: () => {} }),
1168
+ };
1169
+
1170
+ const pipeline = createScenePipeline(renderer, scene, camera, { style: 'stylized' });
1171
+ pipeline.addEffect(foliage, { strength: 1 });
1172
+ pipeline.updateEffect(foliage, { strength: 0.5 }); // live: no new graph, no recompile
1173
+ pipeline.set({ style: 'realistic' }); // the custom effect stays, rebuilt with its latest options
1174
+ pipeline.removeEffect(foliage);
1175
+ ```
1176
+
1177
+ - The channels it declares (`treeId`, `normal`) are added to the scene pass by the same rule as for the
1178
+ built-in effects, and go again when it is removed and nothing else needs them.
1179
+ - With no custom effect the pipeline is unchanged. A custom effect alone (no Style, no overrides) makes
1180
+ the pipeline render through its `RenderPipeline` instead of `renderer.render()`.
1181
+
1182
+ ### Scene Effects in your own pipeline
1183
+
1184
+ Every Scene Effect is also a stand-alone builder (every number and colour a uniform, every option with a
1185
+ default), for apps that already have a `RenderPipeline`. Pick by what you need:
1186
+
1187
+ | Builder | Returns | Use it when |
1188
+ | --- | --- | --- |
1189
+ | `sceneToneMapping(color, { mapping, exposure })` | display colours | you want AgX / Neutral without setting `renderer.toneMapping`; set `pipeline.outputColorTransform = false` |
1190
+ | `sceneAntialias(color, 'smaa' \| 'fxaa')` | display colours | edges alias (MSAA is off with the Tree ID, or you render without it); give it display colours (after `sceneToneMapping`, or `renderOutput(color)`); SMAA is sharper, FXAA cheaper |
1191
+ | `sceneAntialias(color, 'traa', { depth, velocity, camera })` | linear colours | you want the smoothest still image and alpha-cut leaves; before tone mapping, velocity from `windVelocityMRT()`; sets `samples = 0` (no MSAA) on the scene pass of `depth` |
1192
+ | `sceneAO(scene, camera, options)` | `{ prePass, node, context }` | trees and rocks float on the ground; set `scenePass.contextNode = context` (only ambient light darkens; the scene is drawn twice) |
1193
+ | `sceneFog(options, scene.background)` | a fog node | depth and mist; set `scene.fogNode` yourself (no pipeline needed) |
1194
+ | `sceneGodrays(color, depth, camera, sun, options)` | linear colours | light shafts; needs the shadow-casting `sun` and the scene pass's depth |
1195
+ | `sceneMotionBlur(color, velocity, options)` | linear colours | fast camera or strong Wind; velocity from `windVelocityMRT()` |
1196
+ | `sceneBloom(color, options)` | linear colours | bright skies or emissive parts should glow; before tone mapping |
1197
+ | `applySceneEffects(input, settings)` | the whole stack as one node | you want a Style's look in your own pipeline (like `applyTreeEffects`) |
1198
+
1199
+ ```ts
1200
+ import * as THREE from 'three/webgpu';
1201
+ import { mrt, output, pass } from 'three/tsl';
1202
+ import { applyTreeEffects, SUGGESTED_TREE_EFFECTS, treeMaskMRT, TREE_MASK } from '@casmo/tree.js/effects';
1203
+ import { sceneAntialias, sceneBloom, sceneMotionBlur, sceneToneMapping, windVelocityMRT, WIND_VELOCITY } from '@casmo/tree.js/scene';
1204
+
1205
+ const scenePass = pass(scene, camera);
1206
+ scenePass.setMRT(mrt({ output }).merge(treeMaskMRT()).merge(windVelocityMRT())); // Wind-aware velocity
1207
+ const color = scenePass.getTextureNode();
1208
+ const trees = applyTreeEffects({ color, mask: scenePass.getTextureNode(TREE_MASK) }, SUGGESTED_TREE_EFFECTS.realistic); // grade + leaf glow: no extra channels
1209
+ const blurred = sceneMotionBlur(trees, scenePass.getTextureNode(WIND_VELOCITY));
1210
+ const display = sceneToneMapping(sceneBloom(blurred, { strength: 0.1 }), { mapping: 'agx' });
1211
+ const pipeline = new THREE.RenderPipeline(renderer);
1212
+ pipeline.outputNode = sceneAntialias(display, 'smaa');
1213
+ pipeline.outputColorTransform = false; // tone mapping already output display colours
1214
+ ```
1215
+
1216
+ `applySceneEffects({ color, depth, camera, sun, velocity }, settings)` builds the same colour stack from
1217
+ settings (fog and AO are not colour steps: use `sceneFog` and `sceneAO` for them). The velocity channel
1218
+ (ADR 0011) is three's `velocity` (NDC per frame) plus the Wind sway since the previous frame:
1219
+ `windVelocityMRT()` adds it to a scene pass under the name `WIND_VELOCITY`, and `windVelocity` is the
1220
+ node for your own MRT. TRAA changes your scene pass: `sceneAntialias(color, 'traa', input)` sets its
1221
+ `options.samples = 0`, because TRAA copies the depth each frame and a multisampled depth cannot be copied
1222
+ (TRAA anti-aliases instead). The Scene Pipeline restores the old value when TRAA goes off.
1223
+
554
1224
  ## React Three Fiber
555
1225
 
556
1226
  ![Two low-poly trees rendered with React Three Fiber](docs/images/react.png)
557
1227
 
558
- `@casmo/tree.js/react` has `<Tree>`, `<Forest>`, `<Wind>` and `useTreeStyle`. Trees use TSL node
1228
+ `@casmo/tree.js/react` has `<Tree>`, `<Forest>`, `<Wind>` and `useTreeStyle` (and, opt-in, the [hooks, weather, Wind Bursts and custom Tree Effects](#tree-shader-hooks-weather-wind-bursts-and-custom-tree-effects-in-react)). Trees use TSL node
559
1229
  materials, so give `<Canvas>` a `WebGPURenderer` (it falls back to WebGL2 by itself). R3F v9 takes an
560
1230
  async `gl` factory, which must `await renderer.init()` before it returns:
561
1231
 
@@ -614,8 +1284,106 @@ createRoot(document.getElementById('root')!).render(<App />);
614
1284
  - A new `seed`, `definition` (compared by value) or `style`/`form` regenerates the tree. Trees are disposed of on unmount.
615
1285
  - `style` also takes a Style name (`<Tree style="low-poly" />`), which suspends like `useTreeStyle`. The `ref` is the tree.js `Tree` (or `Forest`) object.
616
1286
  - `<Forest>` diffs its `placements` by id: changing the array plants and cuts trees without touching the others; per-tree `growth`/`season` override the forest's.
1287
+ - `<Forest lod>` takes `createForest`'s `lod`. Switching it on or off (or a new `impostorAtlas`/`lightDefinition`) rebuilds the forest; new distances, `fade` or `camera` only write `forest.lod`.
617
1288
  - Use `shadows="percentage"` (plain `shadows` asks for a shadow type WebGPURenderer no longer has).
618
1289
 
1290
+ `<ScenePipeline>` renders the canvas through a [Scene Pipeline](#scene-pipeline) (same options as
1291
+ `createScenePipeline`). It takes over rendering (`useFrame` priority 1), follows the camera, calls `set()`
1292
+ when `style`/`treeEffects`/`sceneEffects` change and disposes of the pipeline on unmount. `sun` takes a
1293
+ light or a ref. The `ref` and `useScenePipeline()` (for children) give the `ScenePipeline` (`null` until
1294
+ built). It lazily loads `@casmo/tree.js/scene` (so apps without it don't bundle it) and suspends on
1295
+ its first render until that has loaded: put it inside a `<Suspense>` boundary (like `<Tree style>`), and
1296
+ call `preloadScenePipeline()` early (e.g. at module load) to start the download before it renders.
1297
+
1298
+ ```tsx
1299
+ import { useRef } from 'react';
1300
+ import type { DirectionalLight } from 'three/webgpu';
1301
+ import { ScenePipeline, useScenePipeline } from '@casmo/tree.js/react';
1302
+
1303
+ function PickOnClick() {
1304
+ const pipeline = useScenePipeline(); // needs `treeId` for pick()
1305
+ return <mesh onClick={(e) => void pipeline?.pick(e.nativeEvent.offsetX, e.nativeEvent.offsetY)} />;
1306
+ }
1307
+
1308
+ function Look() {
1309
+ const sun = useRef<DirectionalLight>(null);
1310
+ return (
1311
+ <>
1312
+ <directionalLight ref={sun} position={[5, 8, 3]} castShadow />
1313
+ <ScenePipeline style="realistic" sun={sun} treeId>
1314
+ <PickOnClick />
1315
+ </ScenePipeline>
1316
+ </>
1317
+ );
1318
+ }
1319
+ ```
1320
+
1321
+ ### Tree Shader Hooks, weather, Wind Bursts and custom Tree Effects in React
1322
+
1323
+ All of these are opt-in: a React app that uses none of them renders exactly as before.
1324
+
1325
+ ```tsx
1326
+ import { useState } from 'react';
1327
+ import { mix, vec3, vec4 } from 'three/tsl';
1328
+ import {
1329
+ SceneShaderHooks,
1330
+ ScenePipeline,
1331
+ SnowCover,
1332
+ Tree,
1333
+ TreeEffect,
1334
+ Wetness,
1335
+ useWindBurst,
1336
+ type CustomTreeEffect,
1337
+ type TreeShaderHooks,
1338
+ } from '@casmo/tree.js/react';
1339
+
1340
+ // Module scope (or useMemo): a new function is a new hook, and a new hook rebuilds the node graph.
1341
+ const autumn: TreeShaderHooks = { leaves: ({ color }) => mix(color, vec3(0.9, 0.5, 0.1), 0.5) };
1342
+ const dusk: TreeShaderHooks = { bark: ({ color }) => color.mul(vec3(1, 0.85, 0.7)) };
1343
+ const foliage: CustomTreeEffect<{ strength: number }> = {
1344
+ before: 'outline',
1345
+ build: (input) => ({ node: vec4(input.color.rgb, input.color.a), update: () => {} }), // your look here
1346
+ };
1347
+
1348
+ function Park({ snow, rain }: { snow: number; rain: number }) {
1349
+ const burst = useWindBurst(); // on the scene-wide Wind, or useWindBurst(otherWind)
1350
+ const [fall, setFall] = useState(false);
1351
+ return (
1352
+ <>
1353
+ <SceneShaderHooks hooks={dusk} />
1354
+ <SnowCover amount={snow} slope={60} />
1355
+ <Wetness amount={rain} sheen={0.7} />
1356
+ <Tree style="stylized" seed={1} shaderHooks={fall ? autumn : undefined} onClick={() => setFall(!fall)} />
1357
+ <mesh rotation-x={-Math.PI / 2} onClick={(e) => burst({ x: e.point.x, z: e.point.z, strength: 1, radius: 6 })}>
1358
+ <planeGeometry args={[40, 40]} />
1359
+ </mesh>
1360
+ <ScenePipeline style="stylized">
1361
+ <TreeEffect effect={foliage} options={{ strength: 0.5 }} />
1362
+ </ScenePipeline>
1363
+ </>
1364
+ );
1365
+ }
1366
+ ```
1367
+
1368
+ - `<Tree shaderHooks>` and `<Forest shaderHooks>` set the [Tree Shader Hooks](#tree-shader-hook) of that tree
1369
+ or every tree of the forest (`tree.shaderHooks`, `forest.shaderHooks`); unset is none. Only the parts
1370
+ whose hooks change rebuild their node graph; the tree is never regenerated.
1371
+ - `<SceneShaderHooks hooks>` sets scene-wide default hooks while mounted (`setSceneShaderHooks`). Several
1372
+ stack in the order they mounted, after the hooks the scene already had, which the last one to unmount
1373
+ puts back. Don't call `setSceneShaderHooks` yourself while they are mounted.
1374
+ - `<SnowCover>` and `<Wetness>` put the ready-made [Snow Cover](#snow-cover) and [Wetness](#wetness)
1375
+ hooks on every tree while mounted (scene-wide, before the app's own hooks). `amount` is written to
1376
+ `sceneSnow` / `sceneWetness` (or the `snow` / `wetness` prop) and put back on unmount; the settings
1377
+ (`color`, `slope`, `softness`, `strength`, and Wetness's `darkening`, `sheen`) are live, an unset one is
1378
+ its default. Their `ref` gives the hooks (`SnowCoverHooks`, `WetnessHooks`). They load
1379
+ `@casmo/tree.js/weather` with a dynamic import on first use, so apps without weather never bundle it:
1380
+ they suspend like `<ScenePipeline>` (call `preloadWeather()` to start the download early).
1381
+ - `useWindBurst(wind?)` returns a stable function that starts a [Wind Burst](#wind-burst).
1382
+ - `<TreeEffect effect options>` inside a `<ScenePipeline>` adds a [custom Tree
1383
+ Effect](#custom-tree-effects-in-the-scene-pipeline) while mounted. New `options` (compared by value) go
1384
+ through `updateEffect` (no new graph); it stays through Style changes, moves into a rebuilt pipeline, and
1385
+ is removed on unmount. Several at the same place run in the order they mounted.
1386
+
619
1387
  ## Without a bundler: import map (CDN)
620
1388
 
621
1389
  ![The import map example: dragging the Growth slider shrinks the trees to saplings and grows them back](docs/images/cdn.gif)
@@ -750,10 +1518,13 @@ a live preview (Seed, Growth, Season, Wind, Tree Effects), sculpt single branche
750
1518
  | --- | --- | --- | --- |
751
1519
  | [`examples/vanilla`](examples/vanilla/main.ts) | `/examples/vanilla/` | one tree in plain three.js; `?style=low-poly&form=conifer&seed=2&growth=0.6&season=0.7&wind=0.5` | <img src="docs/images/example-vanilla.png" alt="examples/vanilla" width="160"> |
752
1520
  | [`examples/cdn`](examples/cdn/index.html) | `/examples/cdn/` | no bundler: a single HTML page with an import map | <img src="docs/images/example-cdn.png" alt="examples/cdn" width="160"> |
753
- | [`examples/react`](examples/react/main.tsx) | `/examples/react/` | React Three Fiber: `<Tree>`, `<Wind>`, `useTreeStyle`; `?scene=forest` for `<Forest>` | <img src="docs/images/example-react.png" alt="examples/react" width="160"> |
1521
+ | [`examples/react`](examples/react/main.tsx) | `/examples/react/` | React Three Fiber: `<Tree>`, `<Wind>`, `useTreeStyle`; `?scene=forest` for `<Forest>`, `?scene=pipeline` for `<ScenePipeline>` | <img src="docs/images/example-react.png" alt="examples/react" width="160"> |
754
1522
  | [`examples/forest`](examples/forest/main.ts) | `/examples/forest/` | a 400-tree Forest; `?trees=&variants=&style=&season=` | <img src="docs/images/example-forest.png" alt="examples/forest" width="160"> |
1523
+ | [`examples/large-forest`](examples/large-forest/main.ts) | `/examples/large-forest/` | 10,000 trees with Detail Levels on and off: frame times, draw calls, triangles and trees per Detail Level; `?trees=&lod=0&frames=&orbit=` | <img src="docs/images/example-large-forest.png" alt="examples/large-forest" width="160"> |
755
1524
  | [`examples/effects`](examples/effects/main.ts) | `/examples/effects/` | Tree Effects per Style; `?style=stylized&effects=outline` | <img src="docs/images/example-effects.png" alt="examples/effects" width="160"> |
1525
+ | [`examples/custom-effect`](examples/custom-effect/main.ts) | `/examples/custom-effect/` | a foliage-only [custom Tree Effect](#custom-tree-effects) (the bare setup); `?effect=on\|pass-through\|off&effects=style&view=mask&backend=webgl` | <img src="docs/images/example-custom-effect.png" alt="examples/custom-effect" width="160"> |
756
1526
  | [`examples/material-features`](examples/material-features/main.ts) | `/examples/material-features/` | the same tree with Material Features off and on (`SUGGESTED_MATERIAL_FEATURES`); `?style=realistic&species=oak` | <img src="docs/images/example-material-features.png" alt="examples/material-features" width="160"> |
1527
+ | [`examples/scene-pipeline`](examples/scene-pipeline/main.ts) | `/examples/scene-pipeline/` | the opt-in [Scene Pipeline](#scene-pipeline) (`createScenePipeline`) per Style: `?style=low-poly\|stylized\|realistic`; one Scene Effect alone through its builder: `?scene=tone-mapping\|smaa\|fxaa\|traa\|gtao\|bloom\|fog\|godrays\|motion-blur` (`&sun=back` for light shafts); `?scene=none` (adds nothing) or `plain` (`renderer.render`); the Wind-aware velocity channel: `?scene=velocity&wind=1.5&windTime=3`; motion blur: `?scene=motion-blur&wind=3&windTime=3&cameraStep=0.5`; `?backend=webgl` | <img src="docs/images/example-scene-pipeline.png" alt="examples/scene-pipeline" width="160"> |
757
1528
  | [`examples/species`](examples/species/main.ts) | `/examples/species/` | a Species x Style picker over the whole collection; `?species=douglas-fir&style=realistic` | <img src="docs/images/example-species.png" alt="examples/species" width="160"> |
758
1529
 
759
1530
  ```sh