/
PacketHelperImpl.java
438 lines (394 loc) · 21.6 KB
/
PacketHelperImpl.java
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
package com.denizenscript.denizen.nms.v1_20.helpers;
import com.denizenscript.denizen.nms.NMSHandler;
import com.denizenscript.denizen.nms.interfaces.PacketHelper;
import com.denizenscript.denizen.nms.util.jnbt.CompoundTag;
import com.denizenscript.denizen.nms.util.jnbt.JNBTListTag;
import com.denizenscript.denizen.nms.v1_20.Handler;
import com.denizenscript.denizen.nms.v1_20.ReflectionMappingsInfo;
import com.denizenscript.denizen.nms.v1_20.impl.SidebarImpl;
import com.denizenscript.denizen.nms.v1_20.impl.jnbt.CompoundTagImpl;
import com.denizenscript.denizen.nms.v1_20.impl.network.handlers.DenizenNetworkManagerImpl;
import com.denizenscript.denizen.objects.LocationTag;
import com.denizenscript.denizen.objects.MaterialTag;
import com.denizenscript.denizen.objects.PlayerTag;
import com.denizenscript.denizen.utilities.FormattedTextHelper;
import com.denizenscript.denizen.utilities.Utilities;
import com.denizenscript.denizen.utilities.blocks.FakeBlock;
import com.denizenscript.denizen.utilities.maps.MapImage;
import com.denizenscript.denizencore.objects.core.ColorTag;
import com.denizenscript.denizencore.objects.core.DurationTag;
import com.denizenscript.denizencore.utilities.ReflectionHelper;
import com.denizenscript.denizencore.utilities.debugging.Debug;
import io.netty.buffer.Unpooled;
import net.md_5.bungee.api.ChatColor;
import net.minecraft.core.BlockPos;
import net.minecraft.network.FriendlyByteBuf;
import net.minecraft.network.chat.Component;
import net.minecraft.network.protocol.Packet;
import net.minecraft.network.protocol.game.*;
import net.minecraft.network.syncher.EntityDataAccessor;
import net.minecraft.network.syncher.SynchedEntityData;
import net.minecraft.resources.ResourceLocation;
import net.minecraft.server.level.ChunkMap;
import net.minecraft.server.level.ServerEntity;
import net.minecraft.server.level.ServerLevel;
import net.minecraft.world.entity.RelativeMovement;
import net.minecraft.world.entity.ai.attributes.AttributeInstance;
import net.minecraft.world.entity.ai.attributes.Attributes;
import net.minecraft.world.entity.monster.CaveSpider;
import net.minecraft.world.entity.monster.Creeper;
import net.minecraft.world.entity.monster.EnderMan;
import net.minecraft.world.entity.monster.Spider;
import net.minecraft.world.inventory.AbstractContainerMenu;
import net.minecraft.world.level.block.Block;
import net.minecraft.world.level.block.entity.BlockEntityType;
import net.minecraft.world.level.saveddata.maps.MapItemSavedData;
import net.minecraft.world.scores.PlayerTeam;
import net.minecraft.world.scores.Team;
import org.bukkit.Bukkit;
import org.bukkit.DyeColor;
import org.bukkit.Location;
import org.bukkit.Material;
import org.bukkit.block.banner.Pattern;
import org.bukkit.craftbukkit.v1_20_R1.CraftServer;
import org.bukkit.craftbukkit.v1_20_R1.CraftWorld;
import org.bukkit.craftbukkit.v1_20_R1.entity.CraftEntity;
import org.bukkit.craftbukkit.v1_20_R1.entity.CraftPlayer;
import org.bukkit.craftbukkit.v1_20_R1.inventory.CraftItemStack;
import org.bukkit.craftbukkit.v1_20_R1.map.CraftMapCanvas;
import org.bukkit.craftbukkit.v1_20_R1.map.CraftMapView;
import org.bukkit.entity.Entity;
import org.bukkit.entity.EntityType;
import org.bukkit.entity.LivingEntity;
import org.bukkit.entity.Player;
import org.bukkit.event.player.PlayerRespawnEvent;
import org.bukkit.inventory.ItemStack;
import org.bukkit.map.MapCanvas;
import org.bukkit.map.MapPalette;
import java.lang.invoke.MethodHandle;
import java.lang.reflect.Field;
import java.nio.charset.StandardCharsets;
import java.util.*;
public class PacketHelperImpl implements PacketHelper {
public static final EntityDataAccessor<Float> PLAYER_DATA_ACCESSOR_ABSORPTION = ReflectionHelper.getFieldValue(net.minecraft.world.entity.player.Player.class, ReflectionMappingsInfo.Player_DATA_PLAYER_ABSORPTION_ID, null);
public static final EntityDataAccessor<Byte> ENTITY_DATA_ACCESSOR_FLAGS = ReflectionHelper.getFieldValue(net.minecraft.world.entity.Entity.class, ReflectionMappingsInfo.Entity_DATA_SHARED_FLAGS_ID, null);
public static final MethodHandle ABILITIES_PACKET_FOV_SETTER = ReflectionHelper.getFinalSetter(ClientboundPlayerAbilitiesPacket.class, ReflectionMappingsInfo.ClientboundPlayerAbilitiesPacket_walkingSpeed);
public static Field ENTITY_TRACKER_ENTRY_GETTER = ReflectionHelper.getFields(ChunkMap.TrackedEntity.class).getFirstOfType(ServerEntity.class);
public static MethodHandle CANVAS_GET_BUFFER = ReflectionHelper.getMethodHandle(CraftMapCanvas.class, "getBuffer");
public static Field MAPVIEW_WORLDMAP = ReflectionHelper.getFields(CraftMapView.class).get("worldMap");
public static MethodHandle BLOCK_ENTITY_DATA_PACKET_CONSTRUCTOR = ReflectionHelper.getConstructor(ClientboundBlockEntityDataPacket.class, BlockPos.class, BlockEntityType.class, net.minecraft.nbt.CompoundTag.class);
public static EntityDataAccessor<Optional<Component>> ENTITY_DATA_ACCESSOR_CUSTOM_NAME = ReflectionHelper.getFieldValue(net.minecraft.world.entity.Entity.class, ReflectionMappingsInfo.Entity_DATA_CUSTOM_NAME, null);
public static EntityDataAccessor<Boolean> ENTITY_DATA_ACCESSOR_CUSTOM_NAME_VISIBLE = ReflectionHelper.getFieldValue(net.minecraft.world.entity.Entity.class, ReflectionMappingsInfo.Entity_DATA_CUSTOM_NAME_VISIBLE, null);
@Override
public void setFakeAbsorption(Player player, float value) {
SynchedEntityData dw = new SynchedEntityData(null);
dw.define(PLAYER_DATA_ACCESSOR_ABSORPTION, value);
send(player, new ClientboundSetEntityDataPacket(player.getEntityId(), dw.packDirty()));
}
@Override
public void setSlot(Player player, int slot, ItemStack itemStack, boolean playerOnly) {
AbstractContainerMenu menu = ((CraftPlayer) player).getHandle().containerMenu;
int windowId = playerOnly ? 0 : menu.containerId;
send(player, new ClientboundContainerSetSlotPacket(windowId, menu.incrementStateId(), slot, CraftItemStack.asNMSCopy(itemStack)));
}
@Override
public void setFieldOfView(Player player, float fov) {
ClientboundPlayerAbilitiesPacket packet = new ClientboundPlayerAbilitiesPacket(((CraftPlayer) player).getHandle().getAbilities());
if (!Float.isNaN(fov)) {
try {
ABILITIES_PACKET_FOV_SETTER.invoke(packet, fov);
}
catch (Throwable ex) {
Debug.echoError(ex);
}
}
send(player, packet);
}
@Override
public void respawn(Player player) {
((CraftPlayer) player).getHandle().connection.handleClientCommand(new ServerboundClientCommandPacket(ServerboundClientCommandPacket.Action.PERFORM_RESPAWN));
}
@Override
public void setVision(Player player, EntityType entityType) {
final net.minecraft.world.entity.LivingEntity entity;
if (entityType == EntityType.CREEPER) {
entity = new Creeper(net.minecraft.world.entity.EntityType.CREEPER, ((CraftWorld) player.getWorld()).getHandle());
}
else if (entityType == EntityType.SPIDER) {
entity = new Spider(net.minecraft.world.entity.EntityType.SPIDER, ((CraftWorld) player.getWorld()).getHandle());
}
else if (entityType == EntityType.CAVE_SPIDER) {
entity = new CaveSpider(net.minecraft.world.entity.EntityType.CAVE_SPIDER, ((CraftWorld) player.getWorld()).getHandle());
}
else if (entityType == EntityType.ENDERMAN) {
entity = new EnderMan(net.minecraft.world.entity.EntityType.ENDERMAN, ((CraftWorld) player.getWorld()).getHandle());
}
else {
return;
}
// Spectating an entity then immediately respawning the player prevents a client shader update,
// allowing the player to retain whatever vision the mob they spectated had.
send(player, new ClientboundAddEntityPacket(entity));
send(player, new ClientboundSetCameraPacket(entity));
((CraftServer) Bukkit.getServer()).getHandle().respawn(((CraftPlayer) player).getHandle(),
((CraftWorld) player.getWorld()).getHandle(), true, player.getLocation(), false, PlayerRespawnEvent.RespawnReason.PLUGIN);
}
@Override
public void showBlockAction(Player player, Location location, int action, int state) {
BlockPos position = new BlockPos(location.getBlockX(), location.getBlockY(), location.getBlockZ());
Block block = ((CraftWorld) location.getWorld()).getHandle().getBlockState(position).getBlock();
send(player, new ClientboundBlockEventPacket(position, block, action, state));
}
@Override
public void showBlockCrack(Player player, int id, Location location, int progress) {
BlockPos position = new BlockPos(location.getBlockX(), location.getBlockY(), location.getBlockZ());
send(player, new ClientboundBlockDestructionPacket(id, position, progress));
}
@Override
public void showTileEntityData(Player player, Location location, int action, CompoundTag compoundTag) {
BlockPos position = new BlockPos(location.getBlockX(), location.getBlockY(), location.getBlockZ());
try {
ClientboundBlockEntityDataPacket packet = (ClientboundBlockEntityDataPacket) BLOCK_ENTITY_DATA_PACKET_CONSTRUCTOR.invoke(position, action, ((CompoundTagImpl) compoundTag).toNMSTag());
send(player, packet);
}
catch (Throwable ex) {
Debug.echoError(ex);
}
}
@Override
public void showBannerUpdate(Player player, Location location, DyeColor base, List<Pattern> patterns) {
List<CompoundTag> nbtPatterns = new ArrayList<>();
for (Pattern pattern : patterns) {
nbtPatterns.add(NMSHandler.instance
.createCompoundTag(new HashMap<>())
.createBuilder()
.putInt("Color", pattern.getColor().getDyeData())
.putString("Pattern", pattern.getPattern().getIdentifier())
.build());
}
CompoundTag compoundTag = NMSHandler.blockHelper.getNbtData(location.getBlock())
.createBuilder()
.put("Patterns", new JNBTListTag(CompoundTag.class, nbtPatterns))
.build();
showTileEntityData(player, location, 3, compoundTag);
}
@Override
public void showTabListHeaderFooter(Player player, String header, String footer) {
Component cHeader = Handler.componentToNMS(FormattedTextHelper.parse(header, ChatColor.WHITE));
Component cFooter = Handler.componentToNMS(FormattedTextHelper.parse(footer, ChatColor.WHITE));
ClientboundTabListPacket packet = new ClientboundTabListPacket(cHeader, cFooter);
send(player, packet);
}
@Override
public void showTitle(Player player, String title, String subtitle, int fadeInTicks, int stayTicks, int fadeOutTicks) {
send(player, new ClientboundSetTitlesAnimationPacket(fadeInTicks, stayTicks, fadeOutTicks));
if (title != null) {
send(player, new ClientboundSetTitleTextPacket(Handler.componentToNMS(FormattedTextHelper.parse(title, ChatColor.WHITE))));
}
if (subtitle != null) {
send(player, new ClientboundSetSubtitleTextPacket(Handler.componentToNMS(FormattedTextHelper.parse(subtitle, ChatColor.WHITE))));
}
}
@Override
public void showHealth(Player player, float health, int food, float saturation) {
send(player, new ClientboundSetHealthPacket(health, food, saturation));
}
@Override
public void showMobHealth(Player player, LivingEntity mob, double health, double maxHealth) {
AttributeInstance attr = new AttributeInstance(Attributes.MAX_HEALTH, (a) -> { });
attr.setBaseValue(maxHealth);
send(player, new ClientboundUpdateAttributesPacket(mob.getEntityId(), Collections.singletonList(attr)));
FriendlyByteBuf healthData = new FriendlyByteBuf(Unpooled.buffer());
healthData.writeVarInt(mob.getEntityId());
healthData.writeByte(9); // health id
healthData.writeVarInt(2); // type = float
healthData.writeFloat((float) health);
healthData.writeByte(255); // Mark end of packet
send(player, new ClientboundSetEntityDataPacket(healthData));
}
@Override
public void resetHealth(Player player) {
showHealth(player, (float) player.getHealth(), player.getFoodLevel(), player.getSaturation());
}
@Override
public void showSignEditor(Player player, Location location) {
LocationTag fakeSign = new LocationTag(player.getLocation());
fakeSign.setY(0);
FakeBlock.showFakeBlockTo(Collections.singletonList(new PlayerTag(player)), fakeSign, new MaterialTag(Material.OAK_WALL_SIGN), new DurationTag(1), true);
BlockPos pos = new BlockPos(fakeSign.getBlockX(), 0, fakeSign.getBlockZ());
DenizenNetworkManagerImpl.getNetworkManager(player).packetListener.fakeSignExpected = pos;
send(player, new ClientboundOpenSignEditorPacket(pos, true)); // TODO: 1.20: "isFrontText"?
}
@Override
public void forceSpectate(Player player, Entity entity) {
send(player, new ClientboundSetCameraPacket(((CraftEntity) entity).getHandle()));
}
public static void forceRespawnPlayerEntity(Entity entity, Player viewer) {
ChunkMap tracker = ((ServerLevel) ((CraftEntity) entity).getHandle().level()).getChunkSource().chunkMap;
ChunkMap.TrackedEntity entityTracker = tracker.entityMap.get(entity.getEntityId());
if (entityTracker != null) {
try {
ServerEntity entry = (ServerEntity) ENTITY_TRACKER_ENTRY_GETTER.get(entityTracker);
if (entry != null) {
entry.removePairing(((CraftPlayer) viewer).getHandle());
entry.addPairing(((CraftPlayer) viewer).getHandle());
}
}
catch (Throwable ex) {
Debug.echoError(ex);
}
}
}
@Override
public void sendRename(Player player, Entity entity, String name, boolean listMode) {
try {
if (entity.getType() == EntityType.PLAYER) {
if (listMode) {
send(player, new ClientboundPlayerInfoUpdatePacket(ClientboundPlayerInfoUpdatePacket.Action.UPDATE_DISPLAY_NAME, ((CraftPlayer) player).getHandle()));
}
else {
// For player entities, force a respawn packet and let the dynamic intercept correct the details
forceRespawnPlayerEntity(entity, player);
}
return;
}
SynchedEntityData fakeData = new SynchedEntityData(((CraftEntity) entity).getHandle());
List<SynchedEntityData.DataValue<?>> list = new ArrayList<>();
list.add(new SynchedEntityData.DataValue<>(ENTITY_DATA_ACCESSOR_CUSTOM_NAME.getId(), ENTITY_DATA_ACCESSOR_CUSTOM_NAME.getSerializer(), Optional.of(Handler.componentToNMS(FormattedTextHelper.parse(name, ChatColor.WHITE)))));
list.add(new SynchedEntityData.DataValue<>(ENTITY_DATA_ACCESSOR_CUSTOM_NAME_VISIBLE.getId(), ENTITY_DATA_ACCESSOR_CUSTOM_NAME_VISIBLE.getSerializer(), true));
send(player, new ClientboundSetEntityDataPacket(entity.getEntityId(), list));
}
catch (Throwable ex) {
Debug.echoError(ex);
}
}
public static HashMap<UUID, HashMap<UUID, PlayerTeam>> noCollideTeamMap = new HashMap<>();
@Override
public void generateNoCollideTeam(Player player, UUID noCollide) {
removeNoCollideTeam(player, noCollide);
PlayerTeam team = new PlayerTeam(SidebarImpl.dummyScoreboard, Utilities.generateRandomColors(8));
team.getPlayers().add(noCollide.toString());
team.setCollisionRule(Team.CollisionRule.NEVER);
HashMap<UUID, PlayerTeam> map = noCollideTeamMap.computeIfAbsent(player.getUniqueId(), k -> new HashMap<>());
map.put(noCollide, team);
send(player, ClientboundSetPlayerTeamPacket.createAddOrModifyPacket(team, true));
}
@Override
public void removeNoCollideTeam(Player player, UUID noCollide) {
if (noCollide == null || !player.isOnline()) {
noCollideTeamMap.remove(player.getUniqueId());
return;
}
HashMap<UUID, PlayerTeam> map = noCollideTeamMap.get(player.getUniqueId());
if (map == null) {
return;
}
PlayerTeam team = map.remove(noCollide);
if (team != null) {
send(player, ClientboundSetPlayerTeamPacket.createRemovePacket(team));
}
if (map.isEmpty()) {
noCollideTeamMap.remove(player.getUniqueId());
}
}
@Override
public void sendEntityMetadataFlagsUpdate(Player player, Entity entity) {
List<SynchedEntityData.DataValue<?>> data = new ArrayList<>();
byte flags = ((CraftEntity) entity).getHandle().getEntityData().get(ENTITY_DATA_ACCESSOR_FLAGS);
data.add(SynchedEntityData.DataValue.create(ENTITY_DATA_ACCESSOR_FLAGS, flags));
send(player, new ClientboundSetEntityDataPacket(entity.getEntityId(), data));
}
@Override
public void sendEntityEffect(Player player, Entity entity, byte effectId) {
send(player, new ClientboundEntityEventPacket(((CraftEntity) entity).getHandle(), effectId));
}
@Override
public int getPacketStats(Player player, boolean sent) {
DenizenNetworkManagerImpl netMan = DenizenNetworkManagerImpl.getNetworkManager(player);
return sent ? netMan.packetsSent : netMan.packetsReceived;
}
@Override
public void setMapData(MapCanvas canvas, byte[] bytes, int x, int y, MapImage image) {
if (x > 127 || y > 127) {
return;
}
int width = Math.min(image.width, 128 - x),
height = Math.min(image.height, 128 - y);
if (x + width <= 0 || y + height <= 0) {
return;
}
try {
boolean anyChanged = false;
byte[] buffer = (byte[]) CANVAS_GET_BUFFER.invoke(canvas);
for (int x2 = x < 0 ? -x : 0; x2 < width; ++x2) {
for (int y2 = y < 0 ? -y : 0; y2 < height; ++y2) {
byte p = bytes[y2 * image.width + x2];
if (p != MapPalette.TRANSPARENT) {
int index = (y2 + y) * 128 + (x2 + x);
if (buffer[index] != p) {
buffer[index] = p;
anyChanged = true;
}
}
}
}
if (anyChanged) {
// Flag the whole image as dirty
MapItemSavedData map = (MapItemSavedData) MAPVIEW_WORLDMAP.get(canvas.getMapView());
map.setColorsDirty(Math.max(x, 0), Math.max(y, 0));
map.setColorsDirty(width + x - 1, height + y - 1);
}
}
catch (Throwable ex) {
Debug.echoError(ex);
}
}
@Override
public void setNetworkManagerFor(Player player) {
DenizenNetworkManagerImpl.setNetworkManager(player);
}
@Override
public void enableNetworkManager() {
DenizenNetworkManagerImpl.enableNetworkManager();
}
@Override
public void showDebugTestMarker(Player player, Location location, ColorTag color, String name, int time) {
ResourceLocation packetKey = new ResourceLocation("minecraft", "debug/game_test_add_marker");
FriendlyByteBuf buf = new FriendlyByteBuf(Unpooled.buffer());
buf.writeBlockPos(new BlockPos(location.getBlockX(), location.getBlockY(), location.getBlockZ()));
int colorInt = color.blue | (color.green << 8) | (color.red << 16) | (color.alpha << 24);
buf.writeInt(colorInt);
buf.writeByteArray(name.getBytes(StandardCharsets.UTF_8));
buf.writeInt(time);
ClientboundCustomPayloadPacket packet = new ClientboundCustomPayloadPacket(packetKey, buf);
send(player, packet);
}
@Override
public void clearDebugTestMarker(Player player) {
ResourceLocation packetKey = new ResourceLocation("minecraft", "debug/game_test_clear");
FriendlyByteBuf buf = new FriendlyByteBuf(Unpooled.buffer());
ClientboundCustomPayloadPacket packet = new ClientboundCustomPayloadPacket(packetKey, buf);
send(player, packet);
}
@Override
public void sendBrand(Player player, String brand) {
ResourceLocation packetKey = new ResourceLocation("minecraft", "brand");
FriendlyByteBuf buf = new FriendlyByteBuf(Unpooled.buffer());
buf.writeUtf(brand);
ClientboundCustomPayloadPacket packet = new ClientboundCustomPayloadPacket(packetKey, buf);
send(player, packet);
}
@Override
public void sendCollectItemEntity(Player player, Entity taker, Entity item, int amount) {
ClientboundTakeItemEntityPacket packet = new ClientboundTakeItemEntityPacket(item.getEntityId(), taker.getEntityId(), amount);
send(player, packet);
}
@Override
public void sendRelativeLookPacket(Player player, float yaw, float pitch) {
ClientboundPlayerPositionPacket packet = new ClientboundPlayerPositionPacket(0, 0, 0, yaw, pitch, RelativeMovement.ALL, 0);
DenizenNetworkManagerImpl.getNetworkManager(player).oldManager.channel.writeAndFlush(packet);
}
public static void send(Player player, Packet<?> packet) {
((CraftPlayer) player).getHandle().connection.send(packet);
}
}