Skip to content

Voxel Space terrain: heightfield projection and a corrected Canvas example

Heightfield terrain rendering is associated with games such as Comanche, but this article is an educational reconstruction rather than a verified account of every historical engine or target CPU. The small VoxelSpace reference project provides a useful explanation of the technique.

The terrain method here projects a sampled heightfield into vertical screen spans instead of constructing a general polygon mesh. That does not mean every object in the named games used no polygons.

A compact algorithm can be easier to understand than a general rendering engine, but line count is not a complete application or a benchmark. No recent Hacker News trend, library-size comparison or personal performance result is established here.

We will explain the projection, inspect the source’s mistakes and present a corrected educational Canvas listing. Browser rendering and visual tests were not available, so this is not labeled production-ready or performance-validated.

The Core Concept: Heightmaps and Color Maps

This version uses two equally sized two-dimensional maps: one height sample and one color per location. A power-of-two size is convenient for the bitmask wrapping used below, not a universal requirement of heightfield rendering.

  • The Color Map: A standard 2D texture containing the colors of the terrain (the grass, dirt, roads, or snow) as seen from directly above.
  • The grayscale heightmap supplies values from 0 to 255. Their physical meaning, vertical scale and reference level are choices of the application; zero need not be sea level and 255 need not be a mountain peak.

This is a heightfield, often called 2.5D: each horizontal location has one elevation. It cannot directly represent overhangs, caves or multiple terrain surfaces at the same location. The projection creates a perspective view of that restricted model.

How the Algorithm Works (Without Math Ph.Ds)

The implementation simplifies geometry by choosing a restricted terrain model and camera. These are explicit design constraints, not a general solution to the rendering equation.

  • The example supports yaw and camera height. Shifting the horizon is only an approximation to pitch; it does not implement a full rotated camera or roll.
  • The terrain is viewed from a perspective where we render column-by-column, from the foreground (close to the camera) to the background (far away).

For every vertical column of pixels on your screen (from left to right), the engine casts a ray outward from the camera’s position into the world map. As the ray travels forward, we sample the height and color of the map at discrete steps.

Here is the visual step-by-step logic for a single vertical column on the screen:

1. Start at the camera position.
2. Step forward along the camera's line of sight by a distance 'depth' (z).
3. Compute the 2D map coordinate (x, y) at this step.
4. Retrieve the terrain height (h) and color (c) from our heightmap and colormap at (x, y).
5. Project this 3D height onto the 2D screen using perspective division: 
   screen_y = (camera_height - terrain_height) / depth * scale + horizon
6. Draw a vertical line of color 'c' from this projected screen_y down to the previously drawn highest point.
7. Repeat for the next step forward, moving further into the distance.

For each column, store the smallest screen y already covered by nearer terrain. A farther sample only adds visible pixels above that boundary. This mask costs work and memory, and it is not a general per-pixel depth buffer for arbitrary geometry.

Building Our Voxel Space Renderer in JavaScript

The educational implementation writes an ImageData buffer through a Uint32Array view. This is one design to measure against other Canvas operations, not proof that lineTo or fillRect is always slower. Native typed-array byte order is handled consistently rather than assuming a universal ABGR integer layout.

Step 1: Setting up the HTML Canvas

A 320×240 drawing buffer keeps this example bounded, but does not guarantee 60 fps on mobile devices. The code block below is a demo fragment for a separate test page, not active markup embedded in this article. It includes keyboard focus, instructions and an explicit Start/Pause button.

<!-- Separate demo-page fragment; shown as inert code in the article. -->
<div class="voxel-demo">
  <p id="voxel-help">Start, then focus the canvas. Arrows move or turn; WASD and R/F assume a Latin keyboard layout;
    R/F change height. Pause stops animation.</p>
  <button id="toggle" type="button" disabled>Start</button>
  <p id="status" role="status">Loading local demo maps.</p>
  <canvas id="screen" width="320" height="240" tabindex="0"
    aria-label="Heightfield terrain demonstration" aria-describedby="voxel-help">
    A visual heightfield demonstration; keyboard controls are described above.
  </canvas>
