Skip to content

Instantly share code, notes, and snippets.

@dwilliamson
Created November 20, 2012 20:21
Show Gist options
  • Save dwilliamson/4120787 to your computer and use it in GitHub Desktop.
Save dwilliamson/4120787 to your computer and use it in GitHub Desktop.
3-axis iteration - less branchy, less nesting - easier to look at
struct BoxIterator
{
BoxIterator(const math::boxi& range)
: range(range)
{
// Clamp any negative deltas to zero before calculating volume
// Also add 1 to make the max inclusive
delta.x = max(range.max.x - range.min.x + 1, 0);
delta.y = max(range.max.y - range.min.y + 1, 0);
delta.z = max(range.max.z - range.min.z + 1, 0);
slice_size = delta.x * delta.y;
size = slice_size * delta.z;
}
void GetPos(int i, math::vec3i& pos) const
{
// Calculate position within the range delta
pos.z = i / slice_size;
i -= pos.z * slice_size;
pos.y = i / delta.x;
pos.x = i - pos.y * delta.x;
// Offset that to get the actual position
pos.x += range.min.x;
pos.y += range.min.y;
pos.z += range.min.z;
}
const math::boxi& range;
math::vec3i delta;
i32 slice_size;
i32 size;
};
BoxIterator node_iterator(node_range);
for (i32 i = 0; i < node_iterator.size; i++)
{
math::vec3i node_pos;
node_iterator.GetPos(i, node_pos);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment