Biomes and Vegetation on Voxel Terrain in Babylon.js · Part 6 of 12 in the series
Part 6: Flowers, ferns and reeds
Add eight kinds of small plants as sprites painted on a canvas and drawn on crossed cards: each biome lists its own, every kind grows in patches, reeds stand at the shore, mushrooms in caves, and all of them make way for the blocks you build.
Biomes and Vegetation on Voxel Terrain in Babylon.jsPart 6 of 12
On this page
Quest objectives
- Paint sprites of plants with canvas paths, and turn them into a texture array
- Fix the dark edges that see-through pixels give a sprite
- Let each biome list its plants, and let every kind grow in patches
- Place reeds by the shore and mushrooms by the light of a cave
- Draw the plants as instances of two crossed cards
- Hide the plants where a block stands, and bring them back when it goes
The meadow has grass. This part puts daisies and bluebells into it, ferns and bushes into the forests, dry shrubs into the savanna, heather into the tundra, reeds along the shores and mushrooms into the caves. Eight kinds of plants, and all of them are the same mesh: two cards that cross, with a picture on them. The pictures are painted in code, like every texture so far, but this time with a brush: the canvas of the browser.
Part 5 did the heavy lifting. Finding spots, sending them from the workers and drawing them as instances is all there. What is new is which plant grows where, how it looks, and what happens when you put a block on it.
Patches
Flowers that are spread evenly look like wallpaper. In a real meadow, a kind grows thickly in one place and not at all ten steps further. That takes a noise per kind, and with eight kinds asked at every spot, simplex noise would be a lot of work for a little effect. hash() can do it cheaply. Add to src/random.ts:
/**
* Smooth noise from 0 to 1 made of hash(): random numbers at the whole numbers, blended
* between them. Much cheaper than simplex noise, and good enough for patches of flowers.
*/
export function patchNoise(x: number, z: number, salt: number): number {
const x0 = Math.floor(x);
const z0 = Math.floor(z);
const smooth = (t: number) => t * t * (3 - 2 * t);
const fx = smooth(x - x0);
const fz = smooth(z - z0);
const at = (i: number, k: number) => hash(x0 + i, z0 + k, salt);
return (at(0, 0) * (1 - fx) + at(1, 0) * fx) * (1 - fz) + (at(0, 1) * (1 - fx) + at(1, 1) * fx) * fz;
}A random number sits at every whole number, and between them the four around a point are blended, smoothly. The salt will be the kind's number, so every kind has patches of its own.
What grows where
Each biome lists its plants, with the share of the places that each takes. In src/climate.ts, replace the list of the biomes:
/**
* The biomes, each with the climate it is at home in and a color for the map. A place
* belongs to the biome whose climate is nearest to its own. `ground` is the texture that
* covers its ground, and `tint` colors its soil and rock. `shape` holds the numbers that
* shape its ground, in meters: see Shape. `grass` says how much of the ground grass covers,
* from 0 to 1, how high it grows in meters, and how dry it is: 0 is lush, 1 is straw.
* `plants` lists the small plants that grow in it, each with the share of the places for
* plants that it takes.
*/
export const BIOMES = [
{
name: 'Meadow', temperature: 0.5, moisture: 0.4, color: '#7fae3c', ground: 'grass', tint: '#ffffff',
shape: { base: 12, hills: 40, mountains: 150, knolls: 0, dunes: 0 },
grass: { amount: 1, height: 0.42, tone: 0.1 },
plants: { daisy: 0.1, bluebell: 0.06, bush: 0.012 },
},
{
name: 'Broadleaf forest', temperature: 0.52, moisture: 0.76, color: '#3c7a2a', ground: 'litter', tint: '#f2f0e6',
shape: { base: 14, hills: 46, mountains: 150, knolls: 0, dunes: 0 },
grass: { amount: 0.5, height: 0.36, tone: 0.2 },
plants: { fern: 0.14, bush: 0.05, bluebell: 0.04, mushroom: 0.01 },
},
{
name: 'Conifer forest', temperature: 0.3, moisture: 0.62, color: '#28584a', ground: 'needles', tint: '#e6e8f2',
shape: { base: 20, hills: 55, mountains: 170, knolls: 10, dunes: 0 },
grass: { amount: 0.22, height: 0.3, tone: 0.35 },
plants: { fern: 0.1, mushroom: 0.03, heather: 0.03, bush: 0.01 },
},
{
name: 'Tundra', temperature: 0.1, moisture: 0.45, color: '#c3ccd6', ground: 'moss', tint: '#dfe6f5',
shape: { base: 24, hills: 20, mountains: 190, knolls: 5, dunes: 0 },
grass: { amount: 0.3, height: 0.2, tone: 0.65 },
plants: { heather: 0.1 },
},
{
name: 'Savanna', temperature: 0.76, moisture: 0.5, color: '#c9a545', ground: 'straw', tint: '#ffd9b0',
shape: { base: 7, hills: 12, mountains: 40, knolls: 22, dunes: 0 },
grass: { amount: 0.5, height: 0.75, tone: 1 },
plants: { shrub: 0.05 },
},
{
name: 'Desert', temperature: 0.86, moisture: 0.14, color: '#e8bd7c', ground: 'sand', tint: '#ffc08a',
shape: { base: 9, hills: 14, mountains: 70, knolls: 30, dunes: 9 },
grass: { amount: 0.03, height: 0.5, tone: 1 },
plants: { shrub: 0.012 },
},
] as const;Kinds and rules
The kinds themselves, with how high each grows, belong to the scattering. In src/scatter.ts, import patchNoise from ./random.ts next to hash, and replace Scattered:
/** What grows in a chunk: the plants of each kind, PLANT_FLOATS numbers each. */
export interface Scattered {
grass: Float32Array;
/** The small plants. Their tone is their kind: its number in PLANT_KINDS. */
plants: Float32Array;
}
/** The kinds of small plants, in the order of their sprites, with how high they grow at least and at most. */
export const PLANT_KINDS = [
{ name: 'daisy', size: [0.3, 0.45] },
{ name: 'bluebell', size: [0.3, 0.45] },
{ name: 'fern', size: [0.5, 0.9] },
{ name: 'bush', size: [0.9, 1.6] },
{ name: 'shrub', size: [0.6, 1.1] },
{ name: 'reed', size: [1.6, 2.3] },
{ name: 'mushroom', size: [0.18, 0.3] },
{ name: 'heather', size: [0.3, 0.5] },
] as const;
type KindName = (typeof PLANT_KINDS)[number]['name'];
const kindOf = (name: KindName) => PLANT_KINDS.findIndex((kind) => kind.name === name);
const REED = kindOf('reed');
const MUSHROOM = kindOf('mushroom');The order of the kinds is the order of their sprites: a plant's kind is the number of its picture. Some constants change, and some are new. The spacing of the grass gets a second one for the plants, a place every 1.25 m, the least light gets one for caves, and after SHORE come the reeds' and the patches':
/** Meters between the places where a tuft of grass may grow, and where a small plant may. */
const GRASS_SPACING = 0.4;
const PLANT_SPACING = 1.25;
/** Plants need this much of the sky's light, and mushrooms in caves at least a little. */
const DARKEST = 0.6;
const CAVE_DARKEST = 0.1;
/** Reeds stand in water up to this deep, and this far up the shore, in meters. */
const REED_DEPTH = 0.7;
const REED_SHORE = 0.8;
/** Meters across a patch in which a kind of plant grows thickly. */
const PATCH = 14;A plant can say that it belongs into a cave. Replace Plant:
/** A plant on its way into the list: `values` are its PLANT_FLOATS numbers. */
interface Plant {
rank: number;
values: number[];
/** Grows in the half-dark of a cave, not under the sky. */
cave?: boolean;
}And pack() keeps such a plant where the others are left out: between a tenth and six tenths of the sky's light, the half-dark behind a cave's mouth. Replace the line that makes lit:
const lit = plants
.filter(({ values, cave }) => (cave ? values[5] >= CAVE_DARKEST && values[5] < DARKEST : values[5] >= DARKEST))
.sort((a, b) => a.rank - b.rank);Now the plants themselves. Replace scatter() at the end of the file:
/**
* The small plants of a chunk. Each place takes at most one, of a kind that the biomes
* there list. Every kind grows in patches of its own: thickly in some, not at all in others.
*/
function scatterPlants(grid: DensityGrid, origin: { x: number; y: number; z: number }, light: LightGrid): Float32Array {
const plants: Plant[] = [];
const shares = new Float32Array(PLANT_KINDS.length);
eachSpot(grid, origin, PLANT_SPACING, 10, (spot) => {
const random = (n: number) => hash(spot.cellX, spot.cellZ, 10 + n);
const patch = (kind: number) => {
const noise = patchNoise((origin.x + spot.x) / PATCH, (origin.z + spot.z) / PATCH, kind);
return Math.min(Math.max((noise - 0.35) / 0.3, 0), 1) * 2.2;
};
const add = (kind: number, cave = false) => {
const [smallest, largest] = PLANT_KINDS[kind].size;
const size = smallest + (largest - smallest) * random(4);
plants.push({ rank: random(3), cave, values: [spot.x, spot.y, spot.z, size, random(5) * Math.PI * 2, 1, kind, random(6)] });
};
// Reeds stand at the water's edge, wet feet or dry, where it is not too cold or too dry.
const flat = spot.up > STEEPEST;
if (flat && spot.generated > SEA - REED_DEPTH && spot.generated < SEA + REED_SHORE && spot.temperature > 0.2) {
if (random(2) < 0.5 * patch(REED)) add(REED);
return;
}
// Mushrooms grow on the floors of caves, in what light gets there.
if (flat && spot.generated - spot.height > 3) {
if (random(2) < 0.1) add(MUSHROOM, true);
return;
}
if (!fertile(spot)) return;
// The share of each kind here: what the biomes list, times the kind's patches.
shares.fill(0);
for (let b = 0; b < BIOME_COUNT; b += 1) {
if (spot.biomes[b] === 0) continue;
for (const [name, share] of Object.entries(BIOMES[b].plants)) shares[kindOf(name as KindName)] += share * spot.biomes[b];
}
// One random number picks the kind: each kind gets a stretch as long as its share.
let pick = random(2);
for (let kind = 0; kind < shares.length; kind += 1) {
if (shares[kind] === 0) continue;
pick -= shares[kind] * patch(kind);
if (pick < 0) {
add(kind);
return;
}
}
});
return pack(plants, light, origin);
}
/** Everything that grows on the ground in a chunk's grid. */
export function scatter(grid: DensityGrid, origin: { x: number; y: number; z: number }, light: LightGrid): Scattered {
return { grass: scatterGrass(grid, origin, light), plants: scatterPlants(grid, origin, light) };
}The plants use
eachSpot()with wider cells and another salt: other places and other random numbers than the grass.patch()turns the noise into a factor. Where the noise is below 0.35 the kind doesn't grow at all, from 0.65 on it grows at 2.2 times its share. Over the whole land that comes to about what the biome says, but in patches 14 m across.add()picks a size between the kind's smallest and largest. The plant's seventh number, the tone of a tuft of grass, is its kind.Reeds don't ask the biome but the place: where the generated ground lies between 70 cm under the sea and 80 cm above it, and where it is not too cold. That comes before
fertile(), which would turn the shore down. A reed is about 2 m tall, so one that stands in the water still shows most of itself.A spot more than 3 m under the generated ground is the floor of a cave. One in ten grows mushrooms, marked for the half-dark.
Everywhere else, the biomes' lists are added up by the biomes' weights, and one random number picks the kind: each kind gets a stretch as long as its share, and a number that lies beyond all stretches picks nothing. On the meadow, the shares come to 0.17, so most places stay empty.
Nothing else changes in the workers or in the world: Scattered has one list more, and the worker of part 5 sends every list it finds.
Painting the sprites
The textures so far were painted pixel by pixel, from noise. That suits soil and bark, which have no shapes. A daisy has: petals, a stalk, leaves. The browser's canvas draws such things as paths, with smooth edges, and its pixels can be read back. Create src/plants.ts:
import { Constants, RawTexture2DArray, ShaderMaterial, Texture, Vector2, type Scene } from '@babylonjs/core/pure';
import type { PlantRange, PlantShape } from './chunkPlants.ts';
import { LIGHT_UNIFORMS, setLight, type FogOptions } from './material.ts';
import fragmentSource from './plant.fragment.glsl?raw';
import vertexSource from './plant.vertex.glsl?raw';
import { seededRandom } from './random.ts';
import { PLANT_KINDS } from './scatter.ts';
/** How far the small plants are drawn: all of them near the camera, half of them 90 m away. */
export const PLANT_RANGE: PlantRange = { allWithin: 30, fewest: 0.5, range: 90 };
/** Meters from the camera at which they start to shrink into the ground. */
const FADE_FROM = 70;
/** Pixels along each side of a sprite. */
const SPRITE = 128;
export type Context = CanvasRenderingContext2D;
/** Paints a sprite: one unit wide and high, y up, with (0, 0) at the middle of its bottom edge. */
export type Painter = (ctx: Context, random: () => number) => void;
/** A leaf from (x, y), pointed at both ends. `angle` is 0 straight up, in radians. */
export function leaf(ctx: Context, x: number, y: number, angle: number, length: number, width: number, color: string): void {
ctx.save();
ctx.translate(x, y);
ctx.rotate(-angle);
ctx.beginPath();
ctx.moveTo(0, 0);
ctx.quadraticCurveTo(width, length * 0.5, 0, length);
ctx.quadraticCurveTo(-width, length * 0.5, 0, 0);
ctx.fillStyle = color;
ctx.fill();
ctx.restore();
}
/** A stalk from (x, y) that leans over by `lean` at its top, and where that top is. */
export function stalk(ctx: Context, x: number, y: number, lean: number, height: number, width: number, color: string): [number, number] {
ctx.beginPath();
ctx.moveTo(x, y);
ctx.quadraticCurveTo(x, y + height * 0.6, x + lean, y + height);
ctx.lineWidth = width;
ctx.lineCap = 'round';
ctx.strokeStyle = color;
ctx.stroke();
return [x + lean, y + height];
}
export function dot(ctx: Context, x: number, y: number, radius: number, color: string): void {
ctx.beginPath();
ctx.arc(x, y, radius, 0, Math.PI * 2);
ctx.fillStyle = color;
ctx.fill();
}
export const pick = (random: () => number, colors: string[]) => colors[Math.floor(random() * colors.length)];
const GREENS = ['#4c7a2b', '#5c8f33', '#6da03c'];
/**
* How to paint each kind of plant, by its name in PLANT_KINDS. The plant grows from (0, 0),
* the middle of the sprite's bottom edge.
*/
const PAINTERS: Record<(typeof PLANT_KINDS)[number]['name'], Painter> = {
// White flowers with yellow middles on thin stalks, over a few leaves.
daisy: (ctx, random) => {
for (let i = 0; i < 7; i += 1) leaf(ctx, (random() - 0.5) * 0.2, 0, (random() - 0.5) * 1.6, 0.3 + random() * 0.2, 0.05, pick(random, GREENS));
for (let i = 0; i < 6; i += 1) {
const [x, y] = stalk(ctx, (random() - 0.5) * 0.2, 0, (random() - 0.5) * 0.6, 0.5 + random() * 0.35, 0.018, '#5c8f33');
for (let p = 0; p < 9; p += 1) leaf(ctx, x, y, (p / 9) * Math.PI * 2, 0.085, 0.03, '#f6f3e6');
dot(ctx, x, y, 0.03, '#f2b632');
}
},
// Bells in a row along stalks that bend over.
bluebell: (ctx, random) => {
for (let i = 0; i < 6; i += 1) leaf(ctx, (random() - 0.5) * 0.2, 0, (random() - 0.5) * 1.2, 0.4 + random() * 0.2, 0.04, pick(random, GREENS));
for (let i = 0; i < 5; i += 1) {
const x = (random() - 0.5) * 0.25;
const lean = (random() - 0.5) * 0.5;
const height = 0.6 + random() * 0.35;
stalk(ctx, x, 0, lean, height, 0.018, '#4c7a2b');
for (let b = 0; b < 5; b += 1) {
const t = 0.55 + b * 0.1;
dot(ctx, x + lean * t * t + Math.sign(lean) * 0.03, height * t - 0.02, 0.035, pick(random, ['#6a5acd', '#7b68ee', '#8f7cf5']));
}
}
},
// Fronds that arch out from the middle, each a rib with leaflets on both sides.
fern: (ctx, random) => {
for (let i = 0; i < 9; i += 1) {
const side = (i - 4) / 4 + (random() - 0.5) * 0.2;
const length = 0.6 + random() * 0.35;
const color = pick(random, ['#3f6e2c', '#4d8234', '#5b923b']);
for (let step = 1; step <= 14; step += 1) {
const t = step / 14;
// The frond rises, then bends outward under its own weight.
const x = side * length * t * (0.3 + 0.6 * t);
const y = length * t * (1 - 0.35 * Math.abs(side) * t);
const size = 0.11 * Math.sin(t * Math.PI) + 0.015;
const out = side * 0.8 * t;
leaf(ctx, x, y, out + 1.2, size, size * 0.3, color);
leaf(ctx, x, y, out - 1.2, size, size * 0.3, color);
}
}
},
// A round mass of leaves, the dark ones inside painted first.
bush: (ctx, random) => {
for (let i = 0; i < 260; i += 1) {
const angle = random() * Math.PI * 2;
const reach = Math.sqrt(random());
const x = Math.cos(angle) * reach * 0.42;
const y = 0.46 + Math.sin(angle) * reach * 0.42;
const shade = i < 110 ? ['#2f5a22', '#3a6a28'] : ['#4a7f2e', '#5c9438', '#6fa644'];
leaf(ctx, x, y, random() * Math.PI * 2, 0.1 + random() * 0.05, 0.035, pick(random, shade));
}
},
// Dry twigs that fork, with a few small olive leaves left on them.
shrub: (ctx, random) => {
const twig = (x: number, y: number, angle: number, length: number, width: number) => {
const [x1, y1] = [x + Math.sin(angle) * length, y + Math.cos(angle) * length];
ctx.beginPath();
ctx.moveTo(x, y);
ctx.lineTo(x1, y1);
ctx.lineWidth = width;
ctx.strokeStyle = pick(random, ['#7a5a3a', '#8b6a45', '#6b4d32']);
ctx.stroke();
if (length < 0.09) {
if (random() < 0.6) leaf(ctx, x1, y1, angle + (random() - 0.5), 0.07, 0.022, pick(random, ['#8a8a45', '#9a9550']));
return;
}
twig(x1, y1, angle - 0.3 - random() * 0.4, length * 0.72, width * 0.7);
twig(x1, y1, angle + 0.3 + random() * 0.4, length * 0.72, width * 0.7);
};
for (let i = 0; i < 5; i += 1) twig((random() - 0.5) * 0.1, 0, (i - 2) * 0.35 + (random() - 0.5) * 0.2, 0.2 + random() * 0.08, 0.03);
},
// Tall stalks with long leaves and brown heads.
reed: (ctx, random) => {
for (let i = 0; i < 9; i += 1) {
const x = (random() - 0.5) * 0.5;
const lean = (random() - 0.5) * 0.25;
const height = 0.7 + random() * 0.28;
const [tx, ty] = stalk(ctx, x, 0, lean, height, 0.016, pick(random, ['#6d8f3a', '#86a548']));
leaf(ctx, x, 0, (random() - 0.5) * 0.5, height * 0.8, 0.022, pick(random, ['#5f8535', '#78a044']));
if (i % 2 === 0) {
ctx.beginPath();
ctx.ellipse(tx, ty - 0.04, 0.022, 0.07, 0, 0, Math.PI * 2);
ctx.fillStyle = '#6b4226';
ctx.fill();
}
}
},
// Three toadstools: pale stems, red caps with white spots.
mushroom: (ctx, random) => {
for (const [x, height, cap] of [[-0.22, 0.45, 0.2], [0.05, 0.75, 0.3], [0.3, 0.35, 0.16]]) {
stalk(ctx, x, 0, 0, height, cap * 0.35, '#efe6d2');
ctx.beginPath();
ctx.ellipse(x, height, cap, cap * 0.75, 0, Math.PI, Math.PI * 2, true);
ctx.closePath();
ctx.fillStyle = '#c93a2b';
ctx.fill();
for (let i = 0; i < 6; i += 1) dot(ctx, x + (random() - 0.5) * cap * 1.4, height + cap * (0.15 + random() * 0.4), cap * 0.08, '#f7efe1');
}
},
// A low cushion of tiny leaves, with flowers the color of heather.
heather: (ctx, random) => {
for (let i = 0; i < 320; i += 1) {
const angle = random() * Math.PI;
const reach = Math.sqrt(random());
const x = Math.cos(angle) * reach * 0.46;
const y = Math.sin(angle) * reach * 0.7 + 0.03;
if (i % 4 === 3 && y > 0.3) dot(ctx, x, y, 0.022, pick(random, ['#b06cff', '#c48be8', '#9d5bd6']));
else leaf(ctx, x, y, Math.cos(angle) * -1 + (random() - 0.5), 0.09, 0.02, pick(random, ['#4d5f33', '#5f7040', '#6f7a48']));
}
},
};
/**
* Gives the see-through pixels of a picture its average color. They are black, and would
* darken the picture's edges where the graphics card blends them with their neighbors.
*/
export function bleed(pixels: Uint8ClampedArray | Uint8Array): void {
const sum = [0, 0, 0, 0];
for (let p = 0; p < pixels.length; p += 4) {
if (pixels[p + 3] < 255) continue;
for (let c = 0; c < 3; c += 1) sum[c] += pixels[p + c];
sum[3] += 1;
}
for (let p = 0; p < pixels.length; p += 4) {
if (pixels[p + 3] === 0) for (let c = 0; c < 3; c += 1) pixels[p + c] = sum[c] / sum[3];
}
}
/**
* Paints a sprite of `size` pixels on a canvas and hands out its RGBA bytes, row by row
* from the bottom up, as a texture wants them.
*/
export function paintSprite(size: number, painter: Painter, seed: number): Uint8ClampedArray {
const canvas = document.createElement('canvas');
canvas.width = size;
canvas.height = size;
const ctx = canvas.getContext('2d')!;
// One unit is the whole sprite, y points up, and (0, 0) is the middle of the bottom edge.
ctx.setTransform(size, 0, 0, -size, size / 2, size);
painter(ctx, seededRandom(seed));
const pixels = ctx.getImageData(0, 0, size, size).data;
bleed(pixels);
// The canvas's first row is its top, the texture's its bottom.
const flipped = new Uint8ClampedArray(pixels.length);
for (let row = 0; row < size; row += 1) {
const from = (size - 1 - row) * size * 4;
flipped.set(pixels.subarray(from, from + size * 4), row * size * 4);
}
return flipped;
}
/** A plant's shape: two cards that cross, each showing the whole sprite, one meter high. */
export function crossedCards(): PlantShape {
const positions: number[] = [];
const uvs: number[] = [];
const indices: number[] = [];
for (const [dx, dz] of [[1, 0], [0, 1]]) {
const first = positions.length / 3;
for (const [u, v] of [[0, 0], [1, 0], [1, 1], [0, 1]]) {
positions.push((u - 0.5) * dx, v, (u - 0.5) * dz);
uvs.push(u, v);
}
indices.push(first, first + 1, first + 2, first, first + 2, first + 3);
}
return { positions, indices, extra: { kind: 'uv', data: uvs } };
}
/** The small plants' material: the painted sprites, cut out along their outlines. */
export function createPlantMaterial(scene: Scene, options: FogOptions): ShaderMaterial {
// Every kind's sprite, as the layers of one texture array.
const layers = new Uint8Array(SPRITE * SPRITE * 4 * PLANT_KINDS.length);
PLANT_KINDS.forEach(({ name }, layer) => layers.set(paintSprite(SPRITE, PAINTERS[name], layer + 1), layer * SPRITE * SPRITE * 4));
const sprites = new RawTexture2DArray(
layers,
SPRITE,
SPRITE,
PLANT_KINDS.length,
Constants.TEXTUREFORMAT_RGBA,
scene,
true,
false,
Texture.TRILINEAR_SAMPLINGMODE,
);
const material = new ShaderMaterial(
'plants',
scene,
{ vertexSource, fragmentSource },
{
attributes: ['position', 'uv', 'place', 'look'],
uniforms: ['world', 'viewProjection', ...LIGHT_UNIFORMS, 'plantRange'],
samplers: ['sprites'],
},
);
material.setTexture('sprites', sprites);
setLight(material, options);
material.setVector2('plantRange', new Vector2(FADE_FROM, PLANT_RANGE.range));
material.backFaceCulling = false;
return material;
}A painter works in a square that is one unit wide and high, with y pointing up and (0, 0) at the middle of the bottom edge, where the plant grows out of the ground.
paintSprite()sets the canvas up that way withsetTransform(), so no painter has to know how many pixels a sprite has.leaf(),stalk()anddot()are the brushes: a leaf is two curves, a stalk one curve with a round end, a dot a circle. The painters call them a few hundred times with numbers from a seeded generator, so a kind looks the same on every visit.A bush shows a trick that the trees will use too: the leaves that are painted first end up under the others, so the first ones are dark and the last ones light, and the bush looks round.
The canvas's first row is its top, a texture's first row its bottom:
paintSprite()hands the rows out the other way around.crossedCards()is the shape: two upright squares through the same middle, at a right angle, each with the whole sprite on it. From any side, at least one of them faces you.
Dark edges
bleed() looks like a detail and decides how the plants look. Where the canvas painted nothing, its pixels are see-through and black. The shader will cut the plant out along its outline, but the graphics card blends each pixel of a texture with its neighbors first, and in the smaller copies it keeps for far plants, whole blocks of pixels become one. At the plant's edge, black gets into the mix, and every flower gets a dark rim. The cure is to give the see-through pixels a color that does no harm: the plant's own average. They stay see-through, but what bleeds in from them is green.
The plants' shaders
The vertex shader is the grass's, with a sprite's place instead of a blade's. Create src/plant.vertex.glsl:
precision highp float;
// A corner of a card, and where on the sprite it is.
attribute vec3 position;
attribute vec2 uv;
// The plant, one for every instance: its place from the chunk's corner and its size,
// then its turn, its light, its kind and a random number.
attribute vec4 place;
attribute vec4 look;
uniform mat4 world;
uniform mat4 viewProjection;
uniform vec3 cameraPosition;
// Where the plants start to shrink away, and where they are gone, in meters from the camera.
uniform vec2 plantRange;
varying vec3 vPosition;
varying vec2 vUv;
varying float vLight;
varying float vKind;
void main() {
vec3 root = (world * vec4(place.xyz, 1.0)).xyz;
float size = place.w * (1.0 - smoothstep(plantRange.x, plantRange.y, distance(root, cameraPosition)));
float c = cos(look.x);
float s = sin(look.x);
vec3 turned = vec3(position.x * c - position.z * s, position.y, position.x * s + position.z * c);
vPosition = root + turned * size;
vUv = uv;
vLight = look.y;
vKind = look.z;
gl_Position = viewProjection * vec4(vPosition, 1.0);
}The plants reach further than the grass: all of them up to 30 m, half of them at 90 m, and they shrink into the ground over the last 20 m. A bush is seen from much further away than a blade. Create src/plant.fragment.glsl:
precision highp float;
precision highp sampler2DArray;
varying vec3 vPosition;
varying vec2 vUv;
varying float vLight;
varying float vKind;
uniform sampler2DArray sprites;
uniform vec3 cameraPosition;
uniform vec3 sunDirection;
uniform vec3 sunColor;
uniform vec3 skyColor;
uniform vec3 caveColor;
uniform vec3 lampColor;
uniform vec3 fogColor;
uniform vec2 fogRange;
// Meters the lamp at the camera reaches.
const float LAMP_RANGE = 24.0;
void main() {
// The sprite of the plant's kind. Where it is see-through, there is no plant.
vec4 sprite = texture(sprites, vec3(vUv, floor(vKind + 0.5)));
if (sprite.a < 0.4) discard;
// Darker toward the ground, where the plant stands in its own shade.
vec3 color = sprite.rgb * mix(0.7, 1.0, vUv.y);
// Lit like flat ground, and by the lamp in the dark, as if the card faced the camera.
float sky = vLight;
float sun = max(-sunDirection.y, 0.0) * smoothstep(0.6, 1.0, sky);
float distanceToCamera = distance(vPosition, cameraPosition);
float lamp = pow(1.0 - min(distanceToCamera / LAMP_RANGE, 1.0), 2.0) * (1.0 - sky);
vec3 lit = color * (skyColor * pow(sky, 1.5) + caveColor + sunColor * sun + lampColor * lamp);
float fog = smoothstep(fogRange.x, fogRange.y, distanceToCamera);
gl_FragColor = vec4(mix(lit, fogColor, fog), 1.0);
}A pixel that is less than 0.4 there is thrown away: that cuts the plant out of its card, and needs no blending and no sorting. The light is the grass's, with one addition for the mushrooms: the lamp at the camera from the terrain series, which shines where the sky's light doesn't reach.
Making way for blocks
Put a block on the meadow, and the grass sticks out through its top. The workers can't help: they know the ground, not the blocks. The page knows them. So ChunkPlants keeps all the plants of a chunk and hands the graphics card only those that nothing stands on. In src/chunkPlants.ts, replace everything from interface Patch on:
interface Patch {
mesh: Mesh;
/** All the chunk's plants, and those that show, on the graphics card. */
plants: Float32Array;
buffer: Buffer | null;
count: number;
}
/**
* The plants of one kind in the scene: one mesh per chunk, which draws the same shape once
* for every plant of the chunk.
*/
export class ChunkPlants {
/** Asked for every plant: whether something built stands where it grows. Such plants don't show. */
blocked: (x: number, y: number, z: number) => boolean = () => false;
private readonly patches = new Map<string, Patch>();
private readonly scene: Scene;
private readonly material: Material;
private readonly shape: PlantShape;
private readonly range: PlantRange;
constructor(scene: Scene, material: Material, shape: PlantShape, range: PlantRange) {
this.scene = scene;
this.material = material;
this.shape = shape;
this.range = range;
}
/** How many plants are drawn. */
get shown(): number {
let shown = 0;
for (const { mesh, count } of this.patches.values()) if (mesh.isEnabled() && count > 0) shown += mesh.forcedInstanceCount;
return shown;
}
/** A chunk's plants came, or went: then `plants` is null. */
set(position: ChunkPosition, plants: Float32Array | null): void {
const key = chunkKey(position);
const old = this.patches.get(key);
if (old) {
old.mesh.dispose();
old.buffer?.dispose();
this.patches.delete(key);
}
if (!plants || plants.length === 0) return;
const mesh = new Mesh(`plants ${key}`, this.scene);
const data = new VertexData();
data.positions = this.shape.positions;
data.indices = this.shape.indices;
data.applyToMesh(mesh);
mesh.setVerticesData(this.shape.extra.kind, this.shape.extra.data, false, 2);
mesh.position.set(position.x * CHUNK_SIZE, position.y * CHUNK_SIZE, position.z * CHUNK_SIZE);
// The mesh itself is one plant at the chunk's corner. Babylon.js must know that the
// instances fill the whole chunk, or it would not draw them when the corner is out of view.
mesh.setBoundingInfo(new BoundingInfo(new Vector3(-2, -2, -2), new Vector3(CHUNK_SIZE + 2, CHUNK_SIZE + 4, CHUNK_SIZE + 2)));
mesh.material = this.material;
mesh.isPickable = false;
mesh.freezeWorldMatrix();
const patch = { mesh, plants, buffer: null, count: 0 };
this.patches.set(key, patch);
this.fill(patch);
}
/** Something was built or taken away in a box of the world: the chunks it reaches into look again at which of their plants show. */
refresh(low: Vector3, high: Vector3): void {
for (const patch of this.patches.values()) {
const corner = patch.mesh.position;
const apart = (axis: 'x' | 'y' | 'z') => low[axis] > corner[axis] + CHUNK_SIZE + 1 || high[axis] < corner[axis] - 1;
if (!apart('x') && !apart('y') && !apart('z')) this.fill(patch);
}
}
/** Hands the plants of a chunk that show to the graphics card. */
private fill(patch: Patch): void {
const { mesh, plants } = patch;
// The plants that nothing stands on, in their old order.
const shown = new Float32Array(plants.length);
let count = 0;
for (let p = 0; p < plants.length; p += PLANT_FLOATS) {
if (this.blocked(mesh.position.x + plants[p], mesh.position.y + plants[p + 1], mesh.position.z + plants[p + 2])) continue;
shown.set(plants.subarray(p, p + PLANT_FLOATS), count * PLANT_FLOATS);
count += 1;
}
patch.buffer?.dispose();
patch.buffer = instanceBuffer(mesh, shown.subarray(0, count * PLANT_FLOATS));
patch.count = count;
}
/** Once a frame: the further a chunk is from the camera, the fewer of its plants are drawn. */
update(focus: Vector3): void {
const { allWithin, fewest, range } = this.range;
for (const { mesh, count } of this.patches.values()) {
const low = mesh.position;
const nearest = Vector3.Clamp(focus, low, low.add(new Vector3(CHUNK_SIZE, CHUNK_SIZE, CHUNK_SIZE)));
const distance = Vector3.Distance(focus, nearest);
mesh.setEnabled(distance < range && count > 0);
// The plants are in a random order: the first ones are spread as evenly as all.
const share = 1 - (1 - fewest) * Math.min(Math.max((distance - allWithin) / (range - allWithin), 0), 1);
mesh.forcedInstanceCount = Math.max(Math.ceil(count * share), 1);
}
}
}blockedis asked for every plant with its place in the world.fill()copies the plants that show into a new list, in their old order, so the thinning by rank still works, and makes a new buffer of it.refresh()does that again for every chunk that a box of the world reaches into, with a meter to spare.A chunk whose plants are all hidden is not drawn at all.
The block store has one listener for changes, and the BlockWorld uses it. So the BlockWorld passes the news on. In src/blockWorld.ts, add the field and replace touch():
/** Called with every block that came, went or changed its shape. */
onBlock: (block: Block) => void = () => {};
/**
* A block came or went. Its region is out of date, and so are the regions of the blocks
* around it, whose sides it covers or uncovers.
*/
private touch(block: Block): void {
this.onBlock(block);
this.dirty.add(regionOf(block.x, block.y, block.z));
const { x, y, z, size } = block;
for (let k = z - 1; k <= z + size; k += 1) {
for (let j = y - 1; j <= y + size; j += 1) {
for (let i = x - 1; i <= x + size; i += 1) {
const other = this.store.at(i, j, k);
if (other && other !== block) this.dirty.add(regionOf(other.x, other.y, other.z));
}
}
}
}The page
In src/main.ts, import createPlantMaterial, crossedCards and PLANT_RANGE from ./plants.ts. The plants are drawn by a second ChunkPlants, and the world's news goes to both. Replace the lines of the grass:
// The grass of the chunks near the camera.
const grassMaterial = createGrassMaterial(scene, fog);
const grass = new ChunkPlants(scene, grassMaterial, tuft(), GRASS_RANGE);
// The flowers, ferns, bushes and the like: sprites on crossed cards.
const plantMaterial = createPlantMaterial(scene, fog);
const plants = new ChunkPlants(scene, plantMaterial, crossedCards(), PLANT_RANGE);
world.onPlants = (position, scattered) => {
grass.set(position, scattered?.grass ?? null);
plants.set(position, scattered?.plants ?? null);
};After the blocks are made, both are told what blocks them, and when to look again:
// Nothing grows where a block stands: a plant with a block in the cell at its foot is hidden.
for (const greens of [grass, plants]) {
greens.blocked = (x, y, z) => blocks.store.at(Math.floor(x / CELL), Math.floor((y + 0.2) / CELL), Math.floor(z / CELL)) !== undefined;
}
blocks.onBlock = ({ x, y, z, size }) => {
const low = new Vector3(x, y, z).scaleInPlace(CELL);
const high = low.add(new Vector3(size, size, size).scaleInPlace(CELL));
for (const greens of [grass, plants]) greens.refresh(low, high);
};A plant is hidden if a block fills the cell 20 cm above its foot: a block that stands on the ground hides what is under it, a beam two meters up doesn't. In the frame, after grass.update(), add plants.update(camera.position);. In dive(), plantMaterial joins the list. And the HUD's line becomes `${grass.shown} tufts of grass, ${plants.shown} plants\n` +.
Try it
The meadow at the start has daisies in some places, bluebells in others, and a bush here and there. Under the blocks of the sample scene the ground is bare. Put a block on a patch of flowers with the right button, and they are gone, with the grass. Break it with the left, and they are back. Turn around and go down to the lake: reeds stand along its shore, some of them in the water. Then press N: ferns and bushes in the broadleaf forest, ferns, heather and toadstools in the conifer forest, heather in the tundra, dry shrubs in the savanna and, few and far between, in the desert. And if you find the mouth of a cave, go in: where the daylight ends, mushrooms stand in the light of your lamp.
Comments
The comments are GitHub Discussions: sign in with GitHub to write one.
The comments come from GitHub, through giscus. Loading them sends your IP address to giscus.app and GitHub.
