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

Texel-Snapped 3D Pixel Art, Edge Highlights & PS1 Retro Rendering in Three.js

Crisp low-resolution 3D pixel-art pipeline with depth silhouettes, normal-crease bevel highlights, Bayer 4x4 color quantization, texel-snapping helpers, and an optional PS1 clip-space vertex-snapping material patch in Three.js r183.

  • pixel-art
  • retro
  • ps1
  • psx
  • dithering
  • bayer
  • outlines
  • edge-detection
  • quantization
  • postprocessing
  • shader

No demo.

When to Use & Field Best Practices

Low-poly and procedural primitive scenes look extraordinarily intentional and cohesive when rendered through a true 3D Pixel Art or PS1/PSX Retro pipeline instead of raw smooth shading:

  1. Low-Res Nearest-Neighbor Target + Depth/Normal Edge Bevels: Render the scene into a crisp virtual resolution (320×180 to 480×270, NearestFilter) with a DepthTexture and normal pass. Darken pixels where depth jumps across an object silhouette (depthEdge), and *brighten* pixels where surface normals turn convex (normalEdge) — giving every low-poly box and character crisp hand-pixelled bevels!
  2. Ordered 4×4 Bayer Dithering + Color Quantization: Apply a subtle Bayer threshold before quantizing to 16–32 steps per channel so smooth lighting gradients dither cleanly into tactile retro shading instead of ugly flat stripes.
  3. World-Texel Camera Snapping: For orthographic or follow cameras, quantize the camera's view-plane position to integer virtual-pixel increments (snapWorldToPixelGrid) so pixel edges stay rock-steady instead of crawling/shimmering during slow motion.
  4. PS1 Clip-Space Vertex Snapping (applyPsxMaterial): When a brief calls for classic PS1/PSX horror or retro racing aesthetics, snap projected vertices to a coarse clip-space grid (160×120–320×240) inside MeshStandardMaterial.onBeforeCompile — works everywhere including VR stereo rendering!

Mathematical & Algorithmic Core

  • Silhouette Depth Edge & Convex Normal Bevel (4-neighbor cross at texel Δ = (1/W, 1/H)): $e_depth = step\!(τ_d,\, Σ_k=1^4 max(0,\, z_k - z_0)), e_bevel = step\!(τ_n,\, Σ_k=1^4 max(0,\, 1 - n_0 · n_k))$
  • Ordered Bayer Quantization with B_4× 4(x, y) ∈ [-tfrac12, tfrac12] and $L$ levels per channel: $c_q = fraclfloor c· L + s_d\, B_4× 4(p_px) + 0.5 rfloorL$

Engine Implementation (Assets/Game/pixelRetro.ts)

Strict erasable TypeScript module providing both the low-res 3D pixel-art edge-bevel pipeline (createPixelArtPipeline), texel-snapping helper (snapFollowCamera), and PS1 vertex-snapping material patch (applyPsxMaterial):

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

export interface PixelArtOptions {
  /** Virtual vertical resolution in pixels (default 240). */
  virtualHeight?: number;
  /** Dark silhouette strength along depth jumps (0..1, default 0.52). */
  outlineStrength?: number;
  /** Bright bevel strength along convex normal creases (0..1, default 0.24). */
  bevelStrength?: number;
  /** Per-channel color quantization steps (0 disables, 16-32 for retro, default 24). */
  colorSteps?: number;
  /** Ordered 4x4 Bayer dither strength (0..1, default 0.35). */
  ditherStrength?: number;
}

export interface PixelArtController {
  setVirtualHeight(height: number): void;
  setStyle(opts: Partial<PixelArtOptions>): void;
  dispose(): void;
}

export interface PsxMaterialOptions {
  /** Virtual vertex snapping resolution (default 200). */
  snapHeight?: number;
  /** Subtle per-vertex jitter dampening (default 1.0). */
  aspect?: number;
}

const QUAD_VERT = /* glsl */ `
varying vec2 vUv;
void main() {
  vUv = uv;
  gl_Position = vec4(position.xy, 0.0, 1.0);
}
`;

