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) comprising:
V, a set of vertices where each vertex v=(vx,vy,vz) is an ordered triplet of coordinates with vx,vy,vz∈R
F, a set of faces where each face f=(vn,vo,vp) with vn,vo,vp∈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∪FbFf∩Fb=∅
Where:
Ff represents the subset of forward-facing faces.
Fb 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∈R3 ) and a direction (our vview 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^ and any point vn∈P we can define the plane as,
∀v∈P,wheren^⊥Pandvn∈P,thenn^⋅(v−vn)=0
Algebraic Method for a Plane
We can derive the general form for a plane algebraically, if we know n^⊥P we can find any other point v∈P,
ax−ax0+by−by0+cz−cz0=0ax+by+cz=ax0+by0+cz0Letd=ax0+by0+cz0∴ax+by+cz=di.e. the general form for a plane.
Intuitively thinking about this, the coefficients a, b, care the vector components of the plane's normal. The d value expresses how far the plane is from the origin (also meaning that d=0 passes through the origin) and it is calculatable using components of vn and the face normal n^.
View Vector and Plane intersection "Raycast"
The view vector vview is a ray that intersects with any plane that its not parallel with. The intersection point vq can be defined by,
vq=oorigin+tvview
Intuitively thinking about this, we are looking for the vector between the origin and the plane in the view direction. Finding the scale factor t of vview to intercept P,
n^⋅(v−vn)=0#Substitute,vqforvn^⋅((oorigin+tvview)−vn)=0#Rearrange,n^⋅((oorigin−vn)+(tvview))=0#Distributen^,n^⋅(oorigin−vn)+n^⋅(tvview)=0#Rearrange, t is a scalar constantn^⋅(oorigin−vn)+t(n^⋅vview)=0#Subtract,n^⋅(oorigin−vn)and distribute the negative.t(n^⋅vview)=n^⋅(vn−oorigin)#Divide,(n^⋅vview)t=n^⋅vviewn^⋅(vn−oorigin)
We can now find the coordinates of vq∈P using t. If vview is normalised then the distance from oorigin to vq is t. Otherwise, the distance from oorigin to vq is ∥vq−oorigin∥=t∥vview∥.
When n^⋅vview=0, the vview is parallel to P and they never intersect leaving t undefined.
Mesh Face View Intercept Check
Given we can calculate t, the scale factor locating the intercept point vq on plane P, we need to verify that vq is inside the face f=(vn,vo,vp) on P using an edge-side test.
#Find all 3 edges offLete1=vo−vnLete2=vp−voLete3=vn−vp#Find the 3 edges betweenvqand each ofvn,vo,vpLetc1=vq−vnLetc2=vq−voLetc3=vq−vpIfsign((e1×c1)⋅n^)=sign((e2×c2)⋅n^)=sign((e3×c3)⋅n^)thenvqinterceptsPinsidef.
Ray-Triangle Intersection
The two steps above, finding t on the plane and then checking that vq is inside f, are what a ray-triangle intersection test does. The implementation uses the Möller–Trumbore algorithm1, which does both at once. It writes vq in barycentric coordinates(u,v) of the face,
vq=(1−u−v)vn+uvo+vvp
and solves for t, u and v together. The ray hits inside f when u≥0, v≥0 and u+v≤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 −vview. 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) is therefore tested from four sample points, its three vertices and its centroid,
S(f)={vn,vo,vp,cf}wherecf=31(vn+vo+vp)
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=0. A hit only counts when t>ε, where ε 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:#assumehiddenuntilasamplepointisseenLetoccluded=trueFor each s∈S(f):#casttherays+t(−vview)againsteveryotherfaceLetblocked=∃g∈Ff∖{f}:tg>εIf¬blockedthenoccluded=falseIfoccludedthen discardfelsefis visible
With n=∣Ff∣ faces and four rays per face, the processing complexity is O(n2). 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 vview. 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^ and w^ that span the plane perpendicular to vview. Projecting a point onto that plane is two dot products,
π(v)=(v⋅u^,v⋅w^)
The footprint of a face is the bounding box of its three projected vertices. The footprints are binned into an m×m grid with m≈n, which gives about one face per cell. A ray from s only needs testing against the faces in the cell that holds π(s), and only those whose footprint contains π(s),
For each f∈Ff, bin f into every cell its footprint overlapsFor each f∈Ff:For each s∈S(f):#onlythefaceswhosefootprintcoverstherayLetGs={g∈cell(π(s)):π(s)∈footprint(g)}Letblocked=∃g∈Gs∖{f}:tg>ε(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) 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).
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 Ff, 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 Ff 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 };}
The Möller–Trumbore intersection returns t, 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;}
A ray from a sample point is blocked by a face when it crosses it further away than ε.
// 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;}
// 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]);}
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 };}
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 };}
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 };}
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 vview 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):
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); 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.
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.52. ↩