GameCrew AIEarly access
Sign in
Three.jsoptimizationRevision 1 · Compile-verified pattern

Octahedral Impostor Forests & Procedural Trees in Three.js

Render thousands of 3D trees or distant props in a single Three.js r183 InstancedMesh draw call by baking an NxN hemisphere octahedral atlas at startup from a procedural ez-tree-style branching tree mesh.

  • impostor
  • octahedral
  • trees
  • forest
  • lod
  • instancing
  • foliage
  • procedural
  • optimization
  • vr
  • webgl2

No demo.

When to Use & Field Best Practices

Rendering 1,500 full-geometry trees crushes WebGL 2 and Quest VR frame budgets (where draw calls must stay < 200 and triangles < 300k). Octahedral Impostors bake a 3D tree or complex prop from an N× N grid of hemisphere viewing angles once at startup, then draw thousands of parallax-accurate trees as 1 single InstancedMesh of camera-facing quads:

  1. Hemisphere Octahedral Mapping: Map every upper-hemisphere view direction d = (x, y, z) (y ≥ 0) continuously onto [0, 1]^2 via octahedral folding with zero pole pinching. Each atlas cell (i, j) stores the orthographic render from direction hemiOctaDecode(i/(N-1), j/(N-1)).
  2. Smooth 3-Cell Barycentric Blending: Unlike stiff 1-angle billboards that pop sharply as you orbit, sampling the 3 enclosing octahedral grid corners and blending by triangle barycentric weights makes distant trees rotate smoothly in 3D as the player moves!
  3. One-Shot Startup Bake + Zero Runtime Overheads: Bake a 512×512 (8×8 cells of 64×64 px) atlas in < 8 ms on load from either a procedural createProceduralTree() mesh or an imported GLB (game.models), dispose the temporary baker camera/scene immediately, and keep near hero trees as real 3D geometry while drawing the outer forest as octahedral impostors.
  4. VR Stereo Safe: The impostor shader uses modelViewMatrix billboarding per eye (cameraPosition in world space), working cleanly in both flat play and WebXR headsets.

Mathematical & Algorithmic Core

  • Hemisphere Octahedral Encode / Decode for v = (x, y, z) with y ≥ 0: $p = ((x, z))/(|x| + y + |z|), o = (1)/(2)beginpmatrix p_x + p_z + 1 \\ p_z - p_x + 1 endpmatrix ∈ [0, 1]^2$ Inverse for $\mathbf{u} \in [0, 1]^2$: let $a = 2u_x - 1, b = 2u_y - 1$, $t_x = \tfrac{1}{2}(a - b)$, $t_z = \tfrac{1}{2}(a + b)$, $t_y = 1 - |t_x| - |t_z|$, then $\mathbf{d} = \mathrm{normalize}(t_x, \max(0, t_y), t_z)$.

Engine Implementation (Assets/Game/impostorForest.ts)

Strict erasable TypeScript providing a procedural stylized tree builder (createProceduralTree), startup octahedral atlas baker (bakeOctahedralAtlas), and single-draw-call InstancedMesh forest (createImpostorForest):

import * as THREE from 'three';
import type { Game } from 'ccgd';

export interface ProceduralTreeOptions {
  seed?: number;
  trunkHeight?: number;
  canopyRadius?: number;
  barkColor?: number;
  leafColor?: number;
}

export interface ImpostorAtlas {
  texture: THREE.Texture;
  gridSize: number;
  boundingRadius: number;
  dispose(): void;
}

export interface ForestSpot {
  x: number;
  y: number;
  z: number;
  scale?: number;
  yaw?: number;
}

function seededRand(seed: number): () => number {
  let s = seed | 0;
  return () => {
    s = (s * 1664525 + 1013904223) | 0;
    return ((s >>> 0) % 100000) / 100000;
  };
}

/** Builds a zero-asset stylized branching tree centered around origin for baking or near-LOD placement. */
export function createProceduralTree(opts: ProceduralTreeOptions = {}): THREE.Group {
  const rand = seededRand(opts.seed ?? 42);
  const trunkH = opts.trunkHeight ?? 2.6;
  const canopyR = opts.canopyRadius ?? 1.85;
  const group = new THREE.Group();

  const barkMat = new THREE.MeshStandardMaterial({
    color: opts.barkColor ?? 0x7c573c,
    emissive: 0x1a110b,
    emissiveIntensity: 0.35,
    roughness: 0.90,
  });
  const leafMat = new THREE.MeshStandardMaterial({
    color: opts.leafColor ?? 0x59a646,
    emissive: 0x183014,
    emissiveIntensity: 0.45,
    roughness: 0.72,
  });

  const trunk = new THREE.Mesh(new THREE.CylinderGeometry(0.16, 0.30, trunkH, 7), barkMat);
  trunk.position.y = trunkH * 0.5;
  group.add(trunk);

  // Forked boughs + layered canopy puffs
  for (let i = 0; i < 4; i++) {
    const ang = (i / 4) * Math.PI * 2 + rand() * 0.5;
    const branchLen = trunkH * (0.42 + rand() * 0.18);
    const branch = new THREE.Mesh(new THREE.CylinderGeometry(0.07, 0.13, branchLen, 6), barkMat);
    branch.position.set(Math.cos(ang) * 0.32, trunkH * 0.72, Math.sin(ang) * 0.32);
    branch.rotation.z = -Math.cos(ang) * 0.58;
    branch.rotation.x = Math.sin(ang) * 0.58;
    group.add(branch);

    const puffR = canopyR * (0.58 + rand() * 0.24);
    const puff = new THREE.Mesh(new THREE.IcosahedronGeometry(puffR, 1), leafMat);
    puff.position.set(
      Math.cos(ang) * canopyR * 0.45,
      trunkH + puffR * 0.35 + (rand() - 0.5) * 0.35,
      Math.sin(ang) * canopyR * 0.45
    );
    puff.scale.y = 0.78;
    group.add(puff);
  }

  const crown = new THREE.Mesh(new THREE.IcosahedronGeometry(canopyR * 0.78, 1), leafMat);
  crown.position.y = trunkH + canopyR * 0.65;
  crown.scale.y = 0.82;
  group.add(crown);
  return group;
}

function hemiOctaDecode(u: number, v: number, out: THREE.Vector3): THREE.Vector3 {
  const a = u * 2 - 1;
  const b = v * 2 - 1;
  const x = (a - b) * 0.5;
  const z = (a + b) * 0.5;
  const y = Math.max(0.02, 1 - Math.abs(x) - Math.abs(z));
  return out.set(x, y, z).normalize();
}

/**
 * Bakes an NxN upper-hemisphere octahedral billboard atlas of `source` once at startup
 * (zero runtime baker cost once returned).
 */
export function bakeOctahedralAtlas(
  renderer: THREE.WebGLRenderer,
  source: THREE.Object3D,
  gridSize = 8,
  atlasSize = 512
): ImpostorAtlas {
  const bakeScene = new THREE.Scene();
  const clone = source.clone(true);
  const box = new THREE.Box3().setFromObject(clone);
  const center = new THREE.Vector3();
  const sphere = new THREE.Sphere();
  box.getCenter(center);
  box.getBoundingSphere(sphere);
  const radius = Math.max(0.5, sphere.radius * 1.06);

  clone.position.sub(center);
  bakeScene.add(clone);
  const sun = new THREE.DirectionalLight(0xfff4dd, 3.4);
  sun.position.set(5, 9, 5);
  bakeScene.add(sun);
  const fill = new THREE.DirectionalLight(0xb6dcff, 1.5);
  fill.position.set(-5, 4, -5);
  bakeScene.add(fill);
  bakeScene.add(new THREE.HemisphereLight(0xc2e2ff, 0x526b44, 2.2));

  const rt = new THREE.WebGLRenderTarget(atlasSize, atlasSize, {
    minFilter: THREE.LinearMipmapLinearFilter,
    magFilter: THREE.LinearFilter,
    format: THREE.RGBAFormat,
    type: THREE.UnsignedByteType,
    depthBuffer: true,
    generateMipmaps: true,
  });

  const cam = new THREE.OrthographicCamera(-radius, radius, radius, -radius, 0.1, radius * 6);
  const dir = new THREE.Vector3();
  const cellPx = Math.floor(atlasSize / gridSize);

  const prevRt = renderer.getRenderTarget();
  const prevAutoClear = renderer.autoClear;
  const prevClearAlpha = renderer.getClearAlpha();
  const prevClearCol = new THREE.Color();
  renderer.getClearColor(prevClearCol);
  const prevScissorTest = renderer.getScissorTest();

  renderer.setRenderTarget(rt);
  renderer.autoClear = false;
  renderer.setScissorTest(false);
  renderer.setClearColor(0x000000, 0);
  renderer.clear(true, true, false);
  renderer.setScissorTest(true);

  for (let iy = 0; iy < gridSize; iy++) {
    for (let ix = 0; ix < gridSize; ix++) {
      const u = gridSize > 1 ? ix / (gridSize - 1) : 0.5;
      const v = gridSize > 1 ? iy / (gridSize - 1) : 0.5;
      hemiOctaDecode(u, v, dir);
      cam.position.copy(dir).multiplyScalar(radius * 2.6);
      cam.up.set(0, 1, 0);
      if (dir.y > 0.995) cam.up.set(0, 0, -1);
      cam.lookAt(0, 0, 0);
      cam.updateProjectionMatrix();

      const vx = ix * cellPx;
      const vy = iy * cellPx;
      renderer.setViewport(vx, vy, cellPx, cellPx);
      renderer.setScissor(vx, vy, cellPx, cellPx);
      renderer.clearDepth();
      renderer.render(bakeScene, cam);
    }
  }

  renderer.setScissorTest(prevScissorTest);
  renderer.setViewport(0, 0, renderer.domElement.width, renderer.domElement.height);
  renderer.setRenderTarget(prevRt);
  renderer.autoClear = prevAutoClear;
  renderer.setClearColor(prevClearCol, prevClearAlpha);

  return {
    texture: rt.texture,
    gridSize,
    boundingRadius: radius,
    dispose() {
      rt.dispose();
    },
  };
}