const PIXEL_COMPOSITE_FRAG = /* glsl */ `
precision highp float;
uniform sampler2D uColor;
uniform sampler2D uNormal;
uniform sampler2D uDepth;
uniform vec2 uVirtualRes;
uniform float uNear;
uniform float uFar;
uniform float uOutlineStrength;
uniform float uBevelStrength;
uniform float uColorSteps;
uniform float uDitherStrength;
varying vec2 vUv;

float linearDepth(vec2 uv) {
  float d = texture2D(uDepth, uv).r;
  float z = d * 2.0 - 1.0;
  return (2.0 * uNear * uFar) / max(1e-4, uFar + uNear - z * (uFar - uNear));
}

float bayer4(vec2 p) {
  int x = int(mod(p.x, 4.0));
  int y = int(mod(p.y, 4.0));
  int idx = y * 4 + x;
  float m = 0.0;
  if (idx == 0) m = 0.0; else if (idx == 1) m = 8.0; else if (idx == 2) m = 2.0; else if (idx == 3) m = 10.0;
  else if (idx == 4) m = 12.0; else if (idx == 5) m = 4.0; else if (idx == 6) m = 14.0; else if (idx == 7) m = 6.0;
  else if (idx == 8) m = 3.0; else if (idx == 9) m = 11.0; else if (idx == 10) m = 1.0; else if (idx == 11) m = 9.0;
  else if (idx == 12) m = 15.0; else if (idx == 13) m = 7.0; else if (idx == 14) m = 13.0; else m = 5.0;
  return (m / 16.0) - 0.5;
}

void main() {
  vec2 pixCoord = floor(vUv * uVirtualRes);
  vec2 uv = (pixCoord + 0.5) / uVirtualRes;
  vec2 tx = 1.0 / uVirtualRes;

  vec3 col = texture2D(uColor, uv).rgb;
  float d0 = linearDepth(uv);
  vec3 n0 = texture2D(uNormal, uv).xyz * 2.0 - 1.0;

  float depthDiff = 0.0;
  float normalDiff = 0.0;
  vec2 offs[4];
  offs[0] = vec2(tx.x, 0.0);
  offs[1] = vec2(-tx.x, 0.0);
  offs[2] = vec2(0.0, tx.y);
  offs[3] = vec2(0.0, -tx.y);

  for (int i = 0; i < 4; i++) {
    vec2 nuv = clamp(uv + offs[i], tx * 0.5, 1.0 - tx * 0.5);
    float dk = linearDepth(nuv);
    depthDiff += max(0.0, dk - d0) / max(1.0, d0 * 0.12);
    vec3 nk = texture2D(uNormal, nuv).xyz * 2.0 - 1.0;
    float bias = dot(n0 - nk, vec3(0.45, 0.78, 0.43));
    if (abs(dk - d0) < max(0.35, d0 * 0.04)) {
      normalDiff += max(0.0, 1.0 - dot(n0, nk)) * smoothstep(0.0, 0.15, bias);
    }
  }

  float silhouette = smoothstep(0.42, 0.85, depthDiff) * uOutlineStrength;
  float bevel = smoothstep(0.28, 0.65, normalDiff) * (1.0 - silhouette) * uBevelStrength;

  col = col * (1.0 - silhouette) + col * bevel * 0.85 + vec3(bevel * 0.08);
  if (uColorSteps > 1.5) {
    float b = bayer4(pixCoord) * uDitherStrength;
    col = floor(clamp(col, 0.0, 1.0) * uColorSteps + b + 0.5) / uColorSteps;
  }
  gl_FragColor = vec4(clamp(col, 0.0, 1.0), 1.0);
}
`;

