PathNavigation .java

net.minecraft.world.entity.ai.navigation.PathNavigation (class): members: STUCK_THRESHOLD_DISTANCE_FACTOR, updatePathfinderMaxVisitedNodes, isStuck.

net.minecraft.world.entity.ai.navigationclass437 linescommon14.7 KB

API Surface (31)

void updatePathfinderMaxVisitedNodes()
void setRequiredPathLength(final float length)
void resetMaxVisitedNodesMultiplier()
void setMaxVisitedNodesMultiplier(final float maxVisitedNodesMultiplier)
void setSpeedModifier(final double speedModifier)
void recomputePath()
boolean moveTo(final double x, final double y, final double z, final double speedModifier)
boolean moveTo(final double x, final double y, final double z, final int reachRange, final double speedModifier)
boolean moveTo(final Entity target, final double speedModifier)
boolean moveTo(final Entity target, final int reachRange, final double speedModifier)
boolean moveTo(final @Nullable Path newPath, final double speedModifier)
void tick()
double getGroundY(final Vec3 target)
void followThePath()
void doStuckDetection(final Vec3 mobPos)
boolean isDone()
boolean isInProgress()
void stop()
void trimPath()
boolean canMoveDirectly(final Vec3 startPos, final Vec3 stopPos)
boolean canCutCorner(final PathType pathType)
boolean isClearForMovementBetween(final Mob mob, final Vec3 startPos, final Vec3 stopPos, final boolean blockedByFluids)
boolean isStableDestination(final BlockPos pos)
NodeEvaluator getNodeEvaluator()
void setCanFloat(final boolean canFloat)
boolean canFloat()
boolean shouldRecomputePath(final BlockPos pos)
float getMaxDistanceToWaypoint()
float getMaxVerticalDistanceToWaypoint()
boolean isStuck()
void setCanOpenDoors(final boolean canOpenDoors)

Fields & Constants (24)

MAX_TIME_RECOMPUTE
STUCK_CHECK_INTERVAL
STUCK_THRESHOLD_DISTANCE_FACTOR
mob
level
path
speedModifier
tick
lastStuckCheck
lastStuckCheckPos
timeoutCachedNode
timeoutTimer
lastTimeoutCheck
timeoutLimit
maxDistanceToWaypoint
hasDelayedRecomputation
timeLastRecompute
nodeEvaluator
targetPos
reachRange
maxVisitedNodesMultiplier
pathFinder
isStuck
requiredPathLength

String literals (1)

"pathfind"

Full Source

