render(scene, camera) {
const { width, height, context, lightDirection, depthBuffer, imageBuffer } = this;
if (context) {
if (imageBuffer) imageBuffer.data.fill(0);
else this.imageBuffer = context.createImageData(width, height);
depthBuffer.fill(Infinity);
}
const cameraMatrix = camera.cameraMatrix;
const cameraPosition = camera.position;
const backfaceCulling = camera.backfaceCullingEnabled;
const toScreen = (v) => [
(v[0] / v[3] + 1) * 0.5 * width,
(v[1] / v[3] + 1) * 0.5 * height,
v[2] / v[3]
];
for (const mesh of scene.meshes) {
const {transformMatrix, geometry} = mesh;
const {vertices, vertexNormals, indices} = geometry;
const worldVertices = new Array(vertices.length);
const worldNormals = new Array(vertexNormals.length);
for (let i = 0; i < vertices.length; i++) {
const v = vertices[i];
const n = vertexNormals[i];
worldVertices[i] = fast4x1mul(transformMatrix, [v[0], v[1], v[2], 1]);
worldNormals[i] = normalize(fast4x1mul(transformMatrix, [n[0], n[1], n[2], 0]));
}
const viewVertices = new Array(worldVertices.length);
for (let i = 0; i < worldVertices.length; i++) {
viewVertices[i] = fast4x1mul(cameraMatrix, worldVertices[i]);
}
for (const triangle of indices) {
if (backfaceCulling) {
const [wv0, wv1, wv2] = [
worldVertices[triangle[0]],
worldVertices[triangle[1]],
worldVertices[triangle[2]]
];
const faceNormal = computeNormal(wv0, wv1, wv2);
const camToTri = [
wv0[0] - cameraPosition[0],
wv0[1] - cameraPosition[1],
wv0[2] - cameraPosition[2]
];
if (dotProduct(faceNormal, camToTri) <= 0) {
continue;
}
}
const [vv0, vv1, vv2] = [
viewVertices[triangle[0]],
viewVertices[triangle[1]],
viewVertices[triangle[2]]
];
const [n0, n1, n2] = [
worldNormals[triangle[0]],
worldNormals[triangle[1]],
worldNormals[triangle[2]]
];
let triangles = [[vv0, vv1, vv2]];
let normalSets = [[n0, n1, n2]];
for (const [axis, min, max] of [[0, -1, 1], [1, -1, 1], [2, 0, 1]]) {
const newTriangles = [];
const newNormals = [];
for (let i = 0; i < triangles.length; i++) {
const clipped = clipTriangle(triangles[i], normalSets[i], axis, min, max);
for (const [clippedVertices, clippedNormals] of clipped) {
newTriangles.push(clippedVertices);
newNormals.push(clippedNormals);
}
}
triangles = newTriangles;
normalSets = newNormals;
if (triangles.length === 0) break;
}
for (let i = 0; i < triangles.length; i++) {
const [cV0, cV1, cV2] = triangles[i];
const [nV0, nV1, nV2] = normalSets[i];
const [vv0, vv1, vv2] = [toScreen(cV0), toScreen(cV1), toScreen(cV2)];
const colorV0 = Math.max(0, dotProduct(nV0, lightDirection)) * 255;
const colorV1 = Math.max(0, dotProduct(nV1, lightDirection)) * 255;
const colorV2 = Math.max(0, dotProduct(nV2, lightDirection)) * 255;
this.fillTriangle(vv0, vv1, vv2, colorV0, colorV1, colorV2);
}
}
}
context.putImageData(this.imageBuffer, 0, 0);
}
fillTriangle(v0, v1, v2, color0, color1, color2) {
const { width, height, imageBuffer, depthBuffer } = this;
// Combine vertices with their associated colors
let vertices = [
{ pos: v0, color: color0 },
{ pos: v1, color: color1 },
{ pos: v2, color: color2 },
];
// Sort the vertices by y-coordinate ascending (sv0.y <= sv1.y <= sv2.y)
vertices.sort((a, b) => a.pos[1] - b.pos[1]);
// Unpack the sorted vertices and colors
const [sv0, sv1, sv2] = vertices.map(v => v.pos);
const [sc0, sc1, sc2] = vertices.map(v => v.color);
// Precompute the denominator for barycentric coordinates
const denom = (sv1[1] - sv2[1]) * (sv0[0] - sv2[0]) + (sv2[0] - sv1[0]) * (sv0[1] - sv2[1]);
if (denom === 0) return; // Degenerate triangle
const invDenom = 1 / denom;
// Determine the bounding box of the triangle
const yStart = Math.max(0, Math.ceil(sv0[1]));
const yEnd = Math.min(height - 1, Math.floor(sv2[1]));
// Define the triangle edges for intersection tests
const edges = [
{ v1: sv0, v2: sv1 },
{ v1: sv1, v2: sv2 },
{ v1: sv2, v2: sv0 }
];
for (let y = yStart; y <= yEnd; y++) {
let xMin = width, xMax = 0;
// Find intersection points of the current scanline with the triangle edges
for (const edge of edges) {
const { v1, v2 } = edge;
if (y < Math.min(v1[1], v2[1]) || y > Math.max(v1[1], v2[1])) continue;
const dy = v2[1] - v1[1];
if (dy === 0) continue; // Skip horizontal edges
const t = (y - v1[1]) / dy;
const x = v1[0] + t * (v2[0] - v1[0]);
xMin = Math.min(xMin, x);
xMax = Math.max(xMax, x);
}
// Clamp the x boundaries to the screen dimensions
const xStart = Math.max(0, Math.ceil(xMin));
const xEnd = Math.min(width - 1, Math.floor(xMax));
// Precompute the base index for the current scanline in the buffer
const baseIndex = y * width;
for (let x = xStart; x <= xEnd; x++) {
// Compute barycentric coordinates
const w0 = ((sv1[1] - sv2[1]) * (x - sv2[0]) + (sv2[0] - sv1[0]) * (y - sv2[1])) * invDenom;
const w1 = ((sv2[1] - sv0[1]) * (x - sv2[0]) + (sv0[0] - sv2[0]) * (y - sv2[1])) * invDenom;
const w2 = 1 - w0 - w1;
// Early rejection if the point is outside the triangle
if (w0 < 0 || w1 < 0 || w2 < 0) continue;
// Depth interpolation (assuming z is at index 2)
const zInterpolated = 1 / (w0 / sv0[2] + w1 / sv1[2] + w2 / sv2[2]);
// Buffer index for depth and color
const index = baseIndex + x;
if (zInterpolated < depthBuffer[index]) {
depthBuffer[index] = zInterpolated;
// Perspective-correct color interpolation
const interpolatedColor = (w0 * sc0 + w1 * sc1 + w2 * sc2) / (w0 + w1 + w2);
const shadedColor = [
interpolatedColor,
interpolatedColor,
interpolatedColor,
255
];
const bufferIndex = index * 4;
imageBuffer.data[bufferIndex] = shadedColor[0];
imageBuffer.data[bufferIndex + 1] = shadedColor[1];
imageBuffer.data[bufferIndex + 2] = shadedColor[2];
imageBuffer.data[bufferIndex + 3] = shadedColor[3];
}
}
}
}
}
To enhance the Renderer class with Web Workers for parallel processing, we'll divide the rendering task among multiple workers. Each worker will handle a specific portion of the image, allowing simultaneous rendering and efficient utilization of CPU cores. We'll utilize SharedArrayBuffer to share the depthBuffer and imageBuffer between the main thread and workers, ensuring synchronized access without regions overlapping.
Here's a step-by-step guide to implementing Web Workers in your Renderer class:
Setup Shared Buffers:
Use SharedArrayBuffer for both depthBuffer and imageBuffer.data to allow shared memory access between the main thread and workers.
Initialize these buffers in the main thread and pass them to each worker.
Create the Worker Script:
The worker will receive a portion of the scene and camera data, process it, and write the results directly to the shared buffers.
Since workers operate in separate contexts, we'll create the worker script as a Blob and instantiate workers from it.
Divide the Work Among Workers:
Split the image into horizontal or vertical slices based on the number of workers.
Assign each slice to a different worker to ensure no overlapping regions, eliminating the need for complex synchronization.
Handle Rendering in Workers:
Each worker performs rendering operations on its assigned slice.
Workers update the shared depthBuffer and imageBuffer directly.
Finalize Rendering:
Once all workers complete their tasks, the main thread will update the canvas with the contents of the shared imageBuffer.
Below is the complete implementation incorporating these steps:
javascript
// renderer.js
class Renderer {
constructor({ width = 256, height = 256, context = null, numWorkers = navigator.hardwareConcurrency || 4 } = {}) {
this.width = width;
this.height = height;
this.context = context;
this.numWorkers = numWorkers;
this.workers = [];
this.initBuffers();
this.initWorkers();
this.lightDirection = normalize([0, 0, 1]);
}
initBuffers() {
// Initialize shared buffers
this.depthBuffer = new Float32Array(new SharedArrayBuffer(this.width * this.height * Float32Array.BYTES_PER_ELEMENT));
this.depthBuffer.fill(Infinity);
// Create a shared buffer for image data (RGBA)
this.imageBuffer = new Uint8ClampedArray(new SharedArrayBuffer(this.width * this.height * 4));
this.imageBuffer.fill(0);
}
initWorkers() {
// Create a blob URL for the worker script
const workerScript = `
self.onmessage = function(e) {
const { scene, camera, width, height, lightDirection, depthBuffer, imageBuffer, startY, endY } = e.data;
// Import necessary functions or include them within the worker script
// For simplicity, assume all helper functions are available
// You might need to use importScripts or include the functions directly
function normalize(v) {
const len = Math.hypot(...v);
return v.map(coord => coord / len);
}
function fast4x1mul(matrix, vector) {
const [a, b, c, d,
e, f, g, h,
i, j, k, l,
m, n, o, p] = matrix;
const [x, y, z, w] = vector;
return [
a * x + b * y + c * z + d * w,
e * x + f * y + g * z + h * w,
i * x + j * y + k * z + l * w,
m * x + n * y + o * z + p * w
];
}
function computeNormal(v0, v1, v2) {
const u = [
v1[0] - v0[0],
v1[1] - v0[1],
v1[2] - v0[2]
];
const v = [
v2[0] - v0[0],
v2[1] - v0[1],
v2[2] - v0[2]
];
// Cross product
return normalize([
u[1] * v[2] - u[2] * v[1],
u[2] * v[0] - u[0] * v[2],
u[0] * v[1] - u[1] * v[0]
]);
}
function dotProduct(a, b) {
return a.reduce((sum, val, idx) => sum + val * b[idx], 0);
}
// Add implementations for clipTriangle and other helper functions if necessary
// Function to convert to screen coordinates
const toScreen = (v) => [
(v[0] / v[3] + 1) * 0.5 * width,
(v[1] / v[3] + 1) * 0.5 * height,
v[2] / v[3]
];
// Rendering logic similar to the main thread, but confined to [startY, endY]
const cameraMatrix = camera.cameraMatrix;
const cameraPosition = camera.position;
const backfaceCulling = camera.backfaceCullingEnabled;
for (const mesh of scene.meshes) {
const { transformMatrix, geometry } = mesh;
const { vertices, vertexNormals, indices } = geometry;
const worldVertices = new Array(vertices.length);
const worldNormals = new Array(vertexNormals.length);
for (let i = 0; i < vertices.length; i++) {
const v = vertices[i];
const n = vertexNormals[i];
worldVertices[i] = fast4x1mul(transformMatrix, [v[0], v[1], v[2], 1]);
worldNormals[i] = normalize(fast4x1mul(transformMatrix, [n[0], n[1], n[2], 0]));
}
const viewVertices = new Array(worldVertices.length);
for (let i = 0; i < worldVertices.length; i++) {
viewVertices[i] = fast4x1mul(cameraMatrix, worldVertices[i]);
}
for (const triangle of indices) {
if (backfaceCulling) {
const [wv0, wv1, wv2] = [
worldVertices[triangle[0]],
worldVertices[triangle[1]],
worldVertices[triangle[2]]
];
const faceNormal = computeNormal(wv0, wv1, wv2);
const camToTri = [
wv0[0] - cameraPosition[0],
wv0[1] - cameraPosition[1],
wv0[2] - cameraPosition[2]
];
if (dotProduct(faceNormal, camToTri) <= 0) {
continue;
}
}
const [vv0, vv1, vv2] = [
viewVertices[triangle[0]],
viewVertices[triangle[1]],
viewVertices[triangle[2]]
];
const [n0, n1, n2] = [
worldNormals[triangle[0]],
worldNormals[triangle[1]],
worldNormals[triangle[2]]
];
let triangles = [[vv0, vv1, vv2]];
let normalSets = [[n0, n1, n2]];
for (const [axis, min, max] of [[0, -1, 1], [1, -1, 1], [2, 0, 1]]) {
const newTriangles = [];
const newNormals = [];
for (let i = 0; i < triangles.length; i++) {
const clipped = clipTriangle(triangles[i], normalSets[i], axis, min, max);
for (const [clippedVertices, clippedNormals] of clipped) {
newTriangles.push(clippedVertices);
newNormals.push(clippedNormals);
}
}
triangles = newTriangles;
normalSets = newNormals;
if (triangles.length === 0) break;
}
for (let i = 0; i < triangles.length; i++) {
const [cV0, cV1, cV2] = triangles[i];
const [nV0, nV1, nV2] = normalSets[i];
const [sv0, sv1, sv2] = [toScreen(cV0), toScreen(cV1), toScreen(cV2)];
const colorV0 = Math.max(0, dotProduct(nV0, lightDirection)) * 255;
const colorV1 = Math.max(0, dotProduct(nV1, lightDirection)) * 255;
const colorV2 = Math.max(0, dotProduct(nV2, lightDirection)) * 255;
// Rasterize the triangle within the worker's assigned Y range
fillTriangleWorker(sv0, sv1, sv2, colorV0, colorV1, colorV2, depthBuffer, imageBuffer, width, height, startY, endY);
}
}
}
self.postMessage({ done: true });
};
// Example implementation of fillTriangleWorker
function fillTriangleWorker(v0, v1, v2, color0, color1, color2, depthBuffer, imageBuffer, width, height, startY, endY) {
// Similar to the main thread's fillTriangle but confined to [startY, endY]
// Implement the same logic with direct access to shared buffers
// This is a simplified placeholder
// You should implement the full fillTriangle logic here, ensuring it only writes within [startY, endY]
}
// Implement clipTriangle and any other necessary helper functions within the worker
`;
const blob = new Blob([workerScript], { type: 'application/javascript' });
const workerURL = URL.createObjectURL(blob);
for (let i = 0; i < this.numWorkers; i++) {
const worker = new Worker(workerURL);
this.workers.push(worker);
}
}
render(scene, camera) {
const { width, height, context, lightDirection, depthBuffer, imageBuffer, workers, numWorkers } = this;
if (context) {
context.clearRect(0, 0, width, height);
// Clear image buffer
imageBuffer.fill(0);
// Reset depth buffer
depthBuffer.fill(Infinity);
}
const cameraMatrix = camera.cameraMatrix;
const cameraPosition = camera.position;
const backfaceCulling = camera.backfaceCullingEnabled;
// Split the image vertically among workers
const sliceHeight = Math.ceil(height / numWorkers);
let completedWorkers = 0;
return new Promise((resolve, reject) => {
workers.forEach((worker, index) => {
const startY = index * sliceHeight;
const endY = Math.min(startY + sliceHeight, height);
worker.onmessage = (e) => {
if (e.data.done) {
completedWorkers++;
if (completedWorkers === numWorkers) {
// All workers have finished
if (context) {
// Transfer the imageBuffer to ImageData
const imageData = new ImageData(new Uint8ClampedArray(imageBuffer), width, height);
context.putImageData(imageData, 0, 0);
}
resolve();
}
}
};
const message = {
scene,
camera,
width,
height,
lightDirection,
depthBuffer: depthBuffer.buffer,
imageBuffer: imageBuffer.buffer,
startY,
endY
};
worker.postMessage(message, [depthBuffer.buffer, imageBuffer.buffer]);
});
});
}
// Optional: Add a method to terminate workers when done
terminate() {
this.workers.forEach(worker => worker.terminate());
}
}
// Helper Functions (Assumed to be available in the main thread)
function normalize(v) {
const len = Math.hypot(...v);
return v.map(coord => coord / len);
}
function fast4x1mul(matrix, vector) {
const [a, b, c, d,
e, f, g, h,
i, j, k, l,
m, n, o, p] = matrix;
const [x, y, z, w] = vector;
return [
a * x + b * y + c * z + d * w,
e * x + f * y + g * z + h * w,
i * x + j * y + k * z + l * w,
m * x + n * y + o * z + p * w
];
}
function computeNormal(v0, v1, v2) {
const u = [
v1[0] - v0[0],
v1[1] - v0[1],
v1[2] - v0[2]
];
const v = [
v2[0] - v0[0],
v2[1] - v0[1],
v2[2] - v0[2]
];
// Cross product
return normalize([
u[1] * v[2] - u[2] * v[1],
u[2] * v[0] - u[0] * v[2],
u[0] * v[1] - u[1] * v[0]
]);
}
function dotProduct(a, b) {
return a.reduce((sum, val, idx) => sum + val * b[idx], 0);
}
// Implement the fillTriangle function as in the original Renderer class
// ...
// Usage Example:
// Assuming you have a canvas context
const canvas = document.getElementById('canvas');
const context = canvas.getContext('2d');
const renderer = new Renderer({ width: 800, height: 600, context });
const scene = {
// Define your scene with meshes, transforms, etc.
};
const camera = {
cameraMatrix: [/* 16 elements */],
position: [0, 0, 0],
backfaceCullingEnabled: true
};
renderer.render(scene, camera).then(() => {
console.log('Rendering complete');
// Optionally terminate workers if no longer needed
renderer.terminate();
});
Explanation of the Implementation
Shared Buffers Initialization:
SharedArrayBuffer is used to create depthBuffer and imageBuffer, allowing multiple workers to access and modify these buffers concurrently.
depthBuffer is initialized with Infinity to ensure any rendered depth will be closer initially.
imageBuffer is initialized with zeros, representing a black image.
Worker Script Creation:
The worker script is defined as a string and converted into a Blob URL, allowing dynamic creation of workers without separate files.
Inside the worker, necessary helper functions like normalize, fast4x1mul, and computeNormal are defined. Ensure that all required helper functions (clipTriangle, fillTriangleWorker, etc.) are either included in the worker script or imported using importScripts.
The worker listens for messages containing scene data, camera data, buffer references, and the specific Y-range (startY and endY) it needs to render.
Dividing Work Among Workers:
The image is divided vertically into slices based on the number of available workers (numWorkers).
Each worker receives a unique slice (startY to endY) to render, ensuring that no two workers write to the same portion of the depthBuffer or imageBuffer.
Rendering in Workers:
Workers perform rendering operations only within their assigned Y-range.
Since each worker handles exclusive regions of the image, no synchronization mechanisms like Atomics are needed for buffer access.
After completing their tasks, workers notify the main thread via postMessage.
Finalizing Rendering in the Main Thread:
The main thread waits for all workers to complete rendering.
Once all workers signal completion, the main thread updates the canvas using the imageBuffer.
Optionally, workers can be terminated if they're no longer needed to free up resources.
Important Considerations
Helper Functions in Workers:
Ensure all necessary helper functions (clipTriangle, fillTriangleWorker, etc.) are available within the worker's scope. You might need to include their implementations directly in the worker script or load them using importScripts.
Error Handling:
Implement error handling for workers to catch and manage any unexpected issues during rendering.
Performance Optimization:
Depending on the complexity of the scene and the number of workers, you might need to fine-tune the division of work for optimal performance.
Consider load balancing if certain slices take significantly longer to render than others.
Browser Compatibility:
Ensure that the target browsers support SharedArrayBuffer. Some browsers might have restrictions due to security concerns like Spectre.
Security Headers:
SharedArrayBuffer requires specific HTTP headers (Cross-Origin-Opener-Policy and Cross-Origin-Embedder-Policy) to be set for security reasons. Ensure your server is configured accordingly.
Conclusion
By integrating Web Workers and shared buffers into your Renderer class, you can significantly improve rendering performance through parallel processing. This implementation allows multiple workers to collaborate efficiently, rendering different parts of the image simultaneously while maintaining synchronized access to shared resources.