This code defines a function `OctreeRaycast` which performs a raycasting...

August 25, 2025 at 10:52 PM

public bool OctreeRaycast(Vector3 origin, Vector3 direction, float maxDistance, out Vector3 hitPoint) { hitPoint = origin; if (Octree is null) return false; var maxIterations = 500; var currentIteration = 0; var startOrigin = origin; var prevOffset = 0f; while (currentIteration < maxIterations) { currentIteration++; var octreePos = WorldToOctreeSpace(origin, VoxelConstants.OriginOffsetInt); if (Octree.OutsideBounds(octreePos)) return false; var nodeInfo = Get(octreePos); if (nodeInfo.Density > OCTREE_RAYCAST_DENSITY_THRESHOLD) return true; var size = GetSize(nodeInfo.Depth); var nodePos = FloorToNodeSize(octreePos, size); var worldPos = OctreeToWorldSpace(nodePos, VoxelConstants.OriginOffsetInt); #if UNITY_EDITOR if (_debugOctreeRaycast) DebugHelpers.DrawWireCube(worldPos, size, Color.blue, 0.2f); #endif if (!GetNodeBoxIntersection(size, worldPos, origin, direction, out var exitPoint)) return false; var prevOrigin = origin; // Advance a little to ensure we are in the next node origin = exitPoint + direction * 0.01f; if (Vector3.SqrMagnitude(origin - prevOrigin) > MAX_RAY_DISTANCE_SQ) { origin = Vector3.Lerp(prevOrigin, origin, (origin - prevOrigin).magnitude / MAX_RAY_DISTANCE); } var currentOffset = VoxelConstants.GetCurvatureOffset(startOrigin, origin); var offset = new Vector3(0, currentOffset - prevOffset, 0); origin -= offset; prevOffset = currentOffset; #if UNITY_EDITOR if (_debugOctreeRaycast && prevOrigin != origin) { Debug.DrawLine(prevOrigin, origin, Color.red, 0.2f,false); } #endif } return false; }

This code defines a function OctreeRaycast which performs a raycasting operation within a hierarchical data structure called an Octree. The purpose of this function is to determine whether a ray, originating from a given point and moving in a specified direction, intersects with any voxel (or node) in the Octree structure based on a density threshold. Here's a breakdown of the function:


Key Inputs:

  1. origin - The starting point of the ray in world space.
  2. direction - The direction vector for the ray in world space.
  3. maxDistance - The maximum range the ray can travel.
  4. hitPoint - An output parameter that records the intersection point if the ray hits a voxel.

Key Outputs:

  • Return Value (bool):
    • true if the ray intersects a voxel/node with density above a certain threshold.
    • false if the ray does not intersect any such voxel/node or leaves the Octree bounds.
  • hitPoint:
    • The world-space position where the intersection occurred, if a hit is detected.

How It Works:

  1. Initialization:

    • Assigns the initial origin to hitPoint.
    • Returns false immediately if the Octree is null, as there is no structure to raycast against.
  2. Iteration Limit:

    • Limits the number of ray steps through the Octree to maxIterations (set to 500). This ensures that the algorithm won't loop indefinitely.
  3. World to Octree Space Conversion:

    • Converts the ray’s origin point from world space to Octree space using the WorldToOctreeSpace function. This maps the ray’s coordinates to the Octree coordinate system (scaled appropriately).
  4. Bounds Check:

    • Terminates the raycast if the converted position (octreePos) is outside the bounds of the Octree, returning false.
  5. Density Test:

    • Retrieves information (nodeInfo) about the current node the ray is passing through using the Get() function.
    • Compares the node’s density to a predefined threshold (OCTREE_RAYCAST_DENSITY_THRESHOLD).
    • If the density exceeds the threshold, a hit is detected, the function returns true, and the raycast ends.
  6. Node and Intersection Calculations:

    • Determines the size of the current node using GetSize().
    • Computes the exact position of the node’s boundaries using FloorToNodeSize() and converts it to world space with OctreeToWorldSpace().
  7. Node Box-Ray Intersection:

    • Calculates where the ray exits the current node’s bounding box using GetNodeBoxIntersection(). This point becomes the next origin for the ray.
  8. Adjustments and Curvature Handling:

    • Advances the ray slightly beyond the exit point (exitPoint) to ensure movement to the next node.
    • Keeps track of the curvature offset between the initial and current origin (possibly for terrain or non-flat environments).
    • Adjusts the ray's position (origin) accordingly to account for curvature effects.
  9. Debugging and Visualization (Optional):

    • If running in the Unity Editor with debugging enabled (_debugOctreeRaycast), visualizes the raycast path and node boundaries using debug lines and wireframe boxes.
  10. Iteration Termination:

    • If the ray surpasses the maximum allowable distance (MAX_RAY_DISTANCE_SQ), the loop terminates early.
    • If the maximum number of iterations (maxIterations) is reached without detecting a hit, the function exits and returns false.

What the Code Does:

In summary, this function simulates a ray traveling through an Octree to determine whether it intersects any "solid" content within the structure (voxel/node with high density). It dynamically steps the ray from node to node, calculating intersections and handling edge cases like curvature, bounds, and long ray distances. If a hit is detected, the intersection point is returned; otherwise, the function concludes that no hit was found.

This implementation is commonly used in spatial partitioning systems, such as voxel terrains, rendering engines, and physics simulations, to efficiently query large, hierarchical data structures.

Generate your own explanations
Download our vscode extension
Read other generated explanations

Built by @thebuilderjr
Sponsored by beam analytics
Read our terms and privacy policy
Forked from openai-quickstart-node