PathNavigation.java437 lines · Minecraft 26.3 · verbatim
1
package net.minecraft.world.entity.ai.navigation;
2
3
import com.google.common.collect.ImmutableSet;
4
import java.util.Set;
5
import java.util.stream.Collectors;
6
import java.util.stream.Stream;
7
import net.minecraft.core.BlockPos;
8
import net.minecraft.core.Vec3i;
9
import net.minecraft.server.level.ServerLevel;
10
import net.minecraft.tags.BlockTags;
11
import net.minecraft.util.Mth;
12
import net.minecraft.util.debug.DebugSubscriptions;
13
import net.minecraft.util.debug.ServerDebugSubscribers;
14
import net.minecraft.util.profiling.Profiler;
15
import net.minecraft.util.profiling.ProfilerFiller;
16
import net.minecraft.world.entity.Entity;
17
import net.minecraft.world.entity.Mob;
18
import net.minecraft.world.entity.ai.attributes.Attributes;
19
import net.minecraft.world.level.ClipContext;
20
import net.minecraft.world.level.Level;
21
import net.minecraft.world.level.PathNavigationRegion;
22
import net.minecraft.world.level.block.state.BlockState;
23
import net.minecraft.world.level.pathfinder.Node;
24
import net.minecraft.world.level.pathfinder.NodeEvaluator;
25
import net.minecraft.world.level.pathfinder.Path;
26
import net.minecraft.world.level.pathfinder.PathFinder;
27
import net.minecraft.world.level.pathfinder.PathType;
28
import net.minecraft.world.level.pathfinder.WalkNodeEvaluator;
29
import net.minecraft.world.phys.HitResult;
30
import net.minecraft.world.phys.Vec3;
31
import org.jspecify.annotations.Nullable;
32
33
public abstract class PathNavigation {
34
	private static final int MAX_TIME_RECOMPUTE = 20;
35
	private static final int STUCK_CHECK_INTERVAL = 100;
36
	private static final float STUCK_THRESHOLD_DISTANCE_FACTOR = 0.25F;
37
	protected final Mob mob;
38
	protected final Level level;
39
	protected @Nullable Path path;
40
	protected double speedModifier;
41
	protected int tick;
42
	protected int lastStuckCheck;
43
	protected Vec3 lastStuckCheckPos = Vec3.ZERO;
44
	protected Vec3i timeoutCachedNode = Vec3i.ZERO;
45
	protected long timeoutTimer;
46
	protected long lastTimeoutCheck;
47
	protected double timeoutLimit;
48
	protected float maxDistanceToWaypoint = 0.5F;
49
	protected boolean hasDelayedRecomputation;
50
	protected long timeLastRecompute;
51
	protected NodeEvaluator nodeEvaluator;
52
	private @Nullable BlockPos targetPos;
53
	private int reachRange;
54
	private float maxVisitedNodesMultiplier = 1.0F;
55
	private final PathFinder pathFinder;
56
	private boolean isStuck;
57
	private float requiredPathLength = 16.0F;
58
59
	public PathNavigation(final Mob mob, final Level level) {
60
		this.mob = mob;
61
		this.level = level;
62
		this.pathFinder = this.createPathFinder(Mth.floor(mob.getAttributeBaseValue(Attributes.FOLLOW_RANGE) * 16.0));
63
		if (level instanceof ServerLevel serverLevel) {
64
			ServerDebugSubscribers subscribers = serverLevel.getServer().debugSubscribers();
65
			this.pathFinder.setCaptureDebug(() -> subscribers.hasAnySubscriberFor(DebugSubscriptions.ENTITY_PATHS));
66
		}
67
	}
68
69
	public void updatePathfinderMaxVisitedNodes() {
70
		int maxVisitedNodes = Mth.floor(this.getMaxPathLength() * 16.0F);
71
		this.pathFinder.setMaxVisitedNodes(maxVisitedNodes);
72
	}
73
74
	public void setRequiredPathLength(final float length) {
75
		this.requiredPathLength = length;
76
		this.updatePathfinderMaxVisitedNodes();
77
	}
78
79
	private float getMaxPathLength() {
80
		return Math.max((float)this.mob.getAttributeValue(Attributes.FOLLOW_RANGE), this.requiredPathLength);
81
	}
82
83
	public void resetMaxVisitedNodesMultiplier() {
84
		this.maxVisitedNodesMultiplier = 1.0F;
85
	}
86
87
	public void setMaxVisitedNodesMultiplier(final float maxVisitedNodesMultiplier) {
88
		this.maxVisitedNodesMultiplier = maxVisitedNodesMultiplier;
89
	}
90
91
	public @Nullable BlockPos getTargetPos() {
92
		return this.targetPos;
93
	}
94
95
	protected abstract PathFinder createPathFinder(final int maxVisitedNodes);
96
97
	public void setSpeedModifier(final double speedModifier) {
98
		this.speedModifier = speedModifier;
99
	}
100
101
	public void recomputePath() {
102
		if (this.level.getGameTime() - this.timeLastRecompute <= 20L || !this.canUpdatePath()) {
103
			this.hasDelayedRecomputation = true;
104
		} else if (this.targetPos != null) {
105
			this.path = null;
106
			this.path = this.createPath(this.targetPos, this.reachRange);
107
			this.timeLastRecompute = this.level.getGameTime();
108
			this.hasDelayedRecomputation = false;
109
		}
110
	}
111
112
	public final @Nullable Path createPath(final double x, final double y, final double z, final int reachRange) {
113
		return this.createPath(BlockPos.containing(x, y, z), reachRange);
114
	}
115
116
	public @Nullable Path createPath(final Stream<BlockPos> positions, final int reachRange) {
117
		return this.createPath(positions.collect(Collectors.toSet()), 8, false, reachRange);
118
	}
119
120
	public @Nullable Path createPath(final Set<BlockPos> positions, final int reachRange) {
121
		return this.createPath(positions, 8, false, reachRange);
122
	}
123
124
	public @Nullable Path createPath(final BlockPos pos, final int reachRange) {
125
		return this.createPath(ImmutableSet.of(pos), 8, false, reachRange);
126
	}
127
128
	public @Nullable Path createPath(final BlockPos pos, final int reachRange, final int maxPathLength) {
129
		return this.createPath(ImmutableSet.of(pos), 8, false, reachRange, maxPathLength);
130
	}
131
132
	public @Nullable Path createPath(final Entity target, final int reachRange) {
133
		return this.createPath(ImmutableSet.of(target.blockPosition()), 16, true, reachRange);
134
	}
135
136
	protected @Nullable Path createPath(final Set<BlockPos> targets, final int radiusOffset, final boolean above, final int reachRange) {
137
		return this.createPath(targets, radiusOffset, above, reachRange, this.getMaxPathLength());
138
	}
139
140
	protected @Nullable Path createPath(final Set<BlockPos> targets, final int radiusOffset, final boolean above, final int reachRange, final float maxPathLength) {
141
		if (targets.isEmpty()) {
142
			return null;
143
		}
144
145
		if (this.mob.getY() < this.level.getMinY()) {
146
			return null;
147
		}
148
149
		if (!this.canUpdatePath()) {
150
			return null;
151
		}
152
153
		if (this.path != null && !this.path.isDone() && targets.contains(this.targetPos)) {
154
			return this.path;
155
		}
156
157
		ProfilerFiller profiler = Profiler.get();
158
		profiler.push("pathfind");
159
		BlockPos fromPos = above ? this.mob.blockPosition().above() : this.mob.blockPosition();
160
		int radius = (int)(maxPathLength + radiusOffset);
161
		PathNavigationRegion region = new PathNavigationRegion(this.level, fromPos.offset(-radius, -radius, -radius), fromPos.offset(radius, radius, radius));
162
		Path path = this.pathFinder.findPath(region, this.mob, targets, maxPathLength, reachRange, this.maxVisitedNodesMultiplier);
163
		profiler.pop();
164
		if (path != null && path.getTarget() != null) {
165
			this.targetPos = path.getTarget();
166
			this.reachRange = reachRange;
167
			this.resetStuckTimeout();
168
		}
169
170
		return path;
171
	}
172
173
	public boolean moveTo(final double x, final double y, final double z, final double speedModifier) {
174
		return this.moveTo(this.createPath(x, y, z, 1), speedModifier);
175
	}
176
177
	public boolean moveTo(final double x, final double y, final double z, final int reachRange, final double speedModifier) {
178
		return this.moveTo(this.createPath(x, y, z, reachRange), speedModifier);
179
	}
180
181
	public boolean moveTo(final Entity target, final double speedModifier) {
182
		return this.moveTo(target, 1, speedModifier);
183
	}
184
185
	public boolean moveTo(final Entity target, final int reachRange, final double speedModifier) {
186
		Path newPath = this.createPath(target, reachRange);
187
		return newPath != null && this.moveTo(newPath, speedModifier);
188
	}
189
190
	public boolean moveTo(final @Nullable Path newPath, final double speedModifier) {
191
		if (newPath == null) {
192
			this.path = null;
193
			return false;
194
		}
195
196
		if (!newPath.sameAs(this.path)) {
197
			this.path = newPath;
198
		}
199
200
		if (this.isDone()) {
201
			return false;
202
		}
203
204
		this.trimPath();
205
		if (this.path.getNodeCount() <= 0) {
206
			return false;
207
		}
208
209
		this.speedModifier = speedModifier;
210
		Vec3 mobPos = this.getTempMobPos();
211
		this.lastStuckCheck = this.tick;
212
		this.lastStuckCheckPos = mobPos;
213
		return true;
214
	}
215
216
	public @Nullable Path getPath() {
217
		return this.path;
218
	}
219
220
	public void tick() {
221
		this.tick++;
222
		if (this.hasDelayedRecomputation) {
223
			this.recomputePath();
224
		}
225
226
		if (!this.isDone()) {
227
			if (this.canUpdatePath()) {
228
				this.followThePath();
229
			} else if (this.path != null && !this.path.isDone()) {
230
				Vec3 mobPos = this.getTempMobPos();
231
				Vec3 pos = this.path.getNextEntityPos(this.mob);
232
				if (mobPos.y > pos.y && !this.mob.onGround() && Mth.floor(mobPos.x) == Mth.floor(pos.x) && Mth.floor(mobPos.z) == Mth.floor(pos.z)) {
233
					this.path.advance();
234
				}
235
			}
236
237
			if (!this.isDone()) {
238
				Vec3 target = this.path.getNextEntityPos(this.mob);
239
				this.mob.getMoveControl().setWantedPosition(target.x, this.getGroundY(target), target.z, this.speedModifier);
240
			}
241
		}
242
	}
243
244
	protected double getGroundY(final Vec3 target) {
245
		BlockPos blockPos = BlockPos.containing(target);
246
		return this.level.getBlockState(blockPos.below()).isAir() ? target.y : WalkNodeEvaluator.getFloorLevel(this.level, blockPos);
247
	}
248
249
	protected void followThePath() {
250
		Vec3 mobPos = this.getTempMobPos();
251
		this.maxDistanceToWaypoint = this.mob.getBbWidth() > 0.75F ? this.mob.getBbWidth() / 2.0F : 0.75F - this.mob.getBbWidth() / 2.0F;
252
		Vec3i currentNodePos = this.path.getNextNodePos();
253
		double xDistance = Math.abs(this.mob.getX() - (currentNodePos.getX() + 0.5));
254
		double yDistance = Math.abs(this.mob.getY() - currentNodePos.getY());
255
		double zDistance = Math.abs(this.mob.getZ() - (currentNodePos.getZ() + 0.5));
256
		boolean isCloseEnoughToCurrentNode = xDistance < this.maxDistanceToWaypoint
257
			&& zDistance < this.maxDistanceToWaypoint
258
			&& yDistance < this.getMaxVerticalDistanceToWaypoint();
259
		if (isCloseEnoughToCurrentNode || this.canCutCorner(this.path.getNextNode().type) && this.shouldTargetNextNodeInDirection(mobPos)) {
260
			this.path.advance();
261
		}
262
263
		this.doStuckDetection(mobPos);
264
	}
265
266
	private boolean shouldTargetNextNodeInDirection(final Vec3 mobPosition) {
267
		if (this.path.getNextNodeIndex() + 1 >= this.path.getNodeCount()) {
268
			return false;
269
		}
270
271
		Vec3 currentNode = Vec3.atBottomCenterOf(this.path.getNextNodePos());
272
		if (!mobPosition.closerThan(currentNode, 2.0)) {
273
			return false;
274
		}
275
276
		if (this.canMoveDirectly(mobPosition, this.path.getNextEntityPos(this.mob))) {
277
			return true;
278
		}
279
280
		Vec3 nextNode = Vec3.atBottomCenterOf(this.path.getNodePos(this.path.getNextNodeIndex() + 1));
281
		Vec3 mobToCurrent = currentNode.subtract(mobPosition);
282
		Vec3 mobToNext = nextNode.subtract(mobPosition);
283
		double mobToCurrentSqr = mobToCurrent.lengthSqr();
284
		double mobToNextSqr = mobToNext.lengthSqr();
285
		boolean closerToNextThanCurrent = mobToNextSqr < mobToCurrentSqr;
286
		boolean withinCurrentBlock = mobToCurrentSqr < 0.5;
287
		if (!closerToNextThanCurrent && !withinCurrentBlock) {
288
			return false;
289
		}
290
291
		Vec3 mobDirection = mobToCurrent.normalize();
292
		Vec3 pathDirection = mobToNext.normalize();
293
		return pathDirection.dot(mobDirection) < 0.0;
294
	}
295
296
	protected void doStuckDetection(final Vec3 mobPos) {
297
		if (this.tick - this.lastStuckCheck > 100) {
298
			float effectiveSpeed = this.mob.getSpeed() >= 1.0F ? this.mob.getSpeed() : this.mob.getSpeed() * this.mob.getSpeed();
299
			float thresholdDistance = effectiveSpeed * 100.0F * 0.25F;
300
			if (mobPos.distanceToSqr(this.lastStuckCheckPos) < thresholdDistance * thresholdDistance) {
301
				this.isStuck = true;
302
				this.stop();
303
			} else {
304
				this.isStuck = false;
305
			}
306
307
			this.lastStuckCheck = this.tick;
308
			this.lastStuckCheckPos = mobPos;
309
		}
310
311
		if (this.path != null && !this.path.isDone()) {
312
			Vec3i pos = this.path.getNextNodePos();
313
			long time = this.level.getGameTime();
314
			if (pos.equals(this.timeoutCachedNode)) {
315
				this.timeoutTimer = this.timeoutTimer + (time - this.lastTimeoutCheck);
316
			} else {
317
				this.timeoutCachedNode = pos;
318
				double distToNode = mobPos.distanceTo(Vec3.atBottomCenterOf(this.timeoutCachedNode));
319
				this.timeoutLimit = this.mob.getSpeed() > 0.0F ? distToNode / this.mob.getSpeed() * 20.0 : 0.0;
320
			}
321
322
			if (this.timeoutLimit > 0.0 && this.timeoutTimer > this.timeoutLimit * 3.0) {
323
				this.timeoutPath();
324
			}
325
326
			this.lastTimeoutCheck = time;
327
		}
328
	}
329
330
	private void timeoutPath() {
331
		this.resetStuckTimeout();
332
		this.stop();
333
	}
334
335
	private void resetStuckTimeout() {
336
		this.timeoutCachedNode = Vec3i.ZERO;
337
		this.timeoutTimer = 0L;
338
		this.timeoutLimit = 0.0;
339
		this.isStuck = false;
340
	}
341
342
	public boolean isDone() {
343
		return this.path == null || this.path.isDone();
344
	}
345
346
	public boolean isInProgress() {
347
		return !this.isDone();
348
	}
349
350
	public void stop() {
351
		this.path = null;
352
	}
353
354
	protected abstract Vec3 getTempMobPos();
355
356
	protected abstract boolean canUpdatePath();
357
358
	protected void trimPath() {
359
		if (this.path != null) {
360
			for (int i = 0; i < this.path.getNodeCount(); i++) {
361
				Node node = this.path.getNode(i);
362
				Node nextNode = i + 1 < this.path.getNodeCount() ? this.path.getNode(i + 1) : null;
363
				BlockState state = this.level.getBlockState(new BlockPos(node.x, node.y, node.z));
364
				if (state.is(BlockTags.CAULDRONS)) {
365
					this.path.replaceNode(i, node.cloneAndMove(node.x, node.y + 1, node.z));
366
					if (nextNode != null && node.y >= nextNode.y) {
367
						this.path.replaceNode(i + 1, node.cloneAndMove(nextNode.x, node.y + 1, nextNode.z));
368
					}
369
				}
370
			}
371
		}
372
	}
373
374
	protected boolean canMoveDirectly(final Vec3 startPos, final Vec3 stopPos) {
375
		return false;
376
	}
377
378
	public boolean canCutCorner(final PathType pathType) {
379
		return pathType != PathType.FIRE_IN_NEIGHBOR && pathType != PathType.DAMAGING_IN_NEIGHBOR && pathType != PathType.WALKABLE_DOOR;
380
	}
381
382
	protected static boolean isClearForMovementBetween(final Mob mob, final Vec3 startPos, final Vec3 stopPos, final boolean blockedByFluids) {
383
		Vec3 to = new Vec3(stopPos.x, stopPos.y + mob.getBbHeight() * 0.5, stopPos.z);
384
		return mob.level()
385
				.clip(new ClipContext(startPos, to, ClipContext.Block.COLLIDER, blockedByFluids ? ClipContext.Fluid.ANY : ClipContext.Fluid.NONE, mob))
386
				.getType()
387
			== HitResult.Type.MISS;
388
	}
389
390
	public boolean isStableDestination(final BlockPos pos) {
391
		BlockPos below = pos.below();
392
		return this.level.getBlockState(below).isSolidRender();
393
	}
394
395
	public NodeEvaluator getNodeEvaluator() {
396
		return this.nodeEvaluator;
397
	}
398
399
	public void setCanFloat(final boolean canFloat) {
400
		this.nodeEvaluator.setCanFloat(canFloat);
401
	}
402
403
	public boolean canFloat() {
404
		return this.nodeEvaluator.canFloat();
405
	}
406
407
	public boolean shouldRecomputePath(final BlockPos pos) {
408
		if (this.hasDelayedRecomputation) {
409
			return false;
410
		} else if (this.path != null && !this.path.isDone() && this.path.getNodeCount() != 0) {
411
			Node target = this.path.getEndNode();
412
			Vec3 middlePos = new Vec3((target.x + this.mob.getX()) / 2.0, (target.y + this.mob.getY()) / 2.0, (target.z + this.mob.getZ()) / 2.0);
413
			return pos.closerToCenterThan(middlePos, this.path.getNodeCount() - this.path.getNextNodeIndex());
414
		} else {
415
			return false;
416
		}
417
	}
418
419
	public float getMaxDistanceToWaypoint() {
420
		return this.maxDistanceToWaypoint;
421
	}
422
423
	public float getMaxVerticalDistanceToWaypoint() {
424
		return 1.0F;
425
	}
426
427
	public boolean isStuck() {
428
		return this.isStuck;
429
	}
430
431
	public abstract boolean canNavigateGround();
432
433
	public void setCanOpenDoors(final boolean canOpenDoors) {
434
		this.nodeEvaluator.setCanOpenDoors(canOpenDoors);
435
	}
436
}
437

Decompiled Minecraft 26.3 source of PathNavigation (net/minecraft/world/entity/ai/navigation/PathNavigation.java) with Mojang official mappings, stored verbatim on the site.