fillTriangle(vv0, vv1, vv2, color0, color1, color2) { const { width, height,…
- User
fillTriangle(vv0, vv1, vv2, color0, color1, color2) { const { width, height, imageBuffer, depthBuffer } = this;
codeconst sortedVertices = [vv0, vv1, vv2].sort((a, b) => a[1] - b[1]); const [vv0Sorted, vv1Sorted, vv2Sorted] = sortedVertices; function barycentric(px, py, v0, v1, v2) { const denom = (v1[1] - v2[1]) * (v0[0] - v2[0]) + (v2[0] - v1[0]) * (v0[1] - v2[1]); if (denom === 0) return [-1, -1, -1]; const w0 = ((v1[1] - v2[1]) * (px - v2[0]) + (v2[0] - v1[0]) * (py - v2[1])) / denom; const w1 = ((v2[1] - v0[1]) * (px - v2[0]) + (v0[0] - v2[0]) * (py - v2[1])) / denom; const w2 = 1 - w0 - w1; return [w0, w1, w2]; } const yStart = Math.max(0, Math.ceil(vv0Sorted[1])); const yEnd = Math.min(height - 1, Math.floor(vv2Sorted[1])); for (let y = yStart; y <= yEnd; y++) { let xStart = width, xEnd = 0; for (const [v1, v2] of [[vv0Sorted, vv1Sorted], [vv1Sorted, vv2Sorted], [vv2Sorted, vv0Sorted]]) { if (y < Math.min(v1[1], v2[1]) || y > Math.max(v1[1], v2[1])) continue; const t = (y - v1[1]) / (v2[1] - v1[1]); const x = v1[0] + t * (v2[0] - v1[0]); xStart = Math.min(xStart, x); xEnd = Math.max(xEnd, x); } xStart = Math.max(0, Math.ceil(xStart)); xEnd = Math.min(width - 1, Math.floor(xEnd)); for (let x = xStart; x <= xEnd; x++) { const [w0, w1, w2] = barycentric(x, y, vv0, vv1, vv2); if (w0 < 0 || w1 < 0 || w2 < 0) continue; let index = y * width + x; const zInterpolated = 1 / (w0 / vv0[2] + w1 / vv1[2] + w2 / vv2[2]); if (zInterpolated < depthBuffer[index]) { depthBuffer[index] = zInterpolated; const interpolatedColor = w0 * color0 + w1 * color1 + w2 * color2; const shadedColor = [ interpolatedColor, interpolatedColor, interpolatedColor, 255 ]; index *= 4; imageBuffer.data[index] = shadedColor[0]; imageBuffer.data[index + 1] = shadedColor[1]; imageBuffer.data[index + 2] = shadedColor[2]; imageBuffer.data[index + 3] = shadedColor[3]; } } } } - Assistant