const IMPOSTOR_VERT = /* glsl */ `
attribute vec3 aTint;
uniform float uGridSize;
varying vec2 vCellUv;
varying vec2 vCellA;
varying vec2 vCellB;
varying vec2 vCellC;
varying vec3 vWeights;
varying vec3 vTint;

vec2 hemiOctaEncode(vec3 d) {
  d.y = max(0.0, d.y);
  vec2 p = d.xz / max(1e-4, abs(d.x) + d.y + abs(d.z));
  return vec2(p.x + p.y, p.y - p.x) * 0.5 + 0.5;
}

void main() {
  vCellUv = uv;
  vTint = aTint;

  vec3 instPos = (modelMatrix * instanceMatrix * vec4(0.0, 0.0, 0.0, 1.0)).xyz;
  float sx = length(vec3(instanceMatrix[0][0], instanceMatrix[0][1], instanceMatrix[0][2]));
  float sy = length(vec3(instanceMatrix[1][0], instanceMatrix[1][1], instanceMatrix[1][2]));

  // Local view direction in instance space for octahedral cell selection
  vec3 toCamW = normalize(cameraPosition - instPos);
  mat3 invRot = transpose(mat3(
    normalize(instanceMatrix[0].xyz),
    normalize(instanceMatrix[1].xyz),
    normalize(instanceMatrix[2].xyz)
  ));
  vec3 viewLocal = normalize(invRot * toCamW);
  vec2 oct = clamp(hemiOctaEncode(viewLocal), 0.0, 0.999) * (uGridSize - 1.0);
  vec2 c0 = floor(oct);
  vec2 f = fract(oct);

  vCellA = c0;
  vCellB = c0 + vec2(1.0, 1.0);
  vCellC = f.x > f.y ? (c0 + vec2(1.0, 0.0)) : (c0 + vec2(0.0, 1.0));
  vWeights = vec3(1.0 - max(f.x, f.y), min(f.x, f.y), abs(f.x - f.y));

  // Spherical billboard facing the active eye camera
  vec3 right = normalize(cross(vec3(0.0, 1.0, 0.0), toCamW));
  vec3 up = cross(toCamW, right);
  vec3 worldPos = instPos + right * (position.x * sx) + up * (position.y * sy);
  gl_Position = projectionMatrix * viewMatrix * vec4(worldPos, 1.0);
}
`;

const IMPOSTOR_FRAG = /* glsl */ `
precision highp float;
uniform sampler2D uAtlas;
uniform float uGridSize;
varying vec2 vCellUv;
varying vec2 vCellA;
varying vec2 vCellB;
varying vec2 vCellC;
varying vec3 vWeights;
varying vec3 vTint;

vec4 sampleCell(vec2 cell, vec2 uv) {
  vec2 padUv = clamp(uv, 0.02, 0.98);
  vec2 atlasUv = (cell + padUv) / uGridSize;
  return texture2D(uAtlas, atlasUv);
}

void main() {
  vec4 sa = sampleCell(vCellA, vCellUv);
  vec4 sb = sampleCell(vCellB, vCellUv);
  vec4 sc = sampleCell(vCellC, vCellUv);
  vec4 col = sa * vWeights.x + sb * vWeights.y + sc * vWeights.z;
  if (col.a < 0.35) discard;
  vec3 rgb = col.rgb / max(0.001, col.a);
  gl_FragColor = vec4(rgb * vTint, 1.0);
  #include <colorspace_fragment>
}
`;

