diff --git a/tiny_bvh.h b/tiny_bvh.h index 85057b9..1c096d0 100644 --- a/tiny_bvh.h +++ b/tiny_bvh.h @@ -2656,18 +2656,21 @@ void BVH::Compact() memcpy( tmp, bvhNode, 2 * sizeof( BVHNode ) ); newNodePtr = 2; uint32_t nodeIdx = 0, stack[128], stackPtr = 0; - while (1) - { - BVHNode& node = tmp[nodeIdx]; - const BVHNode& left = bvhNode[node.leftFirst]; - const BVHNode& right = bvhNode[node.leftFirst + 1]; - tmp[newNodePtr] = left, tmp[newNodePtr + 1] = right; - const uint32_t todo1 = newNodePtr, todo2 = newNodePtr + 1; - node.leftFirst = newNodePtr, newNodePtr += 2; - if (!left.isLeaf()) stack[stackPtr++] = todo1; - if (!right.isLeaf()) stack[stackPtr++] = todo2; - if (!stackPtr) break; - nodeIdx = stack[--stackPtr]; + if (!tmp[nodeIdx].isLeaf()) + { // If the root node is a leaf the BVH is already as compact as it can be. + while (1) + { + BVHNode& node = tmp[nodeIdx]; + const BVHNode& left = bvhNode[node.leftFirst]; + const BVHNode& right = bvhNode[node.leftFirst + 1]; + tmp[newNodePtr] = left, tmp[newNodePtr + 1] = right; + const uint32_t todo1 = newNodePtr, todo2 = newNodePtr + 1; + node.leftFirst = newNodePtr, newNodePtr += 2; + if (!left.isLeaf()) stack[stackPtr++] = todo1; + if (!right.isLeaf()) stack[stackPtr++] = todo2; + if (!stackPtr) break; + nodeIdx = stack[--stackPtr]; + } } usedNodes = newNodePtr; AlignedFree( bvhNode ); @@ -2812,18 +2815,21 @@ void BVH_Verbose::Compact() BVHNode* tmp = (BVHNode*)AlignedAlloc( sizeof( BVHNode ) * usedNodes ); memcpy( tmp, bvhNode, 2 * sizeof( BVHNode ) ); uint32_t newNodePtr = 2, nodeIdx = 0, stack[64], stackPtr = 0; - while (1) - { - BVHNode& node = tmp[nodeIdx]; - const BVHNode& left = bvhNode[node.left]; - const BVHNode& right = bvhNode[node.right]; - tmp[newNodePtr] = left, tmp[newNodePtr + 1] = right; - const uint32_t todo1 = newNodePtr, todo2 = newNodePtr + 1; - node.left = newNodePtr++, node.right = newNodePtr++; - if (!left.isLeaf()) stack[stackPtr++] = todo1; - if (!right.isLeaf()) stack[stackPtr++] = todo2; - if (!stackPtr) break; - nodeIdx = stack[--stackPtr]; + if (!tmp[nodeIdx].isLeaf()) + { // If the root node is a leaf the BVH is already as compact as it can be. + while (1) + { + BVHNode& node = tmp[nodeIdx]; + const BVHNode& left = bvhNode[node.left]; + const BVHNode& right = bvhNode[node.right]; + tmp[newNodePtr] = left, tmp[newNodePtr + 1] = right; + const uint32_t todo1 = newNodePtr, todo2 = newNodePtr + 1; + node.left = newNodePtr++, node.right = newNodePtr++; + if (!left.isLeaf()) stack[stackPtr++] = todo1; + if (!right.isLeaf()) stack[stackPtr++] = todo2; + if (!stackPtr) break; + nodeIdx = stack[--stackPtr]; + } } usedNodes = newNodePtr; AlignedFree( bvhNode );