我正在为我的计算机图形课程编写一个光线追踪程序。到目前为止,我只实现了球体和阴影射线。当前的问题是,当我将球体移离中心时,它会伸展。这是我用来计算光线是否与球体相交的代码:
bool Sphere::onSphere(Ray r)
{
float b = (r.dir*2).innerProduct(r.pos + centre*-1);
float c = (r.pos + centre*-1).innerProduct(r.pos + centre*-1) - radius*radius;
return b*b - 4*c >= 0;
}
这是我用来产生每条射线的代码:
for(int i = -cam.width/2; i < cam.width/2; i++)
{
for(int j = -cam.height/2; j < cam.height/2; j++)
{
float normi = (float)i;
float normj = (float)j;
Vector pixlePos = cam.right*normi + cam.up*normj + cam.forward*cam.dist + cam.pos*1;
Vector direction = pixlePos + cam.pos*-1;
direction.normalize();
Vector colour = recursiveRayTrace(Ray(pixlePos, direction), 30, 1, 0);
float red = colour.getX()/255;
float green = colour.getY()/255;
float blue = colour.getZ()/255;
fwrite (&red, sizeof(float), 1, myFile);
fwrite (&green, sizeof(float), 1, myFile);
fwrite (&blue, sizeof(float), 1, myFile);
}
}
递归RayTrace:
Vector Scene::recursiveRayTrace(Ray r, float maxDist, int maxBounces, int bounces)
{
if(maxBounces < bounces)
return Vector(0,0,0);
int count = 0;
for(int i = 0; i < spheres.size(); i++)
{
if(spheres.at(i).onSphere(r))
{
Vector colour(ambiant.colour);
for(int j = 0; j < lights.size(); j++)
{
Vector intersection(r.pos + r.dir*spheres.at(i).getT(r));
Ray nRay(intersection, lights.at(i).centre + intersection*-1);
colour = colour + lights.at(i).colour;
}
return colour;
}
}
return Vector(0,0,0);
}
我得到的是一个从圆心到圆心在向量方向上拉伸的球体。我不是在寻找任何人来做我的功课。我只是很难调试这个。任何提示表示赞赏:) 谢谢!
编辑:cam.dist 是相机到视图平面的距离