From 40f6d3bcfefa5adcb1605d3240d8d5eb3e2b6196 Mon Sep 17 00:00:00 2001 From: daoge_cmd <3523206925@qq.com> Date: Sun, 29 Dec 2024 22:09:53 +0800 Subject: [PATCH] refactor: --- CHANGELOG.md | 5 ++ .../allaymc/api/container/BaseContainer.java | 21 ++++--- .../BlockEntityBaseComponentImpl.java | 28 +++++---- ...ckEntityEnchantTableBaseComponentImpl.java | 4 +- .../BlockEntityJukeboxBaseComponentImpl.java | 7 ++- .../BlockEntitySignBaseComponentImpl.java | 49 ++++++++++------ ...lockEntityShulkerBoxBaseComponentImpl.java | 9 ++- .../EntityAttributeComponentImpl.java | 6 +- .../component/EntityBaseComponentImpl.java | 51 +++++++++------- .../EntityPlayerAttributeComponentImpl.java | 6 +- .../player/EntityPlayerBaseComponentImpl.java | 58 ++++++++++--------- .../EntityPlayerNetworkComponentImpl.java | 11 ++-- .../item/component/ItemBaseComponentImpl.java | 35 ++++++----- 13 files changed, 178 insertions(+), 112 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 0557bf8f58..0f900a53d9 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -19,6 +19,11 @@ Unless otherwise specified, any version comparison below is the comparison of se - (API) Added an extra argument to `Dimension#breakBlock` method to control if the block breaking particle should be played. +### Changed + +- Introduced tag name constants where a large number of nbt saves and reads are involved. This improved the + maintainability of the project. + ### Fixed - (API) Corrected the return type of `Dimension#breakBlock(Vector3ic, ItemStack, Entity)` from `void` to `boolean`. Some diff --git a/api/src/main/java/org/allaymc/api/container/BaseContainer.java b/api/src/main/java/org/allaymc/api/container/BaseContainer.java index 6211dbdc27..deadad454c 100644 --- a/api/src/main/java/org/allaymc/api/container/BaseContainer.java +++ b/api/src/main/java/org/allaymc/api/container/BaseContainer.java @@ -27,16 +27,23 @@ */ @Slf4j public class BaseContainer implements Container { + + protected static final String TAG_SLOT = "Slot"; + protected final FullContainerType containerType; - protected final BiMap viewers = HashBiMap.create(new Byte2ObjectOpenHashMap<>()); + protected final BiMap viewers; protected final ItemStack[] content; - protected final Set> onOpenListeners = new HashSet<>(); - protected final Set> onCloseListeners = new HashSet<>(); - protected final Int2ObjectMap>> onSlotChangeListeners = new Int2ObjectOpenHashMap<>(); + protected final Set> onOpenListeners; + protected final Set> onCloseListeners; + protected final Int2ObjectMap>> onSlotChangeListeners; public BaseContainer(FullContainerType containerType) { this.containerType = containerType; + this.viewers = HashBiMap.create(new Byte2ObjectOpenHashMap<>()); this.content = new ItemStack[containerType.size()]; + this.onOpenListeners = new HashSet<>(); + this.onCloseListeners = new HashSet<>(); + this.onSlotChangeListeners = new Int2ObjectOpenHashMap<>(); Arrays.fill(this.content, ItemAirStack.AIR_STACK); } @@ -179,7 +186,7 @@ public List saveNBT() { // TODO: WasPickedUp? var nbt = itemStack.saveNBT() .toBuilder() - .putByte("Slot", (byte) slot) + .putByte(TAG_SLOT, (byte) slot) .build(); list.add(nbt); } @@ -189,11 +196,11 @@ public List saveNBT() { @Override public void loadNBT(List nbtList) { for (var nbt : nbtList) { - if (!nbt.containsKey("Slot")) { + if (!nbt.containsKey(TAG_SLOT)) { log.warn("Item NBT does not contain a slot key! Skipping item..."); continue; } - int slot = nbt.getByte("Slot"); + int slot = nbt.getByte(TAG_SLOT); ItemStack itemStack = fromNBT(nbt); content[slot] = itemStack; } diff --git a/server/src/main/java/org/allaymc/server/blockentity/component/BlockEntityBaseComponentImpl.java b/server/src/main/java/org/allaymc/server/blockentity/component/BlockEntityBaseComponentImpl.java index 70a9f38b1f..16a486ab05 100644 --- a/server/src/main/java/org/allaymc/server/blockentity/component/BlockEntityBaseComponentImpl.java +++ b/server/src/main/java/org/allaymc/server/blockentity/component/BlockEntityBaseComponentImpl.java @@ -23,9 +23,17 @@ * @author daoge_cmd */ public class BlockEntityBaseComponentImpl implements BlockEntityBaseComponent { + @Identifier.Component public static final Identifier IDENTIFIER = new Identifier("minecraft:block_entity_base_component"); + protected static final String TAG_ID = "id"; + protected static final String TAG_X = "x"; + protected static final String TAG_Y = "y"; + protected static final String TAG_Z = "z"; + protected static final String TAG_IS_MOVABLE = "isMovable"; + protected static final String TAG_CUSTOM_NAME = "CustomName"; + @Manager protected ComponentManager manager; @@ -52,13 +60,13 @@ public void tick(long currentTick) {} @Override public NbtMap saveNBT() { var builder = NbtMap.builder() - .putString("id", blockEntityType.getName()) - .putInt("x", position.x()) - .putInt("y", position.y()) - .putInt("z", position.z()) - .putBoolean("isMovable", true); + .putString(TAG_ID, blockEntityType.getName()) + .putInt(TAG_X, position.x()) + .putInt(TAG_Y, position.y()) + .putInt(TAG_Z, position.z()) + .putBoolean(TAG_IS_MOVABLE, true); if (customName != null) { - builder.putString("CustomName", customName); + builder.putString(TAG_CUSTOM_NAME, customName); } var event = new CBlockEntitySaveNBTEvent(builder); manager.callEvent(event); @@ -67,12 +75,12 @@ public NbtMap saveNBT() { @Override public void loadNBT(NbtMap nbt) { - nbt.listenForString("CustomName", customName -> this.customName = customName); + nbt.listenForString(TAG_CUSTOM_NAME, customName -> this.customName = customName); var pos = new Position3i(position); - pos.x = nbt.getInt("x", position.x()); - pos.y = nbt.getInt("y", position.y()); - pos.z = nbt.getInt("z", position.z()); + pos.x = nbt.getInt(TAG_X, position.x()); + pos.y = nbt.getInt(TAG_Y, position.y()); + pos.z = nbt.getInt(TAG_Z, position.z()); position = pos; var event = new CBlockEntityLoadNBTEvent(nbt); diff --git a/server/src/main/java/org/allaymc/server/blockentity/component/BlockEntityEnchantTableBaseComponentImpl.java b/server/src/main/java/org/allaymc/server/blockentity/component/BlockEntityEnchantTableBaseComponentImpl.java index 5f8559c891..76843382c6 100644 --- a/server/src/main/java/org/allaymc/server/blockentity/component/BlockEntityEnchantTableBaseComponentImpl.java +++ b/server/src/main/java/org/allaymc/server/blockentity/component/BlockEntityEnchantTableBaseComponentImpl.java @@ -8,6 +8,8 @@ */ public class BlockEntityEnchantTableBaseComponentImpl extends BlockEntityBaseComponentImpl { + protected static final String TAG_ROTT = "rott"; + /** * The clockwise rotation of the book in radians. Top of the book points West when 0 * @@ -21,7 +23,7 @@ public BlockEntityEnchantTableBaseComponentImpl(BlockEntityInitInfo initInfo) { @Override public NbtMap saveNBT() { - return super.saveNBT().toBuilder().putFloat("rott", bookRot).build(); + return super.saveNBT().toBuilder().putFloat(TAG_ROTT, bookRot).build(); } @Override diff --git a/server/src/main/java/org/allaymc/server/blockentity/component/BlockEntityJukeboxBaseComponentImpl.java b/server/src/main/java/org/allaymc/server/blockentity/component/BlockEntityJukeboxBaseComponentImpl.java index 3adcb86c32..9eefb71217 100644 --- a/server/src/main/java/org/allaymc/server/blockentity/component/BlockEntityJukeboxBaseComponentImpl.java +++ b/server/src/main/java/org/allaymc/server/blockentity/component/BlockEntityJukeboxBaseComponentImpl.java @@ -18,6 +18,9 @@ * @author IWareQ */ public class BlockEntityJukeboxBaseComponentImpl extends BlockEntityBaseComponentImpl implements BlockEntityJukeboxBaseComponent { + + protected static final String TAG_RECORD_ITEM = "RecordItem"; + @Getter @Setter private ItemStack musicDiscItem; @@ -60,7 +63,7 @@ public NbtMap saveNBT() { var savedNbt = super.saveNBT(); if (musicDiscItem != null) { savedNbt = savedNbt.toBuilder() - .putCompound("RecordItem", this.musicDiscItem.saveNBT()) + .putCompound(TAG_RECORD_ITEM, this.musicDiscItem.saveNBT()) .build(); } return savedNbt; @@ -69,6 +72,6 @@ public NbtMap saveNBT() { @Override public void loadNBT(NbtMap nbt) { super.loadNBT(nbt); - nbt.listenForCompound("RecordItem", value -> this.musicDiscItem = ItemHelper.fromNBT(value)); + nbt.listenForCompound(TAG_RECORD_ITEM, value -> this.musicDiscItem = ItemHelper.fromNBT(value)); } } diff --git a/server/src/main/java/org/allaymc/server/blockentity/component/BlockEntitySignBaseComponentImpl.java b/server/src/main/java/org/allaymc/server/blockentity/component/BlockEntitySignBaseComponentImpl.java index 29fe1545e3..1f675ff93c 100644 --- a/server/src/main/java/org/allaymc/server/blockentity/component/BlockEntitySignBaseComponentImpl.java +++ b/server/src/main/java/org/allaymc/server/blockentity/component/BlockEntitySignBaseComponentImpl.java @@ -25,6 +25,17 @@ @Getter public class BlockEntitySignBaseComponentImpl extends BlockEntityBaseComponentImpl implements BlockEntitySignBaseComponent { + protected static final String TAG_IS_WAXED = "IsWaxed"; + protected static final String TAG_FRONT_TEXT = "FrontText"; + protected static final String TAG_BACK_TEXT = "BackText"; + protected static final String TAG_LOCKED_FOR_EDITING_BY = "LockedForEditingBy"; + protected static final String TAG_TEXT = "Text"; + protected static final String TAG_IGNORE_LIGHTING = "IgnoreLighting"; + protected static final String TAG_SIGN_TEXT_COLOR = "SignTextColor"; + protected static final String TAG_HIDE_GLOW_OUTLINE = "HideGlowOutline"; + protected static final String TAG_PERSIST_FORMATTING = "PersistFormatting"; + protected static final String TAG_TEXT_OWNER = "TextOwner"; + protected SignText frontText = new SignTextImpl(); protected SignText backText = new SignTextImpl(); protected boolean waxed = false; @@ -37,20 +48,20 @@ public BlockEntitySignBaseComponentImpl(BlockEntityInitInfo initInfo) { public void loadNBT(NbtMap nbt) { super.loadNBT(nbt); - nbt.listenForBoolean("IsWaxed", value -> waxed = value); - nbt.listenForCompound("FrontText", value -> frontText = readSignTextFromNBT(value)); - nbt.listenForCompound("BackText", value -> backText = readSignTextFromNBT(value)); + nbt.listenForBoolean(TAG_IS_WAXED, value -> waxed = value); + nbt.listenForCompound(TAG_FRONT_TEXT, value -> frontText = readSignTextFromNBT(value)); + nbt.listenForCompound(TAG_BACK_TEXT, value -> backText = readSignTextFromNBT(value)); } @Override public NbtMap saveNBT() { return super.saveNBT() .toBuilder() - .putBoolean("IsWaxed", waxed) - .putCompound("FrontText", frontText.saveNBT()) - .putCompound("BackText", backText.saveNBT()) + .putBoolean(TAG_IS_WAXED, waxed) + .putCompound(TAG_FRONT_TEXT, frontText.saveNBT()) + .putCompound(TAG_BACK_TEXT, backText.saveNBT()) // Unused - .putLong("LockedForEditingBy", -1L) + .putLong(TAG_LOCKED_FOR_EDITING_BY, -1L) .build(); } @@ -67,11 +78,11 @@ public void openSignEditorFor(EntityPlayer player, boolean frontSide) { public void applyClientChange(EntityPlayer player, NbtMap nbt) { String[] newText; boolean isFrontSide = true; - if (!frontText.flattenText().equals(nbt.getCompound("FrontText").getString("Text"))) { - newText = AllayStringUtils.fastSplit(nbt.getCompound("FrontText").getString("Text"), "\n").toArray(String[]::new); - } else if (!backText.flattenText().equals(nbt.getCompound("BackText").getString("Text"))) { + if (!frontText.flattenText().equals(nbt.getCompound(TAG_FRONT_TEXT).getString(TAG_TEXT))) { + newText = AllayStringUtils.fastSplit(nbt.getCompound(TAG_FRONT_TEXT).getString(TAG_TEXT), "\n").toArray(String[]::new); + } else if (!backText.flattenText().equals(nbt.getCompound(TAG_BACK_TEXT).getString(TAG_TEXT))) { isFrontSide = false; - newText = AllayStringUtils.fastSplit(nbt.getCompound("BackText").getString("Text"), "\n").toArray(String[]::new); + newText = AllayStringUtils.fastSplit(nbt.getCompound(TAG_BACK_TEXT).getString(TAG_TEXT), "\n").toArray(String[]::new); } else { // No changes return; @@ -182,10 +193,10 @@ protected boolean isFrontSideInteracted(BlockFace interactedFace) { protected SignText readSignTextFromNBT(NbtMap nbt) { var signText = new SignTextImpl(); - nbt.listenForString("Text", value -> { + nbt.listenForString(TAG_TEXT, value -> { signText.text = AllayStringUtils.fastSplit(value, "\n", 4).toArray(String[]::new); }); - nbt.listenForBoolean("IgnoreLighting", value -> signText.glowing = value); + nbt.listenForBoolean(TAG_IGNORE_LIGHTING, value -> signText.glowing = value); return signText; } @@ -236,16 +247,16 @@ public String flattenText() { @Override public NbtMap saveNBT() { return NbtMap.builder() - .putString("Text", flattenText()) - .putBoolean("IgnoreLighting", glowing) + .putString(TAG_TEXT, flattenText()) + .putBoolean(TAG_IGNORE_LIGHTING, glowing) // Not implemented - .putInt("SignTextColor", -16777216) + .putInt(TAG_SIGN_TEXT_COLOR, -16777216) // true if the outer glow of a sign with glowing text does not show. - .putBoolean("HideGlowOutline", false) + .putBoolean(TAG_HIDE_GLOW_OUTLINE, false) // Unknown. Maybe save formatting character like ยง? - .putBoolean("PersistFormatting", true) + .putBoolean(TAG_PERSIST_FORMATTING, true) // Unknown. The player who placed the sign? - .putString("TextOwner", "") + .putString(TAG_TEXT_OWNER, "") .build(); } } diff --git a/server/src/main/java/org/allaymc/server/blockentity/component/shulkerbox/BlockEntityShulkerBoxBaseComponentImpl.java b/server/src/main/java/org/allaymc/server/blockentity/component/shulkerbox/BlockEntityShulkerBoxBaseComponentImpl.java index a4845e502d..d646cd45d8 100644 --- a/server/src/main/java/org/allaymc/server/blockentity/component/shulkerbox/BlockEntityShulkerBoxBaseComponentImpl.java +++ b/server/src/main/java/org/allaymc/server/blockentity/component/shulkerbox/BlockEntityShulkerBoxBaseComponentImpl.java @@ -13,9 +13,12 @@ import org.cloudburstmc.protocol.bedrock.packet.BlockEventPacket; /** - * @author IWareQ + * @author IWareQ | daoge_cmd */ public class BlockEntityShulkerBoxBaseComponentImpl extends BlockEntityBaseComponentImpl { + + protected static final String TAG_FACING = "facing"; + @Dependency private BlockEntityContainerHolderComponent containerHolderComponent; @@ -67,13 +70,13 @@ public void onInitFinish(BlockEntityInitInfo initInfo) { @Override public void loadNBT(NbtMap nbt) { super.loadNBT(nbt); - nbt.listenForByte("facing", facing -> this.facing = BlockFace.fromId(facing)); + nbt.listenForByte(TAG_FACING, facing -> this.facing = BlockFace.fromId(facing)); } @Override public NbtMap saveNBT() { return super.saveNBT().toBuilder() - .putByte("facing", (byte) facing.ordinal()) + .putByte(TAG_FACING, (byte) facing.ordinal()) .build(); } diff --git a/server/src/main/java/org/allaymc/server/entity/component/EntityAttributeComponentImpl.java b/server/src/main/java/org/allaymc/server/entity/component/EntityAttributeComponentImpl.java index 5456574017..5cae17b40f 100644 --- a/server/src/main/java/org/allaymc/server/entity/component/EntityAttributeComponentImpl.java +++ b/server/src/main/java/org/allaymc/server/entity/component/EntityAttributeComponentImpl.java @@ -33,6 +33,8 @@ public class EntityAttributeComponentImpl implements EntityAttributeComponent { @Identifier.Component public static final Identifier IDENTIFIER = new Identifier("minecraft:entity_attribute_component"); + protected static final String TAG_ATTRIBUTES = "Attributes"; + protected final Map attributes = new EnumMap<>(AttributeType.class); @ComponentObject @@ -64,7 +66,7 @@ public EntityAttributeComponentImpl(AttributeType[] attributeTypes, Attribute... @EventHandler protected void onLoadNBT(CEntityLoadNBTEvent event) { var nbt = event.getNbt(); - nbt.listenForList("Attributes", NbtType.COMPOUND, attributesNbt -> { + nbt.listenForList(TAG_ATTRIBUTES, NbtType.COMPOUND, attributesNbt -> { attributesNbt.forEach(attributeNbt -> { var attribute = Attribute.fromNBT(attributeNbt); attributes.put(AttributeType.byKey(attribute.getKey()), attribute); @@ -76,7 +78,7 @@ protected void onLoadNBT(CEntityLoadNBTEvent event) { @EventHandler protected void onSaveNBT(CEntitySaveNBTEvent event) { event.getNbt().putList( - "Attributes", + TAG_ATTRIBUTES, NbtType.COMPOUND, saveAttributes() ); diff --git a/server/src/main/java/org/allaymc/server/entity/component/EntityBaseComponentImpl.java b/server/src/main/java/org/allaymc/server/entity/component/EntityBaseComponentImpl.java index 452ea7a45d..db2ab904fa 100644 --- a/server/src/main/java/org/allaymc/server/entity/component/EntityBaseComponentImpl.java +++ b/server/src/main/java/org/allaymc/server/entity/component/EntityBaseComponentImpl.java @@ -72,10 +72,19 @@ public class EntityBaseComponentImpl implements EntityBaseComponent { @Identifier.Component public static final Identifier IDENTIFIER = new Identifier("minecraft:entity_base_component"); - public static final int DEFAULT_DEAD_TIMER = 20; - + protected static final int DEFAULT_DEAD_TIMER = 20; protected static final AtomicLong RUNTIME_ID_COUNTER = new AtomicLong(0); + protected static final String TAG_IDENTIFIER = "identifier"; + protected static final String TAG_ON_GROUND = "OnGround"; + // This tag is also used in EntityPlayerNetworkComponentImpl, so make it public for reuse + public static final String TAG_POS = "Pos"; + protected static final String TAG_MOTION = "Motion"; + protected static final String TAG_ROTATION = "Rotation"; + protected static final String TAG_TAGS = "Tags"; + protected static final String TAG_ACTIVE_EFFECTS = "ActiveEffects"; + protected static final String TAG_UNIQUE_ID = "UniqueID"; + private static final CommandOriginData ENTITY_COMMAND_ORIGIN_DATA = new CommandOriginData(CommandOriginType.ENTITY, UUID.randomUUID(), "", 0); @Getter @@ -654,16 +663,16 @@ protected Set computeMoveFlags(Location3fc newLoc) { @Override public NbtMap saveNBT() { var builder = NbtMap.builder(); - builder.putString("identifier", entityType.getIdentifier().toString()) - .putBoolean("OnGround", onGround); - AllayNbtUtils.writeVector3f(builder, "Pos", location); - AllayNbtUtils.writeVector3f(builder, "Motion", motion); - AllayNbtUtils.writeVector2f(builder, "Rotation", (float) location.yaw(), (float) location.pitch()); + builder.putString(TAG_IDENTIFIER, entityType.getIdentifier().toString()); + builder.putBoolean(TAG_ON_GROUND, onGround); + AllayNbtUtils.writeVector3f(builder, TAG_POS, location); + AllayNbtUtils.writeVector3f(builder, TAG_MOTION, motion); + AllayNbtUtils.writeVector2f(builder, TAG_ROTATION, (float) location.yaw(), (float) location.pitch()); if (!tags.isEmpty()) { - builder.putList("Tags", NbtType.STRING, new ArrayList<>(tags)); + builder.putList(TAG_TAGS, NbtType.STRING, new ArrayList<>(tags)); } if (!effects.isEmpty()) { - builder.putList("ActiveEffects", NbtType.COMPOUND, effects.values().stream().map(EffectInstance::saveNBT).toList()); + builder.putList(TAG_ACTIVE_EFFECTS, NbtType.COMPOUND, effects.values().stream().map(EffectInstance::saveNBT).toList()); } saveUniqueId(builder); var event = new CEntitySaveNBTEvent(builder); @@ -672,30 +681,30 @@ public NbtMap saveNBT() { } protected void saveUniqueId(NbtMapBuilder builder) { - builder.putLong("UniqueID", uniqueId); + builder.putLong(TAG_UNIQUE_ID, uniqueId); } @Override public void loadNBT(NbtMap nbt) { - if (nbt.containsKey("Pos")) { - var pos = readVector3f(nbt, "Pos"); + if (nbt.containsKey(TAG_POS)) { + var pos = readVector3f(nbt, TAG_POS); location.set(pos.x, pos.y, pos.z); } - if (nbt.containsKey("Motion")) { - var motion = readVector3f(nbt, "Motion"); + if (nbt.containsKey(TAG_MOTION)) { + var motion = readVector3f(nbt, TAG_MOTION); this.motion.set(motion); } - if (nbt.containsKey("Rotation")) { - var rot = readVector2f(nbt, "Rotation"); + if (nbt.containsKey(TAG_ROTATION)) { + var rot = readVector2f(nbt, TAG_ROTATION); location.setYaw(rot.x); location.setPitch(rot.y); } - nbt.listenForBoolean("OnGround", onGround -> this.onGround = onGround); - nbt.listenForList("Tags", NbtType.STRING, tags -> this.tags.addAll(tags)); - nbt.listenForList("ActiveEffects", NbtType.COMPOUND, activeEffects -> { + nbt.listenForBoolean(TAG_ON_GROUND, onGround -> this.onGround = onGround); + nbt.listenForList(TAG_TAGS, NbtType.STRING, tags -> this.tags.addAll(tags)); + nbt.listenForList(TAG_ACTIVE_EFFECTS, NbtType.COMPOUND, activeEffects -> { for (NbtMap activeEffect : activeEffects) { var effectInstance = EffectInstance.fromNBT(activeEffect); addEffect(effectInstance); @@ -708,8 +717,8 @@ public void loadNBT(NbtMap nbt) { } protected void loadUniqueId(NbtMap nbt) { - if (nbt.containsKey("UniqueID")) { - this.uniqueId = nbt.getLong("UniqueID"); + if (nbt.containsKey(TAG_UNIQUE_ID)) { + this.uniqueId = nbt.getLong(TAG_UNIQUE_ID); return; } diff --git a/server/src/main/java/org/allaymc/server/entity/component/player/EntityPlayerAttributeComponentImpl.java b/server/src/main/java/org/allaymc/server/entity/component/player/EntityPlayerAttributeComponentImpl.java index 111af3874b..f25a98c521 100644 --- a/server/src/main/java/org/allaymc/server/entity/component/player/EntityPlayerAttributeComponentImpl.java +++ b/server/src/main/java/org/allaymc/server/entity/component/player/EntityPlayerAttributeComponentImpl.java @@ -22,6 +22,8 @@ */ public class EntityPlayerAttributeComponentImpl extends EntityAttributeComponentImpl implements EntityPlayerAttributeComponent { + protected static final String TAG_FOOD_TICK_TIMER = "foodTickTimer"; + @Dependency(soft = true) protected EntityPlayerNetworkComponent networkComponent; @@ -191,14 +193,14 @@ protected void onAttributeChange(CEntityAttributeChangeEvent event) { @Override protected void onSaveNBT(CEntitySaveNBTEvent event) { super.onSaveNBT(event); - event.getNbt().putInt("foodTickTimer", foodTickTimer); + event.getNbt().putInt(TAG_FOOD_TICK_TIMER, foodTickTimer); } @EventHandler @Override protected void onLoadNBT(CEntityLoadNBTEvent event) { super.onLoadNBT(event); - event.getNbt().listenForInt("foodTickTimer", value -> foodTickTimer = value); + event.getNbt().listenForInt(TAG_FOOD_TICK_TIMER, value -> foodTickTimer = value); } @EventHandler diff --git a/server/src/main/java/org/allaymc/server/entity/component/player/EntityPlayerBaseComponentImpl.java b/server/src/main/java/org/allaymc/server/entity/component/player/EntityPlayerBaseComponentImpl.java index d0f0167512..dd7fa688fc 100644 --- a/server/src/main/java/org/allaymc/server/entity/component/player/EntityPlayerBaseComponentImpl.java +++ b/server/src/main/java/org/allaymc/server/entity/component/player/EntityPlayerBaseComponentImpl.java @@ -88,6 +88,16 @@ @Slf4j public class EntityPlayerBaseComponentImpl extends EntityBaseComponentImpl implements EntityPlayerBaseComponent { + protected static final String TAG_PERMISSION = "Permission"; + protected static final String TAG_OFFHAND = "Offhand"; + protected static final String TAG_INVENTORY = "Inventory"; + protected static final String TAG_ARMOR = "Armor"; + protected static final String TAG_ENCHANTMENT_SEED = "EnchantmentSeed"; + protected static final String TAG_GAME_TYPE = "GameType"; + protected static final String TAG_SPAWN_POINT = "SpawnPoint"; + protected static final String TAG_WORLD = "World"; + protected static final String TAG_DIMENSION = "Dimension"; + @Dependency protected EntityPlayerContainerHolderComponent containerHolderComponent; @Dependency @@ -469,72 +479,68 @@ public boolean computeMovementServerSide() { @Override public NbtMap saveNBT() { return super.saveNBT().toBuilder() - .putCompound("Permission", permissionTree.saveNBT()) + .putCompound(TAG_PERMISSION, permissionTree.saveNBT()) .putList( - "Offhand", + TAG_OFFHAND, NbtType.COMPOUND, containerHolderComponent.getContainer(FullContainerType.OFFHAND).saveNBT()) .putList( - "Inventory", + TAG_INVENTORY, NbtType.COMPOUND, containerHolderComponent.getContainer(FullContainerType.PLAYER_INVENTORY).saveNBT()) .putList( - "Armor", + TAG_ARMOR, NbtType.COMPOUND, containerHolderComponent.getContainer(FullContainerType.ARMOR).saveNBT()) - .putInt("EnchantmentSeed", enchantmentSeed) - .putInt("GameType", gameType.ordinal()) - .putCompound("SpawnPoint", saveSpawnPoint()) + .putInt(TAG_ENCHANTMENT_SEED, enchantmentSeed) + .putInt(TAG_GAME_TYPE, gameType.ordinal()) + .putCompound(TAG_SPAWN_POINT, saveSpawnPoint()) .build(); } protected NbtMap saveSpawnPoint() { var builder = NbtMap.builder() - .putString("World", spawnPoint.dimension().getWorld().getWorldData().getDisplayName()) - .putInt("Dimension", spawnPoint.dimension().getDimensionInfo().dimensionId()); - AllayNbtUtils.writeVector3i(builder, "Pos", spawnPoint); + .putString(TAG_WORLD, spawnPoint.dimension().getWorld().getWorldData().getDisplayName()) + .putInt(TAG_DIMENSION, spawnPoint.dimension().getDimensionInfo().dimensionId()); + AllayNbtUtils.writeVector3i(builder, TAG_POS, spawnPoint); return builder.build(); } @Override public void loadNBT(NbtMap nbt) { super.loadNBT(nbt); - nbt.listenForCompound("Permission", permNbt -> permissionTree.loadNBT(permNbt, true)); - nbt.listenForList("Offhand", NbtType.COMPOUND, offhandNbt -> + nbt.listenForCompound(TAG_PERMISSION, permNbt -> permissionTree.loadNBT(permNbt, true)); + nbt.listenForList(TAG_OFFHAND, NbtType.COMPOUND, offhandNbt -> containerHolderComponent.getContainer(FullContainerType.OFFHAND).loadNBT(offhandNbt) ); - nbt.listenForList("Inventory", NbtType.COMPOUND, inventoryNbt -> + nbt.listenForList(TAG_INVENTORY, NbtType.COMPOUND, inventoryNbt -> containerHolderComponent.getContainer(FullContainerType.PLAYER_INVENTORY).loadNBT(inventoryNbt) ); - nbt.listenForList("Armor", NbtType.COMPOUND, armorNbt -> + nbt.listenForList(TAG_ARMOR, NbtType.COMPOUND, armorNbt -> containerHolderComponent.getContainer(FullContainerType.ARMOR).loadNBT(armorNbt) ); - nbt.listenForInt("EnchantmentSeed", this::setEnchantmentSeed); - nbt.listenForInt("GameType", id -> setGameType(GameType.from(id))); - if (nbt.containsKey("SpawnPoint")) { - loadSpawnPoint(nbt.getCompound("SpawnPoint")); + nbt.listenForInt(TAG_ENCHANTMENT_SEED, this::setEnchantmentSeed); + nbt.listenForInt(TAG_GAME_TYPE, id -> setGameType(GameType.from(id))); + if (nbt.containsKey(TAG_SPAWN_POINT)) { + loadSpawnPoint(nbt.getCompound(TAG_SPAWN_POINT)); } else { spawnPoint = Server.getInstance().getWorldPool().getGlobalSpawnPoint(); } } protected void loadSpawnPoint(NbtMap nbt) { - var world = Server.getInstance().getWorldPool().getWorld(nbt.getString("World")); + var world = Server.getInstance().getWorldPool().getWorld(nbt.getString(TAG_WORLD)); if (world == null) { spawnPoint = Server.getInstance().getWorldPool().getGlobalSpawnPoint(); return; } - var dimension = world.getDimension(nbt.getInt("Dimension")); + var dimension = world.getDimension(nbt.getInt(TAG_DIMENSION)); if (dimension == null) { spawnPoint = Server.getInstance().getWorldPool().getGlobalSpawnPoint(); return; } - var pos = AllayNbtUtils.readVector3i(nbt, "Pos"); - spawnPoint = new Location3i( - pos, - 0, 0, 0, - dimension - ); + var pos = AllayNbtUtils.readVector3i(nbt, TAG_POS); + spawnPoint = new Location3i(pos, 0, 0, 0, dimension); } @Override diff --git a/server/src/main/java/org/allaymc/server/entity/component/player/EntityPlayerNetworkComponentImpl.java b/server/src/main/java/org/allaymc/server/entity/component/player/EntityPlayerNetworkComponentImpl.java index 655d6ff8ab..be360b40b4 100644 --- a/server/src/main/java/org/allaymc/server/entity/component/player/EntityPlayerNetworkComponentImpl.java +++ b/server/src/main/java/org/allaymc/server/entity/component/player/EntityPlayerNetworkComponentImpl.java @@ -298,6 +298,7 @@ public void initializePlayer() { // Validate and set player pos Dimension dimension; Vector3fc currentPos; + var logOffWorld = server.getWorldPool().getWorld(playerData.getWorld()); if (logOffWorld == null || logOffWorld.getDimension(playerData.getDimension()) == null) { // The world or dimension where player logged off doesn't exist @@ -306,20 +307,18 @@ public void initializePlayer() { currentPos = new org.joml.Vector3f(server.getWorldPool().getGlobalSpawnPoint()); // The old pos stored in playerNBT is invalid, we should replace it with the new one! var builder = playerData.getNbt().toBuilder(); - writeVector3f(builder, "Pos", currentPos); + writeVector3f(builder, EntityPlayerBaseComponentImpl.TAG_POS, currentPos); playerData.setNbt(builder.build()); // Save new player data back to storage server.getPlayerStorage().savePlayerData(thisPlayer.getUUID(), playerData); } else { dimension = logOffWorld.getDimension(playerData.getDimension()); // Read current pos from playerNBT - currentPos = readVector3f(playerData.getNbt(), "Pos"); + currentPos = readVector3f(playerData.getNbt(), EntityPlayerBaseComponentImpl.TAG_POS); } + // Load the current point chunk firstly so that we can add player entity into the chunk - dimension.getChunkService().getOrLoadChunkSync( - (int) currentPos.x() >> 4, - (int) currentPos.z() >> 4 - ); + dimension.getChunkService().getOrLoadChunkSync((int) currentPos.x() >> 4, (int) currentPos.z() >> 4); baseComponent.setLocationBeforeSpawn(new Location3f(currentPos.x(), currentPos.y(), currentPos.z(), dimension)); dimension.addPlayer(thisPlayer); diff --git a/server/src/main/java/org/allaymc/server/item/component/ItemBaseComponentImpl.java b/server/src/main/java/org/allaymc/server/item/component/ItemBaseComponentImpl.java index bd035e3f42..becb43b006 100644 --- a/server/src/main/java/org/allaymc/server/item/component/ItemBaseComponentImpl.java +++ b/server/src/main/java/org/allaymc/server/item/component/ItemBaseComponentImpl.java @@ -55,6 +55,14 @@ public class ItemBaseComponentImpl implements ItemBaseComponent { @Identifier.Component public static final Identifier IDENTIFIER = new Identifier("minecraft:item_base_component"); + // The following tag is in extra tag. + protected static final String TAG_DAMAGE = "Damage"; + protected static final String TAG_DISPLAY = "display"; + protected static final String TAG_NAME = "Name"; + protected static final String TAG_LORE = "Lore"; + protected static final String TAG_ENCHANTMENT = "ench"; + protected static final String TAG_CUSTOM_NBT = "CustomNBT"; + private static int STACK_NETWORK_ID_COUNTER = 1; @Dependency @@ -81,7 +89,8 @@ public class ItemBaseComponentImpl implements ItemBaseComponent { @Setter protected List lore = new ArrayList<>(); protected Map enchantments = new HashMap<>(); - //TODO: item lock type + // TODO: item lock type + // TODO: replace custom nbt content with pdc @Getter @Setter protected NbtMap customNBTContent = NbtMap.EMPTY; @@ -113,18 +122,18 @@ public void onInitFinish(ItemStackInitInfo initInfo) { @Override public void loadExtraTag(NbtMap extraTag) { - this.durability = extraTag.getInt("Damage", 0); - extraTag.listenForCompound("display", displayNbt -> { - this.customName = displayNbt.getString("Name"); - this.lore = displayNbt.getList("Lore", NbtType.STRING); + this.durability = extraTag.getInt(TAG_DAMAGE, 0); + extraTag.listenForCompound(TAG_DISPLAY, displayNbt -> { + this.customName = displayNbt.getString(TAG_NAME); + this.lore = displayNbt.getList(TAG_LORE, NbtType.STRING); }); - extraTag.listenForList("ench", NbtType.COMPOUND, enchsNbt -> enchsNbt.forEach(enchNbt -> { + extraTag.listenForList(TAG_ENCHANTMENT, NbtType.COMPOUND, enchsNbt -> enchsNbt.forEach(enchNbt -> { var enchantment = EnchantmentHelper.fromNBT(enchNbt); this.enchantments.put(enchantment.getType(), enchantment); })); - extraTag.listenForCompound("CustomNBT", customNbt -> this.customNBTContent = customNbt); + extraTag.listenForCompound(TAG_CUSTOM_NBT, customNbt -> this.customNBTContent = customNbt); var event = new CItemLoadExtraTagEvent(extraTag); manager.callEvent(event); @@ -134,32 +143,32 @@ public void loadExtraTag(NbtMap extraTag) { public NbtMap saveExtraTag() { var nbtBuilder = NbtMap.builder(); if (durability != 0) { - nbtBuilder.putInt("Damage", durability); + nbtBuilder.putInt(TAG_DAMAGE, durability); } var displayBuilder = NbtMap.builder(); if (!this.customName.isEmpty()) { - displayBuilder.put("Name", this.customName); + displayBuilder.put(TAG_NAME, this.customName); } if (!this.lore.isEmpty()) { - displayBuilder.putList("Lore", NbtType.STRING, this.lore); + displayBuilder.putList(TAG_LORE, NbtType.STRING, this.lore); } if (!displayBuilder.isEmpty()) { - nbtBuilder.putCompound("display", displayBuilder.build()); + nbtBuilder.putCompound(TAG_DISPLAY, displayBuilder.build()); } if (!enchantments.isEmpty()) { var enchantmentNBT = this.enchantments.values().stream() .map(EnchantmentInstance::saveNBT) .toList(); - nbtBuilder.putList("ench", NbtType.COMPOUND, enchantmentNBT); + nbtBuilder.putList(TAG_ENCHANTMENT, NbtType.COMPOUND, enchantmentNBT); } // TODO: item lock type // Custom NBT content if (!customNBTContent.isEmpty()) { - nbtBuilder.put("CustomNBT", customNBTContent); + nbtBuilder.put(TAG_CUSTOM_NBT, customNBTContent); } var event = new CItemSaveExtraTagEvent(nbtBuilder);