Optimizing the fillTriangle function involves reducing redundant calculations, minimizing the number of operations within loops, and precomputing values that remain constant throughout the rendering process. Below is an optimized version of your function with explanations of the changes made:
fillTriangle(v0, v1, v2, color0, color1, color2) {
const { width, height, imageBuffer, depthBuffer } = this;
// Sort vertices by ascending y-coordinate using a more efficient method
let vertices = [v0, v1, v2].map((pos, idx) => ({ pos, color: [color0, color1, color2][idx] }));
// Simple bubble sort for 3 elements
if (vertices[1].pos[1] < vertices[0].pos[1]) {
[vertices[0], vertices[1]] = [vertices[1], vertices[0]];
}
if (vertices[2].pos[1] < vertices[1].pos[1]) {
[vertices[1], vertices[2]] = [vertices[2], vertices[1]];
// After swapping vertices[1] and vertices[2], check again if vertices[1] is less than vertices[0]
if (vertices[1].pos[1] < vertices[0].pos[1]) {
[vertices[0], vertices[1]] = [vertices[1], vertices[0]];
}
}
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 constants for barycentric coordinates
const w0_a = sv1[1] - sv2[1];
const w0_b = sv2[0] - sv1[0];
const denom = w0_a * (sv0[0] - sv2[0]) + w0_b * (sv0[1] - sv2[1]);
if (denom === 0) return; // Degenerate triangle
const invDenom = 1 / denom;
const w1_a = sv2[1] - sv0[1];
const w1_b = sv0[0] - sv2[0];
// Calculate bounding box clamped to screen dimensions
const yStart = Math.max(0, Math.floor(sv0[1]));
const yEnd = Math.min(height, Math.ceil(sv2[1]));
// Precompute edge information to reduce calculations inside the loop
const edges = [
{ v1: sv0, v2: sv1 },
{ v1: sv1, v2: sv2 },
{ v1: sv2, v2: sv0 }
];
// Precompute edge bounds to avoid redundant Math.min and Math.max calls
const edgeBounds = edges.map(edge => ({
minY: Math.floor(Math.min(edge.v1[1], edge.v2[1])),
maxY: Math.ceil(Math.max(edge.v1[1], edge.v2[1])),
v1: edge.v1,
v2: edge.v2,
dy: edge.v2[1] - edge.v1[1],
dx: edge.v2[0] - edge.v1[0]
}));
for (let y = yStart; y < yEnd; y++) {
let xMin = width, xMax = -1;
// Iterate through edges to find intersections with the current scanline y
for (let i = 0; i < edgeBounds.length; i++) {
const edge = edgeBounds[i];
if (y < edge.minY || y >= edge.maxY || edge.dy === 0) continue;
// Calculate intersection x using precomputed dx and dy
const t = (y + 0.5 - edge.v1[1]) / edge.dy; // +0.5 for pixel center
const x = edge.v1[0] + t * edge.dx;
if (x < xMin) xMin = x;
if (x > xMax) xMax = x;
}
if (xMax < xMin) continue; // No valid pixels on this scanline
const xStart = Math.max(0, Math.floor(xMin));
const xEnd = Math.min(width, Math.ceil(xMax));
const baseIndex = y * width;
for (let x = xStart; x < xEnd; x++) {
const dx = x - sv2[0];
const dy = y - sv2[1];
// Compute barycentric weights
const w0 = (w0_a * dx + w0_b * dy) * invDenom;
const w1 = (w1_a * dx + w1_b * dy) * 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 with perspective correction
const zInv = w0 / sv0[2] + w1 / sv1[2] + w2 / sv2[2];
const zInterpolated = 1 / zInv;
const index = baseIndex + x;
if (zInterpolated < depthBuffer[index]) {
depthBuffer[index] = zInterpolated;
// Color interpolation
const interpolatedColor = w0 * sc0 + w1 * sc1 + w2 * sc2;
const bufferIndex = index << 2; // Equivalent to index * 4
imageBuffer.data[bufferIndex] = interpolatedColor;
imageBuffer.data[bufferIndex + 1] = interpolatedColor;
imageBuffer.data[bufferIndex + 2] = interpolatedColor;
imageBuffer.data[bufferIndex + 3] = 255; // Alpha channel
}
}
}
}
Optimizations Implemented
-
Efficient Vertex Sorting:
- Original: Three separate
if statements to sort the vertices by their y-coordinates.
- Optimized: Implemented a simple bubble sort tailored for three elements, reducing unnecessary swaps and comparisons.
-
Precomputing Constants:
- w1_a and w1_b: Moved outside the main loop since they are constant for the entire triangle.
- Edge Boundaries: Calculated
minY, maxY, dx, and dy for each edge upfront to avoid recalculating them inside the scanline loop.
-
Reducing Math Operations Inside Loops:
- Intersection Calculation: Precomputed differences (
dx and dy) for each edge to streamline the intersection computation.
- Pixel Center Adjustment: Added
0.5 to y when calculating t to align with pixel centers, which can slightly improve visual accuracy and consistency.
-
Early Rejection:
- Bounding Box Check: If
xMax < xMin, the scanline doesn't intersect with the triangle, allowing an immediate continue to skip unnecessary processing.
- Barycentric Check: Early
continue if any of the barycentric weights are negative, ensuring only pixels inside the triangle are processed.
-
Avoiding Redundant Calculations:
- Base Index: Calculated once per scanline to avoid repeated multiplications.
- Color Interpolation: Computed only when a pixel passes the depth test, reducing unnecessary color calculations.
-
Memory Access Optimization:
- Buffer Indexing: Utilized bit shifting (
index << 2) for faster multiplication by 4 when accessing the imageBuffer.
-
Clamping and Rounding:
- Bounding Box: Used
Math.floor for yStart and Math.ceil for yEnd to ensure all relevant pixels are covered without overstepping.
Additional Recommendations
-
Use Typed Arrays: Ensure that imageBuffer.data and depthBuffer are typed arrays (e.g., Uint8ClampedArray for imageBuffer.data and Float32Array for depthBuffer) to improve performance.
-
Perspective-Correct Interpolation:
- The current implementation includes perspective correction for depth (
zInterpolated). If colors need to be perspective-corrected as well, additional calculations are necessary.
-
Parallel Processing:
- For further optimization, especially for large images or numerous triangles, consider leveraging Web Workers or GPU-based rendering via WebGL.
-
Caching Reusable Values:
- If multiple triangles share vertices, caching shared values can reduce redundant computations.
-
Branch Optimization:
- Minimizing the use of conditional statements (
if checks) inside tight loops can lead to performance gains, as branch prediction failures can be costly.
-
Inline Calculations:
- Where possible, inline simple calculations to reduce function call overhead, especially within loops.
Conclusion
The optimized fillTriangle function reduces redundant calculations, precomputes constant values, and streamlines the iteration process to enhance performance. These changes make the function more efficient, especially when rendering numerous or large triangles. For even greater performance improvements, especially in JavaScript, consider utilizing libraries or WebGL for hardware-accelerated rendering.