</div>
<style>
.voxel-demo canvas { width: min(100%, 640px); height: auto; image-rendering: pixelated; }
.voxel-demo canvas:focus-visible { outline: 3px solid #1769aa; outline-offset: 3px; }
</style>
<!-- On a separate test page, load the following JS after these elements. -->

Step 2: Loading Map Data into Memory

Use trusted, licensed same-origin maps of exactly 1024×1024 pixels. The loader attaches handlers before src, rejects errors/timeouts and size mismatches, checks Canvas availability and catches pixel-read failures. A failed map load must not start the animation. The red channel supplies the expected grayscale height values.

// Educational separate-page JS, not executed or benchmarked here.
const canvas = document.getElementById('screen');
const ctx = canvas.getContext('2d');
if (!ctx) throw new Error('Canvas 2D is unavailable');
const width = canvas.width, height = canvas.height;
const screenImg = ctx.createImageData(width, height);
const screenBuffer = new Uint32Array(screenImg.data.buffer);
const skyWord = new Uint32Array(new Uint8Array([48, 160, 224, 255]).buffer)[0];
const mapSize = 1024; // Power of two is required by the mask below.
const colorMap = new Uint32Array(mapSize * mapSize);
const heightMap = new Uint8Array(mapSize * mapSize);

function loadMap(path, isHeightMap) {
  return new Promise((resolve, reject) => {
    const url = new URL(path, location.href);
    if (url.origin !== location.origin) {
      reject(new Error('Use trusted same-origin maps')); return;
    }
    const img = new Image();
    let settled = false;
    const timer = setTimeout(() => finish(new Error('Map load timed out')), 15000);
    function finish(error) {
      if (settled) return;
      settled = true;
      clearTimeout(timer);
      img.onload = img.onerror = null;
      if (error) reject(error); else resolve();
    }
    img.onerror = () => finish(new Error('Map load failed'));
    img.onload = () => {
      try {
        if (img.naturalWidth !== mapSize || img.naturalHeight !== mapSize)
          throw new Error('Map must be 1024 by 1024');
        const temp = document.createElement('canvas');
        temp.width = temp.height = mapSize;
        const tc = temp.getContext('2d');
        if (!tc) throw new Error('Canvas 2D is unavailable');
        tc.drawImage(img, 0, 0);
        const rgba = tc.getImageData(0, 0, mapSize, mapSize).data;
        if (isHeightMap) {
          for (let i = 0; i < heightMap.length; i++) heightMap[i] = rgba[4 * i];
        } else {
          // Terrain is opaque in this model. Preserve platform byte order.
          for (let i = 3; i < rgba.length; i += 4) rgba[i] = 255;
          colorMap.set(new Uint32Array(rgba.buffer, rgba.byteOffset, rgba.length / 4));
        }
        finish();
      } catch (error) { finish(error); }
    };
    img.src = url.href;
  });
}

Step 3: The Core Render Loop

The camera stores horizontal position, height in arbitrary map units, yaw, a horizon offset, projection scale and a fixed forward-depth limit. These units do not automatically correspond to metres or sea level.

Compute sine and cosine once per frame, then build each column’s ray from its screen position. The code still uses floating-point arithmetic. Depth is measured along the camera-forward axis, and the movement code must use the same orientation.

const camera = { x: 512, y: 512, height: 120, angle: 0,
  horizon: 60, distance: 400, scale_height: 120 };
function render() {
  screenBuffer.fill(skyWord);
  const sin = Math.sin(camera.angle), cos = Math.cos(camera.angle);
  for (let column = 0; column < width; column++) {
    const side = ((column + 0.5) / width - 0.5) * 2;
    // Forward=(sin,cos), right=(cos,-sin); fixed roughly 90-degree FOV.
    const rx = sin + side * cos, ry = cos - side * sin;
    let top = height;
    for (let z = 1; z < camera.distance && top > 0; z += 1.5) {
      const mx = Math.floor(camera.x + rx * z) & (mapSize - 1);
      const my = Math.floor(camera.y + ry * z) & (mapSize - 1);
      const index = my * mapSize + mx;
      const projected = Math.floor((camera.height - heightMap[index]) /
        z * camera.scale_height + camera.horizon);
      // A sample above the screen may cover the whole remaining column.
      const y0 = Math.max(0, Math.min(height, projected));
      if (y0 < top) {
        for (let y = y0; y < top; y++) screenBuffer[y * width + column] = colorMap[index];
        top = y0;
      }
    }
  }
  ctx.putImageData(screenImg, 0, 0);
}

Step 4: Making It Interactive

Keyboard input is scoped to the focused canvas so page navigation is not globally hijacked. Movement uses elapsed time rather than a fixed distance per frame; focus/visibility changes clear held keys. Start is explicit and Pause cancels the animation loop. Touch controls and full nonvisual equivalence are outside this illustrative listing. Letter keys assume a Latin keyboard layout; arrow keys remain available for movement and turning.

const keys = new Set();
const button = document.getElementById('toggle');
const status = document.getElementById('status');
const allowed = new Set(['arrowleft','arrowright','arrowup','arrowdown','w','a','s','d','r','f']);
let running = false, frame = null, previous = null;
canvas.addEventListener('keydown', event => {
  const k = event.key.toLowerCase();
  if (!allowed.has(k) || event.ctrlKey || event.metaKey || event.altKey) return;
  event.preventDefault(); keys.add(k);
});
canvas.addEventListener('keyup', event => keys.delete(event.key.toLowerCase()));
canvas.addEventListener('blur', () => keys.clear());
function wrap(value) { return ((value % mapSize) + mapSize) % mapSize; }
function pause() {
  running = false;
  if (frame !== null) cancelAnimationFrame(frame);
  frame = null; previous = null; keys.clear(); button.textContent = 'Start';
}
function update(time) {
  if (!running) return;
  const dt = previous === null ? 0 : Math.min((time - previous) / 1000, 0.05);
  previous = time;
  if (keys.has('arrowleft') || keys.has('a')) camera.angle -= 1.8 * dt;
  if (keys.has('arrowright') || keys.has('d')) camera.angle += 1.8 * dt;
  const move = Number(keys.has('arrowup') || keys.has('w')) -
    Number(keys.has('arrowdown') || keys.has('s'));
  camera.x = wrap(camera.x + Math.sin(camera.angle) * move * 120 * dt);
  camera.y = wrap(camera.y + Math.cos(camera.angle) * move * 120 * dt);
  const climb = Number(keys.has('r')) - Number(keys.has('f'));
  camera.height = Math.max(1, Math.min(512, camera.height + climb * 90 * dt));
  render();
  frame = requestAnimationFrame(update);
}
button.addEventListener('click', () => {
  if (running) { pause(); return; }
  running = true; previous = null; button.textContent = 'Pause';
  canvas.focus(); frame = requestAnimationFrame(update);
});
document.addEventListener('visibilitychange', () => { if (document.hidden) pause(); });
async function init() {
  try {
    await Promise.all([loadMap('color.png', false), loadMap('height.png', true)]);
    render(); button.disabled = false; status.textContent = 'Ready. Choose Start.';
  } catch {
    pause(); status.textContent = 'Unable to load the trusted demo maps.';
  }
}
init();

Why Does This Algorithm Matter Today?

Why study a restricted CPU-side heightfield renderer when modern graphics APIs are available? It offers a clear case for examining tradeoffs, not a replacement for every GPU engine.

There are three critical lessons modern developers can take away from this retro technology:

1. CPU Cache Locality & Memory Efficiency

The arrays are compact, but access is not uniformly sequential. In this source layout, vertical screen writes advance by width elements, and map samples depend on ray direction. Those are strided or irregular accesses, not proof of ideal cache locality. Profile traversal and data layout before claiming an improvement.

2. The Power of Software Fallbacks

Canvas 2D can be a practical alternative for some constrained visualizations. Browser implementations may still use graphics acceleration internally, and support or performance is not universal. Handle missing contexts and resource errors; CPU-side pixel generation does not guarantee no driver issues, memory leaks or context loss.

3. Algorithmic Thinking over Brute Force

Restricting geometry and camera behavior can reduce the work required for a specific scene. The tradeoff is lost capability and approximation error. Compare quality, frame time and memory on the target device instead of asserting orders-of-magnitude gains.

Conclusion: The Beauty of Doing More with Less

Voxel Space shows us that elegance in software development isn't about using the newest, most complex framework. It's about knowing your constraints, understanding your data, and writing clean, intentional code to solve a problem beautifully.

For an authorized separate test page, prepare trusted matching 1024×1024 maps you may legally use, place the three JavaScript sections in order, and serve only a dedicated demo directory on loopback. Do not expose personal directories with a general HTTP server. Validate missing images, wrong sizes, keyboard focus, pause, foreground clipping and different refresh rates before any demo release. No server was started and no browser test was performed here.

Which retro rendering tradeoffs have you explored? Share a small non-sensitive example and the measurements you used, rather than an unsupported performance claim.

Primary references

Post a Comment

Previous Post Next Post