Occlusion Culling

Introduction

Occlusion culling is the fundamental operation in which faces of a geometric mesh are discarded if they are being obstructed by other objects and therefore not visible from a viewing direction.

The wider use case motivating this article is where three-dimensional real-world geometry is being pre-processed in a process to find a two-dimensional spatial representation for usage within a Geographical Information System (GIS). The most common spatial representation is looking directly down with an orthogonal view onto a flat plane of spatial shapes. In reality, things are more complex with a modern map (consider the buildings that are available in the built-up areas on a lot of maps) but this article will follow the simpler paradigm. The objective is to view our mesh from a view vector looking directly downwards. Essentially we are creating top-down two-dimensional silhouette corresponding to the three-dimensional geometry as it would be seen from above.

This article will focus on taking a Back-face culled mesh of the geometry (made up of vertices and triangle faces) alongside a view point as inputs and explain in detail the step to implement a process to discard any occluded polygons.

Definition & Method

The following section provides a formal definition of our occlusion culling processes.

Mesh Definition

We have a mesh M=(V,F)M = (V, F) comprising:

  • VV, a set of vertices where each vertex v=(vx,vy,vz)v = (v_{x}, v_{y}, v_{z}) is an ordered triplet of coordinates with vx,vy,vz∈Rv_{x}, v_{y}, v_{z} \in \mathbb{R}
  • FF, a set of faces where each face f=(vn,vo,vp)f = (v_{n},v_{o},v_{p}) with vn,vo,vp∈Vv_{n},v_{o},v_{p} \in V using a clockwise orientation for the representation of front-facing polygons

Building upon our Back-face culling article we also have the following:

F=Ff∪FbF = F_{f} \cup F_{b} Ff∩Fb=∅F_{f} \cap F_{b} = \emptyset

Where:

  • FfF_{f} represents the subset of forward-facing faces.
  • FbF_{b} represents the subset of backward-facing faces.

View Point Definition

The view point is extended from a direction in the Back-face culling to an origin in space (formally oorigin∈R3o_{origin} \in \mathbb{R}^3 ) and a direction (our v⃗view\vec{v}_{view} representation).

Mesh Face Plane

Geometric representation for a Plane

Fundamentally, the dot product of any vector on a plane and the plane normal is equal to zero. Expressing this formally, if we know n^\hat{n} and any point vn∈Pv_{n} \in P we can define the plane as,

∀v∈P, where n^⊥P and vn∈P, thenn^⋅(v−vn)=0\forall v \in P, \:\text{where}\:\hat{n} \perp P \:\text{and}\: v_{n} \in P, \:\text{then} \quad \hat{n} \cdot (v-v_n) = 0

Algebraic Method for a Plane

We can derive the general form for a plane algebraically, if we know n^⊥P\hat{n} \perp P we can find any other point v∈Pv \in P,

