Zum Inhalt springen

Biome und Vegetation auf Voxel-Terrain in Babylon.js · Teil 7 von 12 der Serie

Teil 7: Einen Baum wachsen lassen

Lass Bäume als Skelette wachsen: ein Stamm, Äste, die nach dem Umriss einer Krone greifen, und Zweige an den Ästen. Leg Röhren darum, mal vier Rinden in Code und hol sechs Arten, von der Eiche bis zum Kaktus, aus einem einzigen Satz Zahlen.

Quest-Ziele

  • Eine Baumart mit einer Handvoll Zahlen und einem Kronenumriss beschreiben
  • Stamm, Äste und Zweige als gebogene Röhren wachsen lassen, für denselben Startwert immer gleich
  • Die Röhren mit Ringen vernetzen, die sich nicht verdrehen, und dicke Enden schließen
  • Rindentexturen in Code malen und um das Holz legen
  • Die Bäume als Instanzen zeichnen, wie das Gras, und in eine Baumschule stellen

Das Land hat jetzt Gras, Blumen und Schilf, und nichts, das höher wäre als ein Busch. Dieser Teil und der nächste machen Bäume, und sie machen sie so, wie das Terrain und die Texturen gemacht sind: in Code, aus ein paar Zahlen. Ein Baum wächst als Skelett, als die Linien, denen sein Holz folgt: ein Stamm, Äste am Stamm, Zweige an den Ästen. Um jede Linie kommt eine Röhre, und auf die Röhren kommt Rinde. Dieser Teil endet mit kahlen Bäumen von sechs Arten in einer Baumschule neben dem Start. Teil 8 gibt ihnen ihre Blätter, und Teil 9 pflanzt sie als Wälder.

Eine Krone, nach der man greift

Regeln, die einen Baum frei verzweigen lassen, eine Gabel nach der anderen, lassen etwas Baumartiges wachsen, aber es ist schwer, sie eine Eiche statt einer Fichte wachsen zu lassen. Das Wachsen beginnt hier deshalb am anderen Ende: beim Umriss der Krone. Jede Art hat eine Funktion, die sagt, wie weit ihre Krone in jeder Höhe reicht, von 0 am unteren Rand der Krone bis 1 an ihrer Spitze: eine Kuppel für eine Eiche, ein Ei für eine Birke, ein Kegel für eine Fichte, ein Schirm für eine Akazie. Jeder Ast greift dann nach einem Punkt auf diesem Umriss. Was auch immer die Zufallszahlen mit einem einzelnen Ast machen, der Baum als Ganzes behält die Form seiner Art.

Der Rest einer Art ist eine Handvoll Zahlen, alle als Anteile an der Höhe des Baums, sodass ein kleiner Baum ein verkleinerter großer ist:

  • girth ist der Radius des Stamms am Boden, und taper, wie viel davon an der Spitze übrig ist.

  • leader sagt, ob der Stamm bis ganz nach oben läuft, wie bei einer Fichte, oder dort endet, wo die Äste auseinandergehen, wie bei einer Eiche.

  • bare ist der Anteil der Höhe unter der Krone, und spread, wie weit die Krone höchstens reicht.

  • limbs und branches zählen die Äste am Stamm und die Zweige an jedem Ast.

  • rise sagt, wie steil ein Ast auf seinem Weg nach außen steigt, und droop, wie er sich biegt: unter 0 wölbt er sich nach oben und hängt an seiner Spitze, über 0 hängt er durch und biegt sich am Ende nach oben.

Ein Kaktus passt in dieselbe Tabelle: ein dicker Stamm, der seinen Umfang behält, zwei Äste, die weit durchhängen und sich dann senkrecht nach oben biegen, und keine Zweige.

Das Skelett wachsen lassen

Jeder Teil des Holzes ist ein Limb: eine Liste von Punkten und ein Radius an jedem davon. Der Stamm geht in acht Schritten nach oben und wandert auf dem Weg ein wenig zur Seite, weniger, wenn er bis zur Spitze durchläuft. Zur Spitze hin wird er dünner, und in seinem untersten Achtel ist er bis zur Hälfte dicker, dort, wo ein echter Stamm in seine Wurzeln übergeht.

Als Nächstes kommen die Äste. Ast Nummer i endet beim Anteil (i + 0,5) / limbs der Kronenhöhe, der unterste Ast also nahe am unteren Rand der Krone und der oberste nahe an ihrer Spitze, und er reicht so weit nach außen, wie der Umriss es dort sagt, ein Fünftel mehr oder weniger. Von einem Ast zum nächsten dreht sich die Richtung um den Goldenen Winkel, etwa 137,5°. So setzen viele Pflanzen ihre Blätter an, und aus demselben Grund: Keine zwei Äste landen übereinander, egal wie viele es sind.

