3D engine that AI agents drive
Replace procedural leaf cards with scanned CC0 leaves
Nguyen Xuan An04788933bf0b
diff --git a/index.html b/index.htmlindex a6ff3101..a7f7dea2 100644--- a/index.html+++ b/index.html@@ -98,7 +98,7 @@ renderer.render({<a class="example" href="./view2d.html"><img src="./previews/view2d.webp" alt="A flat orbital poster rendered through an orthographic camera" width="960" height="540" loading="lazy" /><div class="example-caption"><h3>Orbital field</h3></div><p>Orthographic and 2D views</p></a><a class="example" href="./assets.html"><img src="./previews/assets.webp" alt="An imported geometric study displayed in the asset viewer" width="960" height="540" loading="lazy" /><div class="example-caption"><h3>Your models</h3></div><p>Open a GLB and play its clips</p></a><a class="example" href="./terrain.md"><img src="./previews/terrain.webp" alt="Rolling hills of scanned grass and mud rising to rocky ridges under a cloudy sky" width="1280" height="720" loading="lazy" /><div class="example-caption"><h3>Terrain</h3></div><p>Scanned ground layers blended by slope and height</p></a>- <a class="example" href="./vegetation.md"><img src="./previews/forest.webp" alt="A clearing of seeded trees with leaf cards around a fountain of baked liquid" width="1280" height="720" loading="lazy" /><div class="example-caption"><h3>Forest clearing</h3></div><p>Seeded trees, leaf cutouts and a fountain</p></a>+ <a class="example" href="./vegetation.md"><img src="./previews/forest.webp" alt="Birch, beech and fir trees with scanned leaves over a grassy slope" width="1280" height="720" loading="lazy" /><div class="example-caption"><h3>Forest</h3></div><p>Seeded trees with scanned leaves and bark</p></a><a class="example" href="./spume.md"><img src="./previews/spume.webp" alt="A jet of baked liquid hitting a concrete slab, refracting the columns behind it" width="1280" height="720" loading="lazy" /><div class="example-caption"><h3>Spume liquid</h3></div><p>Baked water that refracts and sprays</p></a><a class="example" href="./vehicle.md"><img src="./previews/vehicle.webp" alt="A jeep leaning into a bend as it follows a marked path" width="1280" height="720" loading="lazy" /><div class="example-caption"><h3>Vehicles</h3></div><p>Steering, roll and wheels on a path</p></a><a class="example" href="./lighting.md"><img src="./previews/lighting.webp" alt="Metal spheres of rising roughness lit by an HDR environment" width="1280" height="720" loading="lazy" /><div class="example-caption"><h3>HDRI lighting</h3></div><p>Reflections that blur with roughness</p></a>diff --git a/public/previews/forest.webp b/public/previews/forest.webpindex ae19b71d..e477eb67 100644Binary files a/public/previews/forest.webp and b/public/previews/forest.webp differdiff --git a/public/textures/CREDITS.md b/public/textures/CREDITS.mdindex e0633dda..da1774ec 100644--- a/public/textures/CREDITS.md+++ b/public/textures/CREDITS.md@@ -1,6 +1,6 @@# Texture and HDRI credits-Every file under `public/textures/` and `public/hdri/` comes from [Poly Haven](https://polyhaven.com) and is released under+Every file under `public/textures/` and `public/hdri/` comes from [Poly Haven](https://polyhaven.com) or [ambientCG](https://ambientcg.com) and is released under[CC0 1.0](https://creativecommons.org/publicdomain/zero/1.0/): free for any use, no attribution required. The authors arecredited here anyway.@@ -18,3 +18,14 @@ Per folder: `color` (base color, sRGB), `normal` (OpenGL convention, linear), `r| `pine_bark` | [Pine Bark](https://polyhaven.com/a/pine_bark) | Dimitrios Savva || `palm_tree_bark` | [Palm Tree Bark](https://polyhaven.com/a/palm_tree_bark) | Dimitrios Savva, Rico Cilliers || `hdri/kloofendal_48d_partly_cloudy_puresky_1k.hdr` | [Kloofendal 48d Partly Cloudy (Pure Sky)](https://polyhaven.com/a/kloofendal_48d_partly_cloudy_puresky) | Greg Zaal, Jarod Guest |++## Leaf cards (`leaves/`)++`leaves/<species>/{color,normal,crown}.webp` are composited by `scripts/build-leaf-cards.py` from three ambientCG leaf+atlases (1K PNG, downloaded 2026-10-29), all CC0 1.0 by Lennart Demes / ambientCG:++| Species folders | Atlas |+| --- | --- |+| `broadleaf`, `birch` | [LeafSet024](https://ambientcg.com/view?id=LeafSet024) |+| `bush` | [LeafSet022](https://ambientcg.com/view?id=LeafSet022) |+| `conifer` | [LeafSet019](https://ambientcg.com/view?id=LeafSet019) |diff --git a/public/textures/leaves/birch/color.webp b/public/textures/leaves/birch/color.webpnew file mode 100644index 00000000..229cb85cBinary files /dev/null and b/public/textures/leaves/birch/color.webp differdiff --git a/public/textures/leaves/birch/crown.webp b/public/textures/leaves/birch/crown.webpnew file mode 100644index 00000000..b4aa64ddBinary files /dev/null and b/public/textures/leaves/birch/crown.webp differdiff --git a/public/textures/leaves/birch/normal.webp b/public/textures/leaves/birch/normal.webpnew file mode 100644index 00000000..c0e967f9Binary files /dev/null and b/public/textures/leaves/birch/normal.webp differdiff --git a/public/textures/leaves/broadleaf/color.webp b/public/textures/leaves/broadleaf/color.webpnew file mode 100644index 00000000..d09aa3f9Binary files /dev/null and b/public/textures/leaves/broadleaf/color.webp differdiff --git a/public/textures/leaves/broadleaf/crown.webp b/public/textures/leaves/broadleaf/crown.webpnew file mode 100644index 00000000..273e6abbBinary files /dev/null and b/public/textures/leaves/broadleaf/crown.webp differdiff --git a/public/textures/leaves/broadleaf/normal.webp b/public/textures/leaves/broadleaf/normal.webpnew file mode 100644index 00000000..06e39ea3Binary files /dev/null and b/public/textures/leaves/broadleaf/normal.webp differdiff --git a/public/textures/leaves/bush/color.webp b/public/textures/leaves/bush/color.webpnew file mode 100644index 00000000..fcb6a266Binary files /dev/null and b/public/textures/leaves/bush/color.webp differdiff --git a/public/textures/leaves/bush/crown.webp b/public/textures/leaves/bush/crown.webpnew file mode 100644index 00000000..652641b3Binary files /dev/null and b/public/textures/leaves/bush/crown.webp differdiff --git a/public/textures/leaves/bush/normal.webp b/public/textures/leaves/bush/normal.webpnew file mode 100644index 00000000..0f571ad4Binary files /dev/null and b/public/textures/leaves/bush/normal.webp differdiff --git a/public/textures/leaves/conifer/color.webp b/public/textures/leaves/conifer/color.webpnew file mode 100644index 00000000..a48ba3c2Binary files /dev/null and b/public/textures/leaves/conifer/color.webp differdiff --git a/public/textures/leaves/conifer/crown.webp b/public/textures/leaves/conifer/crown.webpnew file mode 100644index 00000000..2963abb8Binary files /dev/null and b/public/textures/leaves/conifer/crown.webp differdiff --git a/public/textures/leaves/conifer/normal.webp b/public/textures/leaves/conifer/normal.webpnew file mode 100644index 00000000..3c8737a5Binary files /dev/null and b/public/textures/leaves/conifer/normal.webp differdiff --git a/scripts/build-leaf-cards.py b/scripts/build-leaf-cards.pynew file mode 100644index 00000000..8c348be5--- /dev/null+++ b/scripts/build-leaf-cards.py@@ -0,0 +1,239 @@+"""Composite scanned CC0 leaf atlases into the leaf-card textures used by the vegetation addon.++Inputs are ambientCG LeafSet atlases (1K PNG: Color, Opacity, NormalGL). Each species gets+`public/textures/leaves/<species>/color.webp` (RGBA, alpha = leaf mask) and `normal.webp` (OpenGL tangent space),+plus `crown.webp` for the far level-of-detail clump cards. The stem base sits at the bottom centre of every card,+which is where `addLeafSurface` puts the twig.++Run:+ uv run --no-project --python 3.12 --with pillow --with numpy --with scipy python -I scripts/build-leaf-cards.py <atlas folder>+where <atlas folder> holds LeafSet019/, LeafSet022/ and LeafSet024/ unzipped from ambientcg.com/get?file=LeafSetNNN_1K-PNG.zip.+"""++import math+import random+import sys+from pathlib import Path++import numpy+from PIL import Image, ImageDraw+from scipy import ndimage++sys.stdout.reconfigure(encoding="utf-8", errors="replace")++CARD_SIZE = 512+FLAT_NORMAL = (128, 128, 255)+OUTPUT_ROOT = Path(__file__).resolve().parent.parent / "public" / "textures" / "leaves"+++class Leaf:+ """One leaf cut from an atlas, upright, with its stem base at the bottom centre of the image."""++ def __init__(self, color, normal):+ self.color = color+ self.normal = normal++ @property+ def length(self):+ return self.color.height+++def load_atlas(folder, atlas_name):+ prefix = folder / atlas_name / f"{atlas_name}_1K-PNG"+ color = Image.open(f"{prefix}_Color.png").convert("RGB")+ opacity = Image.open(f"{prefix}_Opacity.png").convert("L")+ normal = Image.open(f"{prefix}_NormalGL.png").convert("RGB")+ return color, opacity, normal+++def rotate_normal_pixels(normal_rgba, clockwise_degrees):+ """Rotating an image also rotates its tangent-space normals. Image y points down, GL green points up."""+ pixels = numpy.asarray(normal_rgba).astype(numpy.float32)+ x_component = pixels[..., 0] / 127.5 - 1+ y_component = pixels[..., 1] / 127.5 - 1+ angle = math.radians(clockwise_degrees)+ rotated_x = x_component * math.cos(angle) + y_component * math.sin(angle)+ rotated_y = -x_component * math.sin(angle) + y_component * math.cos(angle)+ pixels[..., 0] = (rotated_x + 1) * 127.5+ pixels[..., 1] = (rotated_y + 1) * 127.5+ return Image.fromarray(numpy.clip(pixels, 0, 255).astype(numpy.uint8), "RGBA")+++def rotate_leaf_pair(color_rgba, normal_rgba, clockwise_degrees):+ rotated_color = color_rgba.rotate(-clockwise_degrees, resample=Image.BICUBIC, expand=True)+ rotated_normal = normal_rgba.rotate(-clockwise_degrees, resample=Image.BICUBIC, expand=True)+ return rotated_color, rotate_normal_pixels(rotated_normal, clockwise_degrees)+++def cut_leaves(folder, atlas_name, base_side, minimum_pixels=4000):+ """Split an atlas into its separate leaves. `base_side` names the edge each leaf's stem points to."""+ color, opacity, normal = load_atlas(folder, atlas_name)+ mask = numpy.asarray(opacity) > 96+ labels, count = ndimage.label(mask)+ leaves = []+ for index, region in enumerate(ndimage.find_objects(labels), start=1):+ if region is None:+ continue+ component = labels[region] == index+ if component.sum() < minimum_pixels:+ continue+ box = (region[1].start, region[0].start, region[1].stop, region[0].stop)+ alpha = Image.fromarray(numpy.where(component, numpy.asarray(opacity)[region], 0).astype(numpy.uint8), "L")+ leaf_color = color.crop(box).convert("RGBA")+ leaf_color.putalpha(alpha)+ leaf_normal = normal.crop(box).convert("RGBA")+ leaf_normal.putalpha(alpha)+ turn = {"bottom": 0, "right": 90, "left": -90}[base_side]+ if turn:+ leaf_color, leaf_normal = rotate_leaf_pair(leaf_color, leaf_normal, turn)+ trimmed = leaf_color.getbbox()+ leaf_color = leaf_color.crop(trimmed)+ leaf_normal = leaf_normal.crop(trimmed)+ leaves.append(Leaf(leaf_color, leaf_normal))+ return leaves+++def new_card():+ color = Image.new("RGBA", (CARD_SIZE, CARD_SIZE), (0, 0, 0, 0))+ normal = Image.new("RGBA", (CARD_SIZE, CARD_SIZE), (*FLAT_NORMAL, 0))+ return color, normal+++def tint_image(image, multiplier):+ pixels = numpy.asarray(image).astype(numpy.float32)+ pixels[..., :3] *= numpy.asarray(multiplier, dtype=numpy.float32)+ return Image.fromarray(numpy.clip(pixels, 0, 255).astype(numpy.uint8), "RGBA")+++def paint_leaf(card, leaf, base_x, base_y, length, clockwise_degrees, tint=(1, 1, 1)):+ """Paint `leaf` with its stem base at (base_x, base_y), `length` pixels long, leaning clockwise from straight up."""+ card_color, card_normal = card+ scale = length / leaf.length+ width = max(1, round(leaf.color.width * scale))+ height = max(1, round(leaf.color.height * scale))+ color = tint_image(leaf.color.resize((width, height), Image.LANCZOS), tint)+ normal = leaf.normal.resize((width, height), Image.LANCZOS)+ # Pad so the stem base is the image centre, then rotate about it.+ half = math.ceil(max(width, height)) + 2+ padded_color = Image.new("RGBA", (half * 2, half * 2), (0, 0, 0, 0))+ padded_normal = Image.new("RGBA", (half * 2, half * 2), (*FLAT_NORMAL, 0))+ corner = (half - width // 2, half - height)+ padded_color.paste(color, corner)+ padded_normal.paste(normal, corner)+ rotated_color = padded_color.rotate(-clockwise_degrees, resample=Image.BICUBIC)+ rotated_normal = rotate_normal_pixels(padded_normal.rotate(-clockwise_degrees, resample=Image.BICUBIC), clockwise_degrees)+ target = (round(base_x) - half, round(base_y) - half)+ layer_color = Image.new("RGBA", card_color.size, (0, 0, 0, 0))+ layer_color.paste(rotated_color, target)+ layer_normal = Image.new("RGBA", card_normal.size, (*FLAT_NORMAL, 0))+ layer_normal.paste(rotated_normal, target)+ card_color.alpha_composite(layer_color)+ card_normal.alpha_composite(layer_normal)+++def paint_stem(card, points, thickness, color):+ card_color, card_normal = card+ ImageDraw.Draw(card_color).line(points, fill=(*color, 255), width=thickness, joint="curve")+ ImageDraw.Draw(card_normal).line(points, fill=(*FLAT_NORMAL, 255), width=thickness, joint="curve")+++def bleed_into_transparent(image, background):+ """Copy the nearest leaf colour into transparent pixels so mipmaps and filtering never pull in black fringes."""+ pixels = numpy.asarray(image).copy()+ covered = pixels[..., 3] > 8+ if not covered.any():+ pixels[..., :3] = background+ return Image.fromarray(pixels, "RGBA")+ _, nearest = ndimage.distance_transform_edt(~covered, return_indices=True)+ pixels[..., :3] = pixels[nearest[0], nearest[1], :3]+ return Image.fromarray(pixels, "RGBA")+++def save_card(card, species, crown=None):+ folder = OUTPUT_ROOT / species+ folder.mkdir(parents=True, exist_ok=True)+ color, normal = card+ bleed_into_transparent(color, (60, 90, 30)).save(folder / "color.webp", quality=90, method=6, exact=True)+ bleed_into_transparent(normal, FLAT_NORMAL).convert("RGB").save(folder / "normal.webp", quality=92, method=6)+ if crown is not None:+ bleed_into_transparent(crown[0], (40, 70, 25)).save(folder / "crown.webp", quality=88, method=6, exact=True)+ print(f"wrote {folder.relative_to(OUTPUT_ROOT.parent.parent.parent)}")+++def build_sprig(leaves, randomness, pairs, leaf_length, tint, stem_color):+ """Alternate leaves along a gently curved twig, largest in the middle, with one leaf at the tip."""+ card = new_card()+ top_y = CARD_SIZE * 0.2+ bend = randomness.uniform(-18, 18)+ stem = [(CARD_SIZE / 2 + bend * (1 - (y / CARD_SIZE)) ** 2, y) for y in numpy.linspace(CARD_SIZE - 1, top_y, 24)]+ paint_stem(card, stem, 6, stem_color)+ for pair in range(pairs):+ progress = (pair + 0.5) / pairs+ stem_index = min(len(stem) - 1, round(progress * (len(stem) - 1) * 0.92))+ base_x, base_y = stem[stem_index]+ size = leaf_length * (0.72 + 0.4 * math.sin(math.pi * (0.25 + progress * 0.7)))+ for side in (-1, 1):+ lean = side * randomness.uniform(58, 82)+ shade = randomness.uniform(0.82, 1.08)+ paint_leaf(card, randomness.choice(leaves), base_x, base_y - (10 if side > 0 else 0), size * randomness.uniform(0.9, 1.08), lean, [tint[channel] * shade for channel in range(3)])+ tip_x, tip_y = stem[-1]+ paint_leaf(card, randomness.choice(leaves), tip_x, tip_y + 8, leaf_length * 0.95, randomness.uniform(-8, 8), tint)+ return card+++def build_conifer_spray(sprays, randomness, tint):+ """One long spray up the middle with two short ones close beside its base, so the card reads as a narrow branch tip."""+ card = new_card()+ longest = sorted(sprays, key=lambda spray: spray.length)[-1]+ shorter = sorted(sprays, key=lambda spray: spray.length)[:-1] or [longest]+ for side in (-1, 1):+ paint_leaf(card, randomness.choice(shorter), CARD_SIZE / 2, CARD_SIZE * 0.86, CARD_SIZE * 0.42, side * randomness.uniform(12, 18), [value * 0.85 for value in tint])+ paint_leaf(card, longest, CARD_SIZE / 2, CARD_SIZE - 2, CARD_SIZE * 0.96, randomness.uniform(-4, 4), tint)+ return card+++def build_crown(leaves, randomness, count, leaf_length, tint):+ """A dense rounded clump for far crowns: darker toward the lower centre, like a lit canopy."""+ card = new_card()+ centre = CARD_SIZE / 2+ radius = CARD_SIZE * 0.3+ for _ in range(count):+ angle = randomness.uniform(0, math.tau)+ distance = math.sqrt(randomness.random()) * radius+ x = centre + math.cos(angle) * distance+ y = centre + math.sin(angle) * distance * 0.85+ light = 0.62 + 0.45 * (1 - (y - centre + radius) / (2 * radius)) + 0.12 * (distance / radius)+ paint_leaf(card, randomness.choice(leaves), x, y, leaf_length * randomness.uniform(0.8, 1.15), randomness.uniform(0, 360), [value * light for value in tint])+ return card+++def main():+ if len(sys.argv) != 2:+ sys.exit(__doc__)+ atlas_folder = Path(sys.argv[1])+ randomness = random.Random(67)+ beech = cut_leaves(atlas_folder, "LeafSet024", "bottom")+ laurel = cut_leaves(atlas_folder, "LeafSet022", "bottom")+ sprays = cut_leaves(atlas_folder, "LeafSet019", "right", minimum_pixels=8000)+ print(f"cut {len(beech)} beech leaves, {len(laurel)} laurel leaves, {len(sprays)} conifer sprays")+ bark_brown = (74, 58, 40)++ broadleaf = build_sprig(beech, randomness, pairs=4, leaf_length=132, tint=(0.82, 0.92, 0.72), stem_color=bark_brown)+ broadleaf_crown = build_crown(beech, randomness, count=120, leaf_length=86, tint=(0.72, 0.86, 0.62))+ save_card(broadleaf, "broadleaf", broadleaf_crown)++ birch = build_sprig(beech, randomness, pairs=5, leaf_length=100, tint=(1.0, 1.05, 0.72), stem_color=(92, 70, 50))+ birch_crown = build_crown(beech, randomness, count=140, leaf_length=72, tint=(0.95, 1.0, 0.66))+ save_card(birch, "birch", birch_crown)++ bush = build_sprig(laurel, randomness, pairs=4, leaf_length=160, tint=(0.78, 0.9, 0.7), stem_color=bark_brown)+ bush_crown = build_crown(laurel, randomness, count=110, leaf_length=88, tint=(0.7, 0.84, 0.62))+ save_card(bush, "bush", bush_crown)++ conifer = build_conifer_spray(sprays, randomness, tint=(0.8, 0.92, 0.86))+ conifer_crown = build_crown(sprays, randomness, count=60, leaf_length=130, tint=(0.66, 0.8, 0.72))+ save_card(conifer, "conifer", conifer_crown)+++if __name__ == "__main__":+ main()diff --git a/skills/build-67js-scene/references/scene-contract.md b/skills/build-67js-scene/references/scene-contract.mdindex b3ea925b..827bf919 100644--- a/skills/build-67js-scene/references/scene-contract.md+++ b/skills/build-67js-scene/references/scene-contract.md@@ -47,7 +47,7 @@ The material tags select renderer behavior.| `water` | Flat ponds and streams only: replaces normals with a near-horizontal ripple field. || `liquid` | Shaped water (jets, sheets, splashes): refracts the opaque scene, absorbs by thickness, Fresnel reflection. `color` is what one metre lets through. || `foam` | Soft alpha-blended whitewater droplets drawn after liquids. Set `castShadow: false`. |-| `foliage`, `grass` | Wind movement (also in the shadow pass) and backlighting. Accept a base-colour `map` with `alphaMode: 'mask'` and `doubleSided` for leaf cards. |+| `foliage`, `grass` | Wind movement (also in the shadow pass) and backlighting. Accept a base-colour `map` with `alphaMode: 'mask'`, a `normalMap` and `doubleSided` for leaf cards; `loadLeafTextures` gives scanned cards for the `leafTextures` option of `createTree` and `scatterVegetation`. || `terrain` | Subtle natural surface variation. || Standard tag with `layers` and `splat` | Four-layer scanned ground blended by slope, height and mask; see `docs/terrain.md`. Rejects the procedural tags and single PBR maps. || `fire`, `smoke` | Film ignition expansion and procedural shading. |diff --git a/src/environment.js b/src/environment.jsindex 53998753..edbc600e 100644--- a/src/environment.js+++ b/src/environment.js@@ -286,15 +286,20 @@ vec3 environmentDiffuse(vec3 normal) {+ environmentIrradiance[8] * (mapped.x * mapped.x - mapped.y * mapped.y);return max(result, vec3(0.0)) * environmentIntensity;}-vec3 environmentLighting(vec3 normal, vec3 viewDirection, vec3 color, float metallic, float roughness, float occlusion, float ambient) {+// specularWeight scales only the reflected sky; leaf cards use less, since their bent normals face the view at grazing angles.+vec3 environmentLighting(vec3 normal, vec3 viewDirection, vec3 color, float metallic, float roughness, float occlusion, float ambient, float specularWeight) {float normalView = clamp(dot(normal, viewDirection), 0.001, 1.0);vec3 baseReflectance = mix(vec3(0.04), color, metallic);vec2 lookup = texture(environmentBrdf, vec2(normalView, roughness)).rg;- vec3 specularColor = baseReflectance * lookup.x + lookup.y;+ vec3 specularColor = (baseReflectance * lookup.x + lookup.y) * specularWeight;vec3 specular = environmentRadiance(reflect(-viewDirection, normal), roughness * environmentLevelMax) * specularColor;vec3 diffuse = environmentDiffuse(normal) * color * (1.0 - metallic) * (1.0 - specularColor);return (specular + diffuse) * occlusion * ambient;}++vec3 environmentLighting(vec3 normal, vec3 viewDirection, vec3 color, float metallic, float roughness, float occlusion, float ambient) {+ return environmentLighting(normal, viewDirection, color, metallic, roughness, occlusion, ambient, 1.0);+}`;export const environmentBackgroundFragment = `#version 300 esdiff --git a/src/renderer.js b/src/renderer.jsindex f1bfbebe..808ab8f0 100644--- a/src/renderer.js+++ b/src/renderer.js@@ -64,7 +64,9 @@ const SPLAT_UNIFORMS = ['splatEnabled', 'splatColor', 'splatNormal', 'splatPackefunction validateMaterialMaps(material) {if (PROCEDURAL_MATERIAL_TAGS.has(material.tag)) {for (let index = 1; index < MATERIAL_MAPS.length; index++) {- if (material[MATERIAL_MAPS[index]]) throw new Error('Material maps require a standard PBR material tag. Procedural tags are unsupported.');+ // Scanned leaf cards carry a normal map; the swaying tags apply it on top of their canopy normal.+ const leafNormalMap = MATERIAL_MAPS[index] === 'normalMap' && SWAYING_TAGS.has(material.tag);+ if (material[MATERIAL_MAPS[index]] && !leafNormalMap) throw new Error('Material maps require a standard PBR material tag. Procedural tags accept only a base map, and foliage and grass also a normal map.');}}if (material.tag === 'unlit' && (material.normalMap || material.metallicRoughnessMap || material.occlusionMap)) {diff --git a/src/shaders.js b/src/shaders.jsindex 870a77ce..83edcccb 100644--- a/src/shaders.js+++ b/src/shaders.js@@ -590,13 +590,15 @@ void main() {float occlusion = 1.0;if (hasOcclusionMap > 0.5) occlusion = mix(1.0, texture(occlusionMap, textureUV).r, occlusionStrength);occlusion *= splatCavity;+ // Leaf and grass cards keep a faint sheen; full sky reflection washed grazing cards grey-blue.+ float skyReflection = canopyShaded ? 0.3 : 1.0;if (environmentEnabled > 0.5) {- radiance += environmentLighting(normal, viewDirection, color, metallic, roughness, occlusion, ambientIntensity);+ radiance += environmentLighting(normal, viewDirection, color, metallic, roughness, occlusion, ambientIntensity, skyReflection);} else {// Outdoors the surroundings are sky and haze; reflecting the studio softboxes there lit grazing leaves white and cyan.vec3 reflected = reflect(-viewDirection, normal);vec3 surroundings = worldMode > 0.5 ? mix(fogColor * 0.8, vec3(0.20, 0.38, 0.52) * 1.6, smoothstep(-0.15, 0.7, reflected.y)) : studio(reflected, roughness);- radiance += surroundings * reflectance * (1.0 - roughness * 0.55) * mix(1.0, 0.5 * daylight, worldMode) * occlusion * ambientIntensity;+ radiance += surroundings * reflectance * skyReflection * (1.0 - roughness * 0.55) * mix(1.0, 0.5 * daylight, worldMode) * occlusion * ambientIntensity;radiance += color * (1.0 - metallic) * mix(vec3(0.16, 0.20, 0.22), vec3(0.19, 0.25, 0.30) * max(daylight, 0.08), worldMode) * (0.45 + 0.55 * max(normal.y, 0.0)) * occlusion * ambientIntensity;}vec3 keyResponse = keyColor / mix(vec3(5.2, 4.7, 4.1), vec3(3.7, 3.4, 2.9), worldMode);diff --git a/src/texture-set.js b/src/texture-set.jsindex be18a9f6..ae255cd4 100644--- a/src/texture-set.js+++ b/src/texture-set.js@@ -52,3 +52,27 @@ export async function loadTextureSet(baseUrl, { channels, extension = 'webp', feif (Object.keys(set).length === 0) throw new Error(`No texture channels found under ${baseUrl}.`);return set;}++export const LEAF_TEXTURE_SPECIES = Object.freeze(['broadleaf', 'birch', 'bush', 'conifer']);++const CLAMP_TO_EDGE = 33071;++/**+ * Load scanned leaf cards for `createTree` and `scatterVegetation` (`leafTextures`).+ * Each species folder holds `color.webp` (RGBA, alpha is the leaf mask), `normal.webp` and `crown.webp`+ * (the far level-of-detail clump). Cards clamp at their edges so the twig at the bottom never bleeds to the top.+ * Returns `{ broadleaf: { color, normal, crown }, ... }`.+ */+export async function loadLeafTextures(baseUrl, { species = LEAF_TEXTURE_SPECIES, extension = 'webp', fetchBlob: fetchOne = fetchBlob, decodeBlob: decodeOne = decodeBlob } = {}) {+ if (typeof baseUrl !== 'string' || baseUrl.length === 0) throw new TypeError('baseUrl must be a non-empty string.');+ const channels = [['color', 'srgb'], ['normal', 'linear'], ['crown', 'srgb']];+ const entries = await Promise.all(species.map(async (name) => {+ const textures = await Promise.all(channels.map(async ([channel, colorSpace]) => {+ const blob = await fetchOne(joinUrl(baseUrl, `${name}/${channel}.${extension}`));+ const image = await decodeOne(blob);+ return [channel, { image, colorSpace, wrapS: CLAMP_TO_EDGE, wrapT: CLAMP_TO_EDGE }];+ }));+ return [name, Object.fromEntries(textures)];+ }));+ return Object.fromEntries(entries);+}diff --git a/src/vegetation.js b/src/vegetation.jsindex 8726f490..78614766 100644--- a/src/vegetation.js+++ b/src/vegetation.js@@ -24,6 +24,7 @@ const LEAF_MODES = ['cards', 'mesh'];const GRASS_LEVEL_DISTANCES = [24];const LEAF_COLOR_BASE = [0.85, 0.95, 0.8];const LEAF_COLOR_TIP = [1.1, 1.05, 0.9];+const SCANNED_LEAF_TINT = [1.05, 1.08, 1];const DEFAULT_MIX = { broadleaf: 3, birch: 1.5, conifer: 2, bush: 2.5 };function rotateAroundUp(vector, angle) {@@ -187,6 +188,21 @@ export function resolveBarkTextures(barkTextures, species) {return set;}+/**+ * Picks the scanned leaf cards for a species. `leafTextures` is one set (`{ color, normal, crown }`) or an object keyed+ * by species name, as `loadLeafTextures` returns; returns null for procedural leaves.+ */+export function resolveLeafTextures(leafTextures, species) {+ if (!leafTextures) return null;+ const set = isTextureDescriptor(leafTextures.color) ? leafTextures : leafTextures[species];+ if (!set) return null;+ if (!isTextureDescriptor(set.color)) throw new TypeError(`Leaf textures for ${species} need a color texture descriptor.`);+ for (const channel of ['normal', 'crown']) {+ if (set[channel] !== undefined && !isTextureDescriptor(set[channel])) throw new TypeError(`Leaf ${channel} must be a texture descriptor.`);+ }+ return set;+}+function crownShading(skeleton, position) {const { center, radius } = skeleton.crown;const offset = subtractVectors(position, center);@@ -328,7 +344,7 @@ function createBarkMaterial(preset, scannedTextures) {return material;}-function createMaterials(preset, mode, scannedBark) {+function createMaterials(preset, mode, scannedBark, scannedLeaves) {const bark = createBarkMaterial(preset, scannedBark);if (mode === 'mesh') {const foliage = { tag: 'foliage', color: preset.leaf.foliageColor, roughness: 0.8, metallic: 0, emission: 0 };@@ -338,7 +354,17 @@ function createMaterials(preset, mode, scannedBark) {tag: 'foliage', color: preset.leaf.tint, roughness: 0.85, metallic: 0, emission: 0,map: leafTextureDescriptor(texture, preset.leaf.color), alphaMode: 'mask', alphaCutoff: 0.5, doubleSided: true,});- return { bark, foliage: cardMaterial(preset.leaf.texture), crown: cardMaterial('clump') };+ if (!scannedLeaves) return { bark, foliage: cardMaterial(preset.leaf.texture), crown: cardMaterial('clump') };+ // Scanned cards keep their own colour; the vertex colours still shade the crown from its centre outward.+ const scannedCard = (map, normalMap) => ({+ tag: 'foliage', color: SCANNED_LEAF_TINT, roughness: 0.75, metallic: 0, emission: 0,+ map, ...(normalMap ? { normalMap, normalScale: [0.7, 0.7] } : {}), alphaMode: 'mask', alphaCutoff: 0.5, doubleSided: true,+ });+ return {+ bark,+ foliage: scannedCard(scannedLeaves.color, scannedLeaves.normal),+ crown: scannedLeaves.crown ? scannedCard(scannedLeaves.crown) : cardMaterial('clump'),+ };}function boundsOf(geometries) {@@ -360,7 +386,7 @@ function describeLevel(parts) {/*** Grows one tree. `speciesOrOptions` is a preset name ('broadleaf', 'birch', 'conifer', 'palm',- * 'bush') or `{ species, height, leaves, barkTextures, barkTileSize }`. Returns three levels of detail; each level lists the+ * 'bush') or `{ species, height, leaves, barkTextures, barkTileSize, leafTextures }`. Returns three levels of detail; each level lists the* parts (`bark`, `foliage`) with their geometry and material, in local meters with the trunk at the origin.*/export function createTree(speciesOrOptions = 'broadleaf', seed = 1) {@@ -375,7 +401,8 @@ export function createTree(speciesOrOptions = 'broadleaf', seed = 1) {const skeleton = growSkeleton(preset, height, random);const scannedBark = resolveBarkTextures(options.barkTextures, options.species);const bark = { scanned: Boolean(scannedBark), tileSize: options.barkTileSize ?? (scannedBark ? SCANNED_BARK_TILE_SIZE : BARK_TILE_SIZE) };- const materials = createMaterials(preset, leaves, scannedBark);+ const scannedLeaves = leaves === 'cards' ? resolveLeafTextures(options.leafTextures, options.species) : null;+ const materials = createMaterials(preset, leaves, scannedBark, scannedLeaves);const levels = LEVEL_SETTINGS.map((setting, levelIndex) => {const levelRandom = createRandom(seed * 104729 + levelIndex);const foliageMaterial = setting.leafKeep === 0 ? materials.crown : materials.foliage;@@ -494,10 +521,10 @@ export function createFlowerPatch({ flowers = 5, height = 0.4, color = [1, 0.85,const FLOWER_COLORS = [[0.95, 0.8, 0.25], [0.8, 0.35, 0.55], [0.9, 0.9, 0.85], [0.45, 0.4, 0.85]];-function createVariant(species, variantSeed, variantIndex, leaves, barkTextures) {+function createVariant(species, variantSeed, variantIndex, leaves, barkTextures, leafTextures) {if (species === 'grass') return createGrassClump({ seed: variantSeed, height: 0.38 + 0.12 * (variantIndex % 3) });if (species === 'flowers') return createFlowerPatch({ seed: variantSeed, color: FLOWER_COLORS[variantIndex % FLOWER_COLORS.length] });- return createTree({ species, leaves, barkTextures }, variantSeed);+ return createTree({ species, leaves, barkTextures, leafTextures }, variantSeed);}function poissonDiskPoints(area, radius, random, accept) {@@ -587,13 +614,13 @@ function instanceParts(instance, levelIndex, label) {/*** Scatters vegetation with Poisson-disk spacing. `area` is `{ minX, maxX, minZ, maxZ }`, `density` is* instances per square meter, `slopeLimit` is degrees, `exclusion(x, z)` returns true to keep a spot clear- * `barkTextures` (one set or one per species) swaps procedural bark for scanned textures, and `mix` weighs species ('broadleaf', 'birch', 'conifer', 'palm', 'bush', 'grass', 'flowers').+ * `barkTextures` and `leafTextures` (one set or one per species) swap procedural bark and leaf cards for scanned textures, and `mix` weighs species ('broadleaf', 'birch', 'conifer', 'palm', 'bush', 'grass', 'flowers').* A few variants per species are shared by every instance, so the renderer batches them as instances.* Returns `{ instances, parts, variants, counts }`; `parts` shows every instance at full detail.*/export function scatterVegetation({area, density = 0.012, terrainHeight = () => 0, slopeLimit = 32, exclusion = () => false, seed = 1,- mix = DEFAULT_MIX, variants = 3, leaves = 'cards', scale = [0.8, 1.25], spacing, barkTextures,+ mix = DEFAULT_MIX, variants = 3, leaves = 'cards', scale = [0.8, 1.25], spacing, barkTextures, leafTextures,} = {}) {if (!area || ![area.minX, area.maxX, area.minZ, area.maxZ].every(Number.isFinite) || area.maxX <= area.minX || area.maxZ <= area.minZ) {throw new TypeError('Scatter area needs finite minX < maxX and minZ < maxZ.');@@ -608,7 +635,7 @@ export function scatterVegetation({const instances = points.map(([x, z], index) => {const species = chooseSpecies(speciesNames, mix, x, z, seed, random);if (!variantsBySpecies[species]) {- variantsBySpecies[species] = Array.from({ length: variants }, (_, variantIndex) => createVariant(species, seed * 131 + variantIndex * 977 + species.length, variantIndex, leaves, barkTextures));+ variantsBySpecies[species] = Array.from({ length: variants }, (_, variantIndex) => createVariant(species, seed * 131 + variantIndex * 977 + species.length, variantIndex, leaves, barkTextures, leafTextures));}const variant = variantsBySpecies[species][Math.floor(random() * variants)];const size = randomInRange(random, scale);diff --git a/tests/texture-set.test.js b/tests/texture-set.test.jsindex 82f003c4..62197838 100644--- a/tests/texture-set.test.js+++ b/tests/texture-set.test.js@@ -1,6 +1,6 @@import test from 'node:test';import assert from 'node:assert/strict';-import { loadTextureSet } from '../src/texture-set.js';+import { LEAF_TEXTURE_SPECIES, loadLeafTextures, loadTextureSet } from '../src/texture-set.js';function fakeFetch(available) {const requested = [];@@ -45,3 +45,21 @@ test('a color space override applies to its channel', async () => {const set = await loadTextureSet('/x', { channels: ['color'], colorSpaces: { color: 'linear' }, fetchBlob, decodeBlob });assert.equal(set.color.colorSpace, 'linear');});++test('leaf textures load color, normal and crown per species, clamped at the card edges', async () => {+ const requested = [];+ const fetchBlob = async (url) => {+ requested.push(url);+ return { channel: url.split('/').pop().split('.')[0] };+ };+ const leaves = await loadLeafTextures('/textures/leaves/', { fetchBlob, decodeBlob });+ assert.deepEqual(Object.keys(leaves), [...LEAF_TEXTURE_SPECIES]);+ assert.equal(requested.length, LEAF_TEXTURE_SPECIES.length * 3);+ assert.ok(requested.includes('/textures/leaves/conifer/crown.webp'));+ assert.equal(leaves.birch.color.colorSpace, 'srgb');+ assert.equal(leaves.birch.normal.colorSpace, 'linear');+ assert.equal(leaves.birch.crown.colorSpace, 'srgb');+ for (const texture of Object.values(leaves.bush)) assert.deepEqual([texture.wrapS, texture.wrapT], [33071, 33071]);+ const missing = async (url) => { throw new Error(`Texture request failed with status 404: ${url}`); };+ await assert.rejects(loadLeafTextures('/textures/leaves', { species: ['palm'], fetchBlob: missing, decodeBlob }), /404/);+});\ No newline at end of filediff --git a/tests/vegetation-bark-wind.test.js b/tests/vegetation-bark-wind.test.jsindex 4008f77a..0d670056 100644--- a/tests/vegetation-bark-wind.test.js+++ b/tests/vegetation-bark-wind.test.js@@ -1,6 +1,8 @@import test from 'node:test';import assert from 'node:assert/strict';-import { createTree, resolveBarkTextures, scatterVegetation } from '../src/vegetation.js';+import { createTree, resolveBarkTextures, resolveLeafTextures, scatterVegetation } from '../src/vegetation.js';+import { groupParts } from '../src/renderer.js';+import { box } from '../src/geometry.js';import { addLeafSurface, addTube, createLeafFrame, createMeshBuilder } from '../src/vegetation-geometry.js';import { depthVertexShader, vertexShader } from '../src/shaders.js';@@ -134,3 +136,48 @@ test('colour and shadow vertex shaders apply the same wind displacement', () =>assert.match(source, /uniform float wind;/);}});++function syntheticLeafSet() {+ return { color: syntheticDescriptor(), normal: syntheticDescriptor(), crown: syntheticDescriptor() };+}++test('scanned leaf cards reach the foliage and crown materials with the normal map', () => {+ const set = syntheticLeafSet();+ const tree = createTree({ species: 'broadleaf', leafTextures: { broadleaf: set } }, 4);+ assert.equal(tree.materials.foliage.map, set.color);+ assert.equal(tree.materials.foliage.normalMap, set.normal);+ assert.equal(tree.materials.crown.map, set.crown);+ assert.equal(tree.materials.crown.normalMap, undefined);+ for (const material of [tree.materials.foliage, tree.materials.crown]) {+ assert.equal(material.tag, 'foliage');+ assert.equal(material.alphaMode, 'mask');+ assert.equal(material.doubleSided, true);+ }+ const procedural = createTree({ species: 'broadleaf' }, 4);+ assert.deepEqual(tree.levels[0].parts[1].geometry.positions, procedural.levels[0].parts[1].geometry.positions, 'textures do not change the geometry');+});++test('leafTextures resolves per species, ignores mesh leaves and rejects malformed sets', () => {+ const set = syntheticLeafSet();+ assert.equal(resolveLeafTextures(set, 'palm'), set);+ assert.equal(resolveLeafTextures({ conifer: set }, 'palm'), null);+ assert.throws(() => resolveLeafTextures({ conifer: { normal: syntheticDescriptor() } }, 'conifer'), TypeError);+ assert.throws(() => resolveLeafTextures({ color: syntheticDescriptor(), crown: 'x' }, 'conifer'), TypeError);+ const meshTree = createTree({ species: 'conifer', leaves: 'mesh', leafTextures: set }, 2);+ assert.equal(meshTree.materials.foliage.map, undefined);+ const crownless = createTree({ species: 'birch', leafTextures: { color: set.color } }, 2);+ assert.notEqual(crownless.materials.crown.map, undefined, 'without a crown texture the procedural clump stays');+ const forest = scatterVegetation({ area: { minX: 0, maxX: 20, minZ: 0, maxZ: 20 }, density: 0.02, mix: { conifer: 1, palm: 1 }, leafTextures: { conifer: set }, variants: 1, seed: 5 });+ assert.equal(forest.variants.conifer[0].materials.foliage.map, set.color);+ assert.notEqual(forest.variants.palm[0].materials.foliage.map, set.color);+});++test('the renderer accepts a normal map on foliage and grass but not on other procedural tags', () => {+ const geometry = box();+ const part = (tag) => ({ name: tag, geometry, matrix: new Float32Array([1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1]), material: { tag, color: [1, 1, 1], roughness: 1, metallic: 0, emission: 0, normalMap: syntheticDescriptor() } });+ assert.doesNotThrow(() => groupParts([part('foliage'), part('grass')]));+ assert.throws(() => groupParts([part('water')]), /Procedural tags accept only a base map/);+ const roughnessOnLeaves = part('foliage');+ roughnessOnLeaves.material.metallicRoughnessMap = syntheticDescriptor();+ assert.throws(() => groupParts([roughnessOnLeaves]), /standard PBR material tag/);+});\ No newline at end of file