Advertisement
ThomasPixel

Corridor Path Generation - without memory micromanagement

Apr 16th, 2024
592
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 2.05 KB | None | 0 0
  1. // ======================================================
  2. //
  3. // Corridor generations
  4. //
  5. // ======================================================
  6.  
  7. struct PathNode {
  8.     FVector Position;
  9.     PathNode* CameFrom;  
  10.  
  11.     PathNode(const FVector& pos, PathNode* cameFrom = nullptr)
  12.         : Position(pos), CameFrom(cameFrom) {}
  13. };
  14.  
  15. TArray<FVector> UDungeonGeneratorAPI::FindPathDFS(const FVector& start, const FVector& end)
  16. {
  17.     TArray<PathNode> stack;  
  18.     TArray<PathNode> visited;  
  19.  
  20.     stack.Emplace(start);
  21.  
  22.     // While we are still searching...
  23.     while (stack.Num() > 0) {
  24.         PathNode currentNode = stack.Pop();  
  25.  
  26.         // Terminate, reached end vector position
  27.         if (currentNode.Position == end) {
  28.  
  29.             // Build return path
  30.             TArray<FVector> path;
  31.             const PathNode* pathNode = &currentNode;
  32.            
  33.             while (pathNode != nullptr) {
  34.                 path.Add(pathNode->Position);
  35.                 pathNode = pathNode->CameFrom;
  36.             }
  37.            
  38.             Algo::Reverse(path);
  39.             return path;
  40.         }
  41.  
  42.         // Check if a position has been visited
  43.         auto IsVisited = [&visited](const FVector& pos) {
  44.             return visited.ContainsByPredicate([&pos](const PathNode& node) {
  45.                 return node.Position == pos;
  46.                 });
  47.             };
  48.  
  49.         if (!IsVisited(currentNode.Position)) {
  50.            
  51.             // Add to visited
  52.             visited.Add(currentNode);  
  53.  
  54.             // Explore neighbors
  55.             TArray<FVector> directions = { FVector(1, 0, 0), FVector(-1, 0, 0), FVector(0, 1, 0), FVector(0, -1, 0) };
  56.             for (const FVector& dir : directions) {
  57.                 FVector neighborPos = currentNode.Position + dir * UDungeonGeneratorAPI::grid.GetWidth();
  58.                 if (!IsVisited(neighborPos)) {
  59.                     // Make last item in stack last visited
  60.                     stack.Emplace(neighborPos, &visited.Last());
  61.                 }
  62.             }
  63.         }
  64.     }
  65.  
  66.     return {};  
  67. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement