forked from Tofaa2/EntityLib
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathNPCMovement.java
More file actions
528 lines (455 loc) · 19.3 KB
/
Copy pathNPCMovement.java
File metadata and controls
528 lines (455 loc) · 19.3 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
package me.tofaa.entitylib.npc;
import com.github.retrooper.packetevents.PacketEventsAPI;
import com.github.retrooper.packetevents.protocol.world.Location;
import java.util.Map;
import java.util.UUID;
import java.util.concurrent.ConcurrentHashMap;
import com.github.retrooper.packetevents.wrapper.play.server.WrapperPlayServerEntityHeadLook;
import me.tofaa.entitylib.EntityLib;
import me.tofaa.entitylib.movement.MovementEngine;
import me.tofaa.entitylib.movement.SpigotMovementEngine;
import me.tofaa.entitylib.npc.path.NPCPath;
import me.tofaa.entitylib.npc.NPCRegistry;
import me.tofaa.entitylib.wrapper.WrapperEntity;
import org.bukkit.Bukkit;
import org.bukkit.World;
import org.bukkit.block.Block;
import org.bukkit.scheduler.BukkitTask;
import org.bukkit.entity.Player;
import org.jetbrains.annotations.NotNull;
public class NPCMovement {
private static SpigotMovementEngine engine;
private static BukkitTask tickTask;
private static BukkitTask rotationTask;
private static BukkitTask viewerSyncTask;
private static final Map<Integer, PathFollowing> activeFollowers =
new ConcurrentHashMap<>();
public static void init(org.bukkit.plugin.java.JavaPlugin plugin) {
if (engine == null) {
engine = new SpigotMovementEngine();
}
if (tickTask == null) {
tickTask =
org.bukkit.Bukkit.getScheduler().runTaskTimerAsynchronously(
plugin,
() -> {
engine.tick();
processPathFollowing();
},
1L,
1L
);
}
if (rotationTask == null) {
rotationTask =
org.bukkit.Bukkit.getScheduler().runTaskTimerAsynchronously(
plugin,
() -> processAllNPCHeadRotation(),
1L,
2L
);
}
if (viewerSyncTask == null) {
viewerSyncTask =
org.bukkit.Bukkit.getScheduler().runTaskTimerAsynchronously(
plugin,
() -> processViewerSync(),
1L,
10L
);
}
}
public static void shutdown() {
if (tickTask != null) {
tickTask.cancel();
tickTask = null;
}
if (rotationTask != null) {
rotationTask.cancel();
rotationTask = null;
}
if (viewerSyncTask != null) {
viewerSyncTask.cancel();
viewerSyncTask = null;
}
activeFollowers.clear();
}
private static void processViewerSync() {
for (NPC npc : NPCRegistry.getAll()) {
if (!npc.isSpawned() || !npc.getEntity().isPresent()) continue;
WrapperEntity entity = npc.getEntity().get();
World npcWorld = npc.getWorld();
if (npcWorld == null) continue;
Location npcLocation = entity.getLocation();
npc.getHologram().ifPresent(hologram -> {
boolean isSittingNow = npc.getOptions().isSitting();
double yOff = isSittingNow ? 1.1 : 1.0;
Location npcLoc = npc.getEntity().get().getLocation();
hologram.teleport(new Location(npcLoc.getX(), npcLoc.getY() + yOff, npcLoc.getZ(), npcLoc.getYaw(), npcLoc.getPitch()));
});
boolean permanentlyVisible = npc.getOptions().isPermanentlyVisible();
double viewDistance = npc.getOptions().getViewDistance();
boolean isSitting = npc.getSittingEntity().isPresent();
for (org.bukkit.entity.Player player : org.bukkit.Bukkit.getOnlinePlayers()) {
if (player.getWorld() != npcWorld) continue;
UUID playerId = player.getUniqueId();
boolean isViewer = entity.getViewers().contains(playerId);
boolean shouldSee = permanentlyVisible || isPlayerInRange(player, npcLocation, viewDistance);
if (shouldSee && !isViewer) {
if (isSitting) {
npc.getSittingEntity().ifPresent(sitting -> sitting.addViewer(playerId));
}
entity.addViewer(playerId);
npc.getHologram().ifPresent(h -> h.addViewer(playerId));
if (entity instanceof me.tofaa.entitylib.wrapper.WrapperPlayer) {
npc.doStupidDogshitForOldClients(player);
}
} else if (!shouldSee && isViewer) {
entity.removeViewer(playerId);
if (isSitting) {
npc.getSittingEntity().ifPresent(sitting -> sitting.removeViewer(playerId));
}
npc.getHologram().ifPresent(h -> h.removeViewer(playerId));
}
}
}
}
private static boolean isPlayerInRange(Player player, Location npcLocation, double range) {
org.bukkit.Location playerLoc = player.getLocation();
double dx = playerLoc.getX() - npcLocation.getX();
double dy = playerLoc.getY() - npcLocation.getY();
double dz = playerLoc.getZ() - npcLocation.getZ();
return Math.sqrt(dx * dx + dy * dy + dz * dz) <= range;
}
private static void processAllNPCHeadRotation() {
for (NPC npc : NPCRegistry.getAll()) {
if (!npc.isSpawned() || !npc.getEntity().isPresent()) continue;
WrapperEntity entity = npc.getEntity().get();
Location npcLocation = entity.getLocation();
org.bukkit.World world = npc.getWorld();
if (world == null) continue;
float yaw;
if (npc.getOptions().isLookAtPlayersPerPlayer()) {
updatePerPlayerHeadRotation(npc, entity, npcLocation.getYaw());
continue;
} else if (npc.getOptions().isLookAtPlayers()) {
Player nearest = findNearestPlayer(npcLocation, world);
if (nearest != null) {
yaw = (float) (Math.toDegrees(
Math.atan2(
nearest.getLocation().getZ() - npcLocation.getZ(),
nearest.getLocation().getX() - npcLocation.getX()
)
) - 90);
} else {
yaw = npcLocation.getYaw();
}
} else if (npc.getOptions().isLookAtPath()) {
// Gets handled by the movement itself
continue;
} else {
continue;
}
entity.rotateHead(yaw, 0);
}
}
private static void processPathFollowing() {
for (PathFollowing follower : activeFollowers.values()) {
NPC npc = follower.npc;
NPCPath path = npc.getPath();
if (path.isPaused() || path.isFinished()) {
continue;
}
Location target = path.getCurrentWaypoint();
if (target == null) {
continue;
}
npc
.getEntity()
.ifPresent(entity -> {
Location current = entity.getLocation();
// Use horizontal (XZ) distance for waypoint arrival check
double hDistSq =
Math.pow(target.getX() - current.getX(), 2) +
Math.pow(target.getZ() - current.getZ(), 2);
if (hDistSq < 0.25 && Math.abs(target.getY() - current.getY()) < 1.5) {
path.advanceToNext();
return;
}
double speed = npc.getOptions().getMovementSpeed() * 0.1;
// --- Horizontal movement (XZ only) ---
double dx = target.getX() - current.getX();
double dz = target.getZ() - current.getZ();
double hLen = Math.sqrt(dx * dx + dz * dz);
double newX, newZ;
if (hLen > 0.01) {
dx /= hLen;
dz /= hLen;
newX = current.getX() + dx * speed;
newZ = current.getZ() + dz * speed;
} else {
newX = current.getX();
newZ = current.getZ();
dx = 0;
dz = 0;
}
// --- Vertical movement (jump + gravity physics) ---
double newY = current.getY();
if (npc.getOptions().isClampToGround()) {
World world = npc.getWorld();
if (world != null) {
int bx = (int) Math.floor(newX);
int bz = (int) Math.floor(newZ);
int feetY = (int) Math.floor(current.getY());
// Check if there's a solid block ahead at feet level (obstacle)
Block blockAtFeet = world.getBlockAt(bx, feetY, bz);
Block blockAboveFeet = world.getBlockAt(bx, feetY + 1, bz);
boolean obstacleAhead = !blockAtFeet.isPassable()
&& blockAboveFeet.isPassable();
// If we hit a 1-block obstacle and we're on the ground, jump
if (obstacleAhead && follower.isOnGround()) {
follower.jump();
}
// Apply vertical physics (gravity + velocity)
newY = follower.applyVerticalPhysics(current.getY());
// Resolve ground collision: find solid ground below new position
int newFeetY = (int) Math.floor(newY);
double groundLevel = findGroundLevel(world, bx, newFeetY, bz, feetY + 2);
if (newY <= groundLevel) {
// Landed on ground
newY = groundLevel;
follower.land(groundLevel);
} else {
// Still airborne
follower.setOnGround(false);
}
// If jumping into a ceiling (block above head), stop upward velocity
int headY = (int) Math.floor(newY + 1.8);
var blockAtHead = world.getBlockAt(bx, headY, bz);
if (!blockAtHead.isPassable() && follower.verticalVelocity > 0) {
follower.verticalVelocity = 0;
}
// If obstacle is 2+ blocks tall, don't move horizontally into it
if (!blockAtFeet.isPassable() && !blockAboveFeet.isPassable()) {
newX = current.getX();
newZ = current.getZ();
}
}
} else {
// No ground clamping: use linear Y interpolation (original behavior)
double dy = target.getY() - current.getY();
double fullLen = Math.sqrt(dx * dx + dy * dy + dz * dz);
if (fullLen > 0.01) {
newY = current.getY() + (dy / fullLen) * speed;
}
}
float yaw = npc.getOptions().isLookAtPath() ? npc.getPath().getYaw() : current.getYaw();
Location newLoc = new Location(
newX,
newY,
newZ,
yaw,
0
);
entity.teleport(newLoc);
entity.rotateHead(yaw, 0);
});
}
}
/**
* Finds the Y level of the ground (top of highest solid block) at the given XZ,
* searching downward from startY. Returns the Y on top of the first solid block found.
* If no solid block is found down to y=minY or world min, returns startY (no change).
*/
private static double findGroundLevel(org.bukkit.World world, int bx, int startY, int bz, int maxY) {
// Don't search too far down - limit to 4 blocks below current position
int minSearch = Math.max(world.getMinHeight(), startY - 4);
for (int y = startY; y >= minSearch; y--) {
var block = world.getBlockAt(bx, y, bz);
if (!block.isPassable()) {
// Ground found: NPC stands on top of this block
return y + 1;
}
}
// No ground found within search range, keep falling
return startY;
}
private static void updateGlobalHeadRotation(
NPC npc,
WrapperEntity entity,
float pathYaw
) {
World world = npc.getWorld();
if (world == null) return;
Location npcLocation = entity.getLocation();
Player nearest = findNearestPlayer(npcLocation, world);
float yaw = nearest != null
? (float) (Math.toDegrees(
Math.atan2(
nearest.getLocation().getZ() - npcLocation.getZ(),
nearest.getLocation().getX() - npcLocation.getX()
)
) - 90)
: pathYaw;
PacketEventsAPI<?> api = EntityLib.getApi().getPacketEvents();
for (UUID viewerId : entity.getViewers()) {
Player player = org.bukkit.Bukkit.getPlayer(viewerId);
if (player == null || player.getWorld() != world) continue;
WrapperPlayServerEntityHeadLook headPacket = new WrapperPlayServerEntityHeadLook(
entity.getEntityId(),
yaw
);
Object channel = api.getProtocolManager().getChannel(viewerId);
if (channel != null) {
api.getProtocolManager().sendPacket(channel, headPacket);
}
}
}
private static void updatePerPlayerHeadRotation(
NPC npc,
me.tofaa.entitylib.wrapper.WrapperEntity entity,
float pathYaw
) {
World world = npc.getWorld();
Location npcLocation = entity.getLocation();
PacketEventsAPI<?> api = EntityLib.getApi().getPacketEvents();
for (UUID viewerId : entity.getViewers()) {
Player player = org.bukkit.Bukkit.getPlayer(viewerId);
if (player == null || player.getWorld() != world) continue;
Player nearest = findNearestPlayer(player, npcLocation, world);
float yaw;
if (nearest != null) {
org.bukkit.Location playerLoc = nearest.getLocation();
yaw = (float) (Math.toDegrees(
Math.atan2(
playerLoc.getZ() - npcLocation.getZ(),
playerLoc.getX() - npcLocation.getX()
)
) - 90);
} else {
yaw = pathYaw;
}
WrapperPlayServerEntityHeadLook headPacket = new WrapperPlayServerEntityHeadLook(
entity.getEntityId(),
yaw
);
Object channel = api.getProtocolManager().getChannel(viewerId);
if (channel != null) {
api.getProtocolManager().sendPacket(channel, headPacket);
}
}
}
private static Player findNearestPlayer(Location npcLocation, World world) {
if (world == null) return null;
Player nearest = null;
double minDist = Double.MAX_VALUE;
for (Player player : Bukkit.getOnlinePlayers()) {
if (player.getWorld() != world) continue;
double dist = player.getLocation().distance(
new org.bukkit.Location(
world,
npcLocation.getX(),
npcLocation.getY(),
npcLocation.getZ()
)
);
if (dist < minDist) {
minDist = dist;
nearest = player;
}
}
return nearest;
}
private static Player findNearestPlayer(Player exclude, Location npcLocation, World world) {
if (world == null) return null;
Player nearest = null;
double minDist = Double.MAX_VALUE;
for (Player player : Bukkit.getOnlinePlayers()) {
if (player.equals(exclude)) continue;
if (player.getWorld() != world) continue;
double dist = player.getLocation().distance(
new org.bukkit.Location(
world,
npcLocation.getX(),
npcLocation.getY(),
npcLocation.getZ()
)
);
if (dist < minDist) {
minDist = dist;
nearest = player;
}
}
return nearest;
}
private static float getYawTowards(
Location loc,
org.bukkit.Location bukkitLoc
) {
double dx = bukkitLoc.getX() - loc.getX();
double dz = bukkitLoc.getZ() - loc.getZ();
return (float) (Math.toDegrees(Math.atan2(dz, dx)) - 90);
}
public static void startPathFollowing(NPC npc) {
NPCPath path = npc.getPath();
if (path.getWaypointCount() == 0) {
return;
}
path.setStarted(true);
activeFollowers.put(npc.hashCode(), new PathFollowing(npc));
}
public static void stop(NPC npc) {
activeFollowers.remove(npc.hashCode());
npc.getPath().setStarted(false);
npc.getEntity().ifPresent(engine::stopMovement);
}
public static boolean isMoving(NPC npc) {
return activeFollowers.containsKey(npc.hashCode());
}
public static @NotNull MovementEngine getEngine() {
return engine;
}
public static class PathFollowing {
private static final double GRAVITY = 0.08;
private static final double JUMP_VELOCITY = 0.42;
private final NPC npc;
private final long startTime;
private double verticalVelocity = 0.0;
private boolean onGround = true;
public PathFollowing(NPC npc) {
this.npc = npc;
this.startTime = System.currentTimeMillis();
}
public @NotNull NPC getNpc() {
return npc;
}
public long getStartTime() {
return startTime;
}
public void jump() {
if (onGround) {
verticalVelocity = JUMP_VELOCITY;
onGround = false;
}
}
public double applyVerticalPhysics(double currentY) {
if (onGround && verticalVelocity <= 0) {
verticalVelocity = 0;
return currentY;
}
verticalVelocity -= GRAVITY;
double newY = currentY + verticalVelocity;
return newY;
}
public void land(double groundY) {
onGround = true;
verticalVelocity = 0.0;
}
public boolean isOnGround() {
return onGround;
}
public void setOnGround(boolean onGround) {
this.onGround = onGround;
}
}
}