由于某种原因,在我的光线跟踪器中,如果我试图限制光线跟踪器中的递归调用次数,我的反射率就不起作用。
这是我的反射代码:
public static int recursionLevel;
public int maxRecursionLevel;
public Colour shade(Intersection intersection, ArrayList<Light> lights, Ray incidenceRay) {
recursionLevel++;
if(recursionLevel<maxRecursionLevel){
Vector3D reflectedDirection = incidenceRay.direction.subtractNormal(intersection.normal.multiply(2).multiply(incidenceRay.direction.dot(intersection.normal)));
Ray reflectiveRay = new Ray(intersection.point, reflectedDirection);
double min = Double.MAX_VALUE;
Colour tempColour = new Colour();
for(int i = 0; i<RayTracer.world.worldObjects.size(); i++){
Intersection reflectiveRayIntersection = RayTracer.world.worldObjects.get(i).intersect(reflectiveRay);
if (reflectiveRayIntersection != null && reflectiveRayIntersection.distance<min){
min = reflectiveRayIntersection.distance;
recursionLevel++;
tempColour = RayTracer.world.worldObjects.get(i).material.shade(reflectiveRayIntersection, lights, reflectiveRay);
recursionLevel--;
}
}
return tempColour;
}else{
return new Colour(1.0f,1.0f,1.0f);
}
}
如果我摆脱if语句它可以工作,但是如果我放置了太多的反射对象,我的内存会耗尽。我不确定是什么原因引起的。
答案 0 :(得分:0)
问题是你使用recursionLevel
作为全局状态,但它确实应该是本地状态。此外,每次递归调用shade()
时,您都会将其递增两次,并且只递减一次。我会按如下方式重构您的代码:
recursionLevel
全球recursionLevel
方法shade()
参数
if(recursionLevel < maxRecursionLevel)
支票recursionLevel
shade()
增量和减量
shade()
的递归调用,使其调用shade(..., recursionLevel + 1)