修改上述OpenGL代码,实现正确的递归调用Vector3f refractionColor(0.0, 0.0, 0.0); if (mtl._transparent) { /*printf("_transparent"); getchar();*/ //折射光,调用递归 Vector3f refractDir; float ni_over_nt; bool refract; if (ray.Direction().dot(closest_hp.normal) < 0) //入射 { ni_over_nt = 1.0 / mtl._refraction; refract = Refract(ray.Direction(), closest_hp.normal, ni_over_nt, refractDir); } else//出射 { ni_over_nt = mtl._refraction; refract = Refract(ray.Direction(), -closest_hp.normal, ni_over_nt, refractDir); } if (refract) { Ray refractRay(closest_hp.position, refractDir); refractRay._origin = closest_hp.position + 1e-2 * refractDir.normalized(); //请把下面代码改掉,填入正确的递归调用 refractionColor = Vector3f(0, 0, 0); //请把上面代码改掉,填入正确的递归调用 } else { refractionColor = Vector3f(0, 0, 0); } //cout << "refractionColor" << refractionColor << endl; } color = color + 0.2 * reflectColor + 0.9 * refractionColor; if (color[0] > 1.0) color[0] = 1.0; if (color[1] > 1.0) color[1] = 1.0; if (color[2] > 1.0) color[2] = 1.0; return color; }
时间: 2024-04-06 15:28:15 浏览: 69
汉诺塔python3完整源代码可根据输入的圆环个数输出操作步骤,亲测有效
可以添加一个深度限制参数,限制递归的深度,避免无限递归。同时,在递归调用之后,还需要进行颜色的修正,即将递归得到的颜色乘上材质表面的透明度。修改后的代码如下:
Vector3f refractionColor(0.0, 0.0, 0.0);
if (mtl._transparent && depth < MAX_DEPTH)
{
Vector3f refractDir;
float ni_over_nt;
bool refract;
if (ray.Direction().dot(closest_hp.normal) < 0)
{
ni_over_nt = 1.0 / mtl._refraction;
refract = Refract(ray.Direction(), closest_hp.normal, ni_over_nt, refractDir);
}
else
{
ni_over_nt = mtl._refraction;
refract = Refract(ray.Direction(), -closest_hp.normal, ni_over_nt, refractDir);
}
if (refract)
{
Ray refractRay(closest_hp.position, refractDir);
refractRay._origin = closest_hp.position + 1e-2 * refractDir.normalized();
//添加深度限制参数,限制递归的深度
refractionColor = RayColor(refractRay, scene, depth + 1, test, MAX_DEPTH);
//颜色修正,乘上材质表面的透明度
refractionColor = Vector3f(refractionColor[0] * mtl._Kt[0], refractionColor[1] * mtl._Kt[1], refractionColor[2] * mtl._Kt[2]);
}
}
color = color + 0.2 * reflectColor + 0.9 * refractionColor;
if (color[0] > 1.0) color[0] = 1.0;
if (color[1] > 1.0) color[1] = 1.0;
if (color[2] > 1.0) color[2] = 1.0;
return color;
阅读全文