我有以下递归代码,但它的行为不符合预期(请参阅下面的详细信息):
R3Intersection ComputeIntersectionNode(R3Ray *ray, R3Node *node)
{
R3Intersection closest_inter;
R3Intersection child_inter;
R3Intersection shape_inter;
double least_t = DBL_MAX;
// check for intersection with shape
if(node->shape != NULL)
{
shape_inter = ComputeIntersectionShape(ray, node->shape);
if(shape_inter.hit == 1)
closest_inter = shape_inter;
}
// go through all the children and for each child, compute
// the closest intersection with ray
for(int i = 0; i < node->children.size(); i++)
{
// compute intersection with children[i] and ray
child_inter = ComputeIntersectionNode(ray, node->children[i]);
// if there's an intersection with the child node and
// it is the closest intersection, set closest intersection
if(child_inter.hit == 1 && fabs(child_inter.t) < fabs(least_t))
closest_inter = child_inter;
}
return closest_inter;
}
除了ComputeIntersectionNode(...)递归调用之外,程序中的多条光线也会调用 this 。为了测试这个函数,我运行它 4rays和 4 nodes(或者更准确地说,一个roottype node,它没有 a shape,但有 4 children,每个都有一个shape)。对于测试,每个都与一个/ray相交。nodeshape
当我第一次在 GDB 中运行代码时ray,它首先通过root没有 的代码,shape所以它直接转到children. 它正确计算第一个孩子的交集并正确设置closest_inter变量,该变量返回到最高级别的递归,并child_inter在closest_inter此处设置为child_inter.hit = 1;
然后,处理第二个孩子。ComputeIntersectionShape(...)不返回与第二个孩子 ( shape_inter.hit == 0;) 的交集 - 这是预期的行为。但是,当函数返回到最高级别的递归时,由于某种原因 child_inter.hit 被设置为 1(但应该设置为 0)。
有什么建议么?
先感谢您。