Rendering Pipeline¶
Detailed architecture of the WebGPU rendering system.
Overview¶
The rendering pipeline (@ifc-lite/renderer) transforms mesh data into pixels on screen. Key design decisions:
- Reverse-Z depth (
depthCompare: 'greater', depth cleared to 0): near-uniform depth precision without a logarithmic depth trick. - Double-sided rendering (
cullMode: 'none'on every pipeline): IFC winding order is not reliably outward, so backface culling is disabled. - Per-entity depth nudge ("z-hash"): the vertex shader hashes the entity ID (Knuth multiplicative hash) into a tiny deterministic depth offset, so coplanar faces from different entities never z-fight.
- Color batching + GPU instancing: non-instanced meshes are merged into per-color batches; repeated mapped geometry renders as instanced shards (one template, many transforms).
WebGPU Architecture¶
Device Initialization¶
Resource Hierarchy¶
Buffer Management¶
Buffer Types¶
Buffer Layout¶
// Vertex buffer layout (packages/renderer/src/pipeline.ts)
const vertexBufferLayout: GPUVertexBufferLayout = {
arrayStride: 28, // 7 * 4 bytes
attributes: [
{ shaderLocation: 0, offset: 0, format: 'float32x3' }, // position
{ shaderLocation: 1, offset: 12, format: 'float32x3' }, // normal
{ shaderLocation: 2, offset: 24, format: 'uint32' }, // entityId (globalId)
]
};
// Interleaved vertex data
// [px, py, pz, nx, ny, nz, entityId, ...]
The per-vertex entityId is the federated global ID (expressId + model idOffset). It drives picking, the selection/ghost highlight, and the anti-z-fighting depth nudge; the low 24 bits are the picking ID and the high 8 bits carry a color salt used by multi-layer walls so coincident layer caps of the SAME parent entity still get distinct nudges.
Shader Architecture¶
Vertex Shader¶
Simplified from packages/renderer/src/shaders/main.wgsl.ts:
struct VertexInput {
@location(0) position: vec3<f32>,
@location(1) normal: vec3<f32>,
@location(2) entityId: u32,
}
struct VertexOutput {
@builtin(position) position: vec4<f32>,
@location(0) worldPos: vec3<f32>,
@location(1) normal: vec3<f32>,
@location(2) @interpolate(flat) entityId: u32,
}
@vertex
fn vs_main(input: VertexInput) -> VertexOutput {
var output: VertexOutput;
let worldPos = uniforms.model * vec4(input.position, 1.0);
output.position = uniforms.viewProjection * worldPos;
// Anti z-fighting: deterministic per-entity depth nudge.
// Knuth multiplicative hash spreads IDs across 0-255; low 24 bits
// are the picking id, high 8 bits a colour salt for layered walls.
let colorSalt = (input.entityId >> 24u) * 2654435761u;
let zHash = (((input.entityId & 0x00FFFFFFu) ^ colorSalt) * 2654435761u) & 255u;
// ... zHash scales a tiny clip-space depth offset ...
output.worldPos = worldPos.xyz;
output.normal = uniforms.normalMatrix * input.normal;
output.entityId = input.entityId;
return output;
}
The instanced variant (vs_instanced) reads the model matrix, entityId, color, and flags per occurrence from the instance buffer instead.
Orthographic geometric visibility (#6729)¶
Orthographic frames first replay the actual opaque draw submissions into an
unbiased depth32float attachment at the scene's MSAA sample count. The
OpaqueVisibilityPass intercepts those submissions, so full and partial
batches, instances, individual meshes and textured draws share the existing
visibility decisions and exact GPU buffers. The derived depth fragment invokes
the original fragment eligibility, preserving clipping and texture cutouts.
Perspective frames return the original render pass directly.
Colour and visible selection/hover masks compare their unbiased geometric depth with the matching prepass sample before applying the existing coplanar depth rank. This prevents hash rank from pulling a farther opaque face through a nearer one. The deliberate hidden-selection silhouette remains independent. Both prepass storage and acceptance use the same sample-interpolated depth; mixing that value with fixed-function MSAA depth does not reliably compare the same raster position on all backends.
Acceptance permits four float32 ULPs for numerical coincidence, independent of entity rank. This is a numerical tie interval, not a physical clearance promise for every positive separation: sufficiently close surfaces at extreme depth ranges can still tie. The paired ray/plane witness requires correct ownership at ¼/30mm separation over 5.2m, 40m and 1km depth ranges, both draw orders, five orbit angles, all mesh vertex families and MSAA ¼. Existing coplanar and clip-plane viewer tests cover the ranking and clipping contracts separately.
The extra depth attachment and opaque replay cost apply to orthographic frames.
GPU timing reports the additional opaque-visibility pass separately. The depth
attachment is released when switching back to perspective. Colour/depth variants
use asynchronous pipeline validation; an orthographic frame that needs a pending
variant is discarded before submission and requested again when validation
finishes. Failed variants reach renderer diagnostics, never an unconstrained
colour-pipeline fallback.
Fragment Shader¶
struct Material {
color: vec4<f32>,
metallic: f32,
roughness: f32,
}
struct Light {
position: vec3<f32>,
color: vec3<f32>,
intensity: f32,
}
The fragment shader (simplified) shades double-sided, applies the section plane / clip box discards, and writes a SECOND render target carrying the entity ID for picking:
```wgsl
struct FragmentOutput {
@location(0) color: vec4<f32>,
@location(1) objectIdEncoded: vec4<f32>, // rgba8unorm, 24-bit entity id
}
@fragment
fn fs_main(input: VertexOutput) -> FragmentOutput {
// Section plane / clip box test (discard clipped fragments)
// ... see Section Planes below ...
// Double-sided lighting: flip the normal toward the viewer
var N = normalize(input.normal);
// ... diffuse + specular + ambient shading ...
var out: FragmentOutput;
out.color = vec4(finalColor, materialAlpha);
out.objectIdEncoded = encodeId24(input.entityId);
return out;
}
Render Loop¶
Frame Structure¶
Command Encoding¶
render(): void {
// Begin frame
const commandEncoder = device.createCommandEncoder();
const renderPass = commandEncoder.beginRenderPass({
colorAttachments: [{
view: context.getCurrentTexture().createView(),
clearValue: { r: 0.95, g: 0.95, b: 0.95, a: 1.0 },
loadOp: 'clear',
storeOp: 'store'
}],
depthStencilAttachment: {
view: depthTexture.createView(),
depthClearValue: 0.0, // Reverse-Z: clear to far (0), test 'greater'
depthLoadOp: 'clear',
depthStoreOp: 'store'
}
});
// Set pipeline
renderPass.setPipeline(renderPipeline);
// Draw color batches (opaque first, then transparent back-to-front)
for (const batch of visibleBatches) {
renderPass.setBindGroup(0, batch.bindGroup);
renderPass.setVertexBuffer(0, batch.vertexBuffer);
renderPass.setIndexBuffer(batch.indexBuffer, 'uint32');
renderPass.drawIndexed(batch.indexCount);
}
// Draw instanced shards (one template, many occurrences)
for (const shard of instancedTemplates) {
renderPass.setPipeline(instancedPipeline);
renderPass.setVertexBuffer(0, shard.vertexBuffer);
renderPass.setVertexBuffer(1, shard.instanceBuffer);
renderPass.setIndexBuffer(shard.indexBuffer, 'uint32');
renderPass.drawIndexed(shard.indexCount, shard.instanceCount);
}
renderPass.end();
// Submit
device.queue.submit([commandEncoder.finish()]);
}
Frustum Culling¶
Culling happens at two granularities: an optional spatial index answers queryFrustum for per-entity visibility, and each color batch / instanced shard is AABB-tested against the frustum planes before it is drawn. If culling fails, the renderer falls back to drawing everything.
Culling Pipeline¶
AABB-Frustum Test¶
interface Frustum {
planes: Plane[]; // 6 planes: near, far, left, right, top, bottom
}
interface AABB {
min: Vector3;
max: Vector3;
}
function isVisible(aabb: AABB, frustum: Frustum): boolean {
for (const plane of frustum.planes) {
// Get positive vertex (furthest along plane normal)
const pVertex = {
x: plane.normal.x > 0 ? aabb.max.x : aabb.min.x,
y: plane.normal.y > 0 ? aabb.max.y : aabb.min.y,
z: plane.normal.z > 0 ? aabb.max.z : aabb.min.z
};
// If positive vertex is behind plane, AABB is outside
if (dot(plane.normal, pVertex) + plane.d < 0) {
return false;
}
}
return true;
}
Selection & Picking¶
ID Buffer Approach¶
ID Encoding¶
The picked ID is the 24-bit picking portion of the per-vertex entityId (the high 8 bits are the colour salt and are masked off), encoded into an rgba8unorm attachment by encodeId24. The pick pass (packages/renderer/src/picker.ts) mirrors the main pass exactly: same discards (section plane, clip box, hidden flags), plus a dedicated instanced pick pipeline for instanced shards, so anything visible is pickable and nothing else.
Alongside the ID, the pick readback samples the depth buffer and unprojects it through the inverse view-projection matrix to get the world-space hit point:
// Reverse-Z: depth = 1 is the near plane, depth = 0 means "missed
// everything" (the clear value survived), so 0 returns null.
function unprojectPickSample(viewProj, pickX, pickY, width, height, depth) {
if (!Number.isFinite(depth) || depth <= 0) return null;
const ndcX = ((pickX + 0.5) / width) * 2 - 1;
const ndcY = 1 - ((pickY + 0.5) / height) * 2;
return transformPoint(invert(viewProj), { x: ndcX, y: ndcY, z: depth });
}
The decoded ID is a global ID; the application resolves it back to { modelId, expressId } via the federation registry (see Federation). A BVH-based CPU raycaster (bvh.ts, raycast-engine.ts) complements GPU picking for snapping and measurement.
Pick routes¶
PickingManager chooses one of three routes per pick (click, hover and rectangle select alike):
| Route | When | What the pick pass draws |
|---|---|---|
| Per-piece meshes | the visible pieces missing a pick mesh fit MAX_PICK_MESH_CREATION (500) |
one GPU mesh per visible piece, hydrated from the CPU copy |
| Colour batches | over that budget, or CPU geometry released (#10264 S1) | the scene's own batch and textured vertex buffers, whole |
| CPU raycast | neither GPU route can answer for every drawable | nothing; triangles (or boxes for a marquee) on the CPU |
The batch route (lane-pick-pass.ts, pick-lane-route.ts) reads the entity from the per-vertex lane the colour pass already uses: the low 24 bits under the batch's anchor, like section exclusions. Flat (28-byte), textured (36-byte) and quantized (12-byte) layouts each have a pipeline variant. Because a batch is drawn whole, hide/isolate is a fragment test against the shared sorted id table (entity-visibility-table.ts, see Batching Strategy); section planes, extra planes, crop boxes and section exclusions discard as in the flat pick pass. Instanced occurrences, point splats and non-hydrated individual meshes share the same pass and depth target. A single click draws only the batches whose bounds the texel-centre line meets, scissored to that texel.
The route never answers partially. It falls back to the CPU raycast when batches are pending a rebuild or being finalized, a batch the ray meets is evicted from the GPU, a batch's ids span more than one 2^24 page or exceed the 30-bit sample, the instanced pick pipeline is missing while instanced occurrences exist, or the backend rejected the batch pipelines. An edit landing while the readback is in flight voids the pick.
Section Planes¶
Clipping Implementation¶
Section Shader¶
The section plane rides in the shared frame uniforms (a vec4: xyz = normal, w = distance) with an enable bit in the flags word; a separate axis-aligned clip box (crop box) discards fragments outside an AABB. Both cuts apply to every model in the federated scene, and the pick pass applies the same discards.
// In Uniforms:
// sectionPlane: vec4<f32>, // xyz = plane normal, w = plane distance
// flags: vec4<u32>, // y = section/clip enable bits
let sectionEnabled = (uniforms.flags.y & 1u) == 1u;
if (sectionEnabled) {
let d = dot(uniforms.sectionPlane.xyz, input.worldPos) - uniforms.sectionPlane.w;
if (d < 0.0) {
discard;
}
}
// Clip box (crop box): discard fragments OUTSIDE the AABB
Section caps and the 2D section overlay are drawn by dedicated passes (section-cap-style.ts, section-2d-overlay.ts).
Transparency¶
Order-Independent Transparency¶
Blend State¶
const transparentPipeline = device.createRenderPipeline({
// ...
fragment: {
targets: [{
format: 'bgra8unorm',
blend: {
color: {
srcFactor: 'src-alpha',
dstFactor: 'one-minus-src-alpha',
operation: 'add'
},
alpha: {
srcFactor: 'one',
dstFactor: 'one-minus-src-alpha',
operation: 'add'
}
}
}]
}
});
Performance Optimization¶
Batching Strategy¶
Meshes sharing a color are merged into one BatchedMesh (one vertex/index buffer, one draw call), reducing N per-mesh draws to roughly 100-500 batches. Per-entity state (selection, hide, ghost) still works inside a batch because the entity ID travels per vertex. A color group whose geometry would exceed the GPU's maxBufferSize is split into overflow buckets automatically.
Hide and isolate inside a batch (#10264 S2). batch-visibility.ts classifies each batch once per visibility change: fully hidden batches are skipped, fully visible ones draw as before, and a partly hidden one draws whole from its own buffers with MESH_FLAG_ENTITY_VISIBILITY set in its mesh uniform. The fragment resolves the full entity id from the vertex lane under the batch's anchor and discards it when entityVisible says so. The table (entity-visibility-table.ts) is one sorted id image per device, bound at group 3 binding 1 beside the section exclusions, so fs_main and everything derived from it (ghost, the orthographic visibility replay), the shadow pass's fragment stage and the batch pick pass read the same rule as isEntityVisible. The renderer uploads it only when the visibility epoch moves. A partly hidden batch that cannot be tested (the table exceeds the device's storage binding limit, or its ids span two 2^24 pages so no lane anchor exists) is left out and counted as not resident; it is never drawn with its hidden entities. Only colour splits still cut sub-batches from CPU pieces: X-Ray alpha and lens promotion, each restricted to the visible ids, and only while the batch can be partitioned; otherwise the batch draws whole under the test at the lowest alpha of its visible entities. Opaque partly hidden draws use the discard pipeline instead of the discard-free twin.
Selection and hover highlight from the batches (#10264 S3). A colour batch holding a selected entity is drawn again at the end of the colour pass, whole, from its own buffers, through the selection pipeline (no depth write, greater-equal); MESH_FLAG_HIGHLIGHTED_ENTITIES makes the fragment keep only the entities of a second sorted id table, the visible selection (entity-highlight-table.ts, group 3 binding 2). The same draws, with the same uniforms, feed the selection outline masks. The hover outline draws the batches holding the hovered entity into the hover mask with MESH_FLAG_ONE_ENTITY, keeping only the entity named in flags.w, so following the pointer never rewrites a shared table. The batch's vertices are the ones the colour pass drew, so the highlight is coincident with them; quantized batches use a quantized selection pipeline and their dequantization uniforms. batch-highlight.ts draws an entity this way only when every batch holding it can: GPU resident, with a lane anchor, and with a highlight pipeline for its layout, and not when another federated model's entry shares its id in a batch while the selection is scoped to one model. Such entities, an item filter (selectedItemId, which the lane cannot carry) while the CPU pieces are in memory, and every entity while the table cannot be held yet keep the per-entity copies built from CPU pieces (selection-hydration.ts), so no entity is highlighted in part. Textured pieces keep borrowing their own buffers, and instanced occurrences keep their per-instance selected flag.
Instancing¶
Repeated mapped geometry (IfcMappedItem) arrives from the geometry pipeline as instanced shards: one template mesh plus per-occurrence data. Occurrence state (hide/select) is updated by rewriting the flags lane; if the backend rejects the instanced pipeline, the same occurrences fall back to CPU-expanded flat meshes with identical visuals (CPU parity).
// Instance buffer layout (packages/renderer/src/pipeline.ts)
const instanceBufferLayout: GPUVertexBufferLayout = {
arrayStride: 88, // mat4 (64) + entityId (4) + rgba (16) + flags (4)
stepMode: 'instance',
attributes: [
{ shaderLocation: 3, offset: 0, format: 'float32x4' }, // instMat col0
{ shaderLocation: 4, offset: 16, format: 'float32x4' }, // col1
{ shaderLocation: 5, offset: 32, format: 'float32x4' }, // col2
{ shaderLocation: 6, offset: 48, format: 'float32x4' }, // col3
{ shaderLocation: 7, offset: 64, format: 'uint32' }, // entityId
{ shaderLocation: 8, offset: 68, format: 'float32x4' }, // rgba
{ shaderLocation: 9, offset: 84, format: 'uint32' }, // flags (bit 0 = selected, bit 1 = hidden)
]
};
// Draw instanced
renderPass.drawIndexed(indexCount, instanceCount);
Frame Statistics¶
Performance Metrics¶
| Metric | Target | Notes |
|---|---|---|
| FPS | 60 | Minimum for smooth |
| Draw calls | < 1000 | Per frame |
| Triangles | < 5M | Visible |
| GPU memory | < 512 MB | Total |
Next Steps¶
- Coordinate Handling - RTC handling for large coordinates
- Overview - System architecture
- API Reference - Renderer API