2010-03-31 68 views
0

我有以下的递归代码,并没有像预期的那样(详见下文):C++递归误差

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(...),除了递归调用,也被称为多线在节目中。为了测试这个功能,我运行它4 rays和4 nodes(或更准确地说,node类型的一个root,它没有shape,但有4个children,其中每个都有一个shape)。为了测试,每个ray恰好相交一个node/shape

当我运行在GDB代码用于第一ray,它首先通过root通过代码,其不具有shape,所以把它直接转到children。它正确地计算第一个孩子的路口,并设置closest_inter变量正确,以及作为closest_interchild_inter.hit = 1;

然后,第二个孩子被处理这里设置它获取返回递归和child_inter的最高水平为好。 ComputeIntersectionShape(...)返回与第二个孩子没有交集(shape_inter.hit == 0;) - 这是预期的行为。但是,当函数返回到递归的最高级别时,出于某种原因child_inter.hit被设置为1(但应设置为0)。

有什么建议吗?

预先感谢您。

+0

你是否在'for'循环中缺少'break'? – atlpeg 2010-03-31 20:33:29

+0

R3Intersection默认构造函数是否显式初始化了hit? – 2010-03-31 21:04:42

+0

@atlpeg:我不希望打破,一旦我找到了交集,因为我想找到最近的交点,所以我必须遍历所有儿童 – Myx 2010-03-31 22:17:21

回答

1

我认为你的问题是由于你正在返回一个默认初始化的R3Intersection(也就是说,当它不相交时不返回shape_inter)造成的。根据其默认构造函数,您可能会看到您所看到的内容。