Wo ein Ast am Stamm beginnt, folgt daraus, wo er endet: Je steiler die Äste der Art steigen, desto weiter unten beginnt er, aber nie unterhalb der Krone. Zwischen Ansatz und Spitze ist der Ast eine quadratische Bézierkurve: eine Kurve von einem Punkt zu einem anderen, die sich zu einem dritten hin biegt, dem Zugpunkt. Der Zugpunkt liegt auf halbem Weg nach außen. Über die gerade Linie gehoben, lässt er den Ast sich nach oben wölben und zur Spitze hin absinken, wie bei einer Fichte. Abgesenkt, lässt er den Ast durchhängen und sich nach oben biegen, wie den Arm eines Kaktus.

Die Zweige wachsen am äußeren Teil jedes Asts, abwechselnd nach links und nach rechts, kürzer, je weiter außen sie beginnen. Auch sie sind Kurven, mit nur zwei Abschnitten: Sie sind dünn, und es gibt viele davon.

Alle Zufallszahlen kommen aus seededRandom(), derselbe Startwert lässt also denselben Baum wachsen. Drei Startwerte pro Art ergeben drei Varianten: achtzehn verschiedene Bäume insgesamt, die einmal wachsen, wenn die Seite lädt.

Röhren, die sich nicht verdrehen

Das Mesh ist eine Röhre um jeden Ast: ein Ring aus Vertices um jeden seiner Punkte und zwei Dreiecke zwischen je zwei Nachbarn auf zwei Ringen. Der Stamm hat sieben Seiten, ein Ast vier und ein Zweig drei. Mehr würde man nicht sehen: Die Rinde verdeckt die Ecken, und ab Teil 9 sind Hunderte Bäume im Bild.

Ein Ring liegt quer zu der Richtung, in die der Ast an seinem Punkt geht, aber das lässt ihm die Freiheit, sich um den Ast zu drehen, und wenn jeder Ring seine erste Ecke für sich wählte, wäre die Röhre zwischen ihnen verdreht wie ein ausgewrungenes Handtuch. Die erste Ecke wird deshalb weitergereicht: Ihre Richtung auf einem Ring wird zum nächsten mitgenommen, und was davon dort entlang des Asts zeigt, wird abgezogen. Die Ecke bleibt so nah wie möglich dort, wo sie war.

Ein Ring hat eine Ecke mehr, als er Seiten hat. Die erste und die letzte liegen an derselben Stelle, aber an den beiden Enden der Textur, die zweimal um die Röhre geht; die Röhre hinauf wiederholt sie sich alle zwei Meter. Ein Ast, der dicker als 3 cm endet, bekommt eine runde Spitze, einen einzelnen Vertex ein Stück hinter seinem letzten Ring: der Arm eines Kaktus oder das obere Ende eines Eichenstamms. Ein Zweig endet dünn, er braucht keine.

Jeder Vertex trägt außerdem vier Zahlen unter dem Namen paint: wo auf der Textur er liegt, welche Ebene des Textur-Arrays er zeigt, und einen Schatten, der 1 ist, bis die Blätter aus Teil 8 einen werfen. Erstelle src/trees.ts:

src/trees.ts
import { seededRandom } from './random.ts';

export type Vec = [number, number, number];

const add = (a: Vec, b: Vec, times = 1): Vec => [a[0] + b[0] * times, a[1] + b[1] * times, a[2] + b[2] * times];
const subtract = (a: Vec, b: Vec): Vec => [a[0] - b[0], a[1] - b[1], a[2] - b[2]];
const dot = (a: Vec, b: Vec) => a[0] * b[0] + a[1] * b[1] + a[2] * b[2];
const cross = (a: Vec, b: Vec): Vec => [a[1] * b[2] - a[2] * b[1], a[2] * b[0] - a[0] * b[2], a[0] * b[1] - a[1] * b[0]];
const normalize = (a: Vec): Vec => {
  const length = Math.hypot(...a) || 1;
  return [a[0] / length, a[1] / length, a[2] / length];
};
const UP: Vec = [0, 1, 0];

/**
 * A point on the curve from `from` to `to` that bends toward `pull`, at a share `t` of the
 * way: a quadratic Bézier curve.
 */
