2010-03-31 91 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)造成的。根據其默認構造函數,您可能會看到您所看到的內容。