export function createPixelArtPipeline(game: Game, opts: PixelArtOptions = {}): PixelArtController {
  let virtualHeight = Math.max(90, Math.min(480, Math.round(opts.virtualHeight ?? 240)));
  let outlineStrength = opts.outlineStrength ?? 0.52;
  let bevelStrength = opts.bevelStrength ?? 0.24;
  let colorSteps = opts.colorSteps ?? 24;
  let ditherStrength = opts.ditherStrength ?? 0.35;

  const computeDims = (w: number, h: number): [number, number] => {
    const aspect = Math.max(0.5, w / Math.max(1, h));
    return [Math.max(96, Math.round(virtualHeight * aspect)), virtualHeight];
  };

  let [vw, vh] = computeDims(game.canvas.clientWidth || 640, game.canvas.clientHeight || 360);
  const depthTex = new THREE.DepthTexture(vw, vh);
  depthTex.minFilter = THREE.NearestFilter;
  depthTex.magFilter = THREE.NearestFilter;

  const colorRt = new THREE.WebGLRenderTarget(vw, vh, {
    minFilter: THREE.NearestFilter,
    magFilter: THREE.NearestFilter,
    depthBuffer: true,
    depthTexture: depthTex,
  });
  const normalRt = new THREE.WebGLRenderTarget(vw, vh, {
    minFilter: THREE.NearestFilter,
    magFilter: THREE.NearestFilter,
    depthBuffer: true,
  });
  const normalMat = new THREE.MeshNormalMaterial();

  const compMat = new THREE.ShaderMaterial({
    vertexShader: QUAD_VERT,
    fragmentShader: PIXEL_COMPOSITE_FRAG,
    uniforms: {
      uColor: { value: colorRt.texture },
      uNormal: { value: normalRt.texture },
      uDepth: { value: depthTex },
      uVirtualRes: { value: new THREE.Vector2(vw, vh) },
      uNear: { value: game.camera.near },
      uFar: { value: game.camera.far },
      uOutlineStrength: { value: outlineStrength },
      uBevelStrength: { value: bevelStrength },
      uColorSteps: { value: colorSteps },
      uDitherStrength: { value: ditherStrength },
    },
    depthTest: false,
    depthWrite: false,
  });
  const quadGeo = new THREE.PlaneGeometry(2, 2);
  const quadCam = new THREE.OrthographicCamera(-1, 1, 1, -1, 0, 1);
  const quadScene = new THREE.Scene();
  quadScene.add(new THREE.Mesh(quadGeo, compMat));

  const sizeScratch = new THREE.Vector2();
  const baseRender = game.render.bind(game);

  function syncTargets(): void {
    const w = game.canvas.clientWidth || game.canvas.width || 640;
    const h = game.canvas.clientHeight || game.canvas.height || 360;
    game.renderer.getSize(sizeScratch);
    if (sizeScratch.x !== w || sizeScratch.y !== h) {
      game.renderer.setSize(w, h, false);
    }
    if (game.camera.aspect !== w / h) {
      game.camera.aspect = w / h;
      game.camera.updateProjectionMatrix();
    }
    const [nw, nh] = computeDims(w, h);
    if (nw !== vw || nh !== vh) {
      vw = nw;
      vh = nh;
      colorRt.setSize(vw, vh);
      normalRt.setSize(vw, vh);
      (compMat.uniforms.uVirtualRes.value as THREE.Vector2).set(vw, vh);
    }
  }

  game.render = () => {
    if (game.xr.active) {
      baseRender();
      return;
    }
    syncTargets();
    const r = game.renderer;
    const prevOverride = game.scene.overrideMaterial;
    const prevBg = game.scene.background;

    r.setRenderTarget(colorRt);
    r.render(game.scene, game.camera);

    game.scene.overrideMaterial = normalMat;
    game.scene.background = null;
    r.setRenderTarget(normalRt);
    r.clear(true, true, false);
    r.render(game.scene, game.camera);
    game.scene.overrideMaterial = prevOverride;
    game.scene.background = prevBg;

    compMat.uniforms.uNear.value = game.camera.near;
    compMat.uniforms.uFar.value = game.camera.far;
    compMat.uniforms.uOutlineStrength.value = outlineStrength;
    compMat.uniforms.uBevelStrength.value = bevelStrength;
    compMat.uniforms.uColorSteps.value = colorSteps;
    compMat.uniforms.uDitherStrength.value = ditherStrength;

    r.setRenderTarget(null);
    r.render(quadScene, quadCam);
  };

  return {
    setVirtualHeight(height: number) {
      virtualHeight = Math.max(90, Math.min(480, Math.round(height)));
    },
    setStyle(next: Partial<PixelArtOptions>) {
      if (next.virtualHeight !== undefined) virtualHeight = Math.max(90, Math.min(480, Math.round(next.virtualHeight)));
      if (next.outlineStrength !== undefined) outlineStrength = next.outlineStrength;
      if (next.bevelStrength !== undefined) bevelStrength = next.bevelStrength;
      if (next.colorSteps !== undefined) colorSteps = next.colorSteps;
      if (next.ditherStrength !== undefined) ditherStrength = next.ditherStrength;
    },
    dispose() {
      game.render = baseRender;
      colorRt.dispose();
      normalRt.dispose();
      depthTex.dispose();
      normalMat.dispose();
      compMat.dispose();
      quadGeo.dispose();
    },
  };
}

