1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92
| static bool insideTriangle(float x, float y, const Vector3f* _v) { int flag = -1;
for(int i = 0; i < 3; i++) { Eigen::Vector3f p0 = {x, y, 0}; Eigen::Vector3f p1 = _v[i]; Eigen::Vector3f p2 = _v[(i+1)%3]; Eigen::Vector3f v1 = p1-p0; Eigen::Vector3f v2 = p1-p2;
if(cp == 0) continue;
int sign = cp < 0 ? 0: 1; if(flag == -1) flag = sign; if(flag != sign) return false; }
return true; }
float dy[] = {0.25, 0.75, 0.25, 0.75};
void rst::rasterizer::rasterize_triangle(const Triangle& t) { auto v = t.toVector4(); int min_x = INT_MAX; int max_x = INT_MIN; int min_y = INT_MAX; int max_y = INT_MIN;
for (auto point : v) min_x = min((float)min_x, point[0]); max_x = max((float)max_x, point[0]); min_y = min((float)min_y, point[1]); max_y = max((float)max_y, point[1]); } { for (int x = min_x; x < max_x; x++) { for(int i=0;i<4;i++) { float xx = (double)x + dx[i]; float yy = (double)y + dy[i];
if (insideTriangle(xx, yy, t.v)) { auto[alpha, beta, gamma] = computeBarycentric2D(x+0.5, y+0.5, t.v); float w_reciprocal = 1.0/(alpha / v[0].w() + beta / v[1].w() + gamma / v[2].w()); float z_interpolated = alpha * v[0].z() / v[0].w() + beta * v[1].z() / v[1].w() + gamma * v[2].z() / v[2].w(); z_interpolated *= w_reciprocal;
{ color_list[get_index(x, y)*4+i] = t.getColor();
Eigen::Vector3f new_color(0.0f, 0.0f, 0.0f); for(int j=0;j<4;j++) new_color += color_list[get_index(x, y)*4+j]; new_color /= 4;
set_pixel(p, new_color); } } } } } }
|