function curve(from: Vec, pull: Vec, to: Vec, t: number): Vec {
  const a = (1 - t) * (1 - t);
  const b = 2 * (1 - t) * t;
  return [0, 1, 2].map((axis) => from[axis] * a + pull[axis] * b + to[axis] * t * t) as Vec;
}

/** The layers of the trees' texture array: the barks. */
export const TREE_LAYERS = ['oak bark', 'birch bark', 'conifer bark', 'cactus skin'] as const;

type Layer = (typeof TREE_LAYERS)[number];

/** The outlines of crowns: how far a crown reaches at a share `t` of the way from its bottom to its top, from 0 to 1. */
const OUTLINES = {
  /** Widest in the middle and broad on top: an oak. */
  dome: (t: number) => Math.sin(Math.PI * t ** 0.8) ** 0.55,
  /** Widest low down, round on top: a birch. */
  egg: (t: number) => Math.sin(Math.PI * t ** 0.65) ** 0.7,
  /** A cone up to the tip: a spruce. */
  cone: (t: number) => 1 - t * 0.95,
  /** Narrow below and spread out flat on top: an acacia, or an old pine. */
  umbrella: (t: number) => Math.min(0.2 + t * 1.3, 1) * Math.sqrt(1 - t ** 5),
};

/** What makes a kind of tree. Shares are of the tree's height. */
export interface Species {
  name: string;
  /** Meters, at least and at most. */
  height: [number, number];
  /** The trunk's radius at the ground, as a share, and how much of it is left at the top. */
  girth: number;
  taper: number;
  /** Whether the trunk runs up to the very top, or ends where the crown's limbs part. */
  leader: boolean;
  /** The share below the crown, where the trunk is bare. */
  bare: number;
  /** How far the crown reaches from the trunk at most, as a share, and its outline. */
  spread: number;
  outline: (t: number) => number;
  /** How many limbs grow off the trunk, and how many branches off each limb. */
  limbs: number;
  branches: number;
  /** How steeply a limb rises on its way out: 0 is level, 1 is 45°. */
  rise: number;
  /** How a limb bends: below 0 it arches up and hangs at its tip, above 0 it sags and turns up. */
  droop: number;
  bark: Layer;
}

export const SPECIES: Species[] = [
  {
    name: 'oak', height: [9, 13], girth: 0.036, taper: 0.3, leader: false, bare: 0.28, spread: 0.42, outline: OUTLINES.dome,
    limbs: 7, branches: 3, rise: 0.55, droop: 0.1, bark: 'oak bark',
  },
  {
    name: 'birch', height: [9, 13], girth: 0.02, taper: 0.12, leader: true, bare: 0.3, spread: 0.2, outline: OUTLINES.egg,
    limbs: 11, branches: 2, rise: 1, droop: -0.3, bark: 'birch bark',
  },
  {
    name: 'spruce', height: [13, 19], girth: 0.022, taper: 0.06, leader: true, bare: 0.12, spread: 0.18, outline: OUTLINES.cone,
    limbs: 24, branches: 1, rise: 0.1, droop: -0.35, bark: 'conifer bark',
  },
  {
    name: 'pine', height: [11, 15], girth: 0.026, taper: 0.2, leader: true, bare: 0.55, spread: 0.3, outline: OUTLINES.umbrella,
    limbs: 8, branches: 3, rise: 0.35, droop: 0.15, bark: 'conifer bark',
  },
  {
    name: 'acacia', height: [6, 8.5], girth: 0.036, taper: 0.35, leader: false, bare: 0.5, spread: 0.6, outline: OUTLINES.umbrella,
    limbs: 6, branches: 3, rise: 0.8, droop: 0.05, bark: 'oak bark',
  },
  {
    name: 'cactus', height: [3, 5.5], girth: 0.075, taper: 0.8, leader: true, bare: 0.3, spread: 0.24, outline: () => 1,
    limbs: 2, branches: 0, rise: 1.6, droop: 1.3, bark: 'cactus skin',
  },
];

/** How many different trees are grown of each species. */
export const VARIANTS = 3;

/** A part of the tree's wood: a bent tube along `points`, as thick as `radii` at each of them. */
export interface Limb {
  points: Vec[];
  radii: number[];
  /** 0 is the trunk, 1 a limb off it, 2 a branch off a limb. */
  level: number;
}

/** A grown tree, before it is a mesh. */
export interface Tree {
  species: Species;
  height: number;
  limbs: Limb[];
}

const TRUNK_SEGMENTS = 8;
const LIMB_SEGMENTS = 5;
const BRANCH_SEGMENTS = 2;
const GOLDEN_ANGLE = Math.PI * (3 - Math.sqrt(5));

