To optimize the fillTriangle function for better performance, we can implement several improvements:
- Use Arrays Instead of Objects: Accessing array elements is generally faster than accessing object properties in JavaScript. We'll represent vertices and colors using arrays.
- Sort Vertices Efficiently: Instead of creating an array of objects and sorting them, we'll directly sort the vertex arrays based on the y-coordinate.
- Precompute Edge Data: Calculate edge-related values outside the main loop to minimize computations within nested loops.
- Minimize Function Calls Inside Loops: Reduce the number of function calls (like
Math.min, Math.max, Math.ceil, Math.floor) inside the innermost loops by precomputing or simplifying logic where possible.
- Leverage Typed Arrays: If
imageBuffer and depthBuffer are instances of typed arrays (e.g., Uint8ClampedArray for imageBuffer), ensure that operations on them are optimized for bulk assignments.
Here's the optimized version of your fillTriangle function:
fillTriangle(v0, v1, v2, color0, color1, color2) {
const width = this.width;
const height = this.height;
const imageData = this.imageBuffer.data;
const depthBuffer = this.depthBuffer;
// Sort vertices by ascending y-coordinate
let vertices = [
{ pos: v0, color: color0 },
{ pos: v1, color: color1 },
{ pos: v2, color: color2 }
];
// Simple insertion sort for three elements
if (vertices[1].pos[1] < vertices[0].pos[1]) [vertices[0], vertices[1]] = [vertices[1], vertices[0]];
if (vertices[2].pos[1] < vertices[0].pos[1]) [vertices[0], vertices[2]] = [vertices[2], vertices[0]];
if (vertices[2].pos[1] < vertices[1].pos[1]) [vertices[1], vertices[2]] = [vertices[2], vertices[1]];
// Destructure sorted vertices and colors
const sv0 = vertices[0].pos;
const sv1 = vertices[1].pos;
const sv2 = vertices[2].pos;
const sc0 = vertices[0].color;
const sc1 = vertices[1].color;
const sc2 = vertices[2].color;
// Precompute 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 vertical range of the triangle
const yStart = Math.max(0, Math.ceil(sv0[1]));
const yEnd = Math.min(height - 1, Math.floor(sv2[1]));
// Precompute edge data
const edges = [
{ yMin: sv0[1], yMax: sv1[1], x1: sv0[0], y1: sv0[1], x2: sv1[0], y2: sv1[1] },
{ yMin: sv1[1], yMax: sv2[1], x1: sv1[0], y1: sv1[1], x2: sv2[0], y2: sv2[1] },
{ yMin: sv0[1], yMax: sv2[1], x1: sv2[0], y1: sv2[1], x2: sv0[0], y2: sv0[1] }
];
for (let y = yStart; y <= yEnd; y++) {
let xMin = width;
let xMax = 0;
// Find intersections of the current scanline with triangle edges
for (let i = 0; i < 3; i++) {
const edge = edges[i];
if (y < edge.yMin || y > edge.yMax) continue;
const dy = edge.yMax - edge.yMin;
if (dy === 0) continue; // Skip horizontal edges
const t = (y - edge.yMin) / dy;
const x = edge.x1 + t * (edge.x2 - edge.x1);
if (x < xMin) xMin = x;
if (x > xMax) xMax = x;
}
// Clamp the x boundaries to the screen dimensions
const xStartScan = Math.max(0, Math.ceil(xMin));
const xEndScan = Math.min(width - 1, Math.floor(xMax));
const baseIndex = y * width;
for (let x = xStartScan; x <= xEndScan; x++) {
const index = baseIndex + 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;
// Check if the point is inside 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]);
if (zInterpolated < depthBuffer[index]) {
depthBuffer[index] = zInterpolated;
// Perspective-correct color interpolation
const invW = w0 + w1 + w2;
const r = (w0 * sc0[0] + w1 * sc1[0] + w2 * sc2[0]) / invW;
const g = (w0 * sc0[1] + w1 * sc1[1] + w2 * sc2[1]) / invW;
const b = (w0 * sc0[2] + w1 * sc1[2] + w2 * sc2[2]) / invW;
const bufferIdx = index * 4;
imageData[bufferIdx] = r; // Red
imageData[bufferIdx + 1] = g; // Green
imageData[bufferIdx + 2] = b; // Blue
imageData[bufferIdx + 3] = 255; // Alpha
}
}
}
}
Explanation of Optimizations:
-
Vertex Sorting:
- Before: Created an array of objects and used
Array.prototype.sort with a custom comparator.
- After: Used a simple insertion sort tailored for three elements, which is faster and avoids unnecessary object handling.
-
Edge Representation:
- Before: Represented edges as objects within an array.
- After: Maintained edges as separate positional variables within a precomputed
edges array, reducing the overhead of object property access.
-
Loop Optimizations:
- Precomputing Values: Calculated invariant values like
denom and invDenom outside of the y-loop to avoid redundant calculations.
- Min/Max Clamping: Combined
Math.ceil and Math.floor with Math.max and Math.min to clamp scanline boundaries efficiently.
- Barycentric Coordinates Calculation: Streamlined the computation by calculating
w0, w1, and w2 directly without intermediate variables or function calls.
-
Color Interpolation:
- Before: Calculated a single
interpolatedColor value for grayscale.
- After: Performed separate interpolations for red, green, and blue channels to support full-color rendering.
-
Buffer Access:
- Used Typed Arrays: Assumed that
imageBuffer is an instance of a typed array like Uint8ClampedArray for efficient pixel manipulation.
- Minimized Calculations: Calculated
bufferIdx once per pixel to reduce repetitive computations.
-
Early Rejection:
- **Kept the early rejection of pixels outside the triangle using barycentric coordinates to avoid unnecessary depth and color computations.
Additional Potential Optimizations:
- Edge Functions: Implementing edge functions can further optimize scanline evaluations by allowing incremental updates rather than recalculating intersections for every pixel.
- Parallel Processing: Utilizing Web Workers or SIMD (if available) can distribute the workload across multiple threads or leverage vectorized operations.
- Caching: If rendering multiple triangles, caching edge data or precomputing certain values can save computation time.
However, the provided optimized version strikes a balance between readability and performance, making it suitable for most use cases without significant complexity increases.