刚刚开始写光线跟踪,今天准备实现阴影的效果,但是发现了一些问题。
先上图:
球体自身的阴影叠加在了球体上方,
并且来自其他球体的影子显示也不正确。我想了很久也没发现问题在哪。
还请各位前辈指点一下。
相关代码:
RGBColor Phong::Shade(ShadeRec &sr)
{
Vector3D wo(-sr.m_ray.d);
RGBColor L = m_ambientBRDF->rho(sr, wo) * sr.m_world.m_ambient->L(sr);
int lightsNum = sr.m_world.m_lights.size();
for (int i = 0; i < lightsNum; ++i)
{
Vector3D wi = sr.m_world.m_lights[i]->GetDirection(sr);
float ndotwi = sr.m_hitPointNormal * wi;
if(ndotwi > 0.0)
{
bool inShadow = false;
if(sr.m_world.m_lights[i]->castsShadow())
{
Ray shadowRay((sr.m_worldHitPoint + kEpsilon), wi);
inShadow = sr.m_world.m_lights[i]->inShadow(shadowRay, sr);
}
if(!inShadow)
{
L += (m_diffuseBRDF->fr(sr, wo, wi) + m_specularBRDF->fr(sr, wo, wi))
* sr.m_world.m_lights[i]->L(sr) * ndotwi;
}
}
}
return L;
}
bool PointLight::inShadow(const Ray &shadowray, const ShadeRec &sr)
{
float ht(sr.m_t);
float t;
int ObjectNum = sr.m_world.m_objects.size();
float d = m_location.distance(shadowray.o);
for (int i = 0; i < ObjectNum; ++i)
{
if(sr.m_world.m_objects[i]->ShadowHit(shadowray, t) && t < d)
{
return true;
}
}
return false;
}
bool Sphere::ShadowHit(const Ray &ray, float &tmin) const
{
const double ep = 0.01;
double t0, t1;
Vector3D oc = ray.o - center;
double a = ray.d * ray.d;
double b = 2.0 * oc * ray.d;
double c = oc * oc - radius * radius;
double disc = b * b - 4.0 * a * c;
if (disc < 0.0)
{
return false;
}
double e = sqrt(disc);
double denom = 2.0 * a;
t0 = (-b - e) / denom;
if (t0 > ep)
{
tmin = t0;
return true;
}
t1 = (-b + e) / denom;
if (t1 > ep)
{
tmin = t1;
return true;
}
return true;
}
Copyright 2014-2026 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号
1 没有看到您的 kEpsilon 在何处计算的,我猜您想要表达的意思应该是浮在交点表面上一点点的位置重新投射shadow ray,那么是不是应该使用 kEpsilon * normal 来作为bias?
2 inShadow函数没有判断t < 0 的情况,是不是在ShadowHit里计算intersection的时候就已经排除了负向?
3 注意到你的wo有做反向来获取Li Direction 不知道在获取shadow ray方向的时候, wi=light::GetDirection(sr)的方向是否是正确的?