/** Where a limb is at a share `t` of its length, between its points. */
function along(limb: Limb, t: number): { point: Vec; radius: number; direction: Vec } {
  const last = limb.points.length - 1;
  const segment = Math.min(Math.floor(t * last), last - 1);
  const within = t * last - segment;
  const [from, to] = [limb.points[segment], limb.points[segment + 1]];
  return {
    point: add(from, subtract(to, from), within),
    radius: limb.radii[segment] + (limb.radii[segment + 1] - limb.radii[segment]) * within,
    direction: normalize(subtract(to, from)),
  };
}

/** Grows a tree of a species. The same seed grows the same tree. */
export function growTree(species: Species, seed: number): Tree {
  const random = seededRandom(seed);
  const between = (low: number, high: number) => low + (high - low) * random();
  const height = between(...species.height);
  const limbs: Limb[] = [];
  const crownBottom = height * species.bare;

  // The trunk: up to the top, or to where the crown's limbs part. It wanders a little
  // on its way, and is thicker right at the ground.
  const top = species.leader ? height : crownBottom + (height - crownBottom) * 0.6;
  const base = species.girth * height;
  const wander = species.leader ? 0.008 : 0.03;
  const trunk: Limb = { points: [], radii: [], level: 0 };
  let [x, z] = [0, 0];
  for (let i = 0; i <= TRUNK_SEGMENTS; i += 1) {
    const t = i / TRUNK_SEGMENTS;
    trunk.points.push([x, top * t, z]);
    trunk.radii.push(base * (1 - (1 - species.taper) * t) * (1 + 0.5 * Math.max(1 - t * 8, 0)));
    x += between(-1, 1) * wander * height;
    z += between(-1, 1) * wander * height;
  }
  limbs.push(trunk);

  // The limbs: each reaches for a point of the crown's outline. The lowest ends at the
  // crown's bottom, the highest at its top, and they go around the trunk by the golden
  // angle, so that no two grow above each other.
  for (let i = 0; i < species.limbs; i += 1) {
    const share = (i + 0.5) / species.limbs;
    const reach = species.outline(share) * species.spread * height * between(0.8, 1.2);
    const tipHeight = crownBottom + (height - crownBottom) * share * 0.97;
    const turn = i * GOLDEN_ANGLE + between(-0.3, 0.3);
    const out: Vec = [Math.cos(turn), 0, Math.sin(turn)];
    // It starts lower on the trunk the more steeply it rises, but never below the crown.
    const start = Math.min(Math.max(tipHeight - species.rise * reach, crownBottom * 0.85), top * 0.98);
    const from = along(trunk, start / top);
    const tip = add([from.point[0], tipHeight, from.point[2]], out, reach);
    const pull = add([from.point[0], (start + tipHeight) / 2 - species.droop * reach * 0.5, from.point[2]], out, reach * 0.5);
    const thickness = Math.min(from.radius * 0.6, base * 0.4);
    const limb: Limb = { points: [], radii: [], level: 1 };
    for (let s = 0; s <= LIMB_SEGMENTS; s += 1) {
      const t = s / LIMB_SEGMENTS;
      limb.points.push(curve(from.point, pull, tip, t));
      // A cactus keeps its girth to the end; a limb of wood thins out to a twig.
      limb.radii.push(thickness * (1 - (1 - species.taper) * t ** 0.8) + 0.012);
    }
    limbs.push(limb);

    // The branches: off the outer part of the limb, to the left and the right in turn.
    for (let b = 0; b < species.branches; b += 1) {
      const t = 0.35 + (0.55 * (b + between(0, 0.6))) / species.branches;
      const fork = along(limb, t);
      const sideways = normalize(cross(fork.direction, UP));
      const way = normalize(add(add(fork.direction, sideways, b % 2 ? 1.5 : -1.5), UP, between(-0.1, 0.3)));
      const length = reach * 0.42 * (1.15 - t * 0.5);
      const end = add(add(fork.point, way, length), UP, -species.droop * length * 0.3);
      const bend = add(add(fork.point, way, length * 0.5), UP, length * 0.12);
      const branch: Limb = { points: [], radii: [], level: 2 };
      for (let s = 0; s <= BRANCH_SEGMENTS; s += 1) {
        branch.points.push(curve(fork.point, bend, end, s / BRANCH_SEGMENTS));
        branch.radii.push(fork.radius * 0.6 * (1 - s / BRANCH_SEGMENTS) + 0.012);
      }
      limbs.push(branch);
    }
  }
  return { species, height, limbs };
}

