From 0000000000000000000000000000000000000000 Mon Sep 17 00:00:00 2001 From: NONPLAYT <76615486+NONPLAYT@users.noreply.github.com> Date: Tue, 28 Jan 2025 01:04:55 +0300 Subject: [PATCH] Petal: Async Pathfinding Original code by Bloom-host, licensed under GPL v3 You can find the original code on https://github.com/Bloom-host/Petal Makes most pathfinding-related work happen asynchronously diff --git a/net/minecraft/world/entity/ai/behavior/AcquirePoi.java b/net/minecraft/world/entity/ai/behavior/AcquirePoi.java index 21046cde1bd1ede8e7851eb4ea414e33628aa4a9..9fd3b55dc640e96de05c149b90dcbb459b414f4b 100644 --- a/net/minecraft/world/entity/ai/behavior/AcquirePoi.java +++ b/net/minecraft/world/entity/ai/behavior/AcquirePoi.java @@ -93,21 +93,18 @@ public class AcquirePoi { } } // Paper end - optimise POI access - Path path = findPathToPois(mob, set); - if (path != null && path.canReach()) { - BlockPos target = path.getTarget(); - poiManager.getType(target).ifPresent(holder -> { - poiManager.take(acquirablePois, (holder1, blockPos) -> blockPos.equals(target), target, 1); - memoryAccessor.set(GlobalPos.of(level.dimension(), target)); - entityEventId.ifPresent(id -> level.broadcastEntityEvent(mob, id)); - map.clear(); - level.debugSynchronizers().updatePoi(target); + // DivineMC start - Async path processing + if (org.bxteam.divinemc.config.DivineConfig.AsyncCategory.asyncPathfinding) { + Path possiblePath = findPathToPois(mob, set); + + org.bxteam.divinemc.async.pathfinding.AsyncPathProcessor.awaitProcessing(possiblePath, path -> { + processPath(acquirablePois, entityEventId, (Long2ObjectMap) map, memoryAccessor, level, mob, time, poiManager, set, path); }); } else { - for (Pair, BlockPos> pair : set) { - map.computeIfAbsent(pair.getSecond().asLong(), l -> new AcquirePoi.JitteredLinearRetry(level.random, time)); - } + Path path = findPathToPois(mob, set); + processPath(acquirablePois, entityEventId, (Long2ObjectMap) map, memoryAccessor, level, mob, time, poiManager, set, path); } + // DivineMC end - Async path processing return true; } @@ -119,6 +116,34 @@ public class AcquirePoi { : BehaviorBuilder.create(instance -> instance.group(instance.absent(existingAbsentMemory)).apply(instance, memoryAccessor -> oneShot)); } + // DivineMC start - Async path processing + private static void processPath(Predicate> acquirablePois, + Optional entityEventId, + Long2ObjectMap map, + net.minecraft.world.entity.ai.behavior.declarative.MemoryAccessor, GlobalPos> memoryAccessor, + ServerLevel level, + PathfinderMob mob, + long time, + PoiManager poiManager, + Set, BlockPos>> set, + Path path) { + if (path != null && path.canReach()) { + BlockPos target = path.getTarget(); + poiManager.getType(target).ifPresent(holder -> { + poiManager.take(acquirablePois, (holder1, blockPos) -> blockPos.equals(target), target, 1); + memoryAccessor.set(GlobalPos.of(level.dimension(), target)); + entityEventId.ifPresent(id -> level.broadcastEntityEvent(mob, id)); + map.clear(); + level.debugSynchronizers().updatePoi(target); + }); + } else { + for (Pair, BlockPos> pair : set) { + map.computeIfAbsent(pair.getSecond().asLong(), l -> new JitteredLinearRetry(level.random, time)); + } + } + } + // DivineMC end - Async path processing + @Nullable public static Path findPathToPois(Mob mob, Set, BlockPos>> poiPositions) { if (poiPositions.isEmpty()) { diff --git a/net/minecraft/world/entity/ai/behavior/MoveToTargetSink.java b/net/minecraft/world/entity/ai/behavior/MoveToTargetSink.java index 621ba76784f2b92790eca62be4d0688834335ab6..92d8899ff7d42ecc987a7bf2035cc72484ea9e82 100644 --- a/net/minecraft/world/entity/ai/behavior/MoveToTargetSink.java +++ b/net/minecraft/world/entity/ai/behavior/MoveToTargetSink.java @@ -21,6 +21,7 @@ public class MoveToTargetSink extends Behavior { private int remainingCooldown; @Nullable private Path path; + private boolean finishedProcessing; // DivineMC - async path processing @Nullable private BlockPos lastTargetPos; private float speedModifier; @@ -53,9 +54,11 @@ public class MoveToTargetSink extends Behavior { Brain brain = owner.getBrain(); WalkTarget walkTarget = brain.getMemory(MemoryModuleType.WALK_TARGET).get(); boolean flag = this.reachedTarget(owner, walkTarget); - if (!flag && this.tryComputePath(owner, walkTarget, level.getGameTime())) { + if (!org.bxteam.divinemc.config.DivineConfig.AsyncCategory.asyncPathfinding && !flag && this.tryComputePath(owner, walkTarget, level.getGameTime())) { // DivineMC - async path processing this.lastTargetPos = walkTarget.getTarget().currentBlockPosition(); return true; + } else if (org.bxteam.divinemc.config.DivineConfig.AsyncCategory.asyncPathfinding && !flag) { // DivineMC - async pathfinding + return true; } else { brain.eraseMemory(MemoryModuleType.WALK_TARGET); if (flag) { @@ -69,6 +72,7 @@ public class MoveToTargetSink extends Behavior { @Override protected boolean canStillUse(ServerLevel level, Mob entity, long gameTime) { + if (org.bxteam.divinemc.config.DivineConfig.AsyncCategory.asyncPathfinding && !this.finishedProcessing) return true; // DivineMC - wait for processing if (this.path != null && this.lastTargetPos != null) { Optional memory = entity.getBrain().getMemory(MemoryModuleType.WALK_TARGET); boolean flag = memory.map(MoveToTargetSink::isWalkTargetSpectator).orElse(false); @@ -95,27 +99,98 @@ public class MoveToTargetSink extends Behavior { @Override protected void start(ServerLevel level, Mob entity, long gameTime) { + // DivineMC start - start processing + if (org.bxteam.divinemc.config.DivineConfig.AsyncCategory.asyncPathfinding) { + Brain brain = entity.getBrain(); + WalkTarget walkTarget = brain.getMemory(MemoryModuleType.WALK_TARGET).get(); + + this.finishedProcessing = false; + this.lastTargetPos = walkTarget.getTarget().currentBlockPosition(); + this.path = this.computePath(entity, walkTarget); + return; + } + // DivineMC end - start processing entity.getBrain().setMemory(MemoryModuleType.PATH, this.path); entity.getNavigation().moveTo(this.path, (double)this.speedModifier); } @Override protected void tick(ServerLevel level, Mob owner, long gameTime) { - Path path = owner.getNavigation().getPath(); - Brain brain = owner.getBrain(); - if (this.path != path) { - this.path = path; - brain.setMemory(MemoryModuleType.PATH, path); - } + // DivineMC start - Async path processing + if (org.bxteam.divinemc.config.DivineConfig.AsyncCategory.asyncPathfinding) { + if (this.path != null && !this.path.isProcessed()) return; // wait for processing - if (path != null && this.lastTargetPos != null) { - WalkTarget walkTarget = brain.getMemory(MemoryModuleType.WALK_TARGET).get(); - if (walkTarget.getTarget().currentBlockPosition().distSqr(this.lastTargetPos) > 4.0 && this.tryComputePath(owner, walkTarget, level.getGameTime())) { - this.lastTargetPos = walkTarget.getTarget().currentBlockPosition(); - this.start(level, owner, gameTime); + if (!this.finishedProcessing) { + this.finishedProcessing = true; + + Brain brain = owner.getBrain(); + boolean canReach = this.path != null && this.path.canReach(); + if (canReach) { + brain.eraseMemory(MemoryModuleType.CANT_REACH_WALK_TARGET_SINCE); + } else if (!brain.hasMemoryValue(MemoryModuleType.CANT_REACH_WALK_TARGET_SINCE)) { + brain.setMemory(MemoryModuleType.CANT_REACH_WALK_TARGET_SINCE, gameTime); + } + + if (!canReach) { + Optional walkTarget = brain.getMemory(MemoryModuleType.WALK_TARGET); + + if (!walkTarget.isPresent()) return; + + BlockPos blockPos = walkTarget.get().getTarget().currentBlockPosition(); + Vec3 vec3 = DefaultRandomPos.getPosTowards((PathfinderMob) owner, 10, 7, Vec3.atBottomCenterOf(blockPos), (float) Math.PI / 2F); + if (vec3 != null) { + // try recalculating the path using a random position + this.path = owner.getNavigation().createPath(vec3.x, vec3.y, vec3.z, 0); + this.finishedProcessing = false; + return; + } + } + + owner.getBrain().setMemory(MemoryModuleType.PATH, this.path); + owner.getNavigation().moveTo(this.path, this.speedModifier); } + + Path path = owner.getNavigation().getPath(); + Brain brain = owner.getBrain(); + + if (path != null && this.lastTargetPos != null && brain.hasMemoryValue(MemoryModuleType.WALK_TARGET)) { + WalkTarget walkTarget = brain.getMemory(MemoryModuleType.WALK_TARGET).get(); // we know isPresent = true + if (walkTarget.getTarget().currentBlockPosition().distSqr(this.lastTargetPos) > 4.0D) { + this.start(level, owner, gameTime); + } + } + } else { + Path path = owner.getNavigation().getPath(); + Brain brain = owner.getBrain(); + if (this.path != path) { + this.path = path; + brain.setMemory(MemoryModuleType.PATH, path); + } + + if (path != null && this.lastTargetPos != null) { + WalkTarget walkTarget = brain.getMemory(MemoryModuleType.WALK_TARGET).get(); + if (walkTarget.getTarget().currentBlockPosition().distSqr(this.lastTargetPos) > 4.0 + && this.tryComputePath(owner, walkTarget, level.getGameTime())) { + this.lastTargetPos = walkTarget.getTarget().currentBlockPosition(); + this.start(level, owner, gameTime); + } + } + } + // DivineMC end - Async path processing + } + + // DivineMC start - Async path processing + @Nullable + private Path computePath(Mob entity, WalkTarget walkTarget) { + BlockPos blockPos = walkTarget.getTarget().currentBlockPosition(); + this.speedModifier = walkTarget.getSpeedModifier(); + Brain brain = entity.getBrain(); + if (this.reachedTarget(entity, walkTarget)) { + brain.eraseMemory(MemoryModuleType.CANT_REACH_WALK_TARGET_SINCE); } + return entity.getNavigation().createPath(blockPos, 0); } + // DivineMC end - Async path processing private boolean tryComputePath(Mob mob, WalkTarget target, long time) { BlockPos blockPos = target.getTarget().currentBlockPosition(); diff --git a/net/minecraft/world/entity/ai/behavior/SetClosestHomeAsWalkTarget.java b/net/minecraft/world/entity/ai/behavior/SetClosestHomeAsWalkTarget.java index 348ff9ef8595fa9324d41ec1328f8d7a503d1d13..55b57381008deeb4965ecaa29932ae168a201dbb 100644 --- a/net/minecraft/world/entity/ai/behavior/SetClosestHomeAsWalkTarget.java +++ b/net/minecraft/world/entity/ai/behavior/SetClosestHomeAsWalkTarget.java @@ -59,17 +59,18 @@ public class SetClosestHomeAsWalkTarget { poi -> poi.is(PoiTypes.HOME), predicate, mob.blockPosition(), 48, PoiManager.Occupancy.ANY ) .collect(Collectors.toSet()); - Path path = AcquirePoi.findPathToPois(mob, set); - if (path != null && path.canReach()) { - BlockPos target = path.getTarget(); - Optional> type = poiManager.getType(target); - if (type.isPresent()) { - walkTarget.set(new WalkTarget(target, speedModifier, 1)); - level.debugSynchronizers().updatePoi(target); - } - } else if (mutableInt.getValue() < 5) { - map.long2LongEntrySet().removeIf(entry -> entry.getLongValue() < mutableLong.getValue()); + // DivineMC start - async path processing + if (org.bxteam.divinemc.config.DivineConfig.AsyncCategory.asyncPathfinding) { + Path possiblePath = AcquirePoi.findPathToPois(mob, set); + + org.bxteam.divinemc.async.pathfinding.AsyncPathProcessor.awaitProcessing(possiblePath, path -> { + processPath(speedModifier, map, mutableLong, walkTarget, level, poiManager, mutableInt, path); + }); + } else { + Path path = AcquirePoi.findPathToPois(mob, set); + processPath(speedModifier, map, mutableLong, walkTarget, level, poiManager, mutableInt, path); } + // DivineMC end - async path processing return true; } else { @@ -80,4 +81,26 @@ public class SetClosestHomeAsWalkTarget { ) ); } + + // DivineMC start - async path processing + private static void processPath(float speedModifier, + Long2LongMap map, + MutableLong mutableLong, + net.minecraft.world.entity.ai.behavior.declarative.MemoryAccessor, WalkTarget> walkTarget, + net.minecraft.server.level.ServerLevel level, + PoiManager poiManager, + MutableInt mutableInt, + @org.jetbrains.annotations.Nullable Path path) { + if (path != null && path.canReach()) { + BlockPos target = path.getTarget(); + Optional> type = poiManager.getType(target); + if (type.isPresent()) { + walkTarget.set(new WalkTarget(target, speedModifier, 1)); + level.debugSynchronizers().updatePoi(target); + } + } else if (mutableInt.getValue() < 5) { + map.long2LongEntrySet().removeIf(entry -> entry.getLongValue() < mutableLong.getValue()); + } + } + // DivineMC end - async path processing } diff --git a/net/minecraft/world/entity/ai/goal/DoorInteractGoal.java b/net/minecraft/world/entity/ai/goal/DoorInteractGoal.java index 73bba480f3f017a8aed14562bd82ba33db04391c..b31976b68eec3cd0ab0620a487e99ecd49f78186 100644 --- a/net/minecraft/world/entity/ai/goal/DoorInteractGoal.java +++ b/net/minecraft/world/entity/ai/goal/DoorInteractGoal.java @@ -54,7 +54,7 @@ public abstract class DoorInteractGoal extends Goal { return false; } else { Path path = this.mob.getNavigation().getPath(); - if (path != null && !path.isDone()) { + if (path != null && path.isProcessed() && !path.isDone()) { // DivineMC - Async Pathfinding for (int i = 0; i < Math.min(path.getNextNodeIndex() + 2, path.getNodeCount()); i++) { Node node = path.getNode(i); this.doorPos = new BlockPos(node.x, node.y + 1, node.z); diff --git a/net/minecraft/world/entity/ai/navigation/AmphibiousPathNavigation.java b/net/minecraft/world/entity/ai/navigation/AmphibiousPathNavigation.java index 458ceec68ca138b0aa9b70d6c934473c01d468f4..ff06ba3ede2f2e40aae8f9a0b997150cfaaeecb7 100644 --- a/net/minecraft/world/entity/ai/navigation/AmphibiousPathNavigation.java +++ b/net/minecraft/world/entity/ai/navigation/AmphibiousPathNavigation.java @@ -12,9 +12,25 @@ public class AmphibiousPathNavigation extends PathNavigation { super(mob, level); } + // DivineMC start - async path processing + private static final org.bxteam.divinemc.async.pathfinding.NodeEvaluatorGenerator nodeEvaluatorGenerator = (org.bxteam.divinemc.async.pathfinding.NodeEvaluatorFeatures nodeEvaluatorFeatures) -> { + AmphibiousNodeEvaluator nodeEvaluator = new AmphibiousNodeEvaluator(false); + nodeEvaluator.setCanPassDoors(nodeEvaluatorFeatures.canPassDoors()); + nodeEvaluator.setCanFloat(nodeEvaluatorFeatures.canFloat()); + nodeEvaluator.setCanWalkOverFences(nodeEvaluatorFeatures.canWalkOverFences()); + nodeEvaluator.setCanOpenDoors(nodeEvaluatorFeatures.canOpenDoors()); + return nodeEvaluator; + }; + // DivineMC end - async path processing + @Override protected PathFinder createPathFinder(int maxVisitedNodes) { this.nodeEvaluator = new AmphibiousNodeEvaluator(false); + // DivineMC start - async path processing + if (org.bxteam.divinemc.config.DivineConfig.AsyncCategory.asyncPathfinding) { + return new PathFinder(this.nodeEvaluator, maxVisitedNodes, nodeEvaluatorGenerator); + } + // DivineMC end - async path processing return new PathFinder(this.nodeEvaluator, maxVisitedNodes); } diff --git a/net/minecraft/world/entity/ai/navigation/FlyingPathNavigation.java b/net/minecraft/world/entity/ai/navigation/FlyingPathNavigation.java index e21a79f77b6775764816ec45fc9023f52a00af84..2e82b6b884ff6296b2affa29e7b3ce0551372265 100644 --- a/net/minecraft/world/entity/ai/navigation/FlyingPathNavigation.java +++ b/net/minecraft/world/entity/ai/navigation/FlyingPathNavigation.java @@ -15,9 +15,25 @@ public class FlyingPathNavigation extends PathNavigation { super(mob, level); } + // DivineMC start - async path processing + private static final org.bxteam.divinemc.async.pathfinding.NodeEvaluatorGenerator nodeEvaluatorGenerator = (org.bxteam.divinemc.async.pathfinding.NodeEvaluatorFeatures nodeEvaluatorFeatures) -> { + FlyNodeEvaluator nodeEvaluator = new FlyNodeEvaluator(); + nodeEvaluator.setCanPassDoors(nodeEvaluatorFeatures.canPassDoors()); + nodeEvaluator.setCanFloat(nodeEvaluatorFeatures.canFloat()); + nodeEvaluator.setCanWalkOverFences(nodeEvaluatorFeatures.canWalkOverFences()); + nodeEvaluator.setCanOpenDoors(nodeEvaluatorFeatures.canOpenDoors()); + return nodeEvaluator; + }; + // DivineMC end - async path processing + @Override protected PathFinder createPathFinder(int maxVisitedNodes) { this.nodeEvaluator = new FlyNodeEvaluator(); + // DivineMC start - async path processing + if (org.bxteam.divinemc.config.DivineConfig.AsyncCategory.asyncPathfinding) { + return new PathFinder(this.nodeEvaluator, maxVisitedNodes, nodeEvaluatorGenerator); + } + // DivineMC end - async path processing return new PathFinder(this.nodeEvaluator, maxVisitedNodes); } @@ -47,6 +63,7 @@ public class FlyingPathNavigation extends PathNavigation { if (this.hasDelayedRecomputation) { this.recomputePath(); } + if (this.path != null && !this.path.isProcessed()) return; // DivineMC - async path processing if (!this.isDone()) { if (this.canUpdatePath()) { diff --git a/net/minecraft/world/entity/ai/navigation/GroundPathNavigation.java b/net/minecraft/world/entity/ai/navigation/GroundPathNavigation.java index f2f07146a3638fe07f4814abd22a9bf815507fd2..2ee4c8f02bd62c67bacb1d817b3aed24a79dc050 100644 --- a/net/minecraft/world/entity/ai/navigation/GroundPathNavigation.java +++ b/net/minecraft/world/entity/ai/navigation/GroundPathNavigation.java @@ -25,9 +25,25 @@ public class GroundPathNavigation extends PathNavigation { super(mob, level); } + // DivineMC start - async path processing + protected static final org.bxteam.divinemc.async.pathfinding.NodeEvaluatorGenerator nodeEvaluatorGenerator = (org.bxteam.divinemc.async.pathfinding.NodeEvaluatorFeatures nodeEvaluatorFeatures) -> { + WalkNodeEvaluator nodeEvaluator = new WalkNodeEvaluator(); + nodeEvaluator.setCanPassDoors(nodeEvaluatorFeatures.canPassDoors()); + nodeEvaluator.setCanFloat(nodeEvaluatorFeatures.canFloat()); + nodeEvaluator.setCanWalkOverFences(nodeEvaluatorFeatures.canWalkOverFences()); + nodeEvaluator.setCanOpenDoors(nodeEvaluatorFeatures.canOpenDoors()); + return nodeEvaluator; + }; + // DivineMC end - async path processing + @Override protected PathFinder createPathFinder(int maxVisitedNodes) { this.nodeEvaluator = new WalkNodeEvaluator(); + // DivineMC start - async path processing + if (org.bxteam.divinemc.config.DivineConfig.AsyncCategory.asyncPathfinding) { + return new PathFinder(this.nodeEvaluator, maxVisitedNodes, nodeEvaluatorGenerator); + } + // DivineMC end - async path processing return new PathFinder(this.nodeEvaluator, maxVisitedNodes); } diff --git a/net/minecraft/world/entity/ai/navigation/PathNavigation.java b/net/minecraft/world/entity/ai/navigation/PathNavigation.java index 1f45b389553cd5782972193537ce7adcd9c7c600..777b3ccce23b0ffd84176b12207a1bbc4beda379 100644 --- a/net/minecraft/world/entity/ai/navigation/PathNavigation.java +++ b/net/minecraft/world/entity/ai/navigation/PathNavigation.java @@ -173,6 +173,10 @@ public abstract class PathNavigation { return null; } else if (!this.canUpdatePath()) { return null; + // DivineMC start - catch early if it's still processing these positions let it keep processing + } else if (this.path instanceof org.bxteam.divinemc.async.pathfinding.AsyncPath asyncPath && !asyncPath.isProcessed() && asyncPath.hasSameProcessingPositions(targets)) { + return this.path; + // DivineMC end - catch early if it's still processing these positions let it keep processing } else if (this.path != null && !this.path.isDone() && targets.contains(this.targetPos)) { return this.path; } else { @@ -197,11 +201,29 @@ public abstract class PathNavigation { int i = (int)(followRange + regionOffset); PathNavigationRegion pathNavigationRegion = new PathNavigationRegion(this.level, blockPos.offset(-i, -i, -i), blockPos.offset(i, i, i)); Path path = this.pathFinder.findPath(pathNavigationRegion, this.mob, targets, followRange, accuracy, this.maxVisitedNodesMultiplier); - if (path != null && path.getTarget() != null) { - this.targetPos = path.getTarget(); - this.reachRange = accuracy; - this.resetStuckTimeout(); + // DivineMC start - async path processing + if (org.bxteam.divinemc.config.DivineConfig.AsyncCategory.asyncPathfinding) { + // assign early a target position. most calls will only have 1 position + if (!targets.isEmpty()) this.targetPos = targets.iterator().next(); + + org.bxteam.divinemc.async.pathfinding.AsyncPathProcessor.awaitProcessing(path, processedPath -> { + // check that processing didn't take so long that we calculated a new path + if (processedPath != this.path) return; + + if (processedPath != null && processedPath.getTarget() != null) { + this.targetPos = processedPath.getTarget(); + this.reachRange = accuracy; + this.resetStuckTimeout(); + } + }); + } else { + if (path != null && path.getTarget() != null) { + this.targetPos = path.getTarget(); + this.reachRange = accuracy; + this.resetStuckTimeout(); + } } + // DivineMC end - async path processing return path; } @@ -252,8 +274,8 @@ public abstract class PathNavigation { if (this.isDone()) { return false; } else { - this.trimPath(); - if (this.path.getNodeCount() <= 0) { + if (path.isProcessed()) this.trimPath(); // DivineMC - only trim if processed + if (path.isProcessed() && this.path.getNodeCount() <= 0) { // DivineMC - only check node count if processed return false; } else { this.speedModifier = speed; @@ -276,6 +298,7 @@ public abstract class PathNavigation { if (this.hasDelayedRecomputation) { this.recomputePath(); } + if (this.path != null && !this.path.isProcessed()) return; // DivineMC - skip pathfinding if we're still processing if (!this.isDone()) { if (this.canUpdatePath()) { @@ -304,6 +327,7 @@ public abstract class PathNavigation { } protected void followThePath() { + if (!this.path.isProcessed()) return; // DivineMC - skip if not processed Vec3 tempMobPos = this.getTempMobPos(); this.maxDistanceToWaypoint = this.mob.getBbWidth() > 0.75F ? this.mob.getBbWidth() / 2.0F : 0.75F - this.mob.getBbWidth() / 2.0F; Vec3i nextNodePos = this.path.getNextNodePos(); @@ -460,7 +484,7 @@ public abstract class PathNavigation { public boolean shouldRecomputePath(BlockPos pos) { if (this.hasDelayedRecomputation) { return false; - } else if (this.path != null && !this.path.isDone() && this.path.getNodeCount() != 0) { + } else if (this.path != null && this.path.isProcessed() && !this.path.isDone() && this.path.getNodeCount() != 0) { // DivineMC - Skip if not processed Node endNode = this.path.getEndNode(); Vec3 vec3 = new Vec3((endNode.x + this.mob.getX()) / 2.0, (endNode.y + this.mob.getY()) / 2.0, (endNode.z + this.mob.getZ()) / 2.0); return pos.closerToCenterThan(vec3, this.path.getNodeCount() - this.path.getNextNodeIndex()); diff --git a/net/minecraft/world/entity/ai/navigation/WaterBoundPathNavigation.java b/net/minecraft/world/entity/ai/navigation/WaterBoundPathNavigation.java index ea0f6a19e4a79538e68917ba86cbc98be4dbca8d..030d90f93dbbc07e94d4776198c368650539bf91 100644 --- a/net/minecraft/world/entity/ai/navigation/WaterBoundPathNavigation.java +++ b/net/minecraft/world/entity/ai/navigation/WaterBoundPathNavigation.java @@ -15,11 +15,27 @@ public class WaterBoundPathNavigation extends PathNavigation { super(mob, level); } + // DivineMC start - async path processing + private static final org.bxteam.divinemc.async.pathfinding.NodeEvaluatorGenerator nodeEvaluatorGenerator = (org.bxteam.divinemc.async.pathfinding.NodeEvaluatorFeatures nodeEvaluatorFeatures) -> { + SwimNodeEvaluator nodeEvaluator = new SwimNodeEvaluator(nodeEvaluatorFeatures.allowBreaching()); + nodeEvaluator.setCanPassDoors(nodeEvaluatorFeatures.canPassDoors()); + nodeEvaluator.setCanFloat(nodeEvaluatorFeatures.canFloat()); + nodeEvaluator.setCanWalkOverFences(nodeEvaluatorFeatures.canWalkOverFences()); + nodeEvaluator.setCanOpenDoors(nodeEvaluatorFeatures.canOpenDoors()); + return nodeEvaluator; + }; + // DivineMC end - async path processing + @Override protected PathFinder createPathFinder(int maxVisitedNodes) { this.allowBreaching = this.mob.getType() == EntityType.DOLPHIN; this.nodeEvaluator = new SwimNodeEvaluator(this.allowBreaching); this.nodeEvaluator.setCanPassDoors(false); + // DivineMC start - async path processing + if (org.bxteam.divinemc.config.DivineConfig.AsyncCategory.asyncPathfinding) { + return new PathFinder(this.nodeEvaluator, maxVisitedNodes, nodeEvaluatorGenerator); + } + // DivineMC end - async path processing return new PathFinder(this.nodeEvaluator, maxVisitedNodes); } diff --git a/net/minecraft/world/entity/ai/sensing/NearestBedSensor.java b/net/minecraft/world/entity/ai/sensing/NearestBedSensor.java index 1f96fd5085bacb4c584576c7cb9f51e7898e9b03..d975b89c7bb57562852596751a4ff881d3ecf193 100644 --- a/net/minecraft/world/entity/ai/sensing/NearestBedSensor.java +++ b/net/minecraft/world/entity/ai/sensing/NearestBedSensor.java @@ -57,17 +57,32 @@ public class NearestBedSensor extends Sensor { java.util.List, BlockPos>> poiposes = new java.util.ArrayList<>(); // don't ask me why it's unbounded. ask mojang. io.papermc.paper.util.PoiAccess.findAnyPoiPositions(poiManager, type -> type.is(PoiTypes.HOME), predicate, entity.blockPosition(), level.purpurConfig.villagerNearestBedSensorSearchRadius, PoiManager.Occupancy.ANY, false, Integer.MAX_VALUE, poiposes); // Purpur - Configurable villager search radius - Path path = AcquirePoi.findPathToPois(entity, new java.util.HashSet<>(poiposes)); - // Paper end - optimise POI access - if (path != null && path.canReach()) { - BlockPos target = path.getTarget(); - Optional> type = poiManager.getType(target); - if (type.isPresent()) { - entity.getBrain().setMemory(MemoryModuleType.NEAREST_BED, target); - } - } else if (this.triedCount < 5) { - this.batchCache.long2LongEntrySet().removeIf(entry -> entry.getLongValue() < this.lastUpdate); + // DivineMC start - async pathfinding + if (org.bxteam.divinemc.config.DivineConfig.AsyncCategory.asyncPathfinding) { + Path possiblePath = AcquirePoi.findPathToPois(entity, new java.util.HashSet<>(poiposes)); + org.bxteam.divinemc.async.pathfinding.AsyncPathProcessor.awaitProcessing(possiblePath, path -> { + processPath(entity, poiManager, path); + }); + } else { + Path path = AcquirePoi.findPathToPois(entity, new java.util.HashSet<>(poiposes)); + // Paper end - optimise POI access + processPath(entity, poiManager, path); + } + // DivineMC end - async pathfinding + } + } + + // DivineMC start - async pathfinding + private void processPath(Mob entity, PoiManager poiManager, @org.jetbrains.annotations.Nullable Path path) { + if (path != null && path.canReach()) { + BlockPos target = path.getTarget(); + Optional> type = poiManager.getType(target); + if (type.isPresent()) { + entity.getBrain().setMemory(MemoryModuleType.NEAREST_BED, target); } + } else if (this.triedCount < 5) { + this.batchCache.long2LongEntrySet().removeIf(entry -> entry.getLongValue() < this.lastUpdate); } } + // DivineMC end - async pathfinding } diff --git a/net/minecraft/world/entity/animal/Bee.java b/net/minecraft/world/entity/animal/Bee.java index a520052f0feae97c5ed8eb4af4fb48cdf56d6550..127840b75b39ec6a68e504396948c3c523535fd9 100644 --- a/net/minecraft/world/entity/animal/Bee.java +++ b/net/minecraft/world/entity/animal/Bee.java @@ -944,7 +944,7 @@ public class Bee extends Animal implements NeutralMob, FlyingAnimal { } else { Bee.this.pathfindRandomlyTowards(Bee.this.hivePos); } - } else { + } else if (navigation.getPath() != null && navigation.getPath().isProcessed()) { // DivineMC - check processing boolean flag = this.pathfindDirectlyTowards(Bee.this.hivePos); if (!flag) { this.dropAndBlacklistHive(); @@ -998,7 +998,7 @@ public class Bee extends Animal implements NeutralMob, FlyingAnimal { return true; } else { Path path = Bee.this.navigation.getPath(); - return path != null && path.getTarget().equals(pos) && path.canReach() && path.isDone(); + return path != null && path.isProcessed() && path.getTarget().equals(pos) && path.canReach() && path.isDone(); // DivineMC - ensure path is processed } } } diff --git a/net/minecraft/world/entity/animal/frog/Frog.java b/net/minecraft/world/entity/animal/frog/Frog.java index 9656c1bf22b1b6c945a8ba5603742261db650fd5..be75453e5426d2d2819983b17014e0e8675961bd 100644 --- a/net/minecraft/world/entity/animal/frog/Frog.java +++ b/net/minecraft/world/entity/animal/frog/Frog.java @@ -480,6 +480,17 @@ public class Frog extends Animal { super(mob, level); } + // DivineMC start - async path processing + private static final org.bxteam.divinemc.async.pathfinding.NodeEvaluatorGenerator nodeEvaluatorGenerator = (org.bxteam.divinemc.async.pathfinding.NodeEvaluatorFeatures nodeEvaluatorFeatures) -> { + Frog.FrogNodeEvaluator nodeEvaluator = new Frog.FrogNodeEvaluator(true); + nodeEvaluator.setCanPassDoors(nodeEvaluatorFeatures.canPassDoors()); + nodeEvaluator.setCanFloat(nodeEvaluatorFeatures.canFloat()); + nodeEvaluator.setCanWalkOverFences(nodeEvaluatorFeatures.canWalkOverFences()); + nodeEvaluator.setCanOpenDoors(nodeEvaluatorFeatures.canOpenDoors()); + return nodeEvaluator; + }; + // DivineMC end - async path processing + @Override public boolean canCutCorner(PathType pathType) { return pathType != PathType.WATER_BORDER && super.canCutCorner(pathType); @@ -488,6 +499,11 @@ public class Frog extends Animal { @Override protected PathFinder createPathFinder(int maxVisitedNodes) { this.nodeEvaluator = new Frog.FrogNodeEvaluator(true); + // DivineMC start - async path processing + if (org.bxteam.divinemc.config.DivineConfig.AsyncCategory.asyncPathfinding) { + return new PathFinder(this.nodeEvaluator, maxVisitedNodes, nodeEvaluatorGenerator); + } + // DivineMC end - async path processing return new PathFinder(this.nodeEvaluator, maxVisitedNodes); } } diff --git a/net/minecraft/world/entity/monster/Drowned.java b/net/minecraft/world/entity/monster/Drowned.java index 12650e3981fe48ab0cb4398e021e768eea03bd60..63e6fbcdead96fb98a527b8c6ba76d49c9d3eb66 100644 --- a/net/minecraft/world/entity/monster/Drowned.java +++ b/net/minecraft/world/entity/monster/Drowned.java @@ -304,7 +304,7 @@ public class Drowned extends Zombie implements RangedAttackMob { protected boolean closeToNextPos() { Path path = this.getNavigation().getPath(); - if (path != null) { + if (path != null && path.isProcessed()) { // DivineMC - ensure path is processed BlockPos target = path.getTarget(); if (target != null) { double d = this.distanceToSqr(target.getX(), target.getY(), target.getZ()); diff --git a/net/minecraft/world/entity/monster/Strider.java b/net/minecraft/world/entity/monster/Strider.java index 592095f4c78866c53745786a615f1681dcaf6bf6..06a6bc22e408ab4366715fb57edfede37a9e5117 100644 --- a/net/minecraft/world/entity/monster/Strider.java +++ b/net/minecraft/world/entity/monster/Strider.java @@ -560,9 +560,25 @@ public class Strider extends Animal implements ItemSteerable { super(strider, level); } + // DivineMC start - async path processing + private static final org.bxteam.divinemc.async.pathfinding.NodeEvaluatorGenerator nodeEvaluatorGenerator = (org.bxteam.divinemc.async.pathfinding.NodeEvaluatorFeatures nodeEvaluatorFeatures) -> { + WalkNodeEvaluator nodeEvaluator = new WalkNodeEvaluator(); + nodeEvaluator.setCanPassDoors(nodeEvaluatorFeatures.canPassDoors()); + nodeEvaluator.setCanFloat(nodeEvaluatorFeatures.canFloat()); + nodeEvaluator.setCanWalkOverFences(nodeEvaluatorFeatures.canWalkOverFences()); + nodeEvaluator.setCanOpenDoors(nodeEvaluatorFeatures.canOpenDoors()); + return nodeEvaluator; + }; + // DivineMC end - async path processing + @Override protected PathFinder createPathFinder(int maxVisitedNodes) { this.nodeEvaluator = new WalkNodeEvaluator(); + // DivineMC start - async path processing + if (org.bxteam.divinemc.config.DivineConfig.AsyncCategory.asyncPathfinding) { + return new PathFinder(this.nodeEvaluator, maxVisitedNodes, nodeEvaluatorGenerator); + } + // DivineMC end return new PathFinder(this.nodeEvaluator, maxVisitedNodes); } diff --git a/net/minecraft/world/entity/monster/warden/Warden.java b/net/minecraft/world/entity/monster/warden/Warden.java index e3478244e430faa614f23c288019303bd6bb0e04..862a7d464e1045e543049523d771bf79e8da7541 100644 --- a/net/minecraft/world/entity/monster/warden/Warden.java +++ b/net/minecraft/world/entity/monster/warden/Warden.java @@ -572,6 +572,16 @@ public class Warden extends Monster implements VibrationSystem { @Override protected PathFinder createPathFinder(int maxVisitedNodes) { this.nodeEvaluator = new WalkNodeEvaluator(); + // DivineMC start - async path processing + if (org.bxteam.divinemc.config.DivineConfig.AsyncCategory.asyncPathfinding) { + return new PathFinder(this.nodeEvaluator, maxVisitedNodes, GroundPathNavigation.nodeEvaluatorGenerator) { + @Override + protected float distance(Node first, Node second) { + return first.distanceToXZ(second); + } + }; + } + // DivineMC end - async path processing return new PathFinder(this.nodeEvaluator, maxVisitedNodes) { @Override protected float distance(Node first, Node second) { diff --git a/net/minecraft/world/level/pathfinder/Path.java b/net/minecraft/world/level/pathfinder/Path.java index d8d086b54f07a855cf312b6f742802e267dfd034..bd02babf2a9bb4bd5585f408deeba0c70b721dd0 100644 --- a/net/minecraft/world/level/pathfinder/Path.java +++ b/net/minecraft/world/level/pathfinder/Path.java @@ -11,7 +11,7 @@ import net.minecraft.util.VisibleForDebug; import net.minecraft.world.entity.Entity; import net.minecraft.world.phys.Vec3; -public final class Path { +public class Path { public static final StreamCodec STREAM_CODEC = StreamCodec.of((buffer, value) -> value.writeToStream(buffer), Path::createFromStream); public final List nodes; @Nullable @@ -28,6 +28,17 @@ public final class Path { this.reached = reached; } + // DivineMC start - async path processing + /** + * checks if the path is completely processed in the case of it being computed async + * + * @return true if the path is processed + */ + public boolean isProcessed() { + return true; + } + // DivineMC end - async path processing + public void advance() { this.nextNodeIndex++; } @@ -101,6 +112,7 @@ public final class Path { } public boolean sameAs(@Nullable Path pathEntity) { + if (pathEntity == this) return true; // DivineMC - async path processing return pathEntity != null && this.nodes.equals(pathEntity.nodes); } diff --git a/net/minecraft/world/level/pathfinder/PathFinder.java b/net/minecraft/world/level/pathfinder/PathFinder.java index 98abda72d88fb38a5427a15cc59094f3a7db30dc..d829ed8c15779d2c8f2df51d2136f206c79fd2bf 100644 --- a/net/minecraft/world/level/pathfinder/PathFinder.java +++ b/net/minecraft/world/level/pathfinder/PathFinder.java @@ -23,11 +23,19 @@ public class PathFinder { public final NodeEvaluator nodeEvaluator; private final BinaryHeap openSet = new BinaryHeap(); private BooleanSupplier captureDebug = () -> false; + private final @Nullable org.bxteam.divinemc.async.pathfinding.NodeEvaluatorGenerator nodeEvaluatorGenerator; // DivineMC - we use this later to generate an evaluator - public PathFinder(NodeEvaluator nodeEvaluator, int maxVisitedNodes) { + // DivineMC start - support nodeEvaluatorgenerators + public PathFinder(NodeEvaluator nodeEvaluator, int maxVisitedNodes, @Nullable org.bxteam.divinemc.async.pathfinding.NodeEvaluatorGenerator nodeEvaluatorGenerator) { // DivineMC - add nodeEvaluatorGenerator this.nodeEvaluator = nodeEvaluator; this.maxVisitedNodes = maxVisitedNodes; + this.nodeEvaluatorGenerator = nodeEvaluatorGenerator; + } + + public PathFinder(NodeEvaluator nodeEvaluator, int maxVisitedNodes) { + this(nodeEvaluator, maxVisitedNodes, null); } + // DivineMC end - support nodeEvaluatorgenerators public void setCaptureDebug(BooleanSupplier captureDebug) { this.captureDebug = captureDebug; @@ -39,26 +47,63 @@ public class PathFinder { @Nullable public Path findPath(PathNavigationRegion region, Mob mob, Set targetPositions, float maxRange, int accuracy, float searchDepthMultiplier) { - this.openSet.clear(); - this.nodeEvaluator.prepare(region, mob); - Node start = this.nodeEvaluator.getStart(); + // DivineMC start - use a generated evaluator if we have one otherwise run sync + if (!org.bxteam.divinemc.config.DivineConfig.AsyncCategory.asyncPathfinding) + this.openSet.clear(); // it's always cleared in processPath + NodeEvaluator nodeEvaluator = this.nodeEvaluatorGenerator == null + ? this.nodeEvaluator + : org.bxteam.divinemc.async.pathfinding.NodeEvaluatorCache.takeNodeEvaluator(this.nodeEvaluatorGenerator, this.nodeEvaluator); + nodeEvaluator.prepare(region, mob); + Node start = nodeEvaluator.getStart(); + // DivineMC end - use a generated evaluator if we have one otherwise run sync if (start == null) { + org.bxteam.divinemc.async.pathfinding.NodeEvaluatorCache.removeNodeEvaluator(nodeEvaluator); // DivineMC - handle nodeEvaluatorGenerator return null; } else { // Paper start - Perf: remove streams and optimize collection List> map = Lists.newArrayList(); for (BlockPos pos : targetPositions) { - map.add(new java.util.AbstractMap.SimpleEntry<>(this.nodeEvaluator.getTarget(pos.getX(), pos.getY(), pos.getZ()), pos)); + map.add(new java.util.AbstractMap.SimpleEntry<>(nodeEvaluator.getTarget(pos.getX(), pos.getY(), pos.getZ()), pos)); // DivineMC - handle nodeEvaluatorGenerator } // Paper end - Perf: remove streams and optimize collection - Path path = this.findPath(start, map, maxRange, accuracy, searchDepthMultiplier); - this.nodeEvaluator.done(); - return path; + // DivineMC start - async path processing + if (this.nodeEvaluatorGenerator == null) { + // run sync :( + org.bxteam.divinemc.async.pathfinding.NodeEvaluatorCache.removeNodeEvaluator(nodeEvaluator); + return this.findPath(start, map, maxRange, accuracy, searchDepthMultiplier); + } + + return new org.bxteam.divinemc.async.pathfinding.AsyncPath(Lists.newArrayList(), targetPositions, () -> { + try { + return this.processPath(nodeEvaluator, start, map, maxRange, accuracy, searchDepthMultiplier); + } catch (Exception e) { + e.printStackTrace(); + return null; + } finally { + nodeEvaluator.done(); + org.bxteam.divinemc.async.pathfinding.NodeEvaluatorCache.returnNodeEvaluator(nodeEvaluator); + } + }); + // DivineMC end - async path processing } } @Nullable private Path findPath(Node node, List> positions, float maxRange, int accuracy, float searchDepthMultiplier) { // Paper - optimize collection + // DivineMC start - split pathfinding into the original sync method for compat and processing for delaying + try { + return this.processPath(this.nodeEvaluator, node, positions, maxRange, accuracy, searchDepthMultiplier); + } catch (Exception e) { + e.printStackTrace(); + return null; + } finally { + this.nodeEvaluator.done(); + } + } + + private synchronized @org.jetbrains.annotations.NotNull Path processPath(NodeEvaluator nodeEvaluator, Node node, List> positions, float maxRange, int accuracy, float searchDepthMultiplier) { // sync to only use the caching functions in this class on a single thread + org.apache.commons.lang3.Validate.isTrue(!positions.isEmpty()); // ensure that we have at least one position, which means we'll always return a path + // DivineMC end - split pathfinding into the original sync method for compat and processing for delaying // Set set = targetPositions.keySet(); // Paper - unused node.g = 0.0F; node.h = this.getBestH(node, positions); // Paper - optimize collection @@ -96,7 +141,7 @@ public class PathFinder { if (!(node1.distanceTo(node) >= maxRange)) { - int neighbors = this.nodeEvaluator.getNeighbors(this.neighbors, node1); + int neighbors = nodeEvaluator.getNeighbors(this.neighbors, node1); // DivineMC - use provided nodeEvaluator for (int i2 = 0; i2 < neighbors; i2++) { Node node2 = this.neighbors[i2];