【问题标题】:c++ recursion errorc++递归错误
【发布时间】:2010-04-01 04:56:23
【问题描述】:

我有以下递归代码,但它的行为与预期不符(请参阅下面的详细信息):

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 变量,它返回到最高级别的递归,child_inter 以及closest_inter 在此处设置为child_inter.hit = 1;

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

有什么建议吗?

提前谢谢你。

【问题讨论】:

  • 您是否在for 循环中缺少break
  • R3Intersection 默认构造函数是否显式初始化命中?
  • @atlpeg:一旦找到交叉点,我不想中断,因为我希望找到最近的交叉点,所以我必须遍历所有子节点
  • @markB:这实际上是问题的原因。我没有默认构造函数,所以它没有初始化命中。当我在函数开头显式初始化 hit 时,这个问题不再存在。谢谢!

标签: c++ recursion raytracing


【解决方案1】:

我认为您的问题是由于您返回默认初始化的R3Intersection(即,当它不相交时您不返回shape_inter)。根据它的默认构造函数,你可能会得到你所看到的。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2017-06-05
    • 2018-03-30
    • 2016-06-05
    • 2012-06-08
    • 2021-08-15
    • 1970-01-01
    • 1970-01-01
    • 2016-11-11
    相关资源
    最近更新 更多