/**
 * A tree's mesh. Each vertex has four numbers in `paints`: u, v, the texture's layer, and a
 * shade, which is 1 until the tree has leaves to shade it.
 */
export interface TreeMesh {
  positions: Float32Array;
  normals: Float32Array;
  indices: Uint32Array;
  paints: Float32Array;
}

/** A tree as it is drawn: its mesh, and its measures in meters. */
export interface TreeModel {
  species: Species;
  mesh: TreeMesh;
  height: number;
  /** The trunk's radius at the ground. */
  girth: number;
}

/** Sides of the tubes around the trunk, the limbs and the branches. */
const SIDES = [7, 4, 3];
/** Meters of bark that the texture covers, up a limb. */
const BARK_TILE = 2;

/** Makes the mesh of a grown tree: a tube around every limb. */
export function meshTree(tree: Tree): TreeModel {
  const { species, height } = tree;
  const positions: number[] = [];
  const normals: number[] = [];
  const paints: number[] = [];
  const indices: number[] = [];
  const bark = TREE_LAYERS.indexOf(species.bark);

  const vertex = (point: Vec, normal: Vec, u: number, v: number, layer: number) => {
    positions.push(...point);
    normals.push(...normal);
    paints.push(u, v, layer, 1);
    return positions.length / 3 - 1;
  };

  for (const limb of tree.limbs) {
    const sides = SIDES[limb.level];
    const last = limb.points.length - 1;
    let side: Vec = [1, 0, 0];
    let length = 0;
    const rings: number[] = [];
    for (let p = 0; p <= last; p += 1) {
      // The ring around this point lies across the limb's way here. Its first corner
      // stays as near as it can to the first corner of the ring before, so that the
      // tube doesn't twist.
      const way = normalize(subtract(limb.points[Math.min(p + 1, last)], limb.points[Math.max(p - 1, 0)]));
      side = normalize(subtract(side, [way[0] * dot(side, way), way[1] * dot(side, way), way[2] * dot(side, way)]));
      const other = cross(way, side);
      if (p > 0) length += Math.hypot(...subtract(limb.points[p], limb.points[p - 1]));
      rings.push(positions.length / 3);
      // One corner more than sides: the first and the last are at the same place, at
      // both ends of the bark's texture.
      for (let s = 0; s <= sides; s += 1) {
        const angle = (s / sides) * Math.PI * 2;
        const out = add([side[0] * Math.cos(angle), side[1] * Math.cos(angle), side[2] * Math.cos(angle)], other, Math.sin(angle));
        vertex(add(limb.points[p], out, limb.radii[p]), out, (s / sides) * 2, length / BARK_TILE, bark);
      }
    }
    for (let p = 0; p < last; p += 1) {
      for (let s = 0; s < sides; s += 1) {
        const [a, b] = [rings[p] + s, rings[p + 1] + s];
        indices.push(a, b, a + 1, a + 1, b, b + 1);
      }
    }
    // A thick end is closed with a round tip: a cactus's arm doesn't end in a twig.
    if (limb.radii[last] > 0.03) {
      const way = normalize(subtract(limb.points[last], limb.points[last - 1]));
      const tip = vertex(add(limb.points[last], way, limb.radii[last] * 0.7), way, 1, length / BARK_TILE, bark);
      for (let s = 0; s < sides; s += 1) indices.push(rings[last] + s, tip, rings[last] + s + 1);
    }
  }

  return {
    species,
    height,
    girth: tree.limbs[0].radii[0],
    mesh: {
      positions: new Float32Array(positions),
      normals: new Float32Array(normals),
      indices: new Uint32Array(indices),
      paints: new Float32Array(paints),
    },
  };
}

/** Every tree the world has: VARIANTS of each species, in the order of SPECIES. */
export function growModels(): TreeModel[] {
  return SPECIES.flatMap((species, s) => Array.from({ length: VARIANTS }, (_, variant) => meshTree(growTree(species, s * 100 + variant + 1))));
}
  • along() findet den Punkt, den Radius und die Richtung eines Asts bei jedem Anteil seiner Länge, zwischen seinen Punkten. Die Äste setzen damit am Stamm an, die Zweige an einem Ast.

  • In growTree() ist pull der dritte Punkt der Bézierkurve, und curve() läuft die Kurve entlang.

  • In meshTree() ist side die Richtung der ersten Ecke eines Rings. Zieht man way * dot(side, way) ab, bleibt der Teil davon, der quer zum Ast liegt.

  • growModels() lässt jede Variante jeder Art wachsen und vernetzt sie, in der Reihenfolge von SPECIES. Die Nummer eines Modells ist die Nummer seiner Art mal VARIANTS plus die Variante: Darauf verlässt sich Teil 9.

