GAMES101 作业2

作品要求

• rasterize_triangle(): 执行三角形栅格化算法
• static bool insideTriangle(): 测试点是否在三角形内。

第一步:

创建三角形的 2 维 bounding box。

第二步:

遍历此 bounding box 内的所有像素(使用其整数索引)。然后,使用像素中
心的屏幕空间坐标来检查中心点是否在三角形内。

第三步:

如果在内部,则将其位置处的插值深度值 (interpolated depth value) 与深度
缓冲区 (depth buffer) 中的相应值进行比较。

第四步:

 如果当前点更靠近相机,设置像素颜色并更新深度缓冲区 (depth buffer)。

static bool insideTriangle(int x, int y, const Vector3f* _v)//判断点是否在三角形捏内
{   
    Eigen::Vector3f p1, p2, p;
    double t1, t2, t3;
    p1 << _v[1].x() - _v[0].x(), _v[1].y() - _v[0].y(), 0;
    p2 << x*1.0 + 0.5 - _v[0].x(), y*1.0 + 0.5 - _v[0].y(), 0;
    p = p1.cross(p2);
    t1 = p(2);
    p1 << _v[2].x() - _v[1].x(), _v[2].y() - _v[1].y(), 0;
    p2 << x*1.0 + 0.5 - _v[1].x(), y*1.0 + 0.5 - _v[1].y(), 0;
    p = p1.cross(p2);
    t2 = p(2);
    p1 << _v[0].x() - _v[2].x(), _v[0].y() - _v[2].y(), 0;
    p2 << x*1.0 + 0.5 - _v[2].x(), y*1.0 + 0.5 - _v[2].y(), 0;
    p = p1.cross(p2);
    t3 = p(2);
    if((t1>0 && t2>0 && t3>0) || (t1<0 && t2<0 && t3<0) ) return true;
    return false;
}
void rst::rasterizer::rasterize_triangle(const Triangle& t) {
    auto v = t.toVector4();
    int x1, y1, x2, y2;
    x1 = std::floor(std::min(v[0].x(), std::min(v[1].x(), v[2].x())));
    y1 = std::floor(std::min(v[0].y(), std::min(v[1].y(), v[2].y())));
    x2 = std::ceil(std::max(v[0].x(), std::max(v[1].x(), v[2].x())));
    y2 = std::ceil(std::max(v[0].y(), std::max(v[1].y(), v[2].y())));
//寻找bounding box的边界再遍历
    for(int x=x1; x<=x2; x++)
        for(int y=y1; y<=y2; y++)
            if(insideTriangle(x, y, t.v)){//判断屏幕空间坐标是否在三角形内
                auto[alpha, beta, gamma] = computeBarycentric2D(x*1.0 + 0.5, y*1.0 + 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;//得到插值深度
                int ind = get_index(x, y);
                if(z_interpolated < depth_buf[ind]){//是否更新深度缓存和颜色缓存
                    depth_buf[ind] = z_interpolated;
                    Eigen::Vector3f p;
                    p << x, y, z_interpolated;
                    set_pixel(p, t.getColor());
                }
            }
}

评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值