/** Quantizes a camera position along its local right/up axes to eliminate pixel-crawl shimmer. */
const _snapRight = new THREE.Vector3();
const _snapUp = new THREE.Vector3();
export function snapCameraToTexelGrid(
  camera: THREE.Camera,
  worldUnitsPerPixel: number
): void {
  if (worldUnitsPerPixel <= 1e-5) return;
  camera.updateMatrixWorld();
  _snapRight.setFromMatrixColumn(camera.matrixWorld, 0).normalize();
  _snapUp.setFromMatrixColumn(camera.matrixWorld, 1).normalize();
  const rx = camera.position.dot(_snapRight);
  const ry = camera.position.dot(_snapUp);
  const dx = Math.round(rx / worldUnitsPerPixel) * worldUnitsPerPixel - rx;
  const dy = Math.round(ry / worldUnitsPerPixel) * worldUnitsPerPixel - ry;
  camera.position.addScaledVector(_snapRight, dx).addScaledVector(_snapUp, dy);
}

/**
 * Patches a Three.js material for authentic PS1/PSX clip-space vertex grid snapping
 * (zero extra render passes — works in flat play and VR stereo).
 */
export function applyPsxMaterial(
  material: THREE.MeshStandardMaterial | THREE.MeshLambertMaterial,
  opts: PsxMaterialOptions = {}
): void {
  const snapH = Math.max(60, opts.snapHeight ?? 180);
  const snapW = Math.round(snapH * (opts.aspect ?? 16 / 9));
  material.customProgramCacheKey = () => `ccgd-psx-snap-${snapW}x${snapH}`;
  material.onBeforeCompile = (shader) => {
    shader.uniforms.uPsxGrid = { value: new THREE.Vector2(snapW, snapH) };
    shader.vertexShader = shader.vertexShader
      .replace('#include <common>', '#include <common>\nuniform vec2 uPsxGrid;')
      .replace(
        '#include <project_vertex>',
        /* glsl */ `
        #include <project_vertex>
        vec4 snapped = gl_Position;
        snapped.xyz = gl_Position.xyz / max(0.0001, gl_Position.w);
        snapped.xy = floor(uPsxGrid * snapped.xy + 0.5) / uPsxGrid;
        snapped.xyz *= gl_Position.w;
        gl_Position = snapped;
        `
      );
  };
  material.needsUpdate = true;
}

Browser, Mobile & Software-Renderer Budgets

  • Actually Faster Than Native Res: Rendering the 3D scene + normal pass at 426×240 shades ~10x fewer fragments than 1080p, making this one of the fastest looks on phones and headless SwiftShader captures.
  • Avoid Double Post-Processing: Do not chain game.enableBloom() alongside createPixelArtPipeline (both override rendering); use emissive accents + bevelStrength directly.
  • VR Safety: createPixelArtPipeline automatically falls back to baseRender() while game.xr.active is true; applyPsxMaterial stays safe in VR headsets (use gentle snapHeight >= 240 for stereo comfort).

Verification Checklist

  1. Run compile (threeCompile) and verify zero TypeScript, three-lint, or WebGL shader errors.
  2. Inspect a capture at virtualHeight = 240: verify crisp 1-pixel silhouettes around characters/props, bright bevel highlights on top box edges, and opaque canvas alpha.
  3. Move the camera slowly in play mode and confirm snapCameraToTexelGrid prevents shimmering on static architecture.

Official references

  • pizzafaceopossum — threejs-pixel-shader (MIT)
  • leopeltola — 3D Pixel Art Edge Highlight Reference (MIT)
  • scolastico — PSX Visuals Vertex Snapping Reference (MIT)
  • Lucas Pope & t3ssel8r (Texel-Snapped 3D Pixel Art Camera Notes)

Open-source sources

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.

rendering

Jump Flood Algorithm (JFA) Screen-Space Outlines & Selection Glows in Three.js →

WebGL 2 Jump Flood Algorithm (JFA) screen-space distance field pipeline in Three.js r183 producing crisp wide outlines, smooth hover/selection halos, and pulsing highlights in O(log R) passes with VR bypass.

atmosphere

Baked 3D Volumetric Cloud Sea, World-Anchored Marching & TAA in Three.js →

Endless fly-above volumetric cloud sea in Three.js r183 WebGL 2 using a GPU-baked WebGL3DRenderTarget SDF and lighting volume, anti-boiling world-anchored z-plane marching, 3-octave Henyey-Greenstein scattering, and variance-clamped depth-packed TAA.

physics

BVH Mesh & Character Capsule Collision in Three.js →

Fast capsule-vs-triangle pushout and slope resolution using three-mesh-bvh shapecasts, pre-allocated scratch vectors, and CollisionWorld.

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