Let n^=(a,b,c)Let vn=(x0,y0,z0)Let v=(x,y,z) and v∈P\color{#1b3a4bcc} \quad\normalsize Let\: \hat{n} = (a, b, c) \\ \color{#1b3a4bcc} \quad\normalsize Let\: v_n = (x_0, y_0, z_0) \\ \color{#1b3a4bcc} \quad\normalsize Let\: v = (x, y, z) \:\text{and}\: v \in P\\

Given n^⋅(v−vn)=0\hat{n} \cdot (v-v_n) = 0 substitute in n^\hat{n}, vnv_n and vv,

(a,b,c)⋅((x,y,z)−(x0,y0,z0))=0(a,b,c)⋅(x−x0,y−y0,z−z0)=0a(x−x0)+b(y−y0)+c(z−z0)=0\color{#1b3a4bcc} \quad\normalsize (a, b, c) \cdot ((x,y,z) - (x_0, y_0, z_0)) = 0 \\ \color{#1b3a4bcc} \quad\normalsize (a, b, c) \cdot (x-x_0,y-y_0,z-z_0) = 0 \\ \color{#1b3a4bcc} \quad\normalsize {{a}(x-x_0)} + {{b}(y-y_0)} + {{c}(z-z_0)} = 0\\

Expand and rearrange,

ax−ax0+by−by0+cz−cz0=0ax+by+cz=ax0+by0+cz0Let d=ax0+by0+cz0∴ax+by+cz=d  i.e. the general form for a plane.\color{#1b3a4bcc} \quad\normalsize ax - ax_0 + by - by_0 + cz - cz_0 = 0\\ \color{#1b3a4bcc} \quad\normalsize ax + by + cz = {ax_0} + {by_0} + {cz_0}\\ \color{#1b3a4bcc} \quad\normalsize\text{Let\:}d = {ax_0} + {by_0} + {cz_0}\\ \color{#1b3a4bcc} \quad\normalsize\therefore ax+by+cz=d \text{\:\:i.e. the general form for a plane.}

Intuitively thinking about this, the coefficients aa, bb, cc are the vector components of the plane's normal. The dd value expresses how far the plane is from the origin (also meaning that d=0d=0 passes through the origin) and it is calculatable using components of vnv_{n} and the face normal n^\hat{n}.

View Vector and Plane intersection "Raycast"

The view vector v⃗view\vec{v}_{view} is a ray that intersects with any plane that its not parallel with. The intersection point vqv_q can be defined by,

vq=oorigin+tv⃗viewv_q = o_{origin} + t \vec{v}_{view}

Intuitively thinking about this, we are looking for the vector between the origin and the plane in the view direction. Finding the scale factor tt of v⃗view\vec{v}_{view} to intercept PP,

n^⋅(v−vn)=0# Substitute, vq for vn^⋅((oorigin+tv⃗view)−vn)=0# Rearrange,n^⋅((oorigin−vn)+(tv⃗view))=0# Distribute n^, n^⋅(oorigin−vn)+n^⋅(tv⃗view)=0# Rearrange, t is a scalar constantn^⋅(oorigin−vn)+t(n^⋅v⃗view)=0# Subtract, n^⋅(oorigin−vn) and distribute the negative.t(n^⋅v⃗view)=n^⋅(vn−oorigin)# Divide, (n^⋅v⃗view)t=n^⋅(vn−oorigin)n^⋅v⃗view\color{#1b3a4bcc}\quad\quad\normalsize\hat{n} \cdot (v-v_n) = 0\\ \color{#f2a65a}\quad\quad\small\text{\#\:Substitute,\:}v_q\text{\:for\:}v \\ \color{#1b3a4bcc}\quad\quad\normalsize\hat{n} \cdot \Big((o_{origin} + t \vec{v}_{view})-v_n\Big) = 0 \\ \color{#f2a65a}\quad\quad\small\text{\#\:Rearrange,} \\ \color{#1b3a4bcc}\quad\quad\normalsize\hat{n} \cdot \Big((o_{origin} - v_n) + (t \vec{v}_{view})\Big) = 0\\ \color{#f2a65a}\quad\quad\small\text{\#\:Distribute\:}\hat{n}\text{,\:} \\ \color{#1b3a4bcc}\quad\quad\normalsize\hat{n} \cdot (o_{origin} - v_n) + \hat{n} \cdot (t \vec{v}_{view})= 0 \\ \color{#f2a65a}\quad\quad\small\text{\#\:Rearrange, t is a scalar constant} \\ \color{#1b3a4bcc}\quad\quad\normalsize\hat{n} \cdot (o_{origin} - v_n) + t (\hat{n} \cdot \vec{v}_{view}) = 0 \\ \color{#f2a65a}\quad\quad\small\text{\#\:Subtract,\:} \hat{n} \cdot (o_{origin} - v_n) \text{\:and distribute the negative.}\\ \color{#1b3a4bcc}\quad\quad\normalsize t (\hat{n} \cdot \vec{v}_{view}) = \hat{n} \cdot (v_n - o_{origin})\\ \color{#f2a65a}\quad\quad\small\text{\#\:Divide,\:} (\hat{n} \cdot \vec{v}_{view})\\ \color{#1b3a4bcc}\quad\quad\normalsize t = \frac{\hat{n} \cdot (v_n - o_{origin})}{\hat{n} \cdot \vec{v}_{view}}\\

We can now find the coordinates of vq∈Pv_q \in P using tt. If v⃗view\vec{v}_{view} is normalised then the distance from oorigino_{origin} to vqv_q is tt. Otherwise, the distance from oorigino_{origin} to vqv_q is ∥vq−oorigin∥=t∥v⃗view∥\Vert{}v_q - o_{origin}\Vert{} = t\Vert{}\vec{v}_{view}\Vert{}.

When n^⋅v⃗view=0\hat{n} \cdot \vec{v}_{view} = 0, the v⃗view\vec{v}_{view} is parallel to PP and they never intersect leaving tt undefined.

Mesh Face View Intercept Check

Given we can calculate tt, the scale factor locating the intercept point vqv_q on plane PP, we need to verify that vqv_q is inside the face f=(vn,vo,vp)f = (v_{n},v_{o},v_{p}) on PP using an edge-side test.

# Find all 3 edges of fLet e⃗1=vo−vnLet e⃗2=vp−voLet e⃗3=vn−vp# Find the 3 edges between vq and each of vn,vo,vpLet c⃗1=vq−vnLet c⃗2=vq−voLet c⃗3=vq−vpIf sign((e⃗1×c⃗1)⋅n^)=sign((e⃗2×c⃗2)⋅n^)=sign((e⃗3×c⃗3)⋅n^) then vq intercepts P inside f.\color{#f2a65a}\quad\quad\small\text{\#\:Find all 3 edges of\:} f\\ \color{#1b3a4bcc}\quad\quad\normalsize\text{Let}\:\vec{e}_1 = v_{o} - v_{n}\\ \color{#1b3a4bcc}\quad\quad\normalsize\text{Let}\:\vec{e}_2 = v_{p} - v_{o}\\ \color{#1b3a4bcc}\quad\quad\normalsize\text{Let}\:\vec{e}_3 = v_{n} - v_{p}\\ \color{#f2a65a}\quad\quad\small\text{\#\:Find the 3 edges between\:} v_q \text{\:and each of\:} v_{n}, v_{o}, v_{p}\\ \color{#1b3a4bcc}\quad\quad\normalsize\text{Let}\:\vec{c}_1 = v_{q} - v_{n}\\ \color{#1b3a4bcc}\quad\quad\normalsize\text{Let}\:\vec{c}_2 = v_{q} - v_{o}\\ \color{#1b3a4bcc}\quad\quad\normalsize\text{Let}\:\vec{c}_3 = v_{q} - v_{p}\\ \\ \color{#1b3a4bcc}\quad\quad\normalsize\text{If}\:\text{sign}\big((\vec{e}_1 \times \vec{c}_1) \cdot \hat{n}\big) = \text{sign}\big((\vec{e}_2 \times \vec{c}_2) \cdot \hat{n}\big) = \text{sign}\big((\vec{e}_3 \times \vec{c}_3) \cdot \hat{n}\big)\text{\:then\:}v_q\text{\:intercepts\:}P\text{\:inside\:}f.

Ray-Triangle Intersection

The two steps above, finding tt on the plane and then checking that vqv_q is inside ff, are what a ray-triangle intersection test does. The implementation uses the Möller–Trumbore algorithm1, which does both at once. It writes vqv_q in barycentric coordinates (u,v)(u, v) of the face,

vq=(1−u−v) vn+u vo+v vpv_q = (1 - u - v)\,v_{n} + u\,v_{o} + v\,v_{p}

and solves for tt, uu and vv together. The ray hits inside ff when u≥0u \geq 0, v≥0v \geq 0 and u+v≤1u + v \leq 1, which is the edge-side test expressed in the face's own coordinates. It never builds the plane equation, so it saves both work and memory.

Occlusion Rule

For the top-down view the ray runs from a point on a face back towards the viewer, in the direction −v⃗view-\vec{v}_{view}. If that ray passes through another forward-facing face, the other face sits between the point and the viewer, and the point is hidden.

A single point is not enough to decide for a whole face. A face can have its centre hidden under an overhang while one of its corners pokes out and is still seen. Each face f=(vn,vo,vp)f = (v_{n},v_{o},v_{p}) is therefore tested from four sample points, its three vertices and its centroid,

S(f)={ vn,  vo,  vp,  cf }wherecf=13(vn+vo+vp)S(f) = \{\, v_{n},\; v_{o},\; v_{p},\; c_{f} \,\} \quad \text{where} \quad c_{f} = \tfrac{1}{3}(v_{n} + v_{o} + v_{p})

and a face is only occluded when every one of its sample points is hidden. If the viewer can see any of them, the face stays.

Rays cast from a vertex start on every face that shares that vertex, so those neighbours would report a hit at t=0t = 0. A hit only counts when t>εt > \varepsilon, where ε\varepsilon is a millionth of the size of the mesh, so the same rule works for a teapot or a dragon.

The rule is an approximation. A large face can be partly visible between its sample points while all four are hidden, and it is then discarded. The exact answer needs each face clipped against the faces in front of it, which is where the Conclusion picks up.

Algorithm Formalisation

Method One: Brute Force

The first method is a greedy approach: every sample point of every forward-facing face is tested against every other forward-facing face (with in-line comments),

For each f∈Ff:# assume hidden until a sample point is seenLet occluded=trueFor each s∈S(f):# cast the ray s+t(−v⃗view) against every other faceLet blocked=∃ g∈Ff∖{f}:tg>εIf ¬ blocked then occluded=falseIf occluded then discard f else f is visible\quad\normalsize\text{For each } f \in F_{f}: \\ \color{#f2a65a} \quad\quad\small\text{\#\:assume\:hidden\:until\:a\:sample\:point\:is\:seen}\\ \color{#1b3a4bcc} \quad\quad\normalsize\text{Let}\:occluded = \text{true}\\ \color{#1b3a4bcc} \quad\quad\normalsize\text{For each } s \in S(f): \\ \color{#f2a65a} \quad\quad\quad\small\text{\#\:cast\:the\:ray\:}s + t(-\vec{v}_{view})\text{\:against\:every\:other\:face}\\ \color{#1b3a4bcc} \quad\quad\quad\normalsize\text{Let}\:blocked = \exists\, g \in F_{f} \setminus \{f\} : t_{g} > \varepsilon\\ \color{#1b3a4bcc} \quad\quad\quad\normalsize\text{If}\:\neg\,blocked \:\text{then}\: occluded = \text{false}\\ \color{#1b3a4bcc} \quad\quad\normalsize\text{If}\:occluded \:\text{then discard}\: f \:\text{else}\: f \:\text{is visible}\\

With n=∣Ff∣n = \vert{}F_{f}\vert{} faces and four rays per face, the processing complexity is O(n2)O(n^2). That is fine for a teapot but it does not scale into detailed geometry and complex scenes, as the results show.

Method Two: Face Grid

Every ray is parallel to v⃗view\vec{v}_{view}. Looking along the view, a ray is a single point, and the only faces it can pass through are the ones whose outline covers that point. Most faces can be ruled out without casting anything.

Choose two unit axes u^\hat{u} and w^\hat{w} that span the plane perpendicular to v⃗view\vec{v}_{view}. Projecting a point onto that plane is two dot products,

π(v)=(v⋅u^,  v⋅w^)\pi(v) = (v \cdot \hat{u},\; v \cdot \hat{w})

The footprint of a face is the bounding box of its three projected vertices. The footprints are binned into an m×mm \times m grid with m≈nm \approx \sqrt{n}, which gives about one face per cell. A ray from ss only needs testing against the faces in the cell that holds π(s)\pi(s), and only those whose footprint contains π(s)\pi(s),

For each f∈Ff, bin f into every cell its footprint overlapsFor each f∈Ff:For each s∈S(f):# only the faces whose footprint covers the rayLet Gs={ g∈cell(π(s)):π(s)∈footprint(g) }Let blocked=∃ g∈Gs∖{f}:tg>ε(the rest as in method one)\quad\normalsize\text{For each } f \in F_{f}, \text{ bin } f \text{ into every cell its footprint overlaps} \\ \quad\normalsize\text{For each } f \in F_{f}: \\ \color{#1b3a4bcc} \quad\quad\normalsize\text{For each } s \in S(f): \\ \color{#f2a65a} \quad\quad\quad\small\text{\#\:only\:the\:faces\:whose\:footprint\:covers\:the\:ray}\\ \color{#1b3a4bcc} \quad\quad\quad\normalsize\text{Let}\:G_{s} = \{\, g \in \text{cell}(\pi(s)) : \pi(s) \in \text{footprint}(g) \,\}\\ \color{#1b3a4bcc} \quad\quad\quad\normalsize\text{Let}\:blocked = \exists\, g \in G_{s} \setminus \{f\} : t_{g} > \varepsilon\\ \color{#1b3a4bcc} \quad\quad\normalsize\text{(the rest as in method one)}\\

The grid only skips faces that a ray cannot hit, so method two gives exactly the same result as method one. Building the grid is O(n)O(n) and each ray tests a handful of faces, so for a mesh spread fairly evenly across the view the whole process is close to O(n)O(n).

Implementation

The following section is an occlusion culling implementation using three.js. Unlike the Back-face culling article, the code below is not a copy: each listing is pulled from culling.js, the module the scene at the end of the article runs. The vector operations (subtract, normalize, crossProduct and dotProduct) are the ones described in the Back-face culling implementation.

Input Geometry

The input geometry is the same as for Back-face culling: the Utah Teapot, the Stanford Bunny and the XYZ RGB Asian Dragon.

Cull Operation Implementation

Back-face Cull

Occlusion culling starts from the forward-facing faces FfF_{f}, so the back-face cull comes first. It is the same algorithm as before, refactored to return the two face sets rather than build meshes, so the occlusion cull can take FfF_{f} straight from it.

// Splits the faces of a mesh by the direction they face, using a view
// direction vector `v_view`: faces whose normals point toward the viewer
// are front faces (F_f), the rest are back faces (F_b).
export function doBackfaceCull(v_view, vSet, fSet) {
	const frontFaces = []; // faces facing the viewer
	const backFaces  = []; // faces facing away

	for (const f of fSet) {
		// Retrieve the 3 vertices of the face
		const [v1, v2, v3] = [vSet[f[0]], vSet[f[1]], vSet[f[2]]];

		// Compute edge vectors of the face
		const e1 = subtract(v2, v1);
		const e2 = subtract(v3, v1);

		// Compute the unit face normal via the cross product
		const normal = normalize(crossProduct(e1, e2));

		// Dot product with view vector determines orientation
		const z = dotProduct(normal, v_view);

		// If the face normal points toward the viewer, keep it
		if (z <= 0) {
			frontFaces.push(f);
		} else {
			backFaces.push(f);
		}
	}

	return { frontFaces, backFaces };
}

From culling.js, the code the scenes run.

Ray-Triangle Intersect

The Möller–Trumbore intersection returns tt, the distance along the ray to the face, or null when the ray misses.

// Möller–Trumbore ray-triangle intersection. Returns the distance t along
// rayDir from rayOrigin to where the ray crosses triangle (v0, v1, v2),
// or null if the ray misses it.
export function rayTriangleIntersect(rayOrigin, rayDir, v0, v1, v2) {
	const EPSILON = 1e-7;

	const edge1 = subtract(v1, v0);
	const edge2 = subtract(v2, v0);
	const h = crossProduct(rayDir, edge2);
	const a = dotProduct(edge1, h);

	if (Math.abs(a) < EPSILON) return null; // ray parallel to triangle

	const f = 1.0 / a;
	const s = subtract(rayOrigin, v0);
	const u = f * dotProduct(s, h);
	if (u < 0 || u > 1) return null;

	const q = crossProduct(s, edge1);
	const v = f * dotProduct(rayDir, q);
	if (v < 0 || u + v > 1) return null;

	const t = f * dotProduct(edge2, q);
	return t > EPSILON ? t : null;
}

From culling.js, the code the scenes run.

Sample Points

The sample points S(f)S(f): the three vertices and the centroid.

// The points of face f that rays are cast from: its three vertices and
// its centroid.
export function samplePoints(vSet, f) {
	const [v1, v2, v3] = [vSet[f[0]], vSet[f[1]], vSet[f[2]]];
	const centroid = [
		(v1[0] + v2[0] + v3[0]) / 3,
		(v1[1] + v2[1] + v3[1]) / 3,
		(v1[2] + v2[2] + v3[2]) / 3,
	];
	return [v1, v2, v3, centroid];
}

From culling.js, the code the scenes run.

Ray Hit Test

A ray from a sample point is blocked by a face when it crosses it further away than ε\varepsilon.

// Does the ray from point p towards the viewer pass through face g?
// Hits closer than minT don't count: a ray cast from a vertex starts on
// every face that shares that vertex, and those faces don't hide it.
export function rayHitsFace(p, toViewer, vSet, g, minT) {
	const t = rayTriangleIntersect(p, toViewer, vSet[g[0]], vSet[g[1]], vSet[g[2]]);
	return t !== null && t > minT;
}

From culling.js, the code the scenes run.

ε\varepsilon is scaled to the size of the mesh.

// The smallest hit distance that counts, scaled to the size of the mesh
// so the same rule works for a teapot or a dragon.
export function minHitDistance(vSet) {
	const lo = [Infinity, Infinity, Infinity];
	const hi = [-Infinity, -Infinity, -Infinity];
	for (const v of vSet) {
		for (let k = 0; k < 3; k++) {
			lo[k] = Math.min(lo[k], v[k]);
			hi[k] = Math.max(hi[k], v[k]);
		}
	}
	return 1e-6 * Math.max(hi[0] - lo[0], hi[1] - lo[1], hi[2] - lo[2]);
}

From culling.js, the code the scenes run.

Brute Force Occlusion Cull

The brute force method, where every sample point of every face is tested against every other face.

// Method one: occlusion culling by brute force. Every sample point of
// every front face casts a ray towards the viewer (-v_view) and is tested
// against every other front face. A face is occluded only if all of its
// rays are blocked: if the viewer can see any of its points, it stays.
// O(n²) in the number of front faces.
export function occlusionCullBruteForce(v_view, vSet, faces) {
	const view = normalize(v_view);
	const toViewer = [-view[0], -view[1], -view[2]];
	const minT = minHitDistance(vSet);

	const visibleFaces  = []; // faces the viewer can see
	const occludedFaces = []; // faces hidden behind others

	faces.forEach((f, i) => {
		const occluded = samplePoints(vSet, f).every(p =>
			faces.some((g, j) => j !== i && rayHitsFace(p, toViewer, vSet, g, minT))
		);
		(occluded ? occludedFaces : visibleFaces).push(f);
	});

	return { visibleFaces, occludedFaces };
}

From culling.js, the code the scenes run.

Face Grid Occlusion Cull

Building the face grid over the footprints. It returns a candidates function giving the faces a ray from a point could hit.

// A 2D grid over the faces' footprints: each face projected onto the
// plane perpendicular to v_view, binned by its bounding box. A ray cast
// along v_view is a single point on that plane, so the only faces it can
// hit are the ones whose footprint covers that point.
export function buildFaceGrid(v_view, vSet, faces) {
	const view = normalize(v_view);

	// Two axes (u, w) spanning the plane perpendicular to the view
	const helper = Math.abs(view[0]) < 0.9 ? [1, 0, 0] : [0, 1, 0];
	const axisU = normalize(crossProduct(view, helper));
	const axisW = crossProduct(view, axisU);
	const project = (v) => [dotProduct(v, axisU), dotProduct(v, axisW)];

	// Each face's footprint: [minU, minW, maxU, maxW]
	const boxes = faces.map(f => {
		const [a, b, c] = f.map(i => project(vSet[i]));
		return [
			Math.min(a[0], b[0], c[0]), Math.min(a[1], b[1], c[1]),
			Math.max(a[0], b[0], c[0]), Math.max(a[1], b[1], c[1]),
		];
	});

	// n x n cells over all the footprints, about one face per cell
	let minU = Infinity, minW = Infinity, maxU = -Infinity, maxW = -Infinity;
	for (const b of boxes) {
		minU = Math.min(minU, b[0]); minW = Math.min(minW, b[1]);
		maxU = Math.max(maxU, b[2]); maxW = Math.max(maxW, b[3]);
	}
	const n = Math.max(1, Math.min(512, Math.ceil(Math.sqrt(faces.length))));
	const cellU = (maxU - minU) / n || 1;
	const cellW = (maxW - minW) / n || 1;
	const cellOf = (u, w) => [
		Math.min(n - 1, Math.max(0, Math.floor((u - minU) / cellU))),
		Math.min(n - 1, Math.max(0, Math.floor((w - minW) / cellW))),
	];

	// Bin every face into each cell its footprint overlaps
	const cells = new Map();
	boxes.forEach((b, i) => {
		const [u0, w0] = cellOf(b[0], b[1]);
		const [u1, w1] = cellOf(b[2], b[3]);
		for (let cu = u0; cu <= u1; cu++) {
			for (let cw = w0; cw <= w1; cw++) {
				const key = cu * n + cw;
				if (!cells.has(key)) cells.set(key, []);
				cells.get(key).push(i);
			}
		}
	});

	// The faces a ray from point p could hit: those in p's cell whose
	// footprint contains p
	function candidates(p) {
		const [u, w] = project(p);
		const [cu, cw] = cellOf(u, w);
		return (cells.get(cu * n + cw) ?? []).filter(j => {
			const b = boxes[j];
			return u >= b[0] && u <= b[2] && w >= b[1] && w <= b[3];
		});
	}

	return { candidates };
}

From culling.js, the code the scenes run.

The occlusion cull itself is the brute force method with faces.some(...) swapped for grid.candidates(p).some(...).

// Method two: occlusion culling with the face grid. The same rule as the
// brute force method, but each ray is only tested against the faces whose
// footprint covers it. The grid only skips faces a ray can't hit, so the
// result is the same.
export function occlusionCullGrid(v_view, vSet, faces) {
	const view = normalize(v_view);
	const toViewer = [-view[0], -view[1], -view[2]];
	const minT = minHitDistance(vSet);
	const grid = buildFaceGrid(view, vSet, faces);

	const visibleFaces  = []; // faces the viewer can see
	const occludedFaces = []; // faces hidden behind others

	faces.forEach((f, i) => {
		const occluded = samplePoints(vSet, f).every(p =>
			grid.candidates(p).some(j => j !== i && rayHitsFace(p, toViewer, vSet, faces[j], minT))
		);
		(occluded ? occludedFaces : visibleFaces).push(f);
	});

	return { visibleFaces, occludedFaces };
}

From culling.js, the code the scenes run.

Cull Operation Result

The following scene runs the back-face cull and then the occlusion cull (method two) on the input meshes. Visible faces are amber, back faces are red and occluded faces are purple. The checkboxes hide the back faces and the occluded faces, and the view button looks down v⃗view\vec{v}_{view} to show that the amber faces alone make up everything seen from above. The panel in the corner shows the face counts and how long the culling took in your browser.

Occlusion Cull Processing

The two methods were timed on the same meshes (Node.js 24 on a Intel Core i5-7Y54):

Mesh Faces Back faces Occluded Visible Method one Method two
Utah Teapot 6,320 2,797 369 3,154 1,352 ms 88 ms
XYZ RGB Dragon 249,882 117,859 29,245 102,778 about 30 min2 760 ms

Conclusion

This article on occlusion culling builds on Back-face culling: from the faces that point towards the viewer, it discards the ones hidden behind other faces. It derives the ray-plane intercept and the inside-face test, uses Möller–Trumbore to do both at once, and decides each face from rays cast at its vertices and its centroid. The brute force method follows the definition directly but is O(n2)O(n^2); the face grid gives the same result in close to linear time, because looking along the view every ray is just a point.

The occluded faces show up where you would expect: under the teapot's lid knob, inside the curve of its handle and under the spout.

Two limitations remain. The sample point rule is an approximation, so a face that is only partly hidden between its sample points can still be discarded. And the grid relies on every ray being parallel, which holds for the orthographic, top-down view used here but not for a perspective view, where rays fan out from the view point.

The next step on the journey to a two-dimensional silhouette of the geometry as seen from above is to stop treating faces as all-or-nothing: clip each visible face against the faces in front of it, project what is left onto the ground plane, and merge the pieces into polygons a GIS can use.

Footnotes

  1. The Möller–Trumbore ray-triangle intersection algorithm based on Möller and Trumbore (1997). "Fast, Minimum Storage Ray-Triangle Intersection". Journal of Graphics Tools. 2: 21–28. ↩

  2. Estimated from the teapot: method one grows with the square of the number of forward-facing faces, and the dragon has about 37 times as many (132,023 against 3,523), so roughly 1,352 ms×37.521{,}352\text{ ms} \times 37.5^2. ↩