From d25a8444a1b96bb4d307373f4ebc0a39b987ec03 Mon Sep 17 00:00:00 2001 From: zyxkad Date: Sat, 25 Jan 2025 15:10:53 -0700 Subject: [PATCH 1/9] fix smart glasses position should be eye position but not feet position --- .../common/addons/APAddons.java | 4 +- .../computercraft/owner/IPeripheralOwner.java | 19 +++++++- .../owner/PocketPeripheralOwner.java | 1 - .../blockentities/DistanceDetectorEntity.java | 39 ++++------------- .../smartglasses/SmartGlassesComputer.java | 4 +- .../modules/ModulePeripheral.java | 14 +++--- .../modules/ModulePeripheralOwner.java | 25 ++++++++--- .../overlay/OverlayGlassesFunctions.java | 4 +- .../lib/peripherals/BasePeripheral.java | 43 +++++++++++-------- 9 files changed, 86 insertions(+), 67 deletions(-) diff --git a/src/main/java/de/srendi/advancedperipherals/common/addons/APAddons.java b/src/main/java/de/srendi/advancedperipherals/common/addons/APAddons.java index 2c9948e2a..b48fbbfb9 100644 --- a/src/main/java/de/srendi/advancedperipherals/common/addons/APAddons.java +++ b/src/main/java/de/srendi/advancedperipherals/common/addons/APAddons.java @@ -93,14 +93,14 @@ public static ItemStack getCurioGlasses(Player player) { } public static boolean isBlockOnShip(Level level, BlockPos pos) { - if (!vs2Loaded) { + if (level == null || !vs2Loaded) { return false; } return VSGameUtilsKt.isBlockInShipyard(level, pos); } public static Ship getVS2Ship(Level level, BlockPos pos) { - if (!vs2Loaded) { + if (level == null || !vs2Loaded) { return null; } return VSGameUtilsKt.getShipObjectManagingPos(level, pos); diff --git a/src/main/java/de/srendi/advancedperipherals/common/addons/computercraft/owner/IPeripheralOwner.java b/src/main/java/de/srendi/advancedperipherals/common/addons/computercraft/owner/IPeripheralOwner.java index 2dd333a9d..8fea843c6 100644 --- a/src/main/java/de/srendi/advancedperipherals/common/addons/computercraft/owner/IPeripheralOwner.java +++ b/src/main/java/de/srendi/advancedperipherals/common/addons/computercraft/owner/IPeripheralOwner.java @@ -1,6 +1,7 @@ package de.srendi.advancedperipherals.common.addons.computercraft.owner; import dan200.computercraft.api.peripheral.IPeripheral; +import de.srendi.advancedperipherals.common.addons.APAddons; import de.srendi.advancedperipherals.common.util.fakeplayer.APFakePlayer; import de.srendi.advancedperipherals.lib.peripherals.IPeripheralOperation; import net.minecraft.core.BlockPos; @@ -11,9 +12,11 @@ import net.minecraft.world.item.ItemStack; import net.minecraft.world.level.Level; import net.minecraft.world.phys.Vec3; +import org.joml.Vector3d; +import org.valkyrienskies.core.api.ships.Ship; + import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; - import java.util.Collection; public interface IPeripheralOwner { @@ -33,6 +36,20 @@ default Vec3 getCenterPos() { @NotNull FrontAndTop getOrientation(); + @NotNull + default Vec3 getDirection() { + Vec3 dir = Vec3.atLowerCornerOf(getFacing().getNormal()); + if (!APAddons.vs2Loaded) { + return dir; + } + Ship ship = APAddons.getVS2Ship(getLevel(), getPos()); + if (ship == null) { + return dir; + } + Vector3d newDir = ship.getShipToWorld().transformDirection(new Vector3d(dir.x, dir.y, dir.z)); + return new Vec3(newDir.x, newDir.y, newDir.z); + } + @Nullable Player getOwner(); @NotNull CompoundTag getDataStorage(); diff --git a/src/main/java/de/srendi/advancedperipherals/common/addons/computercraft/owner/PocketPeripheralOwner.java b/src/main/java/de/srendi/advancedperipherals/common/addons/computercraft/owner/PocketPeripheralOwner.java index ffafe5d54..42e20349f 100644 --- a/src/main/java/de/srendi/advancedperipherals/common/addons/computercraft/owner/PocketPeripheralOwner.java +++ b/src/main/java/de/srendi/advancedperipherals/common/addons/computercraft/owner/PocketPeripheralOwner.java @@ -67,7 +67,6 @@ public Direction getFacing() { return owner.getDirection(); } - /** * Not used for pockets */ diff --git a/src/main/java/de/srendi/advancedperipherals/common/blocks/blockentities/DistanceDetectorEntity.java b/src/main/java/de/srendi/advancedperipherals/common/blocks/blockentities/DistanceDetectorEntity.java index 89ee03b4d..baa376c6f 100644 --- a/src/main/java/de/srendi/advancedperipherals/common/blocks/blockentities/DistanceDetectorEntity.java +++ b/src/main/java/de/srendi/advancedperipherals/common/blocks/blockentities/DistanceDetectorEntity.java @@ -1,6 +1,6 @@ package de.srendi.advancedperipherals.common.blocks.blockentities; -import de.srendi.advancedperipherals.common.addons.APAddons; +import de.srendi.advancedperipherals.common.addons.computercraft.owner.BlockEntityPeripheralOwner; import de.srendi.advancedperipherals.common.addons.computercraft.peripheral.DistanceDetectorPeripheral; import de.srendi.advancedperipherals.common.blocks.base.BaseBlock; import de.srendi.advancedperipherals.common.blocks.base.PeripheralBlockEntity; @@ -20,8 +20,6 @@ import net.minecraft.world.phys.HitResult; import net.minecraft.world.phys.Vec3; import org.jetbrains.annotations.NotNull; -import org.joml.Vector3d; -import org.valkyrienskies.core.api.ships.Ship; import java.util.concurrent.atomic.AtomicBoolean; import java.util.concurrent.atomic.AtomicInteger; @@ -179,36 +177,15 @@ public ClientboundBlockEntityDataPacket getUpdatePacket() { return ClientboundBlockEntityDataPacket.create(this); } - protected Vec3 getCenterPos() { - Vec3 pos = Vec3.atCenterOf(this.getBlockPos()); - if (!APAddons.vs2Loaded) { - return pos; - } - Ship ship = APAddons.getVS2Ship(this.getLevel(), this.getBlockPos()); - if (ship == null) { - return pos; - } - Vector3d newPos = ship.getShipToWorld().transformPosition(new Vector3d(pos.x, pos.y, pos.z)); - return new Vec3(newPos.x, newPos.y, newPos.z); - } - - protected Vec3 getDirection() { - Vec3 dir = Vec3.atLowerCornerOf(getBlockState().getValue(BaseBlock.ORIENTATION).front().getNormal()); - if (!APAddons.vs2Loaded) { - return dir; - } - Ship ship = APAddons.getVS2Ship(this.getLevel(), this.getBlockPos()); - if (ship == null) { - return dir; - } - Vector3d newDir = ship.getShipToWorld().transformDirection(new Vector3d(dir.x, dir.y, dir.z)); - return new Vec3(newDir.x, newDir.y, newDir.z); - } - public double calculateDistance() { + DistanceDetectorPeripheral peripheral = this.getPeripheral(); + if (peripheral == null) { + return -1; + } + BlockEntityPeripheralOwner owner = peripheral.getPeripheralOwner(); final double maxRange = this.getMaxRange(); - Vec3 direction = getDirection(); - Vec3 center = getCenterPos(); + Vec3 direction = owner.getDirection(); + Vec3 center = peripheral.getWorldPos(); Vec3 from = center; Vec3 to = from.add(direction.x * maxRange, direction.y * maxRange, direction.z * maxRange); diff --git a/src/main/java/de/srendi/advancedperipherals/common/smartglasses/SmartGlassesComputer.java b/src/main/java/de/srendi/advancedperipherals/common/smartglasses/SmartGlassesComputer.java index 8f5049e11..eac317fec 100644 --- a/src/main/java/de/srendi/advancedperipherals/common/smartglasses/SmartGlassesComputer.java +++ b/src/main/java/de/srendi/advancedperipherals/common/smartglasses/SmartGlassesComputer.java @@ -82,7 +82,7 @@ public ServerLevel getLevel() { @Override public BlockPos getPosition() { - return this.entity == null ? super.getPosition() : this.entity.blockPosition(); + return this.entity == null ? super.getPosition() : new BlockPos(this.entity.getEyePosition()); } @Override @@ -212,7 +212,7 @@ public void setEntity(@Nullable Entity entity) { return; } this.setLevel((ServerLevel) this.entity.getCommandSenderWorld()); - this.setPosition(this.entity.blockPosition()); + this.setPosition(new BlockPos(this.entity.getEyePosition())); } public Map getModules() { diff --git a/src/main/java/de/srendi/advancedperipherals/common/smartglasses/modules/ModulePeripheral.java b/src/main/java/de/srendi/advancedperipherals/common/smartglasses/modules/ModulePeripheral.java index e72465756..760b03ed2 100644 --- a/src/main/java/de/srendi/advancedperipherals/common/smartglasses/modules/ModulePeripheral.java +++ b/src/main/java/de/srendi/advancedperipherals/common/smartglasses/modules/ModulePeripheral.java @@ -6,7 +6,7 @@ public class ModulePeripheral extends BasePeripheral { - public static final String PERIPHERAL_TYPE = "smartGlasses"; + public static final String PERIPHERAL_TYPE = "smart_glasses"; public ModulePeripheral(SmartGlassesComputer computer) { super(PERIPHERAL_TYPE, new ModulePeripheralOwner(computer)); @@ -15,14 +15,14 @@ public ModulePeripheral(SmartGlassesComputer computer) { public void updateModules() { // We need to set the initialisation to false so the dynamic peripheral re-builds the plugins - initialized = false; - if (plugins != null) - plugins.clear(); + clearAllPlugins(); - getPeripheralOwner().getComputer().getModules().values().forEach(module -> { - IModuleFunctions functions = module.getFunctions(getPeripheralOwner().getComputer().getSmartGlassesAccess()); - if (functions != null) + SmartGlassesComputer computer = getPeripheralOwner().getComputer(); + computer.getModules().values().forEach(module -> { + IModuleFunctions functions = module.getFunctions(computer.getSmartGlassesAccess()); + if (functions != null) { addPlugin(functions); + } }); } diff --git a/src/main/java/de/srendi/advancedperipherals/common/smartglasses/modules/ModulePeripheralOwner.java b/src/main/java/de/srendi/advancedperipherals/common/smartglasses/modules/ModulePeripheralOwner.java index 62d22cdeb..b7407a577 100644 --- a/src/main/java/de/srendi/advancedperipherals/common/smartglasses/modules/ModulePeripheralOwner.java +++ b/src/main/java/de/srendi/advancedperipherals/common/smartglasses/modules/ModulePeripheralOwner.java @@ -14,6 +14,8 @@ import net.minecraft.world.entity.player.Player; import net.minecraft.world.item.ItemStack; import net.minecraft.world.level.Level; +import net.minecraft.world.phys.Vec3; + import org.apache.commons.lang3.NotImplementedException; import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; @@ -45,19 +47,33 @@ public Level getLevel() { @NotNull @Override public BlockPos getPos() { - return computer.getEntity().getOnPos(); + return new BlockPos(computer.getEntity().getEyePosition()); + } + + @NotNull + @Override + public Vec3 getCenterPos() { + return computer.getEntity().getEyePosition(); } @NotNull @Override public Direction getFacing() { - return Direction.NORTH; + Vec3 dir = getDirection(); + return Direction.getNearest(dir.x, dir.y, dir.z); } @NotNull @Override public FrontAndTop getOrientation() { - return FrontAndTop.NORTH_UP; + Vec3 up = computer.getEntity().getUpVector(1.0f); + return FrontAndTop.fromFrontAndTop(getFacing(), Direction.getNearest(up.x, up.y, up.z)); + } + + @NotNull + @Override + public Vec3 getDirection() { + return computer.getEntity().getLookAngle(); } @NotNull @@ -69,8 +85,7 @@ public SmartGlassesComputer getComputer() { @Override public Player getOwner() { Entity owner = computer.getEntity(); - if (owner instanceof Player player) return player; - return null; + return owner instanceof Player player ? player : null; } @NotNull diff --git a/src/main/java/de/srendi/advancedperipherals/common/smartglasses/modules/overlay/OverlayGlassesFunctions.java b/src/main/java/de/srendi/advancedperipherals/common/smartglasses/modules/overlay/OverlayGlassesFunctions.java index bffed31cb..d0c99a7e5 100644 --- a/src/main/java/de/srendi/advancedperipherals/common/smartglasses/modules/overlay/OverlayGlassesFunctions.java +++ b/src/main/java/de/srendi/advancedperipherals/common/smartglasses/modules/overlay/OverlayGlassesFunctions.java @@ -16,6 +16,7 @@ import de.srendi.advancedperipherals.common.smartglasses.modules.overlay.objects.two_dim.RenderableObject; import de.srendi.advancedperipherals.common.smartglasses.modules.overlay.objects.two_dim.TextObject; import net.minecraft.client.Minecraft; +import net.minecraft.world.phys.Vec3; public class OverlayGlassesFunctions implements IModuleFunctions { @@ -120,7 +121,8 @@ public final MethodResult getSize() { @LuaFunction public final MethodResult getCoords() { - return MethodResult.of(access.getEntity().position().x, access.getEntity().position().y, access.getEntity().position().z); + Vec3 pos = access.getEntity().getEyePosition(); + return MethodResult.of(pos.x, pos.y, pos.z); } @LuaFunction diff --git a/src/main/java/de/srendi/advancedperipherals/lib/peripherals/BasePeripheral.java b/src/main/java/de/srendi/advancedperipherals/lib/peripherals/BasePeripheral.java index eb41f7430..4b99a1f1a 100644 --- a/src/main/java/de/srendi/advancedperipherals/lib/peripherals/BasePeripheral.java +++ b/src/main/java/de/srendi/advancedperipherals/lib/peripherals/BasePeripheral.java @@ -41,7 +41,7 @@ public abstract class BasePeripheral implements IBas protected final O owner; protected final List pluggedMethods = new ArrayList<>(); protected boolean initialized = false; - protected List plugins = null; + protected final List plugins = new LinkedList<>(); protected String[] methodNames = new String[0]; protected BasePeripheral(String type, O owner) { @@ -49,32 +49,41 @@ protected BasePeripheral(String type, O owner) { this.owner = owner; } + protected void clearAllPlugins() { + this.initialized = false; + plugins.clear(); + } + protected void buildPlugins() { - if (!initialized) { - initialized = true; - this.pluggedMethods.clear(); - if (plugins != null) plugins.forEach(plugin -> { - if (plugin.isSuitable(this)) - pluggedMethods.addAll(plugin.getMethods()); - }); - owner.getAbilities().forEach(ability -> { - if (ability instanceof IPeripheralPlugin peripheralPlugin) - pluggedMethods.addAll(peripheralPlugin.getMethods()); - }); - this.methodNames = pluggedMethods.stream().map(BoundMethod::getName).toArray(String[]::new); + if (this.initialized) { + return; } + this.initialized = true; + this.pluggedMethods.clear(); + this.plugins.forEach(plugin -> { + if (plugin.isSuitable(this)) { + this.pluggedMethods.addAll(plugin.getMethods()); + } + }); + owner.getAbilities().forEach(ability -> { + if (ability instanceof IPeripheralPlugin peripheralPlugin) { + this.pluggedMethods.addAll(peripheralPlugin.getMethods()); + } + }); + this.methodNames = this.pluggedMethods.stream().map(BoundMethod::getName).toArray(String[]::new); } protected void addPlugin(@NotNull IPeripheralPlugin plugin) { - if (plugins == null) plugins = new LinkedList<>(); - plugins.add(plugin); + this.plugins.add(plugin); IPeripheralOperation[] operations = plugin.getOperations(); if (operations != null) { OperationAbility operationAbility = owner.getAbility(PeripheralOwnerAbility.OPERATION); - if (operationAbility == null) + if (operationAbility == null) { throw new IllegalArgumentException("This is not possible to attach plugin with operations to not operationable owner"); - for (IPeripheralOperation operation : operations) + } + for (IPeripheralOperation operation : operations) { operationAbility.registerOperation(operation); + } } } From 27be42cf98f1ec59d9b59900441ac1372c9e1219 Mon Sep 17 00:00:00 2001 From: zyxkad Date: Sat, 25 Jan 2025 15:13:14 -0700 Subject: [PATCH 2/9] rename getWorldPos -> getPhysicsPos --- .../peripheral/ChatBoxPeripheral.java | 12 +++++------ .../EnvironmentDetectorPeripheral.java | 12 +++++------ .../peripheral/GeoScannerPeripheral.java | 4 ++-- .../peripheral/PlayerDetectorPeripheral.java | 20 +++++++++---------- .../plugins/AutomataLookPlugin.java | 4 ++-- .../blockentities/DistanceDetectorEntity.java | 2 +- .../lib/peripherals/BasePeripheral.java | 6 +++--- 7 files changed, 30 insertions(+), 30 deletions(-) diff --git a/src/main/java/de/srendi/advancedperipherals/common/addons/computercraft/peripheral/ChatBoxPeripheral.java b/src/main/java/de/srendi/advancedperipherals/common/addons/computercraft/peripheral/ChatBoxPeripheral.java index 9717a36e1..88f3cf3aa 100644 --- a/src/main/java/de/srendi/advancedperipherals/common/addons/computercraft/peripheral/ChatBoxPeripheral.java +++ b/src/main/java/de/srendi/advancedperipherals/common/addons/computercraft/peripheral/ChatBoxPeripheral.java @@ -250,7 +250,7 @@ public final MethodResult sendFormattedMessage(@NotNull IArguments arguments) th if (!APConfig.PERIPHERALS_CONFIG.chatBoxMultiDimensional.get() && player.getLevel().dimension() != dimension) { continue; } - if (CoordUtil.isInRange(getWorldPos(), getLevel(), player, range, maxRange)) { + if (CoordUtil.isInRange(getPhysicsPos(), getLevel(), player, range, maxRange)) { player.sendSystemMessage(preparedMessage); } } @@ -293,7 +293,7 @@ public final MethodResult sendMessage(@NotNull IArguments arguments) throws LuaE if (!APConfig.PERIPHERALS_CONFIG.chatBoxMultiDimensional.get() && player.getLevel().dimension() != dimension) { continue; } - if (CoordUtil.isInRange(getWorldPos(), getLevel(), player, range, maxRange)) { + if (CoordUtil.isInRange(getPhysicsPos(), getLevel(), player, range, maxRange)) { player.sendSystemMessage(preparedMessage); } } @@ -340,7 +340,7 @@ public final MethodResult sendFormattedMessageToPlayer(@NotNull IArguments argum return MethodResult.of(false, "NOT_SAME_DIMENSION"); } - if (CoordUtil.isInRange(getWorldPos(), getLevel(), player, range, maxRange)) { + if (CoordUtil.isInRange(getPhysicsPos(), getLevel(), player, range, maxRange)) { player.sendSystemMessage(preparedMessage); } return MethodResult.of(true); @@ -398,7 +398,7 @@ public final MethodResult sendFormattedToastToPlayer(@NotNull IArguments argumen return MethodResult.of(false, "NOT_SAME_DIMENSION"); } - if (CoordUtil.isInRange(getWorldPos(), getLevel(), player, range, maxRange)) { + if (CoordUtil.isInRange(getPhysicsPos(), getLevel(), player, range, maxRange)) { ToastToClientPacket packet = new ToastToClientPacket(titleComponent, preparedMessage); APNetworking.sendTo(packet, player); } @@ -437,7 +437,7 @@ public final MethodResult sendMessageToPlayer(@NotNull IArguments arguments) thr return MethodResult.of(false, "NOT_SAME_DIMENSION"); } - if (CoordUtil.isInRange(getWorldPos(), getLevel(), player, range, maxRange)) { + if (CoordUtil.isInRange(getPhysicsPos(), getLevel(), player, range, maxRange)) { player.sendSystemMessage(preparedMessage, false); } return MethodResult.of(true); @@ -476,7 +476,7 @@ public final MethodResult sendToastToPlayer(@NotNull IArguments arguments) throw return MethodResult.of(false, "NOT_SAME_DIMENSION"); } - if (CoordUtil.isInRange(getWorldPos(), getLevel(), player, range, maxRange)) { + if (CoordUtil.isInRange(getPhysicsPos(), getLevel(), player, range, maxRange)) { ToastToClientPacket packet = new ToastToClientPacket(Component.literal(title), preparedMessage); APNetworking.sendTo(packet, player); } diff --git a/src/main/java/de/srendi/advancedperipherals/common/addons/computercraft/peripheral/EnvironmentDetectorPeripheral.java b/src/main/java/de/srendi/advancedperipherals/common/addons/computercraft/peripheral/EnvironmentDetectorPeripheral.java index 580d1a7f4..92c668b17 100644 --- a/src/main/java/de/srendi/advancedperipherals/common/addons/computercraft/peripheral/EnvironmentDetectorPeripheral.java +++ b/src/main/java/de/srendi/advancedperipherals/common/addons/computercraft/peripheral/EnvironmentDetectorPeripheral.java @@ -93,24 +93,24 @@ public boolean isEnabled() { @LuaFunction(mainThread = true) public final String getBiome() { - Optional> biome = getLevel().getBiome(this.getWorldBlockPos()).unwrapKey(); + Optional> biome = getLevel().getBiome(this.getPhysicsBlockPos()).unwrapKey(); return biome.map(biomeResourceKey -> biomeResourceKey.location().toString()).orElse("unknown"); } @LuaFunction(mainThread = true) public final int getSkyLightLevel() { - return getLevel().getBrightness(LightLayer.SKY, this.getWorldBlockPos().offset(0, 1, 0)); + return getLevel().getBrightness(LightLayer.SKY, this.getPhysicsBlockPos().offset(0, 1, 0)); } @LuaFunction(mainThread = true) public final int getBlockLightLevel() { - return getLevel().getBrightness(LightLayer.BLOCK, this.getWorldBlockPos().offset(0, 1, 0)); + return getLevel().getBrightness(LightLayer.BLOCK, this.getPhysicsBlockPos().offset(0, 1, 0)); } @LuaFunction(mainThread = true) public final int getDayLightLevel() { Level level = getLevel(); - int i = level.getBrightness(LightLayer.SKY, this.getWorldBlockPos().offset(0, 1, 0)) - level.getSkyDarken(); + int i = level.getBrightness(LightLayer.SKY, this.getPhysicsBlockPos().offset(0, 1, 0)) - level.getSkyDarken(); float f = level.getSunAngle(1.0F); if (i > 0) { float f1 = f < (float) Math.PI ? 0.0F : ((float) Math.PI * 2F); @@ -128,7 +128,7 @@ public final long getTime() { @LuaFunction(mainThread = true) public final boolean isSlimeChunk() { - ChunkPos chunkPos = new ChunkPos(this.getWorldBlockPos()); + ChunkPos chunkPos = new ChunkPos(this.getPhysicsBlockPos()); return WorldgenRandom.seedSlimeChunk(chunkPos.x, chunkPos.z, ((WorldGenLevel) getLevel()).getSeed(), 987234911L).nextInt(10) == 0; } @@ -208,7 +208,7 @@ public final MethodResult scanEntities(@NotNull IArguments arguments) throws Lua return withOperation(SCAN_ENTITIES, new SphereOperationContext(radius), context -> { return context.getRadius() > SCAN_ENTITIES.getMaxCostRadius() ? MethodResult.of(null, "Radius exceeds max value") : null; }, context -> { - Vec3 pos = this.getWorldPos(); + Vec3 pos = this.getPhysicsPos(); AABB box = new AABB(pos, pos); List> entities = getLevel().getEntities((Entity) null, box.inflate(context.getRadius() + 0.5), entity -> entity instanceof LivingEntity && entity.isAlive()).stream().map(entity -> LuaConverter.completeEntityWithPositionToLua(entity, pos, detailed)).toList(); return MethodResult.of(entities); diff --git a/src/main/java/de/srendi/advancedperipherals/common/addons/computercraft/peripheral/GeoScannerPeripheral.java b/src/main/java/de/srendi/advancedperipherals/common/addons/computercraft/peripheral/GeoScannerPeripheral.java index 449256acb..766586170 100644 --- a/src/main/java/de/srendi/advancedperipherals/common/addons/computercraft/peripheral/GeoScannerPeripheral.java +++ b/src/main/java/de/srendi/advancedperipherals/common/addons/computercraft/peripheral/GeoScannerPeripheral.java @@ -103,7 +103,7 @@ public final MethodResult cost(int radius) { public final MethodResult chunkAnalyze() throws LuaException { return withOperation(SCAN_BLOCKS, SCAN_BLOCKS.free(), null, ignored -> { Level level = getLevel(); - LevelChunk chunk = level.getChunkAt(getWorldBlockPos()); + LevelChunk chunk = level.getChunkAt(getPhysicsBlockPos()); ChunkPos chunkPos = chunk.getPos(); HashMap data = new HashMap<>(); for (int x = chunkPos.getMinBlockX(); x <= chunkPos.getMaxBlockX(); x++) { @@ -136,7 +136,7 @@ public final MethodResult scan(@NotNull IArguments arguments) throws LuaExceptio scan(result, getLevel(), getCenterPos(), context.getRadius()); if (isOnShip()) { int i = result.size(); - scan(result, getLevel(), getWorldPos(), context.getRadius()); + scan(result, getLevel(), getPhysicsPos(), context.getRadius()); for (; i < result.size(); i++) { Map data = result.get(i); data.put("notOnShip", true); diff --git a/src/main/java/de/srendi/advancedperipherals/common/addons/computercraft/peripheral/PlayerDetectorPeripheral.java b/src/main/java/de/srendi/advancedperipherals/common/addons/computercraft/peripheral/PlayerDetectorPeripheral.java index c06aa150d..dc05ba478 100644 --- a/src/main/java/de/srendi/advancedperipherals/common/addons/computercraft/peripheral/PlayerDetectorPeripheral.java +++ b/src/main/java/de/srendi/advancedperipherals/common/addons/computercraft/peripheral/PlayerDetectorPeripheral.java @@ -73,7 +73,7 @@ public final MethodResult getPlayersInCoords(Map firstCoord, Map sec if (!isAllowedMultiDimensional() && player.getLevel().dimension() != dimension) { continue; } - if (CoordUtil.isInRange(getWorldPos(), player, getLevel(), firstPos, secondPos, MAX_RANGE)) { + if (CoordUtil.isInRange(getPhysicsPos(), player, getLevel(), firstPos, secondPos, MAX_RANGE)) { playersName.add(player.getName().getString()); } } @@ -86,7 +86,7 @@ public final List getPlayersInCubic(int x, int y, int z) { ResourceKey dimension = getLevel().dimension(); for (ServerPlayer player : getPlayers()) { - if (player.getLevel().dimension() == dimension && CoordUtil.isInRange(getWorldPos(), getLevel(), player, x, y, z, MAX_RANGE)) { + if (player.getLevel().dimension() == dimension && CoordUtil.isInRange(getPhysicsPos(), getLevel(), player, x, y, z, MAX_RANGE)) { playersName.add(player.getName().getString()); } } @@ -99,7 +99,7 @@ public final List getPlayersInRange(int range) { ResourceKey dimension = getLevel().dimension(); for (ServerPlayer player : getPlayers()) { - if (player.getLevel().dimension() == dimension && CoordUtil.isInRange(getWorldPos(), getLevel(), player, range, MAX_RANGE)) { + if (player.getLevel().dimension() == dimension && CoordUtil.isInRange(getPhysicsPos(), getLevel(), player, range, MAX_RANGE)) { playersName.add(player.getName().getString()); } } @@ -118,7 +118,7 @@ public final boolean isPlayersInCoords(Map firstCoord, Map secondCoo if (!isAllowedMultiDimensional() && player.getLevel().dimension() != dimension) { continue; } - if (CoordUtil.isInRange(getWorldPos(), player, getLevel(), firstPos, secondPos, MAX_RANGE)) { + if (CoordUtil.isInRange(getPhysicsPos(), player, getLevel(), firstPos, secondPos, MAX_RANGE)) { return true; } } @@ -132,7 +132,7 @@ public final boolean isPlayersInCubic(int x, int y, int z) { ResourceKey dimension = getLevel().dimension(); for (ServerPlayer player : getPlayers()) { - if (player.getLevel().dimension() == dimension && CoordUtil.isInRange(getWorldPos(), getLevel(), player, x, y, z, MAX_RANGE)) { + if (player.getLevel().dimension() == dimension && CoordUtil.isInRange(getPhysicsPos(), getLevel(), player, x, y, z, MAX_RANGE)) { return true; } } @@ -146,7 +146,7 @@ public final boolean isPlayersInRange(int range) { ResourceKey dimension = getLevel().dimension(); for (ServerPlayer player : getPlayers()) { - if (player.getLevel().dimension() == dimension && CoordUtil.isInRange(getWorldPos(), getLevel(), player, range, MAX_RANGE)) { + if (player.getLevel().dimension() == dimension && CoordUtil.isInRange(getPhysicsPos(), getLevel(), player, range, MAX_RANGE)) { return true; } } @@ -163,7 +163,7 @@ public final boolean isPlayerInCoords(Map firstCoord, Map secondCoor if (!isAllowedMultiDimensional() && player.getLevel().dimension() != dimension) { return false; } - return CoordUtil.isInRange(getWorldPos(), player, getLevel(), firstPos, secondPos, MAX_RANGE); + return CoordUtil.isInRange(getPhysicsPos(), player, getLevel(), firstPos, secondPos, MAX_RANGE); } @LuaFunction(mainThread = true) @@ -171,7 +171,7 @@ public final boolean isPlayerInCubic(int x, int y, int z, String username) { ResourceKey dimension = getLevel().dimension(); ServerPlayer player = getPlayer(username); - return player.getLevel().dimension() == dimension && CoordUtil.isInRange(getWorldPos(), getLevel(), player, x, y, z, MAX_RANGE); + return player.getLevel().dimension() == dimension && CoordUtil.isInRange(getPhysicsPos(), getLevel(), player, x, y, z, MAX_RANGE); } @LuaFunction(mainThread = true) @@ -179,7 +179,7 @@ public final boolean isPlayerInRange(int range, String username) { ResourceKey dimension = getLevel().dimension(); ServerPlayer player = getPlayer(username); - return player.getLevel().dimension() == dimension && CoordUtil.isInRange(getWorldPos(), getLevel(), player, range, MAX_RANGE); + return player.getLevel().dimension() == dimension && CoordUtil.isInRange(getPhysicsPos(), getLevel(), player, range, MAX_RANGE); } @LuaFunction(value = {"getPlayerPos", "getPlayer"}, mainThread = true) @@ -187,7 +187,7 @@ public final Map getPlayerPos(IArguments arguments) throws LuaEx if (!APConfig.PERIPHERALS_CONFIG.playerSpy.get()) throw new LuaException("This function is disabled in the config. Activate it or ask an admin if he can activate it."); ResourceKey dimension = getLevel().dimension(); - Vec3 pos = getWorldPos(); + Vec3 pos = getPhysicsPos(); ServerPlayer player = getPlayer(arguments.getString(0)); if (player == null) { diff --git a/src/main/java/de/srendi/advancedperipherals/common/addons/computercraft/peripheral/plugins/AutomataLookPlugin.java b/src/main/java/de/srendi/advancedperipherals/common/addons/computercraft/peripheral/plugins/AutomataLookPlugin.java index 084f20289..1a7a0201a 100644 --- a/src/main/java/de/srendi/advancedperipherals/common/addons/computercraft/peripheral/plugins/AutomataLookPlugin.java +++ b/src/main/java/de/srendi/advancedperipherals/common/addons/computercraft/peripheral/plugins/AutomataLookPlugin.java @@ -52,7 +52,7 @@ public final MethodResult lookAtBlock(@NotNull IArguments arguments) throws LuaE data.put("name", blockName == null ? null : blockName.toString()); data.put("tags", LuaConverter.tagsToList(() -> state.getBlock().builtInRegistryHolder().tags())); Vec3 pos = blockHit.getLocation(); - Vec3 origin = automataCore.getWorldPos(); + Vec3 origin = automataCore.getPhysicsPos(); data.put("x", pos.x - origin.x); data.put("y", pos.y - origin.y); data.put("z", pos.z - origin.z); @@ -79,7 +79,7 @@ public final MethodResult lookAtEntity(@NotNull IArguments arguments) throws Lua } EntityHitResult entityHit = (EntityHitResult) result; - Vec3 origin = automataCore.getWorldPos(); + Vec3 origin = automataCore.getPhysicsPos(); return MethodResult.of(LuaConverter.completeEntityWithPositionToLua(entityHit.getEntity(), origin, true)); } diff --git a/src/main/java/de/srendi/advancedperipherals/common/blocks/blockentities/DistanceDetectorEntity.java b/src/main/java/de/srendi/advancedperipherals/common/blocks/blockentities/DistanceDetectorEntity.java index baa376c6f..0042788ad 100644 --- a/src/main/java/de/srendi/advancedperipherals/common/blocks/blockentities/DistanceDetectorEntity.java +++ b/src/main/java/de/srendi/advancedperipherals/common/blocks/blockentities/DistanceDetectorEntity.java @@ -185,7 +185,7 @@ public double calculateDistance() { BlockEntityPeripheralOwner owner = peripheral.getPeripheralOwner(); final double maxRange = this.getMaxRange(); Vec3 direction = owner.getDirection(); - Vec3 center = peripheral.getWorldPos(); + Vec3 center = peripheral.getPhysicsPos(); Vec3 from = center; Vec3 to = from.add(direction.x * maxRange, direction.y * maxRange, direction.z * maxRange); diff --git a/src/main/java/de/srendi/advancedperipherals/lib/peripherals/BasePeripheral.java b/src/main/java/de/srendi/advancedperipherals/lib/peripherals/BasePeripheral.java index 4b99a1f1a..72706f173 100644 --- a/src/main/java/de/srendi/advancedperipherals/lib/peripherals/BasePeripheral.java +++ b/src/main/java/de/srendi/advancedperipherals/lib/peripherals/BasePeripheral.java @@ -156,7 +156,7 @@ public boolean isOnShip() { return APAddons.vs2Loaded && APAddons.isBlockOnShip(owner.getLevel(), owner.getPos()); } - public Vec3 getWorldPos() { + public Vec3 getPhysicsPos() { Vec3 pos = this.getCenterPos(); if (!APAddons.vs2Loaded) { return pos; @@ -169,8 +169,8 @@ public Vec3 getWorldPos() { return new Vec3(newPos.x, newPos.y, newPos.z); } - public final BlockPos getWorldBlockPos() { - return new BlockPos(this.getWorldPos()); + public final BlockPos getPhysicsBlockPos() { + return new BlockPos(this.getPhysicsPos()); } protected Direction validateSide(String direction) throws LuaException { From 2e86ba843f00f035824ade4e26115d08565ab573 Mon Sep 17 00:00:00 2001 From: zyxkad Date: Sat, 25 Jan 2025 16:12:13 -0700 Subject: [PATCH 3/9] add IPeripheralOwner.getHoldingEntity --- .../owner/BlockEntityPeripheralOwner.java | 13 +++++++---- .../computercraft/owner/IPeripheralOwner.java | 22 +++++++++++++++++-- .../owner/InventoryManagerOwner.java | 17 ++++++++++++++ .../owner/PocketPeripheralOwner.java | 6 ++--- .../owner/TurtlePeripheralOwner.java | 7 ++++++ 5 files changed, 55 insertions(+), 10 deletions(-) create mode 100644 src/main/java/de/srendi/advancedperipherals/common/addons/computercraft/owner/InventoryManagerOwner.java diff --git a/src/main/java/de/srendi/advancedperipherals/common/addons/computercraft/owner/BlockEntityPeripheralOwner.java b/src/main/java/de/srendi/advancedperipherals/common/addons/computercraft/owner/BlockEntityPeripheralOwner.java index 81250b6f2..c30806f59 100644 --- a/src/main/java/de/srendi/advancedperipherals/common/addons/computercraft/owner/BlockEntityPeripheralOwner.java +++ b/src/main/java/de/srendi/advancedperipherals/common/addons/computercraft/owner/BlockEntityPeripheralOwner.java @@ -12,16 +12,17 @@ import net.minecraft.nbt.CompoundTag; import net.minecraft.network.chat.Component; import net.minecraft.world.Nameable; +import net.minecraft.world.entity.Entity; import net.minecraft.world.entity.player.Player; import net.minecraft.world.item.ItemStack; import net.minecraft.world.level.Level; import net.minecraft.world.level.block.entity.BlockEntity; + +import java.util.Objects; import org.apache.commons.lang3.NotImplementedException; import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; -import java.util.Objects; - public class BlockEntityPeripheralOwner extends BasePeripheralOwner { public final T tileEntity; @@ -70,11 +71,15 @@ public FrontAndTop getOrientation() { return tileEntity.getBlockState().getValue(BaseBlock.ORIENTATION); } + @Nullable + @Override + public Entity getHoldingEntity() { + return null; + } + @Nullable @Override public Player getOwner() { - if (tileEntity instanceof InventoryManagerEntity inventoryManagerEntity) - return inventoryManagerEntity.getOwnerPlayer(); return null; } diff --git a/src/main/java/de/srendi/advancedperipherals/common/addons/computercraft/owner/IPeripheralOwner.java b/src/main/java/de/srendi/advancedperipherals/common/addons/computercraft/owner/IPeripheralOwner.java index 8fea843c6..175df2645 100644 --- a/src/main/java/de/srendi/advancedperipherals/common/addons/computercraft/owner/IPeripheralOwner.java +++ b/src/main/java/de/srendi/advancedperipherals/common/addons/computercraft/owner/IPeripheralOwner.java @@ -15,9 +15,11 @@ import org.joml.Vector3d; import org.valkyrienskies.core.api.ships.Ship; +import java.util.Collection; +import java.util.HashSet; +import java.util.Set; import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; -import java.util.Collection; public interface IPeripheralOwner { @@ -50,7 +52,23 @@ default Vec3 getDirection() { return new Vec3(newDir.x, newDir.y, newDir.z); } - @Nullable Player getOwner(); + @Nullable Entity getHoldingEntity(); + + @Nullable + default Player getOwner() { + Entity owner = pocket.getHoldingEntity(); + Set checked = new HashSet<>(); + while (owner != null && checked.add(owner)) { + if (owner instanceof Player player) { + return (Player) player; + } + if (!(owner instanceof OwnableEntity ownable)) { + break; + } + owner = ownable.getOwner(); + } + return null; + } @NotNull CompoundTag getDataStorage(); diff --git a/src/main/java/de/srendi/advancedperipherals/common/addons/computercraft/owner/InventoryManagerOwner.java b/src/main/java/de/srendi/advancedperipherals/common/addons/computercraft/owner/InventoryManagerOwner.java new file mode 100644 index 000000000..c9bc48605 --- /dev/null +++ b/src/main/java/de/srendi/advancedperipherals/common/addons/computercraft/owner/InventoryManagerOwner.java @@ -0,0 +1,17 @@ +package de.srendi.advancedperipherals.common.addons.computercraft.owner; + +import de.srendi.advancedperipherals.common.blocks.blockentities.InventoryManagerEntity; +import net.minecraft.world.entity.player.Player; +import org.jetbrains.annotations.Nullable; + +public class InventoryManagerOwner extends BlockEntityPeripheralOwner { + public InventoryManagerOwner(InventoryManagerEntity tile) { + super(tile); + } + + @Nullable + @Override + public Player getOwner() { + return tileEntity.getOwnerPlayer(); + } +} diff --git a/src/main/java/de/srendi/advancedperipherals/common/addons/computercraft/owner/PocketPeripheralOwner.java b/src/main/java/de/srendi/advancedperipherals/common/addons/computercraft/owner/PocketPeripheralOwner.java index 42e20349f..3577e8df9 100644 --- a/src/main/java/de/srendi/advancedperipherals/common/addons/computercraft/owner/PocketPeripheralOwner.java +++ b/src/main/java/de/srendi/advancedperipherals/common/addons/computercraft/owner/PocketPeripheralOwner.java @@ -78,10 +78,8 @@ public FrontAndTop getOrientation() { @Nullable @Override - public Player getOwner() { - Entity owner = pocket.getEntity(); - if (owner instanceof Player player) return player; - return null; + public Entity getHoldingEntity() { + return pocket.getEntity(); } @NotNull diff --git a/src/main/java/de/srendi/advancedperipherals/common/addons/computercraft/owner/TurtlePeripheralOwner.java b/src/main/java/de/srendi/advancedperipherals/common/addons/computercraft/owner/TurtlePeripheralOwner.java index 17dd0e3fb..e8365fcc7 100644 --- a/src/main/java/de/srendi/advancedperipherals/common/addons/computercraft/owner/TurtlePeripheralOwner.java +++ b/src/main/java/de/srendi/advancedperipherals/common/addons/computercraft/owner/TurtlePeripheralOwner.java @@ -15,6 +15,7 @@ import net.minecraft.core.Direction; import net.minecraft.core.FrontAndTop; import net.minecraft.nbt.CompoundTag; +import net.minecraft.world.entity.Entity; import net.minecraft.world.entity.player.Player; import net.minecraft.world.item.ItemStack; import net.minecraft.world.level.Level; @@ -64,6 +65,12 @@ public FrontAndTop getOrientation() { return FrontAndTop.fromFrontAndTop(getFacing(), Direction.UP); } + @Nullable + @Override + public Entity getHoldingEntity() { + return null; + } + @Nullable @Override public Player getOwner() { From 2dc9428b73857d639a7583349a73d4f2c5457fcf Mon Sep 17 00:00:00 2001 From: zyxkad Date: Sat, 25 Jan 2025 16:16:26 -0700 Subject: [PATCH 4/9] remove item.copy()s refactor fingerprint generator --- .../InventoryManagerPeripheral.java | 43 ++++++++----------- .../common/util/LuaConverter.java | 12 +++++- .../common/util/inventory/FluidUtil.java | 23 +++++----- .../common/util/inventory/ItemUtil.java | 32 +++++++++----- 4 files changed, 61 insertions(+), 49 deletions(-) diff --git a/src/main/java/de/srendi/advancedperipherals/common/addons/computercraft/peripheral/InventoryManagerPeripheral.java b/src/main/java/de/srendi/advancedperipherals/common/addons/computercraft/peripheral/InventoryManagerPeripheral.java index 21fe14a0d..eaabc32f0 100644 --- a/src/main/java/de/srendi/advancedperipherals/common/addons/computercraft/peripheral/InventoryManagerPeripheral.java +++ b/src/main/java/de/srendi/advancedperipherals/common/addons/computercraft/peripheral/InventoryManagerPeripheral.java @@ -4,7 +4,7 @@ import dan200.computercraft.api.lua.LuaFunction; import dan200.computercraft.api.lua.MethodResult; import de.srendi.advancedperipherals.AdvancedPeripherals; -import de.srendi.advancedperipherals.common.addons.computercraft.owner.BlockEntityPeripheralOwner; +import de.srendi.advancedperipherals.common.addons.computercraft.owner.InventoryManagerOwner; import de.srendi.advancedperipherals.common.blocks.blockentities.InventoryManagerEntity; import de.srendi.advancedperipherals.common.configuration.APConfig; import de.srendi.advancedperipherals.common.util.LuaConverter; @@ -29,12 +29,12 @@ import java.util.List; import java.util.Map; -public class InventoryManagerPeripheral extends BasePeripheral> { +public class InventoryManagerPeripheral extends BasePeripheral { public static final String PERIPHERAL_TYPE = "inventory_manager"; public InventoryManagerPeripheral(InventoryManagerEntity tileEntity) { - super(PERIPHERAL_TYPE, new BlockEntityPeripheralOwner<>(tileEntity)); + super(PERIPHERAL_TYPE, new InventoryManagerOwner(tileEntity)); } @Override @@ -103,13 +103,13 @@ private MethodResult removeItemCommon(String invDirection, ItemFilter filter) th @LuaFunction(value = {"list", "getItems"}, mainThread = true) public final List getItems() throws LuaException { List items = new ArrayList<>(); - int i = 0; //Used to let users easily sort the items by the slots. Also, a better way for the user to see where an item actually is - for (ItemStack stack : getOwnerPlayer().getInventory().items) { - ItemStack copiedStack = stack.copy(); - if (!copiedStack.isEmpty()) - items.add(LuaConverter.stackToObjectWithSlot(copiedStack, i)); - - i++; + List stacks = getOwnerPlayer().getInventory().items; + // Used to let users easily sort the items by the slots. Also, a better way for the user to see where an item actually is + for (int slot = 0; slot < stacks.size(); slot++) { + ItemStack stack = stacks.get(slot); + if (!stack.isEmpty()) { + items.add(LuaConverter.stackToObjectWithSlot(stack, slot)); + } } return items; } @@ -127,7 +127,7 @@ public final MethodResult getItemsChest(String target) throws LuaException { List items = new ArrayList<>(); for (int slot = 0; slot < inventoryTo.getSlots(); slot++) { if (!inventoryTo.getStackInSlot(slot).isEmpty()) { - items.add(LuaConverter.stackToObjectWithSlot(inventoryTo.getStackInSlot(slot).copy(), slot)); + items.add(LuaConverter.stackToObjectWithSlot(inventoryTo.getStackInSlot(slot), slot)); } } return MethodResult.of(items); @@ -137,9 +137,8 @@ public final MethodResult getItemsChest(String target) throws LuaException { public final List getArmor() throws LuaException { List items = new ArrayList<>(); for (ItemStack stack : getOwnerPlayer().getInventory().armor) { - ItemStack copiedStack = stack.copy(); - if (!copiedStack.isEmpty()) { - items.add(LuaConverter.stackToObjectWithSlot(copiedStack, ArmorSlot.getSlotForItem(copiedStack))); + if (!stack.isEmpty()) { + items.add(LuaConverter.stackToObjectWithSlot(stack, ArmorSlot.getSlotForItem(stack))); } } return items; @@ -157,24 +156,18 @@ public final boolean isPlayerEquipped() throws LuaException { @LuaFunction(mainThread = true) public final boolean isWearing(int index) throws LuaException { - int i = 0; - for (ItemStack stack : getOwnerPlayer().getInventory().armor) { - if (!stack.isEmpty()) { - if (index == i - 100) return true; - i++; - } - } - return false; + List armor = getOwnerPlayer().getInventory().armor; + return 0 <= index && index < armor.size() && armor.get(index); } @LuaFunction(mainThread = true) public final int getEmptySpace() throws LuaException { - int i = 0; + int count = 0; for (ItemStack stack : getOwnerPlayer().getInventory().items) { if (stack.isEmpty()) - i++; + count++; } - return i; + return count; } @LuaFunction(mainThread = true) diff --git a/src/main/java/de/srendi/advancedperipherals/common/util/LuaConverter.java b/src/main/java/de/srendi/advancedperipherals/common/util/LuaConverter.java index 32eea9135..4c0dd08ad 100644 --- a/src/main/java/de/srendi/advancedperipherals/common/util/LuaConverter.java +++ b/src/main/java/de/srendi/advancedperipherals/common/util/LuaConverter.java @@ -44,6 +44,8 @@ public class LuaConverter { + private static final CompoundTag EMPTY_TAG = new CompoundTag(); + public static Map entityToLua(Entity entity) { Map data = new HashMap<>(); data.put("id", entity.getId()); @@ -200,7 +202,10 @@ public static Map itemStackToObject(@NotNull ItemStack stack) { return null; } Map map = itemToObject(stack.getItem()); - CompoundTag nbt = stack.copy().getOrCreateTag(); + CompoundTag nbt = stack.getTag(); + if (nbt == null) { + nbt = EMPTY_TAG; + } map.put("count", stack.getCount()); map.put("displayName", stack.getDisplayName().getString()); map.put("maxStackSize", stack.getMaxStackSize()); @@ -216,7 +221,10 @@ public static Map fluidStackToObject(@NotNull FluidStack stack) return null; } Map map = fluidToObject(stack.getFluid()); - CompoundTag nbt = stack.copy().getOrCreateTag(); + CompoundTag nbt = stack.getTag(); + if (nbt == null) { + nbt = EMPTY_TAG; + } map.put("count", stack.getAmount()); map.put("displayName", stack.getDisplayName().getString()); map.put("nbt", NBTUtil.toLua(nbt)); diff --git a/src/main/java/de/srendi/advancedperipherals/common/util/inventory/FluidUtil.java b/src/main/java/de/srendi/advancedperipherals/common/util/inventory/FluidUtil.java index a3d8cdec6..64e61a02a 100644 --- a/src/main/java/de/srendi/advancedperipherals/common/util/inventory/FluidUtil.java +++ b/src/main/java/de/srendi/advancedperipherals/common/util/inventory/FluidUtil.java @@ -28,8 +28,7 @@ public class FluidUtil { - private FluidUtil() { - } + private FluidUtil() {} @Nullable public static IFluidHandler extractHandler(@Nullable Object object) { @@ -76,16 +75,16 @@ public static IFluidHandler getHandlerFromName(@NotNull IComputerAccess access, @NotNull public static String getFingerprint(@NotNull FluidStack stack) { - String fingerprint = stack.getOrCreateTag() + getRegistryKey(stack).toString() + stack.getDisplayName().getString(); - try { - byte[] bytesOfHash = fingerprint.getBytes(StandardCharsets.UTF_8); - MessageDigest md = MessageDigest.getInstance("MD5"); - return StringUtil.toHexString(md.digest(bytesOfHash)); - } catch (NoSuchAlgorithmException ex) { - AdvancedPeripherals.debug("Could not parse fingerprint.", org.apache.logging.log4j.Level.ERROR); - ex.printStackTrace(); + MessageDigest md = ItemUtil.getMessageDigest("MD5"); + if (md == null) { + return ""; + } + CompoundTag tag = stack.getTag(); + md.update(getRegistryKey(stack).toString().getBytes(StandardCharsets.UTF_8)); + if (tag != null && !tag.isEmpty()) { + md.update(tag.getAsString().getBytes(StandardCharsets.UTF_8)); } - return ""; + return StringUtil.toHexString(md.digest()); } public static ResourceLocation getRegistryKey(Fluid fluid) { @@ -93,6 +92,6 @@ public static ResourceLocation getRegistryKey(Fluid fluid) { } public static ResourceLocation getRegistryKey(FluidStack fluid) { - return ForgeRegistries.FLUIDS.getKey(fluid.copy().getFluid()); + return ForgeRegistries.FLUIDS.getKey(fluid.getFluid()); } } diff --git a/src/main/java/de/srendi/advancedperipherals/common/util/inventory/ItemUtil.java b/src/main/java/de/srendi/advancedperipherals/common/util/inventory/ItemUtil.java index 008d4d928..03ee69088 100644 --- a/src/main/java/de/srendi/advancedperipherals/common/util/inventory/ItemUtil.java +++ b/src/main/java/de/srendi/advancedperipherals/common/util/inventory/ItemUtil.java @@ -24,6 +24,18 @@ public class ItemUtil { public static final Item POCKET_NORMAL = Registry.ModItems.POCKET_COMPUTER_NORMAL.get(); public static final Item POCKET_ADVANCED = Registry.ModItems.POCKET_COMPUTER_ADVANCED.get(); + private ItemUtil() {} + + static MessageDigest getMessageDigest(String algorithm) { + try { + return MessageDigest.getInstance(algorithm); + } catch (NoSuchAlgorithmException ex) { + AdvancedPeripherals.debug("Could not generate fingerprint.", Level.ERROR); + ex.printStackTrace(); + return null; + } + } + /** * Fingerprints are MD5 hashes generated out of the nbt tag, the registry name and the display name from item stacks * Used to filter inventory specific operations. {@link de.srendi.advancedperipherals.common.addons.computercraft.peripheral.InventoryManagerPeripheral} @@ -31,16 +43,16 @@ public class ItemUtil { * @return A generated MD5 hash from the item stack */ public static String getFingerprint(ItemStack stack) { - String fingerprint = stack.getOrCreateTag() + getRegistryKey(stack).toString() + stack.getDisplayName().getString(); - try { - byte[] bytesOfHash = fingerprint.getBytes(StandardCharsets.UTF_8); - MessageDigest md = MessageDigest.getInstance("MD5"); - return StringUtil.toHexString(md.digest(bytesOfHash)); - } catch (NoSuchAlgorithmException ex) { - AdvancedPeripherals.debug("Could not parse fingerprint.", Level.ERROR); - ex.printStackTrace(); + MessageDigest md = getMessageDigest("MD5"); + if (md == null) { + return ""; + } + CompoundTag tag = stack.getTag(); + md.update(getRegistryKey(stack).toString().getBytes(StandardCharsets.UTF_8)); + if (tag != null && !tag.isEmpty()) { + md.update(tag.getAsString().getBytes(StandardCharsets.UTF_8)); } - return ""; + return StringUtil.toHexString(md.digest()); } public static ItemStack makeTurtle(Item turtle, String upgrade) { @@ -70,6 +82,6 @@ public static ResourceLocation getRegistryKey(Item item) { } public static ResourceLocation getRegistryKey(ItemStack item) { - return ForgeRegistries.ITEMS.getKey(item.copy().getItem()); + return ForgeRegistries.ITEMS.getKey(item.getItem()); } } From 9c238102356f85a4efd92dcbeb07d155aadece20 Mon Sep 17 00:00:00 2001 From: zyxkad Date: Sat, 25 Jan 2025 18:02:25 -0700 Subject: [PATCH 5/9] refactor DistanceDetector --- .../renderer/DistanceDetectorRenderer.java | 2 +- .../owner/BlockEntityPeripheralOwner.java | 1 - .../computercraft/owner/IPeripheralOwner.java | 4 +- .../owner/PocketPeripheralOwner.java | 1 - .../DistanceDetectorPeripheral.java | 190 ++++++++++++++++-- .../InventoryManagerPeripheral.java | 2 +- .../blocks/base/PeripheralBlockEntity.java | 8 +- .../blockentities/DistanceDetectorEntity.java | 125 +++--------- .../modules/ModulePeripheralOwner.java | 6 + .../common/util/HitResultUtil.java | 31 ++- .../common/util/inventory/FluidUtil.java | 3 +- .../common/util/inventory/ItemUtil.java | 1 + 12 files changed, 247 insertions(+), 127 deletions(-) diff --git a/src/main/java/de/srendi/advancedperipherals/client/renderer/DistanceDetectorRenderer.java b/src/main/java/de/srendi/advancedperipherals/client/renderer/DistanceDetectorRenderer.java index 8c571b8f5..a0b6f8a7c 100644 --- a/src/main/java/de/srendi/advancedperipherals/client/renderer/DistanceDetectorRenderer.java +++ b/src/main/java/de/srendi/advancedperipherals/client/renderer/DistanceDetectorRenderer.java @@ -28,7 +28,7 @@ public DistanceDetectorRenderer(BlockEntityRendererProvider.Context pContext) { @Override public void render(@NotNull DistanceDetectorEntity pBlockEntity, float pPartialTick, @NotNull PoseStack pPoseStack, MultiBufferSource pBufferSource, int pPackedLight, int pPackedOverlay) { - if (pBlockEntity.getLaserVisibility()) { + if (pBlockEntity.getShowLaser()) { float distance = pBlockEntity.getCurrentDistance(); float[] color = EnumColor.RED.getRgb(); if (distance == -1) { diff --git a/src/main/java/de/srendi/advancedperipherals/common/addons/computercraft/owner/BlockEntityPeripheralOwner.java b/src/main/java/de/srendi/advancedperipherals/common/addons/computercraft/owner/BlockEntityPeripheralOwner.java index c30806f59..0a593045a 100644 --- a/src/main/java/de/srendi/advancedperipherals/common/addons/computercraft/owner/BlockEntityPeripheralOwner.java +++ b/src/main/java/de/srendi/advancedperipherals/common/addons/computercraft/owner/BlockEntityPeripheralOwner.java @@ -2,7 +2,6 @@ import dan200.computercraft.api.peripheral.IPeripheral; import de.srendi.advancedperipherals.common.blocks.base.BaseBlock; -import de.srendi.advancedperipherals.common.blocks.blockentities.InventoryManagerEntity; import de.srendi.advancedperipherals.common.util.DataStorageUtil; import de.srendi.advancedperipherals.common.util.fakeplayer.APFakePlayer; import de.srendi.advancedperipherals.lib.peripherals.IPeripheralTileEntity; diff --git a/src/main/java/de/srendi/advancedperipherals/common/addons/computercraft/owner/IPeripheralOwner.java b/src/main/java/de/srendi/advancedperipherals/common/addons/computercraft/owner/IPeripheralOwner.java index 175df2645..c5a4a8975 100644 --- a/src/main/java/de/srendi/advancedperipherals/common/addons/computercraft/owner/IPeripheralOwner.java +++ b/src/main/java/de/srendi/advancedperipherals/common/addons/computercraft/owner/IPeripheralOwner.java @@ -8,6 +8,8 @@ import net.minecraft.core.Direction; import net.minecraft.core.FrontAndTop; import net.minecraft.nbt.CompoundTag; +import net.minecraft.world.entity.Entity; +import net.minecraft.world.entity.OwnableEntity; import net.minecraft.world.entity.player.Player; import net.minecraft.world.item.ItemStack; import net.minecraft.world.level.Level; @@ -56,7 +58,7 @@ default Vec3 getDirection() { @Nullable default Player getOwner() { - Entity owner = pocket.getHoldingEntity(); + Entity owner = getHoldingEntity(); Set checked = new HashSet<>(); while (owner != null && checked.add(owner)) { if (owner instanceof Player player) { diff --git a/src/main/java/de/srendi/advancedperipherals/common/addons/computercraft/owner/PocketPeripheralOwner.java b/src/main/java/de/srendi/advancedperipherals/common/addons/computercraft/owner/PocketPeripheralOwner.java index 3577e8df9..f4ed40416 100644 --- a/src/main/java/de/srendi/advancedperipherals/common/addons/computercraft/owner/PocketPeripheralOwner.java +++ b/src/main/java/de/srendi/advancedperipherals/common/addons/computercraft/owner/PocketPeripheralOwner.java @@ -11,7 +11,6 @@ import net.minecraft.core.FrontAndTop; import net.minecraft.nbt.CompoundTag; import net.minecraft.world.entity.Entity; -import net.minecraft.world.entity.player.Player; import net.minecraft.world.item.ItemStack; import net.minecraft.world.level.Level; import net.minecraft.world.phys.Vec3; diff --git a/src/main/java/de/srendi/advancedperipherals/common/addons/computercraft/peripheral/DistanceDetectorPeripheral.java b/src/main/java/de/srendi/advancedperipherals/common/addons/computercraft/peripheral/DistanceDetectorPeripheral.java index bf1f63655..41f535aad 100644 --- a/src/main/java/de/srendi/advancedperipherals/common/addons/computercraft/peripheral/DistanceDetectorPeripheral.java +++ b/src/main/java/de/srendi/advancedperipherals/common/addons/computercraft/peripheral/DistanceDetectorPeripheral.java @@ -4,16 +4,41 @@ import dan200.computercraft.api.lua.LuaException; import dan200.computercraft.api.lua.LuaFunction; import de.srendi.advancedperipherals.common.addons.computercraft.owner.BlockEntityPeripheralOwner; +import de.srendi.advancedperipherals.common.addons.computercraft.owner.IPeripheralOwner; import de.srendi.advancedperipherals.common.blocks.blockentities.DistanceDetectorEntity; import de.srendi.advancedperipherals.common.configuration.APConfig; +import de.srendi.advancedperipherals.common.util.HitResultUtil; import de.srendi.advancedperipherals.lib.peripherals.BasePeripheral; +import net.minecraft.world.level.ClipContext; +import net.minecraft.world.level.Level; +import net.minecraft.world.phys.HitResult; +import net.minecraft.world.phys.Vec3; -public class DistanceDetectorPeripheral extends BasePeripheral> { +import java.util.concurrent.atomic.AtomicBoolean; +import java.util.concurrent.atomic.AtomicInteger; +import java.util.concurrent.atomic.AtomicReference; + +public class DistanceDetectorPeripheral extends BasePeripheral { public static final String PERIPHERAL_TYPE = "distance_detector"; + private final DistanceDetectorEntity tileEntity; + private final AtomicInteger maxRange; + private volatile float currentDistance; + private final AtomicBoolean showLaser; + private volatile boolean calculatePeriodically; + private volatile boolean ignoreTransparent; + private final AtomicReference detectionType; + public DistanceDetectorPeripheral(DistanceDetectorEntity tileEntity) { super(PERIPHERAL_TYPE, new BlockEntityPeripheralOwner<>(tileEntity)); + this.tileEntity = tileEntity; + this.maxRange = new AtomicInteger(Float.floatToRawIntBits(this.tileEntity.getMaxRange())); + this.currentDistance = this.tileEntity.getCurrentDistance(); + this.showLaser = new AtomicBoolean(this.tileEntity.getShowLaser()); + this.calculatePeriodically = this.tileEntity.getCalculatePeriodically(); + this.ignoreTransparent = this.tileEntity.getIgnoreTransparent(); + this.detectionType = new AtomicReference<>(this.tileEntity.getDetectionType()); } @Override @@ -21,24 +46,115 @@ public boolean isEnabled() { return APConfig.PERIPHERALS_CONFIG.enableDistanceDetector.get(); } + public float getConfiguredMaxRange() { + return APConfig.PERIPHERALS_CONFIG.distanceDetectorRange.get().floatValue(); + } + + public float getMaxRange() { + return Float.intBitsToFloat(this.maxRange.get()); + } + + public void setMaxRange(float maxRange) { + maxRange = Math.min(Math.max(maxRange, 0), this.getConfiguredMaxRange()); + int maxRangeBits = Float.floatToRawIntBits(maxRange); + if (this.maxRange.getAndSet(maxRangeBits) == maxRange) { + return; + } + if (this.tileEntity != null) { + this.tileEntity.setMaxRange(maxRange); + this.tileEntity.sendUpdate(); + } + this.owner.markDataStorageDirty(); + } + + public float getCurrentDistance() { + return this.currentDistance; + } + + public void setCurrentDistance(float currentDistance) { + // Since setCurrentDistance should only invokes from main thread, volatile field should be safe here. + if (this.currentDistance == currentDistance) { + return; + } + this.currentDistance = currentDistance; + if (this.tileEntity != null) { + this.tileEntity.setCurrentDistance(currentDistance); + this.tileEntity.sendUpdate(); + } + this.owner.markDataStorageDirty(); + } + + public boolean getCalculatePeriodically() { + return this.calculatePeriodically; + } + + public void setCalculatePeriodically(boolean calculatePeriodically) { + this.calculatePeriodically = calculatePeriodically; + if (this.tileEntity != null) { + this.tileEntity.setCalculatePeriodically(calculatePeriodically); + } + this.owner.markDataStorageDirty(); + } + + public boolean getShowLaser() { + return this.showLaser.get(); + } + + public void setShowLaser(boolean showLaser) { + if (this.showLaser.getAndSet(showLaser) == showLaser) { + return; + } + if (this.tileEntity != null) { + this.tileEntity.setShowLaser(showLaser); + this.tileEntity.sendUpdate(); + } + this.owner.markDataStorageDirty(); + } + + public boolean getIgnoreTransparent() { + return this.ignoreTransparent; + } + + public void setIgnoreTransparent(boolean ignoreTransparent) { + this.ignoreTransparent = ignoreTransparent; + if (this.tileEntity != null) { + this.tileEntity.setIgnoreTransparent(ignoreTransparent); + } + this.owner.markDataStorageDirty(); + } + + public DetectionType getDetectionType() { + return this.detectionType.get(); + } + + public void setDetectionType(DetectionType detectionType) { + if (this.detectionType.getAndSet(detectionType) == detectionType) { + return; + } + if (this.tileEntity != null) { + this.tileEntity.setDetectionType(detectionType); + } + this.owner.markDataStorageDirty(); + } + @LuaFunction public final void setLaserVisibility(boolean laser) { - getPeripheralOwner().tileEntity.setShowLaser(laser); + this.setShowLaser(laser); } @LuaFunction public final boolean getLaserVisibility() { - return getPeripheralOwner().tileEntity.getLaserVisibility(); + return this.getShowLaser(); } @LuaFunction - public final void setIgnoreTransparency(boolean enable) { - getPeripheralOwner().tileEntity.setIgnoreTransparent(enable); + public final void setIgnoreTransparencyLua(boolean enable) { + this.setIgnoreTransparent(enable); } @LuaFunction public final boolean ignoresTransparency() { - return getPeripheralOwner().tileEntity.ignoreTransparent(); + return this.getIgnoreTransparent(); } @LuaFunction @@ -61,55 +177,85 @@ public final void setDetectionMode(IArguments args) throws LuaException { } else { throw new LuaException("arg #1 must be a string or a number"); } - getPeripheralOwner().tileEntity.setDetectionType(detectionType); + this.setDetectionType(detectionType); } @LuaFunction public final boolean detectsEntities() { - DetectionType detectionType = getPeripheralOwner().tileEntity.getDetectionType(); - return detectionType.detectEntity(); + return this.getDetectionType().detectEntity(); } @LuaFunction public final boolean detectsBlocks() { - DetectionType detectionType = getPeripheralOwner().tileEntity.getDetectionType(); - return detectionType.detectBlock(); + return this.getDetectionType().detectBlock(); } @LuaFunction public final String getDetectionMode() { - DetectionType detectionType = getPeripheralOwner().tileEntity.getDetectionType(); - return detectionType.toString(); + return this.getDetectionType().toString(); } @LuaFunction public final double getDistance() { - return getPeripheralOwner().tileEntity.getCurrentDistance(); + return this.getCurrentDistance(); } @LuaFunction(mainThread = true) public final double calculateDistance() { - return getPeripheralOwner().tileEntity.calculateAndUpdateDistance(); + return this.calculateAndUpdateDistance(); } @LuaFunction public final boolean shouldCalculatePeriodically() { - return getPeripheralOwner().tileEntity.shouldCalculatePeriodically(); + return this.getCalculatePeriodically(); } @LuaFunction - public final void setCalculatePeriodically(boolean shouldRenderPeriodically) { - getPeripheralOwner().tileEntity.setShouldCalculatePeriodically(shouldRenderPeriodically); + public final void setCalculatePeriodicallyLua(boolean shouldCalculatePeriodically) { + this.setCalculatePeriodically(shouldCalculatePeriodically); } @LuaFunction - public final void setMaxRange(double maxDistance) { - getPeripheralOwner().tileEntity.setMaxRange((float) maxDistance); + public final void setMaxRangeLua(double maxDistance) { + this.setMaxRange((float) maxDistance); } @LuaFunction - public final double getMaxRange() { - return getPeripheralOwner().tileEntity.getMaxRange(); + public final double getMaxRangeLua() { + return this.getMaxRange(); + } + + protected double calculateDistanceImpl() { + final double maxRange = this.getMaxRange(); + Vec3 direction = this.owner.getDirection(); + Vec3 center = this.getPhysicsPos(); + Vec3 from = center; + Vec3 to = from.add(direction.scale(maxRange)); + + HitResult result = this.getHitResult(from, to); + if (result.getType() == HitResult.Type.MISS) { + return -1; + } + return result.getLocation().distanceTo(center) - 0.5f; + } + + /** + * calculateAndUpdateDistance should only invokes from server main thread + */ + public double calculateAndUpdateDistance() { + double distance = this.calculateDistanceImpl(); + this.setCurrentDistance((float) distance); + return distance; + } + + protected HitResult getHitResult(Vec3 from, Vec3 to) { + Level level = this.getLevel(); + ClipContext.ShapeGetter shapeGetter = this.ignoreTransparent ? HitResultUtil.IgnoreNoOccludedContext.INSTANCE : ClipContext.Block.COLLIDER; + return switch (this.getDetectionType()) { + case ENTITY -> HitResultUtil.getEntityHitResult(from, to, level, this.owner.getHoldingEntity()); + case BLOCK -> HitResultUtil.getBlockHitResult(from, to, level, shapeGetter, this.getPos()); + case BOTH -> HitResultUtil.getHitResult(from, to, level, shapeGetter, this.owner); + }; } public enum DetectionType { diff --git a/src/main/java/de/srendi/advancedperipherals/common/addons/computercraft/peripheral/InventoryManagerPeripheral.java b/src/main/java/de/srendi/advancedperipherals/common/addons/computercraft/peripheral/InventoryManagerPeripheral.java index eaabc32f0..72fda1b7f 100644 --- a/src/main/java/de/srendi/advancedperipherals/common/addons/computercraft/peripheral/InventoryManagerPeripheral.java +++ b/src/main/java/de/srendi/advancedperipherals/common/addons/computercraft/peripheral/InventoryManagerPeripheral.java @@ -157,7 +157,7 @@ public final boolean isPlayerEquipped() throws LuaException { @LuaFunction(mainThread = true) public final boolean isWearing(int index) throws LuaException { List armor = getOwnerPlayer().getInventory().armor; - return 0 <= index && index < armor.size() && armor.get(index); + return 0 <= index && index < armor.size() && !armor.get(index).isEmpty(); } @LuaFunction(mainThread = true) diff --git a/src/main/java/de/srendi/advancedperipherals/common/blocks/base/PeripheralBlockEntity.java b/src/main/java/de/srendi/advancedperipherals/common/blocks/base/PeripheralBlockEntity.java index 5014be652..e9507f900 100644 --- a/src/main/java/de/srendi/advancedperipherals/common/blocks/base/PeripheralBlockEntity.java +++ b/src/main/java/de/srendi/advancedperipherals/common/blocks/base/PeripheralBlockEntity.java @@ -20,6 +20,7 @@ import net.minecraft.world.entity.player.Player; import net.minecraft.world.inventory.AbstractContainerMenu; import net.minecraft.world.item.ItemStack; +import net.minecraft.world.level.Level; import net.minecraft.world.level.block.entity.BaseContainerBlockEntity; import net.minecraft.world.level.block.entity.BlockEntityType; import net.minecraft.world.level.block.state.BlockState; @@ -230,9 +231,12 @@ public void markSettingsChanged() { this.setChanged(); } - protected void sendUpdate() { + public void sendUpdate() { this.setChanged(); - this.getLevel().sendBlockUpdated(this.getBlockPos(), this.getBlockState(), this.getBlockState(), 11); + Level level = this.getLevel(); + if (level != null) { + level.sendBlockUpdated(this.getBlockPos(), this.getBlockState(), this.getBlockState(), 11); + } } public ComputerSide getComputerSide(Direction direction) { diff --git a/src/main/java/de/srendi/advancedperipherals/common/blocks/blockentities/DistanceDetectorEntity.java b/src/main/java/de/srendi/advancedperipherals/common/blocks/blockentities/DistanceDetectorEntity.java index 0042788ad..828a61b4c 100644 --- a/src/main/java/de/srendi/advancedperipherals/common/blocks/blockentities/DistanceDetectorEntity.java +++ b/src/main/java/de/srendi/advancedperipherals/common/blocks/blockentities/DistanceDetectorEntity.java @@ -1,35 +1,28 @@ package de.srendi.advancedperipherals.common.blocks.blockentities; -import de.srendi.advancedperipherals.common.addons.computercraft.owner.BlockEntityPeripheralOwner; import de.srendi.advancedperipherals.common.addons.computercraft.peripheral.DistanceDetectorPeripheral; import de.srendi.advancedperipherals.common.blocks.base.BaseBlock; import de.srendi.advancedperipherals.common.blocks.base.PeripheralBlockEntity; import de.srendi.advancedperipherals.common.configuration.APConfig; import de.srendi.advancedperipherals.common.setup.APBlockEntityTypes; -import de.srendi.advancedperipherals.common.util.HitResultUtil; import net.minecraft.core.BlockPos; import net.minecraft.core.Direction; import net.minecraft.nbt.CompoundTag; import net.minecraft.network.protocol.game.ClientboundBlockEntityDataPacket; -import net.minecraft.world.level.ClipContext; import net.minecraft.world.level.Level; import net.minecraft.world.level.block.entity.BlockEntity; import net.minecraft.world.level.block.entity.BlockEntityType; import net.minecraft.world.level.block.state.BlockState; import net.minecraft.world.phys.AABB; -import net.minecraft.world.phys.HitResult; import net.minecraft.world.phys.Vec3; import org.jetbrains.annotations.NotNull; -import java.util.concurrent.atomic.AtomicBoolean; -import java.util.concurrent.atomic.AtomicInteger; - public class DistanceDetectorEntity extends PeripheralBlockEntity { - private final AtomicInteger maxRange = new AtomicInteger(Float.floatToRawIntBits(APConfig.PERIPHERALS_CONFIG.distanceDetectorRange.get().floatValue())); - private final AtomicInteger currentDistance = new AtomicInteger(Float.floatToRawIntBits(-1)); - private final AtomicBoolean showLaser = new AtomicBoolean(true); - private volatile boolean periodicallyCalculate = false; + private volatile float maxRange = APConfig.PERIPHERALS_CONFIG.distanceDetectorRange.get().floatValue(); + private float currentDistance = -1; + private volatile boolean showLaser = true; + private volatile boolean calculatePeriodically = false; private volatile boolean ignoreTransparent = true; private volatile DistanceDetectorPeripheral.DetectionType detectionType = DistanceDetectorPeripheral.DetectionType.BOTH; @@ -44,69 +37,43 @@ protected DistanceDetectorPeripheral createPeripheral() { } public float getMaxRange() { - return Float.intBitsToFloat(this.maxRange.get()); - } - - protected void setMaxRangeNoUpdate(float maxRange) { - maxRange = Math.min(Math.max(maxRange, 0), APConfig.PERIPHERALS_CONFIG.distanceDetectorRange.get().floatValue()); - int maxRangeBits = Float.floatToRawIntBits(maxRange); - this.maxRange.set(maxRangeBits); + return this.maxRange; } public void setMaxRange(float maxRange) { - maxRange = Math.min(Math.max(maxRange, 0), APConfig.PERIPHERALS_CONFIG.distanceDetectorRange.get().floatValue()); - int maxRangeBits = Float.floatToRawIntBits(maxRange); - if (this.maxRange.getAndSet(maxRangeBits) != maxRange) { - this.sendUpdate(); - } + this.maxRange = Math.min(Math.max(maxRange, 0), APConfig.PERIPHERALS_CONFIG.distanceDetectorRange.get().floatValue()); } public float getCurrentDistance() { - return Float.intBitsToFloat(this.currentDistance.get()); - } - - protected void setCurrentDistanceNoUpdate(float currentDistance) { - int currentDistanceBits = Float.floatToRawIntBits(currentDistance); - this.currentDistance.set(currentDistanceBits); + return this.currentDistance; } public void setCurrentDistance(float currentDistance) { - int currentDistanceBits = Float.floatToRawIntBits(currentDistance); - if (this.currentDistance.getAndSet(currentDistanceBits) != currentDistanceBits) { - this.sendUpdate(); - } - } - - public boolean getLaserVisibility() { - return this.showLaser.get(); + this.currentDistance = currentDistance; } - protected void setShowLaserNoUpdate(boolean showLaser) { - this.showLaser.set(showLaser); + public boolean getShowLaser() { + return this.showLaser; } public void setShowLaser(boolean showLaser) { - if (this.showLaser.getAndSet(showLaser) != showLaser) { - this.sendUpdate(); - } + this.showLaser = showLaser; } - public boolean shouldCalculatePeriodically() { - return this.periodicallyCalculate; + public boolean getCalculatePeriodically() { + return this.calculatePeriodically; } - public void setShouldCalculatePeriodically(boolean periodicallyCalculate) { - this.periodicallyCalculate = periodicallyCalculate; - this.setChanged(); + public void setCalculatePeriodically(boolean calculatePeriodically) { + this.calculatePeriodically = calculatePeriodically; } - public boolean ignoreTransparent() { + public boolean getIgnoreTransparent() { return this.ignoreTransparent; } public void setIgnoreTransparent(boolean ignoreTransparent) { this.ignoreTransparent = ignoreTransparent; - this.setChanged(); } public DistanceDetectorPeripheral.DetectionType getDetectionType() { @@ -115,17 +82,21 @@ public DistanceDetectorPeripheral.DetectionType getDetectionType() { public void setDetectionType(DistanceDetectorPeripheral.DetectionType detectionType) { this.detectionType = detectionType; - this.setChanged(); } @Override public void handleTick(Level level, BlockState state, BlockEntityType type) { - if (level.getGameTime() % APConfig.PERIPHERALS_CONFIG.distanceDetectorUpdateRate.get() == 0 && this.shouldCalculatePeriodically()) { + DistanceDetectorPeripheral peripheral = this.getPeripheral(); + if (peripheral == null) { + return; + } + + if (level.getGameTime() % APConfig.PERIPHERALS_CONFIG.distanceDetectorUpdateRate.get() == 0 && this.getCalculatePeriodically()) { // We calculate the distance every 2 ticks, so we do not have to run the getDistance function of the peripheral // on the main thread which prevents the 1 tick yield time of the function. // The calculateDistance function is not thread safe, so we have to run it on the main thread. // It should be okay to run that function every 2 ticks, calculating it does not take too much time. - this.calculateAndUpdateDistance(); + peripheral.calculateAndUpdateDistance(); } } @@ -143,10 +114,10 @@ public AABB getRenderBoundingBox() { @Override public void load(@NotNull CompoundTag compound) { - this.setMaxRangeNoUpdate(compound.getFloat("maxRange")); - this.setCurrentDistanceNoUpdate(compound.getFloat("currentDistance")); - this.setShowLaserNoUpdate(compound.getBoolean("showLaser")); - this.setShouldCalculatePeriodically(compound.getBoolean("calculatePeriodically")); + this.setMaxRange(compound.getFloat("maxRange")); + this.setCurrentDistance(compound.getFloat("currentDistance")); + this.setShowLaser(compound.getBoolean("showLaser")); + this.setCalculatePeriodically(compound.getBoolean("calculatePeriodically")); this.setIgnoreTransparent(compound.getBoolean("ignoreTransparent")); this.setDetectionType(DistanceDetectorPeripheral.DetectionType.values()[compound.getByte("detectionType")]); super.load(compound); @@ -157,9 +128,9 @@ public void saveAdditional(@NotNull CompoundTag compound) { super.saveAdditional(compound); compound.putFloat("maxRange", this.getMaxRange()); compound.putFloat("currentDistance", this.getCurrentDistance()); - compound.putBoolean("showLaser", this.getLaserVisibility()); - compound.putBoolean("calculatePeriodically", this.shouldCalculatePeriodically()); - compound.putBoolean("ignoreTransparent", this.ignoreTransparent()); + compound.putBoolean("showLaser", this.getShowLaser()); + compound.putBoolean("calculatePeriodically", this.getCalculatePeriodically()); + compound.putBoolean("ignoreTransparent", this.getIgnoreTransparent()); compound.putByte("detectionType", (byte) this.getDetectionType().ordinal()); } @@ -168,7 +139,7 @@ public CompoundTag getUpdateTag() { CompoundTag compound = super.getUpdateTag(); compound.putFloat("maxRange", this.getMaxRange()); compound.putFloat("currentDistance", this.getCurrentDistance()); - compound.putBoolean("showLaser", this.getLaserVisibility()); + compound.putBoolean("showLaser", this.getShowLaser()); return compound; } @@ -176,38 +147,4 @@ public CompoundTag getUpdateTag() { public ClientboundBlockEntityDataPacket getUpdatePacket() { return ClientboundBlockEntityDataPacket.create(this); } - - public double calculateDistance() { - DistanceDetectorPeripheral peripheral = this.getPeripheral(); - if (peripheral == null) { - return -1; - } - BlockEntityPeripheralOwner owner = peripheral.getPeripheralOwner(); - final double maxRange = this.getMaxRange(); - Vec3 direction = owner.getDirection(); - Vec3 center = peripheral.getPhysicsPos(); - Vec3 from = center; - Vec3 to = from.add(direction.x * maxRange, direction.y * maxRange, direction.z * maxRange); - - HitResult result = this.getHitResult(from, to); - if (result.getType() == HitResult.Type.MISS) { - return -1; - } - return result.getLocation().distanceTo(center) - 0.5f; - } - - public double calculateAndUpdateDistance() { - double distance = this.calculateDistance(); - this.setCurrentDistance((float) distance); - return distance; - } - - private HitResult getHitResult(Vec3 from, Vec3 to) { - Level level = this.getLevel(); - return switch (this.detectionType) { - case ENTITY -> HitResultUtil.getEntityHitResult(from, to, level); - case BLOCK -> HitResultUtil.getBlockHitResult(from, to, level, this.ignoreTransparent ? HitResultUtil.IgnoreNoOccludedContext.INSTANCE : ClipContext.Block.COLLIDER, this.getBlockPos()); - case BOTH -> HitResultUtil.getHitResult(from, to, level, this.ignoreTransparent ? HitResultUtil.IgnoreNoOccludedContext.INSTANCE : ClipContext.Block.COLLIDER, this.getBlockPos()); - }; - } } diff --git a/src/main/java/de/srendi/advancedperipherals/common/smartglasses/modules/ModulePeripheralOwner.java b/src/main/java/de/srendi/advancedperipherals/common/smartglasses/modules/ModulePeripheralOwner.java index b7407a577..f7353f1ef 100644 --- a/src/main/java/de/srendi/advancedperipherals/common/smartglasses/modules/ModulePeripheralOwner.java +++ b/src/main/java/de/srendi/advancedperipherals/common/smartglasses/modules/ModulePeripheralOwner.java @@ -81,6 +81,12 @@ public SmartGlassesComputer getComputer() { return computer; } + @Nullable + @Override + public Entity getHoldingEntity() { + return computer.getEntity(); + } + @Nullable @Override public Player getOwner() { diff --git a/src/main/java/de/srendi/advancedperipherals/common/util/HitResultUtil.java b/src/main/java/de/srendi/advancedperipherals/common/util/HitResultUtil.java index b03e05d77..6112dc4a7 100644 --- a/src/main/java/de/srendi/advancedperipherals/common/util/HitResultUtil.java +++ b/src/main/java/de/srendi/advancedperipherals/common/util/HitResultUtil.java @@ -1,5 +1,8 @@ package de.srendi.advancedperipherals.common.util; +import de.srendi.advancedperipherals.common.addons.computercraft.owner.IPeripheralOwner; +import de.srendi.advancedperipherals.common.addons.computercraft.owner.BlockEntityPeripheralOwner; +import de.srendi.advancedperipherals.common.addons.computercraft.owner.TurtlePeripheralOwner; import de.srendi.advancedperipherals.common.addons.computercraft.peripheral.DistanceDetectorPeripheral; import net.minecraft.core.BlockPos; import net.minecraft.core.Direction; @@ -46,11 +49,18 @@ public static HitResult getHitResult(Vec3 from, Vec3 to, Level level, ClipContex * @param to the target position/max position * @param level the level * @param shapeGetter the block collision shape getter - * @param source the source Entity/BlockPos that will be ignored + * @param source the source Entity/BlockPos that will be ignored, or an {@link IPeripheralOwner} to auto determine the source. * @return the hit result. {@link BlockHitResult#miss(Vec3, Direction, BlockPos)} if nothing found */ @NotNull public static HitResult getHitResult(Vec3 from, Vec3 to, Level level, ClipContext.ShapeGetter shapeGetter, Object source) { + if (source instanceof IPeripheralOwner owner) { + if (owner instanceof BlockEntityPeripheralOwner || owner instanceof TurtlePeripheralOwner) { + source = owner.getPos(); + } else { + source = owner.getHoldingEntity(); + } + } EntityHitResult entityResult = getEntityHitResult(from, to, level, source instanceof Entity ? (Entity) source : null, source instanceof Predicate ? (Predicate) source : EntitySelector.NO_SPECTATORS); BlockHitResult blockResult = getBlockHitResult(from, to, level, shapeGetter, source instanceof BlockPos ? (BlockPos) source : null); @@ -82,7 +92,24 @@ public static HitResult getHitResult(Vec3 from, Vec3 to, Level level, ClipContex */ @NotNull public static EntityHitResult getEntityHitResult(Vec3 from, Vec3 to, Level level) { - return getEntityHitResult(from, to, level, null, EntitySelector.NO_SPECTATORS); + return getEntityHitResult(from, to, level, null); + } + + /** + * This method is used to get the hit result of an entity from the start position of a block + * This could be used to find an entity from the eyes position of another entity but since + * this method uses one AABB made out of the two coordinates, this would also find any entities + * which are not located in the ray you might want. {@link DistanceDetectorPeripheral#getDistance()} + * + * @param from the source position like a block + * @param to the target position/max position + * @param level the world + * @param source the source Entity that will be ignored + * @return the entity hit result. An empty HitResult with {@link HitResult.Type#MISS} as type if nothing found + */ + @NotNull + public static EntityHitResult getEntityHitResult(Vec3 from, Vec3 to, Level level, Entity source) { + return getEntityHitResult(from, to, level, source, EntitySelector.NO_SPECTATORS); } /** diff --git a/src/main/java/de/srendi/advancedperipherals/common/util/inventory/FluidUtil.java b/src/main/java/de/srendi/advancedperipherals/common/util/inventory/FluidUtil.java index 64e61a02a..f6fcbae85 100644 --- a/src/main/java/de/srendi/advancedperipherals/common/util/inventory/FluidUtil.java +++ b/src/main/java/de/srendi/advancedperipherals/common/util/inventory/FluidUtil.java @@ -3,11 +3,11 @@ import dan200.computercraft.api.lua.LuaException; import dan200.computercraft.api.peripheral.IComputerAccess; import dan200.computercraft.api.peripheral.IPeripheral; -import de.srendi.advancedperipherals.AdvancedPeripherals; import de.srendi.advancedperipherals.common.addons.computercraft.owner.IPeripheralOwner; import de.srendi.advancedperipherals.common.util.CoordUtil; import de.srendi.advancedperipherals.common.util.StringUtil; import net.minecraft.core.Direction; +import net.minecraft.nbt.CompoundTag; import net.minecraft.resources.ResourceLocation; import net.minecraft.world.level.Level; import net.minecraft.world.level.block.entity.BlockEntity; @@ -23,7 +23,6 @@ import java.nio.charset.StandardCharsets; import java.security.MessageDigest; -import java.security.NoSuchAlgorithmException; import java.util.Objects; public class FluidUtil { diff --git a/src/main/java/de/srendi/advancedperipherals/common/util/inventory/ItemUtil.java b/src/main/java/de/srendi/advancedperipherals/common/util/inventory/ItemUtil.java index 03ee69088..87f47ae77 100644 --- a/src/main/java/de/srendi/advancedperipherals/common/util/inventory/ItemUtil.java +++ b/src/main/java/de/srendi/advancedperipherals/common/util/inventory/ItemUtil.java @@ -3,6 +3,7 @@ import dan200.computercraft.shared.Registry; import de.srendi.advancedperipherals.AdvancedPeripherals; import de.srendi.advancedperipherals.common.util.StringUtil; +import net.minecraft.nbt.CompoundTag; import net.minecraft.resources.ResourceLocation; import net.minecraft.world.item.Item; import net.minecraft.world.item.ItemStack; From f1e2c5a54f6a9ba3d00bbdd095c991fac3585a9a Mon Sep 17 00:00:00 2001 From: zyxkad Date: Sat, 25 Jan 2025 19:46:46 -0700 Subject: [PATCH 6/9] fix registeriation --- .../ae219fa7c7d3297c14e454863eac3998a4eab78c | 3 +- .../c622617f6fabf890a00b9275cd5f643584a8a2c8 | 4 +- .../advancedperipherals/lang/en_us.json | 1 + .../pocket_upgrades/distance_pocket.json | 4 ++ .../owner/PocketPeripheralOwner.java | 10 ++- .../peripheral/ChatBoxPeripheral.java | 5 +- .../peripheral/ColonyPeripheral.java | 5 +- .../DistanceDetectorPeripheral.java | 29 ++++++-- .../EnvironmentDetectorPeripheral.java | 5 +- .../peripheral/GeoScannerPeripheral.java | 5 +- .../peripheral/PlayerDetectorPeripheral.java | 5 +- .../pocket/PocketChatBoxUpgrade.java | 4 +- .../pocket/PocketColonyIntegratorUpgrade.java | 4 +- .../pocket/PocketDistanceDetectorUpgrade.java | 23 +++++++ .../pocket/PocketEnvironmentUpgrade.java | 4 +- .../pocket/PocketGeoScannerUpgrade.java | 4 +- .../pocket/PocketPlayerDetectorUpgrade.java | 4 +- .../common/data/EnUsLanguageProvider.java | 1 + .../common/data/PocketUpgradesProvider.java | 5 +- .../common/items/SmartGlassesItem.java | 2 +- .../common/setup/CCRegistration.java | 3 + .../smartglasses/SmartGlassesComputer.java | 68 +++++++++++++------ .../smartglasses/SmartGlassesItemHandler.java | 2 +- .../common/util/DataStorageUtil.java | 16 ++++- .../common/util/NBTUtil.java | 1 + .../lib/peripherals/DisabledPeripheral.java | 9 +-- 26 files changed, 166 insertions(+), 60 deletions(-) create mode 100644 src/generated/resources/data/advancedperipherals/computercraft/pocket_upgrades/distance_pocket.json create mode 100644 src/main/java/de/srendi/advancedperipherals/common/addons/computercraft/pocket/PocketDistanceDetectorUpgrade.java diff --git a/src/generated/resources/.cache/ae219fa7c7d3297c14e454863eac3998a4eab78c b/src/generated/resources/.cache/ae219fa7c7d3297c14e454863eac3998a4eab78c index 8fe8c2d79..5821f3f8a 100644 --- a/src/generated/resources/.cache/ae219fa7c7d3297c14e454863eac3998a4eab78c +++ b/src/generated/resources/.cache/ae219fa7c7d3297c14e454863eac3998a4eab78c @@ -1,6 +1,7 @@ -// 1.19.2 2024-05-28T14:53:16.655934 Pocket Computer Upgrades +// 1.19.2 2025-01-25T19:46:21.23515 Pocket Computer Upgrades b672635324c0df354e587efc81d0b19a581eae2f data/advancedperipherals/computercraft/pocket_upgrades/chatty_pocket.json 30b8f663613c7ce77048fd69631afcc11a682276 data/advancedperipherals/computercraft/pocket_upgrades/colony_pocket.json +661dc77bd0442bfb2a5ed80cff271071817bb22d data/advancedperipherals/computercraft/pocket_upgrades/distance_pocket.json d4647159c2f2693a9c5e8d12bf740635751d29a8 data/advancedperipherals/computercraft/pocket_upgrades/environment_pocket.json 8216a0a7d8ebe3ae738c8fc3626df25eb0a2e07a data/advancedperipherals/computercraft/pocket_upgrades/geoscanner_pocket.json a38aa83593f7ad0ace98e01bb3b5f06f272ef734 data/advancedperipherals/computercraft/pocket_upgrades/player_pocket.json diff --git a/src/generated/resources/.cache/c622617f6fabf890a00b9275cd5f643584a8a2c8 b/src/generated/resources/.cache/c622617f6fabf890a00b9275cd5f643584a8a2c8 index 2cb09adb4..c804ec644 100644 --- a/src/generated/resources/.cache/c622617f6fabf890a00b9275cd5f643584a8a2c8 +++ b/src/generated/resources/.cache/c622617f6fabf890a00b9275cd5f643584a8a2c8 @@ -1,2 +1,2 @@ -// 1.19.2 2025-01-20T07:50:09.44057 Languages: en_us -ebf2194b8fece940adb61f1ae317f68799bd498f assets/advancedperipherals/lang/en_us.json +// 1.19.2 2025-01-25T19:46:21.234203 Languages: en_us +e858500d72e9279f0fe0e8b2d03f94469c8d1f65 assets/advancedperipherals/lang/en_us.json diff --git a/src/generated/resources/assets/advancedperipherals/lang/en_us.json b/src/generated/resources/assets/advancedperipherals/lang/en_us.json index ef080ec50..3da1acb77 100644 --- a/src/generated/resources/assets/advancedperipherals/lang/en_us.json +++ b/src/generated/resources/assets/advancedperipherals/lang/en_us.json @@ -80,6 +80,7 @@ "keybind.advancedperipherals.description": "Show Description", "pocket.advancedperipherals.chatty_pocket": "Chatty", "pocket.advancedperipherals.colony_pocket": "Colony", + "pocket.advancedperipherals.distance_pocket": "Distance Detector", "pocket.advancedperipherals.environment_pocket": "Environment", "pocket.advancedperipherals.geoscanner_pocket": "Geo", "pocket.advancedperipherals.player_pocket": "Player Detector", diff --git a/src/generated/resources/data/advancedperipherals/computercraft/pocket_upgrades/distance_pocket.json b/src/generated/resources/data/advancedperipherals/computercraft/pocket_upgrades/distance_pocket.json new file mode 100644 index 000000000..0d83ccc1d --- /dev/null +++ b/src/generated/resources/data/advancedperipherals/computercraft/pocket_upgrades/distance_pocket.json @@ -0,0 +1,4 @@ +{ + "type": "advancedperipherals:distance_pocket", + "item": "advancedperipherals:distance_detector" +} \ No newline at end of file diff --git a/src/main/java/de/srendi/advancedperipherals/common/addons/computercraft/owner/PocketPeripheralOwner.java b/src/main/java/de/srendi/advancedperipherals/common/addons/computercraft/owner/PocketPeripheralOwner.java index f4ed40416..b9bc35ce5 100644 --- a/src/main/java/de/srendi/advancedperipherals/common/addons/computercraft/owner/PocketPeripheralOwner.java +++ b/src/main/java/de/srendi/advancedperipherals/common/addons/computercraft/owner/PocketPeripheralOwner.java @@ -2,6 +2,7 @@ import dan200.computercraft.api.peripheral.IPeripheral; import dan200.computercraft.api.pocket.IPocketAccess; +import dan200.computercraft.api.pocket.IPocketUpgrade; import de.srendi.advancedperipherals.common.configuration.APConfig; import de.srendi.advancedperipherals.common.util.DataStorageUtil; import de.srendi.advancedperipherals.common.util.fakeplayer.APFakePlayer; @@ -20,12 +21,15 @@ public class PocketPeripheralOwner extends BasePeripheralOwner { private final IPocketAccess pocket; + private final IPocketUpgrade upgrade; - public PocketPeripheralOwner(IPocketAccess pocket) { + public PocketPeripheralOwner(IPocketAccess pocket, IPocketUpgrade upgrade) { super(); this.pocket = pocket; - if(APConfig.PERIPHERALS_CONFIG.disablePocketFuelConsumption.get()) + this.upgrade = upgrade; + if (APConfig.PERIPHERALS_CONFIG.disablePocketFuelConsumption.get()) { attachAbility(PeripheralOwnerAbility.FUEL, new InfinitePocketFuelAbility(this)); + } } @Nullable @@ -84,7 +88,7 @@ public Entity getHoldingEntity() { @NotNull @Override public CompoundTag getDataStorage() { - return DataStorageUtil.getDataStorage(pocket); + return DataStorageUtil.getDataStorage(pocket, upgrade); } @Override diff --git a/src/main/java/de/srendi/advancedperipherals/common/addons/computercraft/peripheral/ChatBoxPeripheral.java b/src/main/java/de/srendi/advancedperipherals/common/addons/computercraft/peripheral/ChatBoxPeripheral.java index 88f3cf3aa..7616d1e27 100644 --- a/src/main/java/de/srendi/advancedperipherals/common/addons/computercraft/peripheral/ChatBoxPeripheral.java +++ b/src/main/java/de/srendi/advancedperipherals/common/addons/computercraft/peripheral/ChatBoxPeripheral.java @@ -7,6 +7,7 @@ import dan200.computercraft.api.lua.MethodResult; import dan200.computercraft.api.peripheral.IComputerAccess; import dan200.computercraft.api.pocket.IPocketAccess; +import dan200.computercraft.api.pocket.IPocketUpgrade; import dan200.computercraft.api.turtle.ITurtleAccess; import dan200.computercraft.api.turtle.TurtleSide; import de.srendi.advancedperipherals.AdvancedPeripherals; @@ -66,8 +67,8 @@ public ChatBoxPeripheral(ITurtleAccess turtle, TurtleSide side) { this(new TurtlePeripheralOwner(turtle, side)); } - public ChatBoxPeripheral(IPocketAccess pocket) { - this(new PocketPeripheralOwner(pocket)); + public ChatBoxPeripheral(IPocketAccess pocket, IPocketUpgrade upgrade) { + this(new PocketPeripheralOwner(pocket, upgrade)); } @Override diff --git a/src/main/java/de/srendi/advancedperipherals/common/addons/computercraft/peripheral/ColonyPeripheral.java b/src/main/java/de/srendi/advancedperipherals/common/addons/computercraft/peripheral/ColonyPeripheral.java index 12aefd596..8b5a9a1e9 100644 --- a/src/main/java/de/srendi/advancedperipherals/common/addons/computercraft/peripheral/ColonyPeripheral.java +++ b/src/main/java/de/srendi/advancedperipherals/common/addons/computercraft/peripheral/ColonyPeripheral.java @@ -18,6 +18,7 @@ import dan200.computercraft.api.lua.LuaException; import dan200.computercraft.api.lua.LuaFunction; import dan200.computercraft.api.pocket.IPocketAccess; +import dan200.computercraft.api.pocket.IPocketUpgrade; import de.srendi.advancedperipherals.AdvancedPeripherals; import de.srendi.advancedperipherals.common.addons.computercraft.owner.BlockEntityPeripheralOwner; import de.srendi.advancedperipherals.common.addons.computercraft.owner.IPeripheralOwner; @@ -50,8 +51,8 @@ public ColonyPeripheral(PeripheralBlockEntity tileEntity) { super(PERIPHERAL_TYPE, new BlockEntityPeripheralOwner<>(tileEntity)); } - public ColonyPeripheral(IPocketAccess access) { - super(PERIPHERAL_TYPE, new PocketPeripheralOwner(access)); + public ColonyPeripheral(IPocketAccess access, IPocketUpgrade upgrade) { + super(PERIPHERAL_TYPE, new PocketPeripheralOwner(access, upgrade)); } @Override diff --git a/src/main/java/de/srendi/advancedperipherals/common/addons/computercraft/peripheral/DistanceDetectorPeripheral.java b/src/main/java/de/srendi/advancedperipherals/common/addons/computercraft/peripheral/DistanceDetectorPeripheral.java index 41f535aad..7babcdf91 100644 --- a/src/main/java/de/srendi/advancedperipherals/common/addons/computercraft/peripheral/DistanceDetectorPeripheral.java +++ b/src/main/java/de/srendi/advancedperipherals/common/addons/computercraft/peripheral/DistanceDetectorPeripheral.java @@ -3,12 +3,16 @@ import dan200.computercraft.api.lua.IArguments; import dan200.computercraft.api.lua.LuaException; import dan200.computercraft.api.lua.LuaFunction; +import dan200.computercraft.api.pocket.IPocketAccess; +import dan200.computercraft.api.pocket.IPocketUpgrade; import de.srendi.advancedperipherals.common.addons.computercraft.owner.BlockEntityPeripheralOwner; import de.srendi.advancedperipherals.common.addons.computercraft.owner.IPeripheralOwner; +import de.srendi.advancedperipherals.common.addons.computercraft.owner.PocketPeripheralOwner; import de.srendi.advancedperipherals.common.blocks.blockentities.DistanceDetectorEntity; import de.srendi.advancedperipherals.common.configuration.APConfig; import de.srendi.advancedperipherals.common.util.HitResultUtil; import de.srendi.advancedperipherals.lib.peripherals.BasePeripheral; +import net.minecraft.nbt.CompoundTag; import net.minecraft.world.level.ClipContext; import net.minecraft.world.level.Level; import net.minecraft.world.phys.HitResult; @@ -41,6 +45,23 @@ public DistanceDetectorPeripheral(DistanceDetectorEntity tileEntity) { this.detectionType = new AtomicReference<>(this.tileEntity.getDetectionType()); } + // TODO: thread safely save data + protected DistanceDetectorPeripheral(IPeripheralOwner owner) { + super(PERIPHERAL_TYPE, owner); + this.tileEntity = null; + CompoundTag data = this.owner.getDataStorage(); + this.maxRange = new AtomicInteger(Float.floatToRawIntBits(data.contains("maxRange") ? data.getFloat("maxRange") : this.getConfiguredMaxRange())); + this.currentDistance = data.contains("currentDistance") ? data.getFloat("currentDistance") : -1; + this.showLaser = new AtomicBoolean(data.contains("showLaser") ? data.getBoolean("showLaser") : true); + this.calculatePeriodically = data.contains("calculatePeriodically") ? data.getBoolean("calculatePeriodically") : false; + this.ignoreTransparent = data.contains("ignoreTransparent") ? data.getBoolean("ignoreTransparent") : true; + this.detectionType = new AtomicReference<>(data.contains("detectionType") ? DetectionType.values()[data.getByte("detectionType")] : DetectionType.BOTH); + } + + public DistanceDetectorPeripheral(IPocketAccess pocket, IPocketUpgrade upgrade) { + this(new PocketPeripheralOwner(pocket, upgrade)); + } + @Override public boolean isEnabled() { return APConfig.PERIPHERALS_CONFIG.enableDistanceDetector.get(); @@ -147,7 +168,7 @@ public final boolean getLaserVisibility() { return this.getShowLaser(); } - @LuaFunction + @LuaFunction(value = {"setIgnoreTransparency"}) public final void setIgnoreTransparencyLua(boolean enable) { this.setIgnoreTransparent(enable); } @@ -210,17 +231,17 @@ public final boolean shouldCalculatePeriodically() { return this.getCalculatePeriodically(); } - @LuaFunction + @LuaFunction(value = {"setCalculatePeriodically"}) public final void setCalculatePeriodicallyLua(boolean shouldCalculatePeriodically) { this.setCalculatePeriodically(shouldCalculatePeriodically); } - @LuaFunction + @LuaFunction(value = {"setMaxRange"}) public final void setMaxRangeLua(double maxDistance) { this.setMaxRange((float) maxDistance); } - @LuaFunction + @LuaFunction(value = {"getMaxRange"}) public final double getMaxRangeLua() { return this.getMaxRange(); } diff --git a/src/main/java/de/srendi/advancedperipherals/common/addons/computercraft/peripheral/EnvironmentDetectorPeripheral.java b/src/main/java/de/srendi/advancedperipherals/common/addons/computercraft/peripheral/EnvironmentDetectorPeripheral.java index 92c668b17..a30fd0a5d 100644 --- a/src/main/java/de/srendi/advancedperipherals/common/addons/computercraft/peripheral/EnvironmentDetectorPeripheral.java +++ b/src/main/java/de/srendi/advancedperipherals/common/addons/computercraft/peripheral/EnvironmentDetectorPeripheral.java @@ -5,6 +5,7 @@ import dan200.computercraft.api.lua.LuaFunction; import dan200.computercraft.api.lua.MethodResult; import dan200.computercraft.api.pocket.IPocketAccess; +import dan200.computercraft.api.pocket.IPocketUpgrade; import dan200.computercraft.api.turtle.ITurtleAccess; import dan200.computercraft.api.turtle.TurtleSide; import de.srendi.advancedperipherals.common.addons.computercraft.operations.SphereOperationContext; @@ -68,8 +69,8 @@ public EnvironmentDetectorPeripheral(ITurtleAccess turtle, TurtleSide side) { this(new TurtlePeripheralOwner(turtle, side).attachFuel(1)); } - public EnvironmentDetectorPeripheral(IPocketAccess pocket) { - this(new PocketPeripheralOwner(pocket)); + public EnvironmentDetectorPeripheral(IPocketAccess pocket, IPocketUpgrade upgrade) { + this(new PocketPeripheralOwner(pocket, upgrade)); } private static int estimateCost(int radius) { diff --git a/src/main/java/de/srendi/advancedperipherals/common/addons/computercraft/peripheral/GeoScannerPeripheral.java b/src/main/java/de/srendi/advancedperipherals/common/addons/computercraft/peripheral/GeoScannerPeripheral.java index 766586170..6a9ccacb8 100644 --- a/src/main/java/de/srendi/advancedperipherals/common/addons/computercraft/peripheral/GeoScannerPeripheral.java +++ b/src/main/java/de/srendi/advancedperipherals/common/addons/computercraft/peripheral/GeoScannerPeripheral.java @@ -5,6 +5,7 @@ import dan200.computercraft.api.lua.LuaFunction; import dan200.computercraft.api.lua.MethodResult; import dan200.computercraft.api.pocket.IPocketAccess; +import dan200.computercraft.api.pocket.IPocketUpgrade; import dan200.computercraft.api.turtle.ITurtleAccess; import dan200.computercraft.api.turtle.TurtleSide; import de.srendi.advancedperipherals.common.addons.computercraft.operations.SphereOperationContext; @@ -57,8 +58,8 @@ public GeoScannerPeripheral(ITurtleAccess turtle, TurtleSide side) { this(new TurtlePeripheralOwner(turtle, side).attachFuel(1)); } - public GeoScannerPeripheral(IPocketAccess pocket) { - this(new PocketPeripheralOwner(pocket)); + public GeoScannerPeripheral(IPocketAccess pocket, IPocketUpgrade upgrade) { + this(new PocketPeripheralOwner(pocket, upgrade)); } private static List> scan(List> result, Level level, Vec3 center, int radius) { diff --git a/src/main/java/de/srendi/advancedperipherals/common/addons/computercraft/peripheral/PlayerDetectorPeripheral.java b/src/main/java/de/srendi/advancedperipherals/common/addons/computercraft/peripheral/PlayerDetectorPeripheral.java index dc05ba478..fc3e5c058 100644 --- a/src/main/java/de/srendi/advancedperipherals/common/addons/computercraft/peripheral/PlayerDetectorPeripheral.java +++ b/src/main/java/de/srendi/advancedperipherals/common/addons/computercraft/peripheral/PlayerDetectorPeripheral.java @@ -5,6 +5,7 @@ import dan200.computercraft.api.lua.LuaFunction; import dan200.computercraft.api.lua.MethodResult; import dan200.computercraft.api.pocket.IPocketAccess; +import dan200.computercraft.api.pocket.IPocketUpgrade; import dan200.computercraft.api.turtle.ITurtleAccess; import dan200.computercraft.api.turtle.TurtleSide; import de.srendi.advancedperipherals.common.addons.computercraft.owner.BlockEntityPeripheralOwner; @@ -41,8 +42,8 @@ public PlayerDetectorPeripheral(ITurtleAccess access, TurtleSide side) { super(PERIPHERAL_TYPE, new TurtlePeripheralOwner(access, side)); } - public PlayerDetectorPeripheral(IPocketAccess pocket) { - super(PERIPHERAL_TYPE, new PocketPeripheralOwner(pocket)); + public PlayerDetectorPeripheral(IPocketAccess pocket, IPocketUpgrade upgrade) { + super(PERIPHERAL_TYPE, new PocketPeripheralOwner(pocket, upgrade)); } private boolean isAllowedMultiDimensional() { diff --git a/src/main/java/de/srendi/advancedperipherals/common/addons/computercraft/pocket/PocketChatBoxUpgrade.java b/src/main/java/de/srendi/advancedperipherals/common/addons/computercraft/pocket/PocketChatBoxUpgrade.java index e0a17833b..5264a1b46 100644 --- a/src/main/java/de/srendi/advancedperipherals/common/addons/computercraft/pocket/PocketChatBoxUpgrade.java +++ b/src/main/java/de/srendi/advancedperipherals/common/addons/computercraft/pocket/PocketChatBoxUpgrade.java @@ -15,8 +15,8 @@ public PocketChatBoxUpgrade(ResourceLocation id, ItemStack stack) { @Nullable @Override - public ChatBoxPeripheral getPeripheral(IPocketAccess access) { - return new ChatBoxPeripheral(access); + public ChatBoxPeripheral getPeripheral(IPocketAccess pocketAccess) { + return new ChatBoxPeripheral(pocketAccess, this); } } diff --git a/src/main/java/de/srendi/advancedperipherals/common/addons/computercraft/pocket/PocketColonyIntegratorUpgrade.java b/src/main/java/de/srendi/advancedperipherals/common/addons/computercraft/pocket/PocketColonyIntegratorUpgrade.java index 752ccb18e..6c439404f 100644 --- a/src/main/java/de/srendi/advancedperipherals/common/addons/computercraft/pocket/PocketColonyIntegratorUpgrade.java +++ b/src/main/java/de/srendi/advancedperipherals/common/addons/computercraft/pocket/PocketColonyIntegratorUpgrade.java @@ -13,7 +13,7 @@ public PocketColonyIntegratorUpgrade(ResourceLocation id, ItemStack stack) { } @Override - protected ColonyPeripheral getPeripheral(IPocketAccess access) { - return new ColonyPeripheral(access); + protected ColonyPeripheral getPeripheral(IPocketAccess pocketAccess) { + return new ColonyPeripheral(pocketAccess, this); } } diff --git a/src/main/java/de/srendi/advancedperipherals/common/addons/computercraft/pocket/PocketDistanceDetectorUpgrade.java b/src/main/java/de/srendi/advancedperipherals/common/addons/computercraft/pocket/PocketDistanceDetectorUpgrade.java new file mode 100644 index 000000000..82b47d31f --- /dev/null +++ b/src/main/java/de/srendi/advancedperipherals/common/addons/computercraft/pocket/PocketDistanceDetectorUpgrade.java @@ -0,0 +1,23 @@ +package de.srendi.advancedperipherals.common.addons.computercraft.pocket; + +import dan200.computercraft.api.pocket.IPocketAccess; +import de.srendi.advancedperipherals.common.addons.computercraft.peripheral.DistanceDetectorPeripheral; +import de.srendi.advancedperipherals.lib.pocket.BasePocketUpgrade; +import net.minecraft.resources.ResourceLocation; +import net.minecraft.world.item.ItemStack; +import org.jetbrains.annotations.NotNull; +import org.jetbrains.annotations.Nullable; + +public class PocketDistanceDetectorUpgrade extends BasePocketUpgrade { + + public PocketDistanceDetectorUpgrade(ResourceLocation id, ItemStack stack) { + super(id, stack); + } + + @Nullable + @Override + public DistanceDetectorPeripheral getPeripheral(@NotNull IPocketAccess pocketAccess) { + return new DistanceDetectorPeripheral(pocketAccess, this); + } + +} diff --git a/src/main/java/de/srendi/advancedperipherals/common/addons/computercraft/pocket/PocketEnvironmentUpgrade.java b/src/main/java/de/srendi/advancedperipherals/common/addons/computercraft/pocket/PocketEnvironmentUpgrade.java index dc6719b17..dd23a28b8 100644 --- a/src/main/java/de/srendi/advancedperipherals/common/addons/computercraft/pocket/PocketEnvironmentUpgrade.java +++ b/src/main/java/de/srendi/advancedperipherals/common/addons/computercraft/pocket/PocketEnvironmentUpgrade.java @@ -16,8 +16,8 @@ public PocketEnvironmentUpgrade(ResourceLocation id, ItemStack stack) { @Nullable @Override - public EnvironmentDetectorPeripheral getPeripheral(@NotNull IPocketAccess iPocketAccess) { - return new EnvironmentDetectorPeripheral(iPocketAccess); + public EnvironmentDetectorPeripheral getPeripheral(@NotNull IPocketAccess pocketAccess) { + return new EnvironmentDetectorPeripheral(pocketAccess, this); } } diff --git a/src/main/java/de/srendi/advancedperipherals/common/addons/computercraft/pocket/PocketGeoScannerUpgrade.java b/src/main/java/de/srendi/advancedperipherals/common/addons/computercraft/pocket/PocketGeoScannerUpgrade.java index 98823d94a..03d23d26a 100644 --- a/src/main/java/de/srendi/advancedperipherals/common/addons/computercraft/pocket/PocketGeoScannerUpgrade.java +++ b/src/main/java/de/srendi/advancedperipherals/common/addons/computercraft/pocket/PocketGeoScannerUpgrade.java @@ -16,8 +16,8 @@ public PocketGeoScannerUpgrade(ResourceLocation id, ItemStack stack) { @Nullable @Override - public GeoScannerPeripheral getPeripheral(@NotNull IPocketAccess iPocketAccess) { - return new GeoScannerPeripheral(iPocketAccess); + public GeoScannerPeripheral getPeripheral(@NotNull IPocketAccess pocketAccess) { + return new GeoScannerPeripheral(pocketAccess, this); } } diff --git a/src/main/java/de/srendi/advancedperipherals/common/addons/computercraft/pocket/PocketPlayerDetectorUpgrade.java b/src/main/java/de/srendi/advancedperipherals/common/addons/computercraft/pocket/PocketPlayerDetectorUpgrade.java index 1e2b6bb43..422b02e0f 100644 --- a/src/main/java/de/srendi/advancedperipherals/common/addons/computercraft/pocket/PocketPlayerDetectorUpgrade.java +++ b/src/main/java/de/srendi/advancedperipherals/common/addons/computercraft/pocket/PocketPlayerDetectorUpgrade.java @@ -16,8 +16,8 @@ public PocketPlayerDetectorUpgrade(ResourceLocation id, ItemStack stack) { @Nullable @Override - public PlayerDetectorPeripheral getPeripheral(@NotNull IPocketAccess iPocketAccess) { - return new PlayerDetectorPeripheral(iPocketAccess); + public PlayerDetectorPeripheral getPeripheral(@NotNull IPocketAccess pocketAccess) { + return new PlayerDetectorPeripheral(pocketAccess, this); } } diff --git a/src/main/java/de/srendi/advancedperipherals/common/data/EnUsLanguageProvider.java b/src/main/java/de/srendi/advancedperipherals/common/data/EnUsLanguageProvider.java index 1e874d486..832cf08be 100644 --- a/src/main/java/de/srendi/advancedperipherals/common/data/EnUsLanguageProvider.java +++ b/src/main/java/de/srendi/advancedperipherals/common/data/EnUsLanguageProvider.java @@ -100,6 +100,7 @@ private void addTurtles() { private void addPockets() { addPocket(CCRegistration.ID.CHATTY_POCKET, "Chatty"); addPocket(CCRegistration.ID.COLONY_POCKET, "Colony"); + addPocket(CCRegistration.ID.DISTANCE_POCKET, "Distance Detector"); addPocket(CCRegistration.ID.ENVIRONMENT_POCKET, "Environment"); addPocket(CCRegistration.ID.GEOSCANNER_POCKET, "Geo"); addPocket(CCRegistration.ID.PLAYER_POCKET, "Player Detector"); diff --git a/src/main/java/de/srendi/advancedperipherals/common/data/PocketUpgradesProvider.java b/src/main/java/de/srendi/advancedperipherals/common/data/PocketUpgradesProvider.java index 385b75679..a021dbee7 100644 --- a/src/main/java/de/srendi/advancedperipherals/common/data/PocketUpgradesProvider.java +++ b/src/main/java/de/srendi/advancedperipherals/common/data/PocketUpgradesProvider.java @@ -18,9 +18,10 @@ public PocketUpgradesProvider(DataGenerator output) { @Override protected void addUpgrades(@NotNull Consumer>> addUpgrade) { simpleWithCustomItem(CCRegistration.ID.CHATTY_POCKET, CCRegistration.CHAT_BOX_POCKET.get(), APBlocks.CHAT_BOX.get().asItem()).add(addUpgrade); - simpleWithCustomItem(CCRegistration.ID.PLAYER_POCKET, CCRegistration.PLAYER_DETECTOR_POCKET.get(), APBlocks.PLAYER_DETECTOR.get().asItem()).add(addUpgrade); + simpleWithCustomItem(CCRegistration.ID.COLONY_POCKET, CCRegistration.COLONY_POCKET.get(), APBlocks.COLONY_INTEGRATOR.get().asItem()).add(addUpgrade); + simpleWithCustomItem(CCRegistration.ID.DISTANCE_POCKET, CCRegistration.DISTANCE_DETECTOR_POCKET.get(), APBlocks.DISTANCE_DETECTOR.get().asItem()).add(addUpgrade); simpleWithCustomItem(CCRegistration.ID.ENVIRONMENT_POCKET, CCRegistration.ENVIRONMENT_POCKET.get(), APBlocks.ENVIRONMENT_DETECTOR.get().asItem()).add(addUpgrade); simpleWithCustomItem(CCRegistration.ID.GEOSCANNER_POCKET, CCRegistration.GEO_SCANNER_POCKET.get(), APBlocks.GEO_SCANNER.get().asItem()).add(addUpgrade); - simpleWithCustomItem(CCRegistration.ID.COLONY_POCKET, CCRegistration.COLONY_POCKET.get(), APBlocks.COLONY_INTEGRATOR.get().asItem()).add(addUpgrade); + simpleWithCustomItem(CCRegistration.ID.PLAYER_POCKET, CCRegistration.PLAYER_DETECTOR_POCKET.get(), APBlocks.PLAYER_DETECTOR.get().asItem()).add(addUpgrade); } } diff --git a/src/main/java/de/srendi/advancedperipherals/common/items/SmartGlassesItem.java b/src/main/java/de/srendi/advancedperipherals/common/items/SmartGlassesItem.java index cac85edaf..14b1e8c94 100644 --- a/src/main/java/de/srendi/advancedperipherals/common/items/SmartGlassesItem.java +++ b/src/main/java/de/srendi/advancedperipherals/common/items/SmartGlassesItem.java @@ -248,7 +248,7 @@ public SmartGlassesComputer getOrCreateComputer(ServerLevel level, Entity entity setComputerID(stack, computerID); } - computer = new SmartGlassesComputer(level, getComputerID(stack), getLabel(stack), getFamily()); + computer = new SmartGlassesComputer(level, getComputerID(stack), getLabel(stack), getFamily(), stack.getOrCreateTag().getCompound(SmartGlassesComputer.UPGRADE_DATAS_TAG).copy()); setInstanceID(stack, computer.register()); setSessionID(stack, registry.getSessionID()); diff --git a/src/main/java/de/srendi/advancedperipherals/common/setup/CCRegistration.java b/src/main/java/de/srendi/advancedperipherals/common/setup/CCRegistration.java index 2e44565db..a72ff2f45 100644 --- a/src/main/java/de/srendi/advancedperipherals/common/setup/CCRegistration.java +++ b/src/main/java/de/srendi/advancedperipherals/common/setup/CCRegistration.java @@ -7,6 +7,7 @@ import de.srendi.advancedperipherals.common.addons.computercraft.integrations.IntegrationPeripheralProvider; import de.srendi.advancedperipherals.common.addons.computercraft.pocket.PocketChatBoxUpgrade; import de.srendi.advancedperipherals.common.addons.computercraft.pocket.PocketColonyIntegratorUpgrade; +import de.srendi.advancedperipherals.common.addons.computercraft.pocket.PocketDistanceDetectorUpgrade; import de.srendi.advancedperipherals.common.addons.computercraft.pocket.PocketEnvironmentUpgrade; import de.srendi.advancedperipherals.common.addons.computercraft.pocket.PocketGeoScannerUpgrade; import de.srendi.advancedperipherals.common.addons.computercraft.pocket.PocketPlayerDetectorUpgrade; @@ -46,6 +47,7 @@ public class CCRegistration { public static final RegistryObject> CHAT_BOX_POCKET = APRegistration.POCKET_SERIALIZER.register(ID.CHATTY_POCKET.getPath(), () -> PocketUpgradeSerialiser.simpleWithCustomItem(PocketChatBoxUpgrade::new)); public static final RegistryObject> COLONY_POCKET = APRegistration.POCKET_SERIALIZER.register(ID.COLONY_POCKET.getPath(), () -> PocketUpgradeSerialiser.simpleWithCustomItem(PocketColonyIntegratorUpgrade::new)); + public static final RegistryObject> DISTANCE_DETECTOR_POCKET = APRegistration.POCKET_SERIALIZER.register(ID.DISTANCE_POCKET.getPath(), () -> PocketUpgradeSerialiser.simpleWithCustomItem(PocketDistanceDetectorUpgrade::new)); public static final RegistryObject> ENVIRONMENT_POCKET = APRegistration.POCKET_SERIALIZER.register(ID.ENVIRONMENT_POCKET.getPath(), () -> PocketUpgradeSerialiser.simpleWithCustomItem(PocketEnvironmentUpgrade::new)); public static final RegistryObject> GEO_SCANNER_POCKET = APRegistration.POCKET_SERIALIZER.register(ID.GEOSCANNER_POCKET.getPath(), () -> PocketUpgradeSerialiser.simpleWithCustomItem(PocketGeoScannerUpgrade::new)); public static final RegistryObject> PLAYER_DETECTOR_POCKET = APRegistration.POCKET_SERIALIZER.register(ID.PLAYER_POCKET.getPath(), () -> PocketUpgradeSerialiser.simpleWithCustomItem(PocketPlayerDetectorUpgrade::new)); @@ -76,6 +78,7 @@ public static class ID { public static final ResourceLocation CHATTY_POCKET = new ResourceLocation(AdvancedPeripherals.MOD_ID, "chatty_pocket"); public static final ResourceLocation COLONY_POCKET = new ResourceLocation(AdvancedPeripherals.MOD_ID, "colony_pocket"); + public static final ResourceLocation DISTANCE_POCKET = new ResourceLocation(AdvancedPeripherals.MOD_ID, "distance_pocket"); public static final ResourceLocation ENVIRONMENT_POCKET = new ResourceLocation(AdvancedPeripherals.MOD_ID, "environment_pocket"); public static final ResourceLocation GEOSCANNER_POCKET = new ResourceLocation(AdvancedPeripherals.MOD_ID, "geoscanner_pocket"); public static final ResourceLocation PLAYER_POCKET = new ResourceLocation(AdvancedPeripherals.MOD_ID, "player_pocket"); diff --git a/src/main/java/de/srendi/advancedperipherals/common/smartglasses/SmartGlassesComputer.java b/src/main/java/de/srendi/advancedperipherals/common/smartglasses/SmartGlassesComputer.java index eac317fec..600a21742 100644 --- a/src/main/java/de/srendi/advancedperipherals/common/smartglasses/SmartGlassesComputer.java +++ b/src/main/java/de/srendi/advancedperipherals/common/smartglasses/SmartGlassesComputer.java @@ -34,6 +34,8 @@ */ public class SmartGlassesComputer extends ServerComputer implements IPocketAccess { + public static final String UPGRADE_DATAS_TAG = "UpgradeDatas"; + @Nullable private Entity entity; private ItemStack stack = ItemStack.EMPTY; @@ -42,16 +44,19 @@ public class SmartGlassesComputer extends ServerComputer implements IPocketAcces private SmartGlassesItemHandler itemHandler = null; @NotNull private final ModulePeripheral modulePeripheral; + private final CompoundTag upgradeDatas; + private boolean peripheralOutdated = false; private boolean isDirty = true; private Map upgrades = Collections.emptyMap(); private final Map modules = new HashMap<>(); - public SmartGlassesComputer(ServerLevel world, int computerID, @Nullable String label, ComputerFamily family) { + public SmartGlassesComputer(ServerLevel world, int computerID, @Nullable String label, ComputerFamily family, @NotNull CompoundTag upgradeDatas) { super(world, computerID, label, family, 39, 13); this.addAPI(new SmartGlassesAPI()); this.modulePeripheral = new ModulePeripheral(this); + this.upgradeDatas = upgradeDatas; this.setPeripheral(ComputerSide.BACK, this.modulePeripheral); } @@ -97,6 +102,8 @@ public void setColour(int colour) { public void setStack(ItemStack stack) { this.stack = stack; + this.invalidatePeripheral(); + this.updateUpgradeNBTData(); } public ItemStack getStack() { @@ -116,30 +123,36 @@ public void setItemHandler(@Nullable SmartGlassesItemHandler itemHandler) { this.itemHandler = itemHandler; } - public void markDirty() { - isDirty = true; + @Override + @NotNull + public CompoundTag getUpgradeNBTData() { + return this.upgradeDatas; } - public boolean isDirty() { - return isDirty; + public void setUpgradeData(@NotNull ComputerSide side, @NotNull ResourceLocation id, @NotNull CompoundTag data) { + data.putString("UpgradeSide", side.getName()); + this.upgradeDatas.put(id.toString(), data); + this.updateUpgradeNBTData(); } - @Override - @NotNull - public CompoundTag getUpgradeNBTData() { - return new CompoundTag(); + public void removeUpgradeData(@NotNull ComputerSide side) { + for (String id : this.upgradeDatas.getAllKeys()) { + if (side.getName().equals(this.upgradeDatas.getCompound(id).getString("UpgradeSide"))) { + this.upgradeDatas.remove(id); + this.updateUpgradeNBTData(); + return; + } + } } @Override public void updateUpgradeNBTData() { - if (entity instanceof Player player) { - player.getInventory().setChanged(); - } + this.isDirty = true; } @Override public void invalidatePeripheral() { - updatePeripheralsAndModules(this.itemHandler); + this.peripheralOutdated = true; } @Override @@ -153,7 +166,7 @@ public void setPeripheral(ComputerSide side, IPeripheral peripheral) { super.setPeripheral(side, peripheral); } - public void updatePeripheralsAndModules(SmartGlassesItemHandler itemHandler) { + private void updatePeripheralsAndModules(SmartGlassesItemHandler itemHandler) { Set upgradesIdSet = new HashSet<>(); ImmutableMap.Builder upgradesBuilder = new ImmutableMap.Builder<>(); for (int slot = 0; slot < SmartGlassesItemHandler.PERIPHERAL_SLOTS; slot++) { @@ -162,9 +175,15 @@ public void updatePeripheralsAndModules(SmartGlassesItemHandler itemHandler) { IPocketUpgrade upgrade = PocketUpgrades.instance().get(peripheralItem); IPeripheral peripheral = upgrade != null ? upgrade.createPeripheral(smartGlassesAccess) : null; setPeripheral(side, peripheral); - if (peripheral != null && upgradesIdSet.add(upgrade.getUpgradeID())) { - upgradesBuilder.put(upgrade.getUpgradeID(), peripheral); + if (peripheral != null) { + ResourceLocation id = upgrade.getUpgradeID(); + if (upgradesIdSet.add(id)) { + upgradesBuilder.put(id, peripheral); + setUpgradeData(side, id, this.upgradeDatas.getCompound(id.toString())); + continue; + } } + removeUpgradeData(side); } this.upgrades = upgradesBuilder.build(); for (int slot = SmartGlassesItemHandler.PERIPHERAL_SLOTS; slot < SmartGlassesItemHandler.SLOTS; slot++) { @@ -193,12 +212,21 @@ public void updatePeripheralsAndModules(SmartGlassesItemHandler itemHandler) { public void tickServer() { super.tickServer(); - if (isDirty()) { - invalidatePeripheral(); - isDirty = false; + if (this.peripheralOutdated && this.itemHandler != null) { + this.peripheralOutdated = false; + this.updatePeripheralsAndModules(this.itemHandler); + } + + if (this.isDirty) { + this.isDirty = false; + CompoundTag data = this.stack.getOrCreateTag(); + data.put(UPGRADE_DATAS_TAG, this.upgradeDatas.copy()); + if (entity instanceof Player player) { + player.getInventory().setChanged(); + } } - modules.values().forEach(module -> { + this.modules.values().forEach(module -> { module.tick(smartGlassesAccess); }); } diff --git a/src/main/java/de/srendi/advancedperipherals/common/smartglasses/SmartGlassesItemHandler.java b/src/main/java/de/srendi/advancedperipherals/common/smartglasses/SmartGlassesItemHandler.java index bd4a10a10..d3b27fad6 100644 --- a/src/main/java/de/srendi/advancedperipherals/common/smartglasses/SmartGlassesItemHandler.java +++ b/src/main/java/de/srendi/advancedperipherals/common/smartglasses/SmartGlassesItemHandler.java @@ -157,7 +157,7 @@ public void setStackInSlot(int slot, @NotNull ItemStack stack) { public void setChanged() { if (this.computer != null) { - this.computer.markDirty(); + this.computer.invalidatePeripheral(); } } diff --git a/src/main/java/de/srendi/advancedperipherals/common/util/DataStorageUtil.java b/src/main/java/de/srendi/advancedperipherals/common/util/DataStorageUtil.java index 0499427cc..52585dbb4 100644 --- a/src/main/java/de/srendi/advancedperipherals/common/util/DataStorageUtil.java +++ b/src/main/java/de/srendi/advancedperipherals/common/util/DataStorageUtil.java @@ -1,14 +1,17 @@ package de.srendi.advancedperipherals.common.util; import dan200.computercraft.api.pocket.IPocketAccess; +import dan200.computercraft.api.pocket.IPocketUpgrade; import dan200.computercraft.api.turtle.ITurtleAccess; import dan200.computercraft.api.turtle.TurtleSide; import de.srendi.advancedperipherals.common.addons.computercraft.owner.IPeripheralOwner; import de.srendi.advancedperipherals.lib.peripherals.IPeripheralTileEntity; import net.minecraft.nbt.CompoundTag; +import net.minecraft.nbt.Tag; import org.jetbrains.annotations.NotNull; public class DataStorageUtil { + private DataStorageUtil() {} public static CompoundTag getDataStorage(@NotNull ITurtleAccess access, @NotNull TurtleSide side) { return access.getUpgradeNBTData(side); @@ -18,8 +21,17 @@ public static CompoundTag getDataStorage(@NotNull IPeripheralTileEntity tileEnti return tileEntity.getPeripheralSettings(); } - public static CompoundTag getDataStorage(@NotNull IPocketAccess pocket) { - return pocket.getUpgradeNBTData(); + public static CompoundTag getDataStorage(@NotNull IPocketAccess pocket, @NotNull IPocketUpgrade upgrade) { + String id = upgrade.getUpgradeID().toString(); + CompoundTag datas = pocket.getUpgradeNBTData(); + Tag tag = datas.get(id); + if (tag instanceof CompoundTag data) { + return data; + } + CompoundTag data = new CompoundTag(); + datas.put(id, data); + pocket.updateUpgradeNBTData(); + return data; } /** diff --git a/src/main/java/de/srendi/advancedperipherals/common/util/NBTUtil.java b/src/main/java/de/srendi/advancedperipherals/common/util/NBTUtil.java index 114a6e9ed..bb6e37ebd 100644 --- a/src/main/java/de/srendi/advancedperipherals/common/util/NBTUtil.java +++ b/src/main/java/de/srendi/advancedperipherals/common/util/NBTUtil.java @@ -23,6 +23,7 @@ import java.util.Map; public class NBTUtil { + private NBTUtil() {} public static Tag toDirectNBT(Object object) { // Mostly dan200.computercraft.shared.util toNBTTag method diff --git a/src/main/java/de/srendi/advancedperipherals/lib/peripherals/DisabledPeripheral.java b/src/main/java/de/srendi/advancedperipherals/lib/peripherals/DisabledPeripheral.java index 8fd524d0c..c97099586 100644 --- a/src/main/java/de/srendi/advancedperipherals/lib/peripherals/DisabledPeripheral.java +++ b/src/main/java/de/srendi/advancedperipherals/lib/peripherals/DisabledPeripheral.java @@ -1,17 +1,18 @@ package de.srendi.advancedperipherals.lib.peripherals; import dan200.computercraft.api.pocket.IPocketAccess; +import dan200.computercraft.api.pocket.IPocketUpgrade; import de.srendi.advancedperipherals.common.addons.computercraft.owner.PocketPeripheralOwner; public class DisabledPeripheral extends BasePeripheral { - public static final DisabledPeripheral INSTANCE = new DisabledPeripheral("disabledPeripheral", null); + public static final DisabledPeripheral INSTANCE = new DisabledPeripheral("disabledPeripheral", null, null); - private DisabledPeripheral(String type, IPocketAccess access) { - super(type, new PocketPeripheralOwner(access)); + private DisabledPeripheral(String type, IPocketAccess access, IPocketUpgrade upgrade) { + super(type, new PocketPeripheralOwner(access, upgrade)); } @Override public boolean isEnabled() { - return true; + return false; } } From 7e4b0410c902e1ee1eabcc60b1e84f5ec4893674 Mon Sep 17 00:00:00 2001 From: zyxkad Date: Sat, 25 Jan 2025 20:21:52 -0700 Subject: [PATCH 7/9] fix smartglass direction --- .../owner/PocketPeripheralOwner.java | 31 +++++++++++-------- .../DistanceDetectorPeripheral.java | 6 +++- 2 files changed, 23 insertions(+), 14 deletions(-) diff --git a/src/main/java/de/srendi/advancedperipherals/common/addons/computercraft/owner/PocketPeripheralOwner.java b/src/main/java/de/srendi/advancedperipherals/common/addons/computercraft/owner/PocketPeripheralOwner.java index b9bc35ce5..21dc65ae6 100644 --- a/src/main/java/de/srendi/advancedperipherals/common/addons/computercraft/owner/PocketPeripheralOwner.java +++ b/src/main/java/de/srendi/advancedperipherals/common/addons/computercraft/owner/PocketPeripheralOwner.java @@ -42,41 +42,46 @@ public String getCustomName() { @Override public Level getLevel() { Entity owner = pocket.getEntity(); - if (owner == null) return null; - return owner.getCommandSenderWorld(); + return owner == null ? null : owner.getCommandSenderWorld(); } @NotNull @Override public BlockPos getPos() { Entity owner = pocket.getEntity(); - if (owner == null) return new BlockPos(0, 0, 0); - return owner.blockPosition(); + return owner == null ? BlockPos.ZERO : new BlockPos(owner.getEyePosition()); } @NotNull @Override public Vec3 getCenterPos() { Entity owner = pocket.getEntity(); - if (owner == null) return new Vec3(0, 0, 0); - return owner.position(); + return owner == null ? Vec3.ZERO : owner.getEyePosition(); } @NotNull @Override public Direction getFacing() { - Entity owner = pocket.getEntity(); - if (owner == null) return Direction.NORTH; - return owner.getDirection(); + Vec3 dir = getDirection(); + return Direction.getNearest(dir.x, dir.y, dir.z); } - /** - * Not used for pockets - */ @NotNull @Override public FrontAndTop getOrientation() { - return FrontAndTop.NORTH_UP; + Entity owner = pocket.getEntity(); + if (owner == null) { + return FrontAndTop.NORTH_UP; + } + Vec3 up = owner.getUpVector(1.0f); + return FrontAndTop.fromFrontAndTop(getFacing(), Direction.getNearest(up.x, up.y, up.z)); + } + + @NotNull + @Override + public Vec3 getDirection() { + Entity owner = pocket.getEntity(); + return owner == null ? /* North */ new Vec3(0, 0, -1) : owner.getLookAngle(); } @Nullable diff --git a/src/main/java/de/srendi/advancedperipherals/common/addons/computercraft/peripheral/DistanceDetectorPeripheral.java b/src/main/java/de/srendi/advancedperipherals/common/addons/computercraft/peripheral/DistanceDetectorPeripheral.java index 7babcdf91..b3c01366d 100644 --- a/src/main/java/de/srendi/advancedperipherals/common/addons/computercraft/peripheral/DistanceDetectorPeripheral.java +++ b/src/main/java/de/srendi/advancedperipherals/common/addons/computercraft/peripheral/DistanceDetectorPeripheral.java @@ -257,7 +257,11 @@ protected double calculateDistanceImpl() { if (result.getType() == HitResult.Type.MISS) { return -1; } - return result.getLocation().distanceTo(center) - 0.5f; + double distance = result.getLocation().distanceTo(center); + if (this.tileEntity != null) { + distance -= 0.5; + } + return distance; } /** From 17d99c31724ef4a63fc940eb8a6e84e4fc800546 Mon Sep 17 00:00:00 2001 From: zyxkad Date: Sat, 25 Jan 2025 21:26:23 -0700 Subject: [PATCH 8/9] abstract peripheral ticker --- .../peripheral/ChatBoxPeripheral.java | 1 + .../DistanceDetectorPeripheral.java | 23 +++++++++++++++---- .../peripheral/PlayerDetectorPeripheral.java | 11 +++++++++ .../turtles/TurtleChatBoxUpgrade.java | 11 --------- .../blocks/base/BaseDetectorEntity.java | 3 ++- .../blocks/base/PeripheralBlockEntity.java | 6 +++++ .../blocks/blockentities/ChatBoxEntity.java | 8 ------- .../blockentities/DistanceDetectorEntity.java | 19 --------------- .../blocks/blockentities/MeBridgeEntity.java | 3 ++- .../blockentities/PlayerDetectorEntity.java | 16 ------------- .../smartglasses/SmartGlassesAccess.java | 2 -- .../lib/peripherals/IBasePeripheral.java | 2 ++ .../peripherals/IPeripheralTileEntity.java | 5 +--- .../lib/pocket/BasePocketUpgrade.java | 8 +++++++ .../lib/turtle/PeripheralTurtleUpgrade.java | 8 +++++++ 15 files changed, 60 insertions(+), 66 deletions(-) diff --git a/src/main/java/de/srendi/advancedperipherals/common/addons/computercraft/peripheral/ChatBoxPeripheral.java b/src/main/java/de/srendi/advancedperipherals/common/addons/computercraft/peripheral/ChatBoxPeripheral.java index 7616d1e27..920f64f13 100644 --- a/src/main/java/de/srendi/advancedperipherals/common/addons/computercraft/peripheral/ChatBoxPeripheral.java +++ b/src/main/java/de/srendi/advancedperipherals/common/addons/computercraft/peripheral/ChatBoxPeripheral.java @@ -485,6 +485,7 @@ public final MethodResult sendToastToPlayer(@NotNull IArguments arguments) throw }); } + @Override public void update() { lastConsumedMessage = Events.traverseChatMessages(lastConsumedMessage, message -> { for (IComputerAccess computer : getConnectedComputers()) { diff --git a/src/main/java/de/srendi/advancedperipherals/common/addons/computercraft/peripheral/DistanceDetectorPeripheral.java b/src/main/java/de/srendi/advancedperipherals/common/addons/computercraft/peripheral/DistanceDetectorPeripheral.java index b3c01366d..6a59adba7 100644 --- a/src/main/java/de/srendi/advancedperipherals/common/addons/computercraft/peripheral/DistanceDetectorPeripheral.java +++ b/src/main/java/de/srendi/advancedperipherals/common/addons/computercraft/peripheral/DistanceDetectorPeripheral.java @@ -71,6 +71,10 @@ public float getConfiguredMaxRange() { return APConfig.PERIPHERALS_CONFIG.distanceDetectorRange.get().floatValue(); } + public int getUpdateRate() { + return APConfig.PERIPHERALS_CONFIG.distanceDetectorUpdateRate.get(); + } + public float getMaxRange() { return Float.intBitsToFloat(this.maxRange.get()); } @@ -168,7 +172,7 @@ public final boolean getLaserVisibility() { return this.getShowLaser(); } - @LuaFunction(value = {"setIgnoreTransparency"}) + @LuaFunction(value = "setIgnoreTransparency") public final void setIgnoreTransparencyLua(boolean enable) { this.setIgnoreTransparent(enable); } @@ -231,17 +235,17 @@ public final boolean shouldCalculatePeriodically() { return this.getCalculatePeriodically(); } - @LuaFunction(value = {"setCalculatePeriodically"}) + @LuaFunction(value = "setCalculatePeriodically") public final void setCalculatePeriodicallyLua(boolean shouldCalculatePeriodically) { this.setCalculatePeriodically(shouldCalculatePeriodically); } - @LuaFunction(value = {"setMaxRange"}) + @LuaFunction(value = "setMaxRange") public final void setMaxRangeLua(double maxDistance) { this.setMaxRange((float) maxDistance); } - @LuaFunction(value = {"getMaxRange"}) + @LuaFunction(value = "getMaxRange") public final double getMaxRangeLua() { return this.getMaxRange(); } @@ -273,6 +277,17 @@ public double calculateAndUpdateDistance() { return distance; } + @Override + public void update() { + if (this.getCalculatePeriodically() && this.getLevel().getGameTime() % this.getUpdateRate() == 0) { + // We calculate the distance every 2 ticks, so we do not have to run the getDistance function of the peripheral + // on the main thread which prevents the 1 tick yield time of the function. + // The calculateDistance function is not thread safe, so we have to run it on the main thread. + // It should be okay to run that function every 2 ticks, calculating it does not take too much time. + this.calculateAndUpdateDistance(); + } + } + protected HitResult getHitResult(Vec3 from, Vec3 to) { Level level = this.getLevel(); ClipContext.ShapeGetter shapeGetter = this.ignoreTransparent ? HitResultUtil.IgnoreNoOccludedContext.INSTANCE : ClipContext.Block.COLLIDER; diff --git a/src/main/java/de/srendi/advancedperipherals/common/addons/computercraft/peripheral/PlayerDetectorPeripheral.java b/src/main/java/de/srendi/advancedperipherals/common/addons/computercraft/peripheral/PlayerDetectorPeripheral.java index fc3e5c058..b5f418993 100644 --- a/src/main/java/de/srendi/advancedperipherals/common/addons/computercraft/peripheral/PlayerDetectorPeripheral.java +++ b/src/main/java/de/srendi/advancedperipherals/common/addons/computercraft/peripheral/PlayerDetectorPeripheral.java @@ -14,6 +14,7 @@ import de.srendi.advancedperipherals.common.addons.computercraft.owner.TurtlePeripheralOwner; import de.srendi.advancedperipherals.common.blocks.base.PeripheralBlockEntity; import de.srendi.advancedperipherals.common.configuration.APConfig; +import de.srendi.advancedperipherals.common.events.Events; import de.srendi.advancedperipherals.common.util.CoordUtil; import de.srendi.advancedperipherals.common.util.LuaConverter; import de.srendi.advancedperipherals.lib.peripherals.BasePeripheral; @@ -33,6 +34,7 @@ public class PlayerDetectorPeripheral extends BasePeripheral { public static final String PERIPHERAL_TYPE = "player_detector"; private static final int MAX_RANGE = APConfig.PERIPHERALS_CONFIG.playerDetMaxRange.get(); + private long lastConsumedMessage = Events.getLastPlayerMessageID() - 1; public PlayerDetectorPeripheral(PeripheralBlockEntity tileEntity) { super(PERIPHERAL_TYPE, new BlockEntityPeripheralOwner<>(tileEntity)); @@ -265,4 +267,13 @@ private List getPlayers() { private ServerPlayer getPlayer(String name) { return ServerLifecycleHooks.getCurrentServer().getPlayerList().getPlayerByName(name); } + + @Override + public void update() { + lastConsumedMessage = Events.traversePlayerMessages(lastConsumedMessage, message -> getConnectedComputers().forEach(computer -> { + if(message.eventName().equals("playerChangedDimension")) { + computer.queueEvent(message.eventName(), message.playerName(), message.fromDimension(), message.toDimension()); + } else computer.queueEvent(message.eventName(), message.playerName(), message.fromDimension()); + })); + } } diff --git a/src/main/java/de/srendi/advancedperipherals/common/addons/computercraft/turtles/TurtleChatBoxUpgrade.java b/src/main/java/de/srendi/advancedperipherals/common/addons/computercraft/turtles/TurtleChatBoxUpgrade.java index b82aafab2..f8d9f7e4d 100644 --- a/src/main/java/de/srendi/advancedperipherals/common/addons/computercraft/turtles/TurtleChatBoxUpgrade.java +++ b/src/main/java/de/srendi/advancedperipherals/common/addons/computercraft/turtles/TurtleChatBoxUpgrade.java @@ -29,15 +29,4 @@ public ModelResourceLocation getRightModel() { protected ChatBoxPeripheral buildPeripheral(@NotNull ITurtleAccess turtle, @NotNull TurtleSide side) { return new ChatBoxPeripheral(turtle, side); } - - @Override - public void update(@NotNull ITurtleAccess turtle, @NotNull TurtleSide side) { - super.update(turtle, side); - if (turtle.getLevel().isClientSide) - return; - - if (turtle.getPeripheral(side) instanceof ChatBoxPeripheral chatBox) { - chatBox.update(); - } - } } diff --git a/src/main/java/de/srendi/advancedperipherals/common/blocks/base/BaseDetectorEntity.java b/src/main/java/de/srendi/advancedperipherals/common/blocks/base/BaseDetectorEntity.java index f0a92f033..0912220ab 100644 --- a/src/main/java/de/srendi/advancedperipherals/common/blocks/base/BaseDetectorEntity.java +++ b/src/main/java/de/srendi/advancedperipherals/common/blocks/base/BaseDetectorEntity.java @@ -136,7 +136,8 @@ public void load(@NotNull CompoundTag nbt) { @Override public void handleTick(Level level, BlockState state, BlockEntityType type) { - if (!level.isClientSide) { + super.handleTick(level, state, type); + if (!level.isClientSide()) { this.transferRate = this.proxy.getAndResetTransfered(); } } diff --git a/src/main/java/de/srendi/advancedperipherals/common/blocks/base/PeripheralBlockEntity.java b/src/main/java/de/srendi/advancedperipherals/common/blocks/base/PeripheralBlockEntity.java index e9507f900..e62d578c7 100644 --- a/src/main/java/de/srendi/advancedperipherals/common/blocks/base/PeripheralBlockEntity.java +++ b/src/main/java/de/srendi/advancedperipherals/common/blocks/base/PeripheralBlockEntity.java @@ -22,6 +22,7 @@ import net.minecraft.world.item.ItemStack; import net.minecraft.world.level.Level; import net.minecraft.world.level.block.entity.BaseContainerBlockEntity; +import net.minecraft.world.level.block.entity.BlockEntity; import net.minecraft.world.level.block.entity.BlockEntityType; import net.minecraft.world.level.block.state.BlockState; import net.minecraftforge.common.capabilities.Capability; @@ -243,4 +244,9 @@ public ComputerSide getComputerSide(Direction direction) { FrontAndTop orientation = getBlockState().getValue(BaseBlock.ORIENTATION); return CoordUtil.getComputerSide(orientation, direction); } + + @Override + public void handleTick(Level level, BlockState state, BlockEntityType type) { + this.getLazyPeripheral().ifPresent(BasePeripheral::update); + } } diff --git a/src/main/java/de/srendi/advancedperipherals/common/blocks/blockentities/ChatBoxEntity.java b/src/main/java/de/srendi/advancedperipherals/common/blocks/blockentities/ChatBoxEntity.java index 789b0704f..24e57b8d6 100644 --- a/src/main/java/de/srendi/advancedperipherals/common/blocks/blockentities/ChatBoxEntity.java +++ b/src/main/java/de/srendi/advancedperipherals/common/blocks/blockentities/ChatBoxEntity.java @@ -4,9 +4,6 @@ import de.srendi.advancedperipherals.common.blocks.base.PeripheralBlockEntity; import de.srendi.advancedperipherals.common.setup.APBlockEntityTypes; import net.minecraft.core.BlockPos; -import net.minecraft.world.level.Level; -import net.minecraft.world.level.block.entity.BlockEntity; -import net.minecraft.world.level.block.entity.BlockEntityType; import net.minecraft.world.level.block.state.BlockState; import org.jetbrains.annotations.NotNull; @@ -21,9 +18,4 @@ public ChatBoxEntity(BlockPos pos, BlockState state) { protected ChatBoxPeripheral createPeripheral() { return new ChatBoxPeripheral(this); } - - @Override - public void handleTick(Level level, BlockState state, BlockEntityType type) { - this.getLazyPeripheral().ifPresent(ChatBoxPeripheral::update); - } } diff --git a/src/main/java/de/srendi/advancedperipherals/common/blocks/blockentities/DistanceDetectorEntity.java b/src/main/java/de/srendi/advancedperipherals/common/blocks/blockentities/DistanceDetectorEntity.java index 828a61b4c..9af645790 100644 --- a/src/main/java/de/srendi/advancedperipherals/common/blocks/blockentities/DistanceDetectorEntity.java +++ b/src/main/java/de/srendi/advancedperipherals/common/blocks/blockentities/DistanceDetectorEntity.java @@ -9,9 +9,6 @@ import net.minecraft.core.Direction; import net.minecraft.nbt.CompoundTag; import net.minecraft.network.protocol.game.ClientboundBlockEntityDataPacket; -import net.minecraft.world.level.Level; -import net.minecraft.world.level.block.entity.BlockEntity; -import net.minecraft.world.level.block.entity.BlockEntityType; import net.minecraft.world.level.block.state.BlockState; import net.minecraft.world.phys.AABB; import net.minecraft.world.phys.Vec3; @@ -84,22 +81,6 @@ public void setDetectionType(DistanceDetectorPeripheral.DetectionType detectionT this.detectionType = detectionType; } - @Override - public void handleTick(Level level, BlockState state, BlockEntityType type) { - DistanceDetectorPeripheral peripheral = this.getPeripheral(); - if (peripheral == null) { - return; - } - - if (level.getGameTime() % APConfig.PERIPHERALS_CONFIG.distanceDetectorUpdateRate.get() == 0 && this.getCalculatePeriodically()) { - // We calculate the distance every 2 ticks, so we do not have to run the getDistance function of the peripheral - // on the main thread which prevents the 1 tick yield time of the function. - // The calculateDistance function is not thread safe, so we have to run it on the main thread. - // It should be okay to run that function every 2 ticks, calculating it does not take too much time. - peripheral.calculateAndUpdateDistance(); - } - } - @Override public AABB getRenderBoundingBox() { float currentDistance = this.getCurrentDistance(); diff --git a/src/main/java/de/srendi/advancedperipherals/common/blocks/blockentities/MeBridgeEntity.java b/src/main/java/de/srendi/advancedperipherals/common/blocks/blockentities/MeBridgeEntity.java index d7d857cb1..16a66d976 100644 --- a/src/main/java/de/srendi/advancedperipherals/common/blocks/blockentities/MeBridgeEntity.java +++ b/src/main/java/de/srendi/advancedperipherals/common/blocks/blockentities/MeBridgeEntity.java @@ -54,7 +54,8 @@ protected MeBridgePeripheral createPeripheral() { @Override public void handleTick(Level level, BlockState state, BlockEntityType type) { - if (!this.level.isClientSide) { + super.handleTick(level, state, type); + if (!this.level.isClientSide()) { if (!initialized) { MeBridgePeripheral peripheral = this.getPeripheral(); if (peripheral == null) { diff --git a/src/main/java/de/srendi/advancedperipherals/common/blocks/blockentities/PlayerDetectorEntity.java b/src/main/java/de/srendi/advancedperipherals/common/blocks/blockentities/PlayerDetectorEntity.java index 08a0ac6ef..789d6c36b 100644 --- a/src/main/java/de/srendi/advancedperipherals/common/blocks/blockentities/PlayerDetectorEntity.java +++ b/src/main/java/de/srendi/advancedperipherals/common/blocks/blockentities/PlayerDetectorEntity.java @@ -2,21 +2,14 @@ import de.srendi.advancedperipherals.common.addons.computercraft.peripheral.PlayerDetectorPeripheral; import de.srendi.advancedperipherals.common.blocks.base.PeripheralBlockEntity; -import de.srendi.advancedperipherals.common.events.Events; import de.srendi.advancedperipherals.common.setup.APBlockEntityTypes; import net.minecraft.core.BlockPos; -import net.minecraft.world.level.Level; -import net.minecraft.world.level.block.entity.BlockEntity; -import net.minecraft.world.level.block.entity.BlockEntityType; import net.minecraft.world.level.block.state.BlockState; import org.jetbrains.annotations.NotNull; public class PlayerDetectorEntity extends PeripheralBlockEntity { - private Long lastConsumedMessage; - public PlayerDetectorEntity(BlockPos pos, BlockState state) { super(APBlockEntityTypes.PLAYER_DETECTOR.get(), pos, state); - lastConsumedMessage = Events.getLastPlayerMessageID() - 1; } @NotNull @@ -24,13 +17,4 @@ public PlayerDetectorEntity(BlockPos pos, BlockState state) { protected PlayerDetectorPeripheral createPeripheral() { return new PlayerDetectorPeripheral(this); } - - @Override - public void handleTick(Level level, BlockState state, BlockEntityType type) { - lastConsumedMessage = Events.traversePlayerMessages(lastConsumedMessage, message -> getConnectedComputers().forEach(computer -> { - if(message.eventName().equals("playerChangedDimension")) { - computer.queueEvent(message.eventName(), message.playerName(), message.fromDimension(), message.toDimension()); - } else computer.queueEvent(message.eventName(), message.playerName(), message.fromDimension()); - })); - } } diff --git a/src/main/java/de/srendi/advancedperipherals/common/smartglasses/SmartGlassesAccess.java b/src/main/java/de/srendi/advancedperipherals/common/smartglasses/SmartGlassesAccess.java index 316c7a715..b43017d0c 100644 --- a/src/main/java/de/srendi/advancedperipherals/common/smartglasses/SmartGlassesAccess.java +++ b/src/main/java/de/srendi/advancedperipherals/common/smartglasses/SmartGlassesAccess.java @@ -48,12 +48,10 @@ public CompoundTag getUpgradeNBTData() { @Override public void updateUpgradeNBTData() { - } @Override public void invalidatePeripheral() { - } @Override diff --git a/src/main/java/de/srendi/advancedperipherals/lib/peripherals/IBasePeripheral.java b/src/main/java/de/srendi/advancedperipherals/lib/peripherals/IBasePeripheral.java index d1736f7e6..2bdd8fadc 100644 --- a/src/main/java/de/srendi/advancedperipherals/lib/peripherals/IBasePeripheral.java +++ b/src/main/java/de/srendi/advancedperipherals/lib/peripherals/IBasePeripheral.java @@ -16,4 +16,6 @@ default void queueEvent(String event, Object... args) { } T getPeripheralOwner(); + + default void update() {} } diff --git a/src/main/java/de/srendi/advancedperipherals/lib/peripherals/IPeripheralTileEntity.java b/src/main/java/de/srendi/advancedperipherals/lib/peripherals/IPeripheralTileEntity.java index 47c526faa..cc3caa796 100644 --- a/src/main/java/de/srendi/advancedperipherals/lib/peripherals/IPeripheralTileEntity.java +++ b/src/main/java/de/srendi/advancedperipherals/lib/peripherals/IPeripheralTileEntity.java @@ -11,8 +11,5 @@ public interface IPeripheralTileEntity { void markSettingsChanged(); - default void handleTick(Level level, BlockState state, BlockEntityType type) { - - } - + default void handleTick(Level level, BlockState state, BlockEntityType type) {} } diff --git a/src/main/java/de/srendi/advancedperipherals/lib/pocket/BasePocketUpgrade.java b/src/main/java/de/srendi/advancedperipherals/lib/pocket/BasePocketUpgrade.java index 291a333de..ea6e01fdd 100644 --- a/src/main/java/de/srendi/advancedperipherals/lib/pocket/BasePocketUpgrade.java +++ b/src/main/java/de/srendi/advancedperipherals/lib/pocket/BasePocketUpgrade.java @@ -28,4 +28,12 @@ public IPeripheral createPeripheral(@NotNull IPocketAccess access) { if (!peripheral.isEnabled()) return DisabledPeripheral.INSTANCE; return peripheral; } + + @Override + public void update(@NotNull IPocketAccess access, @Nullable IPeripheral peripheral) { + super.update(access, peripheral); + if (peripheral instanceof IBasePeripheral basePeripheral) { + basePeripheral.update(); + } + } } diff --git a/src/main/java/de/srendi/advancedperipherals/lib/turtle/PeripheralTurtleUpgrade.java b/src/main/java/de/srendi/advancedperipherals/lib/turtle/PeripheralTurtleUpgrade.java index 2f06c5944..9171dc811 100644 --- a/src/main/java/de/srendi/advancedperipherals/lib/turtle/PeripheralTurtleUpgrade.java +++ b/src/main/java/de/srendi/advancedperipherals/lib/turtle/PeripheralTurtleUpgrade.java @@ -47,4 +47,12 @@ public boolean isItemSuitable(@NotNull ItemStack stack) { } return super.isItemSuitable(stack); } + + @Override + public void update(@NotNull ITurtleAccess turtle, @NotNull TurtleSide side) { + super.update(turtle, side); + if (!turtle.getLevel().isClientSide() && turtle.getPeripheral(side) instanceof IBasePeripheral basePeripheral) { + basePeripheral.update(); + } + } } From 34d978905e05d749e5b47c33048d7e0d70ba8666 Mon Sep 17 00:00:00 2001 From: zyxkad Date: Sat, 25 Jan 2025 22:08:10 -0700 Subject: [PATCH 9/9] fix data storage for smartglass and save distance detector data in smartglass --- .../DistanceDetectorPeripheral.java | 32 ++++++++++++------- .../common/items/SmartGlassesItem.java | 2 +- .../smartglasses/SmartGlassesAccess.java | 4 ++- .../smartglasses/SmartGlassesComputer.java | 8 ++--- 4 files changed, 29 insertions(+), 17 deletions(-) diff --git a/src/main/java/de/srendi/advancedperipherals/common/addons/computercraft/peripheral/DistanceDetectorPeripheral.java b/src/main/java/de/srendi/advancedperipherals/common/addons/computercraft/peripheral/DistanceDetectorPeripheral.java index 6a59adba7..8b595fdf8 100644 --- a/src/main/java/de/srendi/advancedperipherals/common/addons/computercraft/peripheral/DistanceDetectorPeripheral.java +++ b/src/main/java/de/srendi/advancedperipherals/common/addons/computercraft/peripheral/DistanceDetectorPeripheral.java @@ -26,6 +26,7 @@ public class DistanceDetectorPeripheral extends BasePeripheral public static final String PERIPHERAL_TYPE = "distance_detector"; + private final AtomicBoolean isDirty = new AtomicBoolean(false); private final DistanceDetectorEntity tileEntity; private final AtomicInteger maxRange; private volatile float currentDistance; @@ -37,6 +38,7 @@ public class DistanceDetectorPeripheral extends BasePeripheral public DistanceDetectorPeripheral(DistanceDetectorEntity tileEntity) { super(PERIPHERAL_TYPE, new BlockEntityPeripheralOwner<>(tileEntity)); this.tileEntity = tileEntity; + // TODO: let distance detector block also use data storage this.maxRange = new AtomicInteger(Float.floatToRawIntBits(this.tileEntity.getMaxRange())); this.currentDistance = this.tileEntity.getCurrentDistance(); this.showLaser = new AtomicBoolean(this.tileEntity.getShowLaser()); @@ -45,7 +47,6 @@ public DistanceDetectorPeripheral(DistanceDetectorEntity tileEntity) { this.detectionType = new AtomicReference<>(this.tileEntity.getDetectionType()); } - // TODO: thread safely save data protected DistanceDetectorPeripheral(IPeripheralOwner owner) { super(PERIPHERAL_TYPE, owner); this.tileEntity = null; @@ -89,7 +90,7 @@ public void setMaxRange(float maxRange) { this.tileEntity.setMaxRange(maxRange); this.tileEntity.sendUpdate(); } - this.owner.markDataStorageDirty(); + this.isDirty.set(true); } public float getCurrentDistance() { @@ -97,16 +98,12 @@ public float getCurrentDistance() { } public void setCurrentDistance(float currentDistance) { - // Since setCurrentDistance should only invokes from main thread, volatile field should be safe here. - if (this.currentDistance == currentDistance) { - return; - } this.currentDistance = currentDistance; if (this.tileEntity != null) { this.tileEntity.setCurrentDistance(currentDistance); this.tileEntity.sendUpdate(); } - this.owner.markDataStorageDirty(); + this.isDirty.set(true); } public boolean getCalculatePeriodically() { @@ -118,7 +115,7 @@ public void setCalculatePeriodically(boolean calculatePeriodically) { if (this.tileEntity != null) { this.tileEntity.setCalculatePeriodically(calculatePeriodically); } - this.owner.markDataStorageDirty(); + this.isDirty.set(true); } public boolean getShowLaser() { @@ -133,7 +130,7 @@ public void setShowLaser(boolean showLaser) { this.tileEntity.setShowLaser(showLaser); this.tileEntity.sendUpdate(); } - this.owner.markDataStorageDirty(); + this.isDirty.set(true); } public boolean getIgnoreTransparent() { @@ -145,7 +142,7 @@ public void setIgnoreTransparent(boolean ignoreTransparent) { if (this.tileEntity != null) { this.tileEntity.setIgnoreTransparent(ignoreTransparent); } - this.owner.markDataStorageDirty(); + this.isDirty.set(true); } public DetectionType getDetectionType() { @@ -159,7 +156,7 @@ public void setDetectionType(DetectionType detectionType) { if (this.tileEntity != null) { this.tileEntity.setDetectionType(detectionType); } - this.owner.markDataStorageDirty(); + this.isDirty.set(true); } @LuaFunction @@ -286,6 +283,19 @@ public void update() { // It should be okay to run that function every 2 ticks, calculating it does not take too much time. this.calculateAndUpdateDistance(); } + + if (this.isDirty.getAndSet(false)) { + if (this.tileEntity == null) { + CompoundTag data = this.owner.getDataStorage(); + data.putFloat("maxRange", this.getMaxRange()); + data.putFloat("currentDistance", this.getCurrentDistance()); + data.putBoolean("showLaser", this.getShowLaser()); + data.putBoolean("calculatePeriodically", this.getCalculatePeriodically()); + data.putBoolean("ignoreTransparent", this.getIgnoreTransparent()); + data.putByte("detectionType", (byte) this.getDetectionType().ordinal()); + } + this.owner.markDataStorageDirty(); + } } protected HitResult getHitResult(Vec3 from, Vec3 to) { diff --git a/src/main/java/de/srendi/advancedperipherals/common/items/SmartGlassesItem.java b/src/main/java/de/srendi/advancedperipherals/common/items/SmartGlassesItem.java index 14b1e8c94..cb5c1a112 100644 --- a/src/main/java/de/srendi/advancedperipherals/common/items/SmartGlassesItem.java +++ b/src/main/java/de/srendi/advancedperipherals/common/items/SmartGlassesItem.java @@ -248,7 +248,7 @@ public SmartGlassesComputer getOrCreateComputer(ServerLevel level, Entity entity setComputerID(stack, computerID); } - computer = new SmartGlassesComputer(level, getComputerID(stack), getLabel(stack), getFamily(), stack.getOrCreateTag().getCompound(SmartGlassesComputer.UPGRADE_DATAS_TAG).copy()); + computer = new SmartGlassesComputer(level, getComputerID(stack), getLabel(stack), getFamily(), stack.getOrCreateTag().getCompound(SmartGlassesComputer.UPGRADE_DATAS_TAG)); setInstanceID(stack, computer.register()); setSessionID(stack, registry.getSessionID()); diff --git a/src/main/java/de/srendi/advancedperipherals/common/smartglasses/SmartGlassesAccess.java b/src/main/java/de/srendi/advancedperipherals/common/smartglasses/SmartGlassesAccess.java index b43017d0c..50420c042 100644 --- a/src/main/java/de/srendi/advancedperipherals/common/smartglasses/SmartGlassesAccess.java +++ b/src/main/java/de/srendi/advancedperipherals/common/smartglasses/SmartGlassesAccess.java @@ -43,15 +43,17 @@ public void setLight(int colour) { @Override public CompoundTag getUpgradeNBTData() { - return new CompoundTag(); + return computer.getUpgradeNBTData(); } @Override public void updateUpgradeNBTData() { + computer.updateUpgradeNBTData(); } @Override public void invalidatePeripheral() { + computer.invalidatePeripheral(); } @Override diff --git a/src/main/java/de/srendi/advancedperipherals/common/smartglasses/SmartGlassesComputer.java b/src/main/java/de/srendi/advancedperipherals/common/smartglasses/SmartGlassesComputer.java index 600a21742..2880f55f4 100644 --- a/src/main/java/de/srendi/advancedperipherals/common/smartglasses/SmartGlassesComputer.java +++ b/src/main/java/de/srendi/advancedperipherals/common/smartglasses/SmartGlassesComputer.java @@ -212,18 +212,18 @@ private void updatePeripheralsAndModules(SmartGlassesItemHandler itemHandler) { public void tickServer() { super.tickServer(); + boolean shouldUpdateInventory = this.peripheralOutdated || this.isDirty; if (this.peripheralOutdated && this.itemHandler != null) { this.peripheralOutdated = false; this.updatePeripheralsAndModules(this.itemHandler); } - if (this.isDirty) { this.isDirty = false; CompoundTag data = this.stack.getOrCreateTag(); data.put(UPGRADE_DATAS_TAG, this.upgradeDatas.copy()); - if (entity instanceof Player player) { - player.getInventory().setChanged(); - } + } + if (shouldUpdateInventory && entity instanceof Player player) { + player.getInventory().setChanged(); } this.modules.values().forEach(module -> {