Rinde

Die Rinden werden gemalt wie die Texturen des Bodens in der Terrain-Serie, Pixel für Pixel aus kachelbarem Rauschen, in die Ebenen eines Textur-Arrays. Was sie zu Rinde macht, ist die Form des Rauschens. tilingNoise(20, 3) wiederholt sich zwanzigmal quer über die Textur und dreimal nach oben, sein Auf und Ab sind also lange Streifen den Stamm hinauf: die Furchen einer Eiche. Fünf quer und 48 nach oben ergibt die dunklen Male, die um eine Birke laufen. Die Nadelbäume bekommen rötliche Platten mit dunklen Spalten, wo ein Rauschen die 0 kreuzt, und der Kaktus acht Rippen um seinen Stamm, aus einem Kosinus, mit hellen Stacheln entlang ihrer Kämme. Erstelle src/treeTextures.ts:

src/treeTextures.ts
import { hex, layeredNoise, mix, shade, tilingNoise, type Rgb } from './textures.ts';
import { TREE_LAYERS } from './trees.ts';

/** Pixels along each side of a tree's texture. */
export const TREE_TEXTURE = 256;

type Bark = (typeof TREE_LAYERS)[number];

/**
 * How to paint each bark, from u around the trunk and v up it, both from 0 to 1. The
 * texture goes twice around a trunk, and covers two meters of its height.
 */
const BARKS: Record<Bark, (u: number, v: number) => Rgb> = (() => {
  const furrows = tilingNoise(20, 3);
  const patches = layeredNoise(4, 8, 16);
  const marks = tilingNoise(5, 48);
  const plates = tilingNoise(9, 6);
  const fine = tilingNoise(64);
  return {
    // Furrows that run up the trunk: the noise is seven times finer around than up.
    'oak bark': (u, v) => shade(mix(hex('#3a2c21'), hex('#7d6549'), furrows(u, v) * 0.9 + 0.5), patches(u, v) * 0.3),
    // White, with dark marks that run around the trunk.
    'birch bark': (u, v) => {
      const color = shade(hex('#e2decf'), patches(u, v) * 0.12);
      const mark = marks(u, v);
      return mark > 0.45 ? mix(color, hex('#2b2826'), (mark - 0.45) * 8) : color;
    },
    // Reddish plates with dark gaps between them.
    'conifer bark': (u, v) => {
      const color = mix(hex('#5d3d2a'), hex('#96643f'), patches(u, v) + 0.5);
      return Math.abs(plates(u, v)) < 0.06 ? shade(color, -0.5) : shade(color, fine(u, v) * 0.2);
    },
    // Eight ribs around the trunk, light on their crests, with pale spines along them.
    'cactus skin': (u, v) => {
      const rib = Math.cos(u * Math.PI * 8);
      return rib > 0.8 && fine(u, v) > 0.25 ? hex('#ebe4b8') : shade(hex('#4c8a3a'), rib * 0.25);
    },
  };
})();

/** Paints every layer of the trees' texture array: RGBA bytes, one layer after the other. */
export function paintTreeLayers(): Uint8Array {
  const pixels = TREE_TEXTURE * TREE_TEXTURE;
  const data = new Uint8Array(pixels * 4 * TREE_LAYERS.length);
  TREE_LAYERS.forEach((name, layer) => {
    const paint = BARKS[name];
    for (let y = 0; y < TREE_TEXTURE; y += 1) {
      for (let x = 0; x < TREE_TEXTURE; x += 1) {
        const [r, g, b] = paint(x / TREE_TEXTURE, y / TREE_TEXTURE);
        data.set([r, g, b, 255], (layer * pixels + y * TREE_TEXTURE + x) * 4);
      }
    }
  });
  return data;
}

Die Shader

Es wird einen Wald aus diesen Bäumen geben, und nur achtzehn Meshes. Die Bäume werden deshalb so gezeichnet wie das Gras aus Teil 5: jedes Mesh einmal für jeden Baum seiner Art, mit zwei vec4 pro Baum statt einer Matrix. place enthält, wo der Baum steht, und seine Größe, look.x, wie weit er um seinen Stamm gedreht ist. Der Vertex-Shader dreht den Vertex und seine Normale, skaliert den Vertex und setzt ihn an seinen Platz. Die anderen drei Zahlen von look sind für spätere Teile. Erstelle src/tree.vertex.glsl:

src/tree.vertex.glsl
precision highp float;

attribute vec3 position;
attribute vec3 normal;
// Where on its texture the vertex is, the texture's layer, and the vertex's shade.
attribute vec4 paint;
// The tree, one for every instance: its place and its size, then its turn and three
// numbers of its own.
attribute vec4 place;
attribute vec4 look;

uniform mat4 world;
uniform mat4 viewProjection;

varying vec3 vPosition;
varying vec3 vNormal;
varying vec4 vPaint;

void main() {
  // Turned about its trunk, sized, and put in its place.
  float c = cos(look.x);
  float s = sin(look.x);
  mat3 turn = mat3(c, 0.0, s, 0.0, 1.0, 0.0, -s, 0.0, c);
  vec4 worldPosition = world * vec4(place.xyz + turn * position * place.w, 1.0);
  vPosition = worldPosition.xyz;
  vNormal = mat3(world) * (turn * normal);
  vPaint = paint;
  gl_Position = viewProjection * worldPosition;
}

Der Fragment-Shader liest die Rinde aus der Ebene des Vertex und beleuchtet sie mit der Sonne und dem Himmel, so wie das Terrain beleuchtet wird. Bäume stehen im Freien, es gibt also kein Lichtgitter zu fragen: Ein Baum sieht den ganzen Himmel. Erstelle src/tree.fragment.glsl:

src/tree.fragment.glsl
precision highp float;
precision highp sampler2DArray;

varying vec3 vPosition;
varying vec3 vNormal;
varying vec4 vPaint;

uniform sampler2DArray layers;
uniform vec3 cameraPosition;
uniform vec3 sunDirection;
uniform vec3 sunColor;
uniform vec3 skyColor;
uniform vec3 groundColor;
uniform vec3 fogColor;
uniform vec2 fogRange;

void main() {
  vec4 texel = texture(layers, vec3(vPaint.xy, floor(vPaint.z + 0.5)));

  // Lit by the sun and the sky. A tree stands in the open: it sees all of the sky.
  vec3 normal = normalize(vNormal);
  float sun = max(dot(normal, -sunDirection), 0.0);
  vec3 ambient = mix(groundColor, skyColor, normal.y * 0.5 + 0.5);
  vec3 lit = texel.rgb * vPaint.w * (ambient + sunColor * sun);

  float fog = smoothstep(fogRange.x, fogRange.y, distance(vPosition, cameraPosition));
  gl_FragColor = vec4(mix(lit, fogColor, fog), 1.0);
}

Das Material malt die Ebenen und wiederholt sie in beide Richtungen, denn die Rinde läuft ohne Ende um den Stamm und ihn hinauf. createTreeMesh() setzt ein Modell in die Szene. Babylon.js entscheidet anhand der eigenen Box eines Meshs, ob es im Bild ist, und die Instanzen dieses Meshs werden überall stehen, also wird das Mesh immer gezeichnet. Erstelle src/treeMaterial.ts:

src/treeMaterial.ts
import { Constants, RawTexture2DArray, ShaderMaterial, Texture, type Mesh, type Scene } from '@babylonjs/core/pure';
import { LIGHT_UNIFORMS, setLight, type FogOptions } from './material.ts';
import { createMesh } from './meshData.ts';
import fragmentSource from './tree.fragment.glsl?raw';
import vertexSource from './tree.vertex.glsl?raw';
import { TREE_LAYERS, type TreeModel } from './trees.ts';
import { paintTreeLayers, TREE_TEXTURE } from './treeTextures.ts';

/** The trees' material: the barks from one texture array, lit by the sun and the sky. */
export function createTreeMaterial(scene: Scene, options: FogOptions): ShaderMaterial {
  const layers = new RawTexture2DArray(
    paintTreeLayers(),
    TREE_TEXTURE,
    TREE_TEXTURE,
    TREE_LAYERS.length,
    Constants.TEXTUREFORMAT_RGBA,
    scene,
    true,
    false,
    Texture.TRILINEAR_SAMPLINGMODE,
  );
  // The bark goes around and up the trunk without an end.
  layers.wrapU = Texture.WRAP_ADDRESSMODE;
  layers.wrapV = Texture.WRAP_ADDRESSMODE;
  const material = new ShaderMaterial(
    'trees',
    scene,
    { vertexSource, fragmentSource },
    {
      attributes: ['position', 'normal', 'paint', 'place', 'look'],
      uniforms: ['world', 'viewProjection', ...LIGHT_UNIFORMS],
      samplers: ['layers'],
    },
  );
  material.setTexture('layers', layers);
  setLight(material, options);
  // Nothing is left out for facing away: the leaves of the next part are seen from both sides.
  material.backFaceCulling = false;
  return material;
}