export function createImpostorForest(
  game: Game,
  atlas: ImpostorAtlas,
  spots: readonly ForestSpot[]
): THREE.InstancedMesh {
  const size = atlas.boundingRadius * 2.0;
  const geo = new THREE.PlaneGeometry(size, size);
  const tints = new Float32Array(spots.length * 3);
  for (let i = 0; i < spots.length; i++) {
    const shade = 0.88 + (((i * 73) % 100) / 100) * 0.24;
    tints[i * 3] = shade;
    tints[i * 3 + 1] = shade * 1.02;
    tints[i * 3 + 2] = shade * 0.96;
  }
  geo.setAttribute('aTint', new THREE.InstancedBufferAttribute(tints, 3));

  const mat = new THREE.ShaderMaterial({
    vertexShader: IMPOSTOR_VERT,
    fragmentShader: IMPOSTOR_FRAG,
    uniforms: {
      uAtlas: { value: atlas.texture },
      uGridSize: { value: atlas.gridSize },
    },
    side: THREE.DoubleSide,
  });

  const mesh = new THREE.InstancedMesh(geo, mat, Math.max(1, spots.length));
  const dummy = new THREE.Object3D();
  for (let i = 0; i < spots.length; i++) {
    const s = spots[i];
    const sc = s.scale ?? 1.0;
    dummy.position.set(s.x, s.y + atlas.boundingRadius * sc * 0.85, s.z);
    dummy.rotation.set(0, s.yaw ?? (i * 2.39996), 0);
    dummy.scale.setScalar(sc);
    dummy.updateMatrix();
    mesh.setMatrixAt(i, dummy.matrix);
  }
  mesh.instanceMatrix.needsUpdate = true;
  mesh.frustumCulled = false;
  game.scene.add(mesh);
  return mesh;
}

Browser, Mobile & Software-Renderer Budgets

  • Massive Draw-Call Compression: 2,000 trees drop from 2,000+ draw calls / 400k triangles down to 1 draw call / 4,000 triangles — staying well within Quest WebXR's 200 draw-call ceiling.
  • Startup Atlas Size: gridSize = 8, atlasSize = 512 (64×64 px per view) uses only 1 MB of VRAM and bakes in < 8 ms even on mobile GPUs.
  • Dispose Cleanly: Call atlas.dispose() when tearing down or changing levels.

Verification Checklist

  1. Run compile (threeCompile) and verify zero TypeScript, three-lint, or WebGL shader errors.
  2. Bake createProceduralTree() into an 8×8 atlas, scatter 150+ impostors around a terrain perimeter, and inspect Captures/overview.png: verify smooth parallax silhouettes with zero black box edges.
  3. Orbit around a single impostor tree and confirm smooth 3-cell cross-fading without abrupt angle popping.

Official references

  • agargaro — octahedral-impostor (MIT)
  • Dan Greenheck — ez-tree (MIT)
  • Ryan Brucks (2018 — Octahedral Impostors)
  • Quirin Meyer et al. (2010 — On Floating-Point Normal Vectors / Octahedral Mapping)

Open-source sources

  • Takes an idea from octahedral-impostor by agargaro (MIT License): hemisphere octahedral billboard atlas baking and 3-cell barycentric blending
  • Takes an idea from ez-tree by Dan Greenheck (MIT License): procedural branching tree mesh silhouette recipe

Games built with this guide carry these credits, and the licence notices they ask for, in their third-party notices.

More Three.js games

Games made with GameCrew on the same engine. No game has been built with this guide yet: these show what Three.js games here look like.

More Three.js techniques

materials

Hexagonal Stochastic Anti-Tiling & Seamless Surface Detail in Three.js →

Eliminate visible texture grid repetition on large floors, terrain, and cliffs in Three.js r183 by patching MeshStandardMaterial with 3-tap hexagonal barycentric stochastic UV sampling and variance-preserving blending.

optimization

Instanced Wind Foliage, Object-Pooled Particles & Spring Feel in Three.js →

Single-draw-call THREE.InstancedMesh wind foliage with player bend, zero-GC pooled burst particles, and dt-invariant second-order springs that keep 60 Hz steps under 2 ms.

atmosphere

Raymarched Volumetric Clouds & Atmospheric Sky Shaders in Three.js (WebGL 2) →

Self-contained THREE.ShaderMaterial sky dome in GLSL ES 3.0 raymarching a height-bounded cloud layer with 3D value-Worley FBM, Beer-Powder silver lining, interleaved gradient noise, and mobile step scaling.

vr

Quest WebXR Performance & Draw-Call Instancing in Three.js →

Stay under 200 draw calls and 300k stereo triangles per frame in WebXR via InstancedMesh batches, zero-alloc updates, and WorldPanel HUDs.

Use verified techniques inside a real game

Describe your game idea for free or connect an MCP assistant to search and contribute techniques.

Learn about collaboration