forked from Tofaa2/EntityLib
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathNPC.java
More file actions
587 lines (492 loc) · 18.1 KB
/
Copy pathNPC.java
File metadata and controls
587 lines (492 loc) · 18.1 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
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
package me.tofaa.entitylib.npc;
import com.github.retrooper.packetevents.PacketEvents;
import com.github.retrooper.packetevents.PacketEventsAPI;
import com.github.retrooper.packetevents.netty.channel.ChannelHelper;
import com.github.retrooper.packetevents.protocol.entity.type.EntityType;
import com.github.retrooper.packetevents.protocol.entity.type.EntityTypes;
import com.github.retrooper.packetevents.protocol.player.ClientVersion;
import com.github.retrooper.packetevents.protocol.player.GameMode;
import com.github.retrooper.packetevents.protocol.player.User;
import com.github.retrooper.packetevents.protocol.player.UserProfile;
import com.github.retrooper.packetevents.protocol.world.Location;
import java.util.*;
import java.util.concurrent.ConcurrentHashMap;
import com.github.retrooper.packetevents.wrapper.PacketWrapper;
import com.github.retrooper.packetevents.wrapper.play.server.WrapperPlayServerEntityHeadLook;
import com.github.retrooper.packetevents.wrapper.play.server.WrapperPlayServerPlayerInfo;
import io.github.retrooper.packetevents.util.viaversion.ViaVersionUtil;
import me.tofaa.entitylib.EntityLib;
import me.tofaa.entitylib.meta.EntityMeta;
import me.tofaa.entitylib.meta.other.ArmorStandMeta;
import me.tofaa.entitylib.meta.types.PlayerMeta;
import me.tofaa.entitylib.npc.path.NPCPath;
import me.tofaa.entitylib.npc.skin.NPCSkin;
import me.tofaa.entitylib.wrapper.WrapperEntity;
import me.tofaa.entitylib.wrapper.WrapperLivingEntity;
import me.tofaa.entitylib.wrapper.WrapperPlayer;
import me.tofaa.entitylib.wrapper.hologram.Hologram;
import net.kyori.adventure.text.Component;
import net.kyori.adventure.text.minimessage.MiniMessage;
import org.bukkit.Bukkit;
import org.bukkit.World;
import org.bukkit.entity.Player;
import org.bukkit.scoreboard.Scoreboard;
import org.bukkit.scoreboard.Team;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;
public class NPC {
private static final String TEAM_NAME = "spacenpcs";
private final String id;
private final EntityType entityType;
private final Map<UUID, PerPlayerData> perPlayerData;
private final NPCOptions options;
private final NPCPath path;
private WrapperEntity entity;
private WrapperEntity sittingEntity;
private Hologram hologram;
private String name;
private NPCSkin skin;
private boolean spawned;
private boolean hologramPassenger;
private Location spawnLocation;
private String worldName;
private String teamEntry;
public NPC(String id, EntityType entityType) {
this.id = id;
this.entityType = entityType;
this.perPlayerData = new ConcurrentHashMap<>();
this.options = new NPCOptions();
this.path = new NPCPath();
this.name = "";
}
public @NotNull String getId() {
return id;
}
public @NotNull EntityType getEntityType() {
return entityType;
}
public void setName(@NotNull String name) {
this.name = name;
if (hologram != null) {
updateHologram();
}
}
public @NotNull String getName() {
return name;
}
public void setSkin(@Nullable NPCSkin skin) {
this.skin = skin;
getEntity().ifPresent(e -> {
e.consumeEntityMeta(PlayerMeta.class, meta -> {
meta.setLeftSleeveEnabled(true);
meta.setRightSleeveEnabled(true);
meta.setCapeEnabled(true);
});
});
}
public @Nullable NPCSkin getSkin() {
return skin;
}
public void setPosition(@NotNull Location location) {
if (spawned) {
entity.teleport(location);
}
this.spawnLocation = location;
}
public @NotNull World getWorld() {
return Objects.requireNonNull(worldName != null ? Bukkit.getWorld(worldName) : null);
}
public void setWorld(@NotNull World world) {
this.worldName = world.getName();
}
public @NotNull String getWorldName() {
return worldName;
}
public void setWorldName(@NotNull String name) {
this.worldName = name;
}
public @NotNull Location getPosition() {
if (spawned && entity != null) {
return entity.getLocation();
}
return spawnLocation;
}
public void setHologramVisible(boolean visible) {
if (hologram != null) {
if (visible) {
hologram.show();
} else {
hologram.hide();
}
}
}
public void spawn(@NotNull Location location) {
if (spawned) return;
this.spawnLocation = location;
if (
entityType ==
EntityTypes.PLAYER
) {
UserProfile profile = new UserProfile(
java.util.UUID.randomUUID(),
name
);
if (skin != null) {
profile.setTextureProperties(skin.getTextureProperties());
}
WrapperPlayer wrapperPlayer = new WrapperPlayer(
profile,
EntityLib.getPlatform()
.getEntityIdProvider()
.provide(profile.getUUID(), entityType)
);
wrapperPlayer.setInTablist(false);
wrapperPlayer.setGameMode(
GameMode.SURVIVAL
);
entity = wrapperPlayer;
Bukkit.getLogger().info(
"[NPC] Created WrapperPlayer with UUID: " +
profile.getUUID() +
", name: " +
name
);
} else {
if (EntityMeta.isLivingEntity(entityType)) {
entity = new WrapperLivingEntity(entityType);
}
else {
entity = new WrapperEntity(entityType);
}
Bukkit.getLogger().info(
"[NPC] Created WrapperEntity with type: " + entityType
);
}
entity.setLocation(location);
if (entityType == EntityTypes.PLAYER) {
entity.getEntityMeta().setCustomNameVisible(false);
registerScoreboardTeam();
} else if (options.hasDisplayName()) {
entity.getEntityMeta().setCustomName(options.getDisplayName());
entity.getEntityMeta().setCustomNameVisible(true);
}
entity.spawn(location);
if (options.isSwimming()) {
entity.getEntityMeta().setSwimming(true);
}
if (options.isCrouching()) {
entity.getEntityMeta().setSneaking(true);
}
World npcWorld = getWorld();
if (options.isSitting()) {
Location sittingLoc = new Location(
location.getX(),
location.getY(),
location.getZ(),
location.getYaw(),
location.getPitch()
);
sittingEntity = new WrapperEntity(EntityTypes.ARMOR_STAND);
sittingEntity.setLocation(sittingLoc);
sittingEntity.spawn(sittingLoc);
ArmorStandMeta meta = (ArmorStandMeta) sittingEntity.getEntityMeta();
meta.setSmall(true);
meta.setInvisible(true);
for (Player player : Bukkit.getOnlinePlayers()) {
if (player.getWorld() != npcWorld) continue;
sittingEntity.addViewer(player.getUniqueId());
}
}
for (Player player : Bukkit.getOnlinePlayers()) {
if (player.getWorld() != npcWorld) continue;
entity.addViewer(player.getUniqueId());
if (entity instanceof me.tofaa.entitylib.wrapper.WrapperPlayer) {
doStupidDogshitForOldClients(player);
}
}
if (options.isSitting()) {
sittingEntity.addPassenger(entity);
}
NPCRegistry.registerEntityId(this);
if (options.isShowNameTag()) {
createHologramWithViewers();
}
spawned = true;
}
private void registerScoreboardTeam() {
if (entity == null) return;
Scoreboard scoreboard = Bukkit.getScoreboardManager().getMainScoreboard();
Team team = scoreboard.getTeam(TEAM_NAME);
if (team == null) {
team = scoreboard.registerNewTeam(TEAM_NAME);
team.setOption(Team.Option.NAME_TAG_VISIBILITY, Team.OptionStatus.NEVER);
team.setOption(Team.Option.DEATH_MESSAGE_VISIBILITY, Team.OptionStatus.NEVER);
}
if (!team.hasEntry(name)) {
team.addEntry(name);
}
teamEntry = name;
}
private void createHologramWithViewers() {
createHologram();
if (hologram != null) {
World npcWorld = getWorld();
for (Player player : Bukkit.getOnlinePlayers()) {
if (player.getWorld() != npcWorld) continue;
hologram.addViewer(player.getUniqueId());
}
}
}
public void despawn() {
if (!spawned) return;
if (teamEntry != null) {
removeScoreboardTeamEntry();
}
if (hologram != null) {
hologram.hide();
hologram = null;
}
if (entity != null) {
for (UUID viewerId : entity.getViewers()) {
org.bukkit.entity.Player player = org.bukkit.Bukkit.getPlayer(viewerId);
if (player != null && entity instanceof me.tofaa.entitylib.wrapper.WrapperPlayer) {
doStupidDogshitForOldClients(player);
}
}
entity.remove();
entity = null;
}
if (sittingEntity != null) {
sittingEntity.remove();
sittingEntity = null;
}
spawned = false;
}
private void removeScoreboardTeamEntry() {
Scoreboard scoreboard = Bukkit.getScoreboardManager().getMainScoreboard();
Team team = scoreboard.getTeam(TEAM_NAME);
if (team != null && teamEntry != null) {
team.removeEntry(teamEntry);
}
}
public void remove() {
despawn();
NPCRegistry.unregister(this);
}
/**
* Splits a Component into multiple lines on {@code <br>} tags.
* MiniMessage keeps {@code <br>} as a tag token through serialize/deserialize round-trips,
* so we serialize back to a MiniMessage string and split on the literal {@code <br>} token
* before re-deserializing each fragment into its own Component. This allows multi-line NPC
* name tags to be rendered as separate hologram line entities, since armor stands and text
* displays do not visually break a single component on newlines.
*/
private List<Component> splitDisplayNameLines(Component component) {
MiniMessage mm = MiniMessage.miniMessage();
String serialized = mm.serialize(component);
// MiniMessage round-trips <br> as the literal tag string "<br>"
String[] parts = serialized.split("(?i)<br>", -1);
if (parts.length == 1) {
return Collections.singletonList(component);
}
List<Component> lines = new ArrayList<>(parts.length);
for (String part : parts) {
lines.add(mm.deserialize(part));
}
return lines;
}
private void createHologram() {
Location loc = getPosition();
double yOffset = options.isSitting() ? 1.1 : 1.0;
Location hologramLoc = new Location(
loc.getX(),
loc.getY() + yOffset,
loc.getZ(),
loc.getYaw(),
loc.getPitch()
);
Hologram.Legacy hologram = Hologram.legacy(hologramLoc);
hologram.setLineOffset(-0.28f);
Component displayName = options.getDisplayName() != null
? options.getDisplayName()
: Component.text(name);
for (Component line : splitDisplayNameLines(displayName)) {
hologram.addLine(line);
}
hologram.show();
// if (hologram.getEntity().getEntityMeta() instanceof AbstractDisplayMeta displayMeta) {
//// displayMeta.setTranslation(new Vector3f(0, 0.5f, 0));
// }
this.hologram = hologram;
}
private void updateHologram() {
if (hologram != null) {
Component displayName = options.getDisplayName() != null
? options.getDisplayName()
: Component.text(name);
hologram.setLines(splitDisplayNameLines(displayName));
}
}
/**
* Very important, fixes legacy garbage clients from
* Seeing the npc name in tab
* @param player
*/
public void doStupidDogshitForOldClients(
Player player
) {
User user = PacketEvents.getAPI().getPlayerManager().getUser(player);
SpaceNPC.getInstance().getServer().getScheduler().runTaskLater(SpaceNPC.getInstance(), () -> {
if (!checkIfStupidDogshitPlayerIsOldClient(player ) || !getEntity().isPresent()) {
return;
}
WrapperPlayer p = (WrapperPlayer) getEntity().get();
PacketWrapper<?> packet = new WrapperPlayServerPlayerInfo(
WrapperPlayServerPlayerInfo.Action.REMOVE_PLAYER,
new WrapperPlayServerPlayerInfo.PlayerData(
p.getDisplayName(),
new UserProfile(p.getUuid(), p.getUsername()),
p.getGameMode(),
null, 0
)
);
// packet = new WrapperPlayServerPlayerInfoRemove(
// getEntity().get().getUuid()
// );
// user.sendPacket(packet);
sendPacketSilentlySkipTranslation(user, packet);
}, 5);
}
public boolean checkIfStupidDogshitPlayerIsOldClient(
Player player
) {
ViaVersionUtil.checkIfViaIsPresent();
if (ViaVersionUtil.isAvailable()) {
int pv = ViaVersionUtil.getProtocolVersion(player);
if (pv < ClientVersion.V_1_18_2.getProtocolVersion()) {
return true;
}
}
return false;
}
public static void sendPacketSilentlySkipTranslation(User user, Object byteBuf) {
if (ChannelHelper.isOpen(user.getChannel())) {
ChannelHelper.writeAndFlushInContext(user.getChannel(), "via-encoder", byteBuf);
}
else {
// ((ByteBuf)byteBuf).release()
// W memory leak
}
}
public static void sendPacketSilentlySkipTranslation(User user, PacketWrapper<?> wrapper) {
wrapper.prepareForSend(user.getChannel(), true, true);
sendPacketSilentlySkipTranslation(user, wrapper.buffer);
}
public void updateHeadRotationForViewers(Location npcLocation) {
if (entity == null || !spawned) return;
PacketEventsAPI<?> api = EntityLib.getApi().getPacketEvents();
for (UUID viewerId : entity.getViewers()) {
org.bukkit.entity.Player player = org.bukkit.Bukkit.getPlayer(
viewerId
);
if (player == null) continue;
double dx = player.getLocation().getX() - npcLocation.getX();
double dz = player.getLocation().getZ() - npcLocation.getZ();
float yaw = (float) Math.toDegrees(Math.atan2(dz, dx));
WrapperPlayServerEntityHeadLook headPacket =
new WrapperPlayServerEntityHeadLook(
entity.getEntityId(),
yaw
);
Object channel = api.getProtocolManager().getChannel(viewerId);
if (channel != null) {
api.getProtocolManager().sendPacket(channel, headPacket);
}
}
}
public @NotNull Collection<UUID> getViewers() {
if (entity == null) return Collections.emptyList();
return entity.getViewers();
}
public void addViewer(@NotNull UUID playerId) {
if (entity != null) {
entity.addViewer(playerId);
}
}
public void removeViewer(@NotNull UUID playerId) {
if (entity != null) {
entity.removeViewer(playerId);
}
}
public @NotNull Optional<WrapperEntity> getEntity() {
return Optional.ofNullable(entity);
}
public @NotNull Optional<Hologram> getHologram() {
return Optional.ofNullable(hologram);
}
public @NotNull Optional<WrapperEntity> getSittingEntity() {
return Optional.ofNullable(sittingEntity);
}
public @NotNull NPCOptions getOptions() {
return options;
}
public @NotNull NPCPath getPath() {
return path;
}
public boolean isHologramPassenger() {
return hologramPassenger;
}
public boolean isSpawned() {
return spawned;
}
public @NotNull Map<UUID, PerPlayerData> getPerPlayerData() {
return perPlayerData;
}
public @Nullable PerPlayerData getPerPlayerData(UUID playerId) {
return perPlayerData.get(playerId);
}
public void setPerPlayerData(UUID playerId, PerPlayerData data) {
perPlayerData.put(playerId, data);
}
public void removePerPlayerData(UUID playerId) {
perPlayerData.remove(playerId);
}
public void moveTo(@NotNull Location target) {
NPCPath path = getPath();
path.clearWaypoints();
path.addWaypoint(target);
NPCMovement.startPathFollowing(this);
}
public void stopMoving() {
if (entity != null) {
NPCMovement.stop(this);
getPath().reset();
}
}
public boolean isMoving() {
return NPCMovement.isMoving(this);
}
public static class PerPlayerData {
private final UUID playerId;
private Component customName;
private boolean hidden;
public PerPlayerData(UUID playerId) {
this.playerId = playerId;
}
public @NotNull UUID getPlayerId() {
return playerId;
}
public void setCustomName(@Nullable Component name) {
this.customName = name;
}
public @Nullable Component getCustomName() {
return customName;
}
public void setHidden(boolean hidden) {
this.hidden = hidden;
}
public boolean isHidden() {
return hidden;
}
}
}