/** A tree's mesh in the scene. It is drawn once for every instance it is given. */
export function createTreeMesh(scene: Scene, model: TreeModel, material: ShaderMaterial): Mesh {
  const mesh = createMesh(model.species.name, model.mesh, scene);
  mesh.setVerticesData('paint', model.mesh.paints, false, 4);
  mesh.material = material;
  mesh.isPickable = false;
  // Its instances stand anywhere: Babylon.js can't tell from the mesh whether they are in view.
  mesh.alwaysSelectAsActiveMesh = true;
  return mesh;
}

Eine Baumschule

Bis Teil 9 sie pflanzt, stehen die Bäume in einer Baumschule: jede Art 14 m weiter entlang x, ihre drei Varianten 14 m auseinander entlang z. Jedes Mesh bekommt eine Liste mit einer Instanz, gemacht mit instanceBuffer() aus Teil 5: der Platz, die Größe 1 und eine Drehung. Erstelle src/nursery.ts:

src/nursery.ts
import type { Scene, ShaderMaterial } from '@babylonjs/core/pure';
import { instanceBuffer } from './chunkPlants.ts';
import { surfaceHeight } from './terrain.ts';
import { createTreeMesh } from './treeMaterial.ts';
import { VARIANTS, type TreeModel } from './trees.ts';

/** Meters between the trees of the nursery. */
const APART = 14;

/**
 * Plants one of every tree in rows from (x, z): a row for each species. Each mesh is drawn
 * for one instance, which says where the tree stands and how it is turned.
 */
export function plantNursery(scene: Scene, models: TreeModel[], material: ShaderMaterial, x: number, z: number): void {
  models.forEach((model, i) => {
    const mesh = createTreeMesh(scene, model, material);
    const treeX = x + Math.floor(i / VARIANTS) * APART;
    const treeZ = z - (i % VARIANTS) * APART;
    // A little into the ground, which is not level.
    instanceBuffer(mesh, new Float32Array([treeX, surfaceHeight(treeX, treeZ) - 0.3, treeZ, 1, i * 2.4, 0, 0, 0]));
  });
}

Importiere in src/main.ts plantNursery aus ./nursery.ts, createTreeMaterial aus ./treeMaterial.ts und growModels aus ./trees.ts. Bevor das Material der Blöcke gemacht wird, lass die Bäume wachsen und pflanze die Baumschule links vom Start:

src/main.ts
// The trees: every species in a few variants, grown once. For now they stand in a nursery
// next to the start.
const treeMaterial = createTreeMaterial(scene, fog);
const treeModels = growModels();
plantNursery(scene, treeModels, treeMaterial, 112, 172);

Unter Wasser brauchen die Bäume den Nebel des Wassers wie alles andere: Füge treeMaterial zur Liste der Materialien in dive() hinzu.

Ausprobieren

Dreh dich am Start nach links: Die Baumschule beginnt 16 m entfernt, mit den Eichen vorn und dahinter den Birken, den Fichten, den Kiefern, den Akazien und den Kakteen. Geh hindurch und vergleiche die drei Varianten einer Art: dieselbe Form, nie derselbe Baum. Schau am Stamm einer Fichte hinauf, um zu sehen, wie ihre Äste im Goldenen Winkel um ihn herumgehen, und am Stamm einer Eiche, um zu sehen, wo er endet und die Äste auseinandergehen. Ändere in src/trees.ts die Zahlen einer Art und lade neu: Ein droop von -1 macht aus der Eiche einen Trauerbaum, und ein spread von 0.1 macht aus einer Fichte eine Stange.

Eine kahle Eiche aus der Nähe: Der Stamm endet, wo die Äste auseinandergehen, jeder Ast biegt sich zu seinem Punkt auf dem Umriss der Krone, und Zweige wachsen nach beiden Seiten aus den Ästen.
Kahle Bäume. Klick, dann dreh dich nach links und geh in die Baumschule: drei Varianten von jeder der sechs Arten. WASD geht, Shift rennt, F fliegt (Q/E runter und rauf).
In neuem Tab öffnen

Kommentare

Die Kommentare sind GitHub Discussions: Zum Schreiben mit GitHub anmelden.

Die Kommentare kommen über giscus von GitHub. Beim Laden gehen deine IP-Adresse